Principles and Defense of SQL Injection Attacks
Description:
SQL injection is a common web security vulnerability where attackers insert malicious SQL code into input fields of an application, tricking the server into executing unintended database operations. This type of attack can lead to data leakage, tampering, or deletion, and may even result in full control of the database. For example, on a login page, if the application does not filter user input, an attacker could bypass password verification and log in directly.
Problem-Solving Process:
-
Understand the Cause of the Vulnerability:
- Assume a login page's backend code uses string concatenation to construct an SQL query:
SELECT * FROM users WHERE username = 'input_username' AND password = 'input_password'; - If the user enters
admin' --in the username field and any password, the query becomes:SELECT * FROM users WHERE username = 'admin' --' AND password = 'xxx'; - Here,
--is an SQL comment delimiter, causing the subsequent password verification to be ignored, allowing the attacker to log in as admin.
- Assume a login page's backend code uses string concatenation to construct an SQL query:
-
Attack Classification and Examples:
- Union Query Injection: Combining data from other tables using
UNION SELECT(e.g.,' UNION SELECT credit_card FROM payments --). - Boolean Blind Injection: Inferring data based on true/false responses from the page (e.g.,
' AND (SELECT SUBSTRING(password,1,1) FROM users)='a' --). - Time-Based Blind Injection: Using delay functions (e.g.,
' AND SLEEP(5) --) to determine whether a condition is true.
- Union Query Injection: Combining data from other tables using
-
Defensive Measures:
- Parameterized Queries (Prepared Statements):
Using placeholders instead of direct concatenation. For example, in Python:
The database distinguishes between code and data, ensuring input is always treated as a parameter.cursor.execute("SELECT * FROM users WHERE username = %s AND password = %s", (username, password)) - Input Validation and Filtering:
Escaping special characters (e.g., single quotes, semicolons) or implementing whitelist validation (e.g., allowing only alphanumeric characters). - Principle of Least Privilege:
Granting the database connection account only necessary permissions (e.g., prohibiting DROP operations). - Web Application Firewall (WAF):
Detecting and intercepting suspicious SQL keywords (e.g.,UNION,SLEEP).
- Parameterized Queries (Prepared Statements):
-
Practical Testing:
Using tools (e.g., SQLMap) or manually testing input points (e.g., URL parameters, form fields) to observe error messages or abnormal behavior, and verifying whether defense mechanisms are effective.
Through the above steps, one can systematically grasp the vulnerability principles, exploitation techniques, and protection strategies of SQL injection.