注入类
数据库注入
SQL注入
结构化查询语言 (Structured Query Language)简称SQL,结构化查询语言是一种数据库查询和程序设计语言,用于存取数据以及查询、更新和管理关系数据库系统关系型数据库 ,是指采用了关系模型来组织数据的数据库,其以行和列的形式存储数据,以便于用户理解,关系型数据库这一系列的行和列被称为表,一组表组成了数据库。常见的关系型数据库有Oracle、DB2、Microsoft SQL Server、MySQL、 Microsoft Access
sql语句可分为
数据查询语言(DQL):用以从表中获得数据。常用保留字: SELECT 、WHERE、ORDER BY、GROUP BY、HAVING数据操作语言(DML):用于添加、修改、删除表中的行。常用保留字: INSERT 、UPDATE 、 DELETE事务控制语言(TCL):确保被DML语句影响的表的所有行及时得以更新。常用保留 字:COMMIT、SAVEPOINT、ROLLBACK数据控制语言(DCL):通过GRANT或REVOKE实现权限控制,确定单个用户和用户组对数据库对象的访问数据定义语言(DDL):在数据库中创建新表或修改、删除表。常用保留字:CREATE、ALERT、DROP指针控制语言(CCL):通过DECLARE CURSOR、FETCH INTO和UPDATEWHERE CURRENT
The SQL injection attack is due to the fact that the legality of the user input data is not judged during the development of the web application. The attacker can use some special characters and instructions of specially constructed SQL to submit the A piece of code that queries a database, manipulates and obtains sensitive data . The object of the attack is: database
Example:
String query = "SELECT * FROM users WHERE userName = '"+ username variable + "' AND password = '"+ password variable + "'";
ResultSet rs = stmt.execute(query);
If using an attack payload:
Username: admin' or '1'='1
Password: admin@123'or '1'='1
single quotes for closing
Steps of sql injection
①Identify the possible input of web application and database interaction (identify potential injection points)② SQL injection statement test③ Determine whether the injected statement has affected the SQL execution result based on the server's return to determine whether there isIn SQL injection
SQL injection classification
– Error-based SQL injection (error-based injection) returns error information
– Boolean-based blind SQL injection (Boolean injection) through the right and wrong judgment of the condition
– Time-based blind SQL injection (time-based delay injection) to determine whether to delay the return of the requested result
According to the injection parameter type, it is divided into
1. Digital injectionhttp://test.com/shownews.php?id=1select * from news where news_id=12. Character injectionhttp://test.com/show.php?name=appleselect * from fruits where name= ' apple '
Test the type of sql injection:
Oracle: JAVADB2: JAVASQL Server: C#、ASP、.NETMySQL: PHP、JAVA
Determine the database type based on a unique function
Judgment based on unique data sheet
SQL injection is divided into according to the injection method
show injection• union query #joint query injection, get query results through union joint query• error based #Error report injection, obtain query results through error informationblind note• boolean based blind #Boolean blind injection, which returns different values to infer the true and false conditions of the application• time based blind #Time blind injection, inferring the true and false conditions through different time delaysPriority: union query≥error based>boolean based blind>time based blind
federated query injection
union queryPrerequisite: The page can display database query resultsid=1 order by 5id=-1 union select 1,2,3,4,5 #Test which field has echoid=-1 union select 1,concat(user(),0x2b,database()),3,4 #Get database user and databasenameid=-1 union select 1,group_concat(distinct table_name),3,4 frominformation_schema.tables where table_schema=database() #Get table nameid=-1 union select 1,group_concat(distinct column_name),3,4 frominformation_schema.columns where table_name= 'user' #Get the column nameid=-1 union select 1,concat(id,0x2b,name,0x2b,password),3,4 from uservolumetric data
Error injection
error basedPremise: The application can output database error messages•floor()and (select 1 from(select count(*),concat(version(),floor(rand(0)*2))x frominformation_schema.tables group by x)a)•updatexml()and 1=(updatexml(1,concat(0x3a,(select user())),1))•extractvalue()and extractvalue(1,concat(0x5c,(select user())))•exp()and exp(~(select * from(select user())a))
Boolean Blind
Premise: There are differences between the true and false pages of the condition and can be distinguished. You can judge whether the condition is true or false according to the return pageNeed to guess the solution one by one, commonly used substr, ascii, mid and other functionsif(substr(flag,1,1)in(0x66),3,0)select case when ascii(mid((select flag from flag),1,1))=65 then 'A' else 'B' end
Premise: Blind time injection will only be considered when other injection methods cannot be used, and time delay function orOther ways to achieve the effect of time delay to judge whether the condition is true or falseif(substr(flag,1,1)in(0x66),sleep(2),0)select case when ascii(mid((select flag from flag),1,1))=65 thenbenchmark(100000,sha1('1 ')) else '' end
submit parameter type
– digital
– character type
– search type
SQL injection prevention measures:
-
Use parameterized queries
-
Strictly limit the parameter type and format, clarify the boundary of parameter inspection, and check the validity of the submitted data before the server formally processes it;
-
Validate input/parameter filtering, i.e. white/blacklist validation;
The dangers of SQL injection:
-
Database information leakage: leakage of user's private information stored in the database.
-
Web page tampering: tampering with a specific web page by manipulating the database.
-
The website is linked to horses and spreads malware: modify the values of some fields in the database, embed links to Internet horses, and carry out attacks by hanging horses
-
The database is maliciously operated: the database server is attacked, and the system administrator account of the database is tampered with.
-
The server is controlled remotely and a backdoor is installed. The operating system support provided by the database server allows hackers to modify or control the operating system.
-
Destroy hard disk data and paralyze the entire system.
cross site scripting attack xss
Cross-site scripting attack: When web developers write applications, they do not filter and restrict the statements and variables submitted by users . Essentially, data is injected into static script code (HTML or Javascript, etc.), and the injected script is triggered when the browser renders the entire HTML document , resulting in an XSS attack.
Classification
1. Reflective XSS : Cross-site code generally exists in links. When such a link is requested, the cross-site code is reflected back by the server, and such cross-site code is generally not stored in the server.
2. Stored XSS : The biggest difference between stored XSS and reflected XSS is that the attack script will be permanently stored in the database and files of the target server. It is usually because the server side stores the malicious script entered by the user in the database without verification, and presents the data on the browser by calling the database.
3. DOM-type XSS : a DOM-based cross-site, which is a security problem caused by incorrect parsing of the client script itself
Reflected XSS :
- The user logs in normally
- The attacker sends a malicious url to the client
- The customer uses a browser to visit a malicious url
- The server responds to the attacker's js
- The js code in the attack is executed
- The user's browser sends the attacker a session token
- Attacker hijacks session user
Stored XSS :
- The user normally browses the information of the server
- Send a post containing malicious code to the server by posting
- The user requests the content of the post from the server
- The server returned a post containing malicious code
- Client server executes malicious code
DOM-type XSS
The difference from reflective XSS and stored XSS is that the xss code does not require the direct participation of the server in parsing the response, and the XSS is triggered by the browser-side DOM parsing
Preventive measures against XSS
Verify the validity of user-submitted contentEscape user-submitted contentLimit the length of user inputLimit cookie expiration timeUse HtmlEncoder to escape some characters on the output data
CSRF cross-site request forgery
The server receives the attacker's forged request from the browser and executes
Compared with cross-site scripting (XSS), XSS uses the user's browser's trust in the website, and CSRF uses the website's trust in the user's browser.
The conditions required to complete the CSRF attack
1. The account cannot be logged out
2. Both parties need to use the same browser
attack process• Attacker discovers XSS vulnerability - constructs code - sendsVictim - Victim Open - Attacker obtains Victim'scookie - complete the attack• Attacker discovers CSRF vulnerability - constructs code - sendsVictim—Victim Open— Victim Executes Code —Finishattack
• XSS is easy to find, because the attacker needs to log in to the background to complete the attack, and the administrator can find the attacker by looking at the log.• CSRF is different, its attack has been implemented by the administrator himself, and the attacker is only responsible for constructing the code
CSRF protection
HTTP Referer is part of the header. When the browser sends a request to the web server, it will usually bring the Referer to tell the server which page I am linking from.request.getHeader("REFERER");By checking the value of Referer, we can judge whether the request is legal or illegal, then Refere Check can be used to monitor the occurrence of CSRF attacks
File Upload Vulnerability
The main reason for illegal file uploads is that the file type uploaded by the user is not verified or the verification is incomplete on the server side , so that the user can upload malicious scripts to the serverThis defect can be used to upload Webshell , virus and other malicious codes to further escalate privileges.Get database information (drag library) and even down server permissions
File upload protection
Path Traversal - Arbitrary File Download
On the server side, receive the file name from the browser, piece together the absolute path of the file on the server side, and download it with the output stream
String path = request.getParameter("path");
java.io.OutputStream os = response.getOutputStream();
java.io.FileInputStream fis = new java.io.FileInputStream(path);
byte[] b = new byte[1024];
int i = 0;
while ((i = fis.read(b)) > 0 ){
os.write(b, 0, i);
}
fis.close();
os.flush();
os.close();
构造攻击载荷
../../../../../../../etc/passwd
Path Traversal Protection
1. Save the address of the file to be downloaded to the database.2. The file ID is named with a random number3. The file path is saved to the database, and the user submits the file corresponding to the ID to download the file.4. Do permission judgment before downloading files.5. Record file download log
For file access, a link to the file path is directly given. like:<a href= “http://xx.xx.xx.xx/upload/file1.jpg”>
broken Authentication invalid authentication
1. User authentication credentials are not hashed or encrypted ;2. Authentication credentials can be guessed ;3. SessionId is exposed in the URL ;4. SessionId has no timeout limit ;5. Passwords, session IDs, and other authentication credentials are transmitted using unencrypted connections
Authentication information is not encrypted:
Password information plaintext transmission, password information plaintext storage
Session management:
Session update:
Whether the session identification information has been updated before and after authentication.Session storage:Whether the session identification information is stored in insecure places such as URL links or page information.Session destruction:Whether to perform session termination and destruction operations after the session is used up or the permission is canceled.
broken access control
Website permissions refer to certain security rules or security policies set by the system, users can access and can only access their ownAuthorized resources.
An unauthorized attack refers to the attacker viewing or using functions or information not under his own authority through technical means.
unauthorized attack
unauthorized viewingThe attacker can view other people's user information through a specific link address without logging inUnauthorized feature useThe attacker uses a specific user or system function through a specific link address without logging in
ultra vires
Vertical privilege escalation vulnerability , also known as privilege escalation vulnerability, because the web application does not have permission control or only controls the permission on the menu, the malicious user can access or control the data owned by other roles as long as they guess the URL of other management pages or pages for the purpose of privilege escalationAttackers use low-privilege accounts to view or use information and functions that can only be used by high-privilege accountsHorizontal overreach vulnerability . When a web application receives a user request and modifies a piece of data, it fails to determine the owner of the data, or when judging the owner of the data, it obtains the data owner from the request parameter (user controllable data) submitted by the user. The person id allows malicious attackers to modify data that does not belong to them by changing the data ID or changing the owner id. maliciousUsers can delete or modify other people's dataThe attacker uses an account with specific permissions to access or use the module functions of other users at the same level
Protection against unauthorized access
Vertical overreach vulnerability: Before calling a function, verify whether the current user identity has permission to call related functions (it is recommended to use filters for unified permission verification)Horizontal unauthorized access vulnerability: When the user performs an operation, the user ID is obtained from the session, and the incoming parameters are bound and verified with the user's identity.
Java deserialization vulnerability
Serialization: ObjectOutputStream class --> writeObject()
This method serializes the obj object specified by the parameter , and writes the byte sequence to a target output stream. According to the Java standard convention, the file is given a .ser extension1) Create an object output stream that can wrap an object of another typeStandard output stream, such as file output stream;2) Write the object through the writeObject() method of the object output stream.Deserialization: ObjectInputStream class --> readObject()This method reads a sequence of bytes from a source input stream, deserializes them into an object, and returns it1) Create an object input stream that can wrap a source input stream of another type, such as a file input stream;2) Read the object through the readObject() method of the object input stream
Attackers can carry out malicious constructions to allow deserialization to generate unexpected objects, which may lead to arbitrary code execution during the generation process.