Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

SQL Injection

SQL Injection

SQL Injection is a common web attack technique in which an attacker injects malicious SQL statements into input fields or requests to manipulate the database into performing unintended operations.

Its goals are usually:

How SQL Injection Works

Normal Query

When a user logs in to a website, they usually enter a username and password.

The following is a normal SQL query code:

SELECT * FROM users WHERE username = 'user1' AND password = 'password1';

Injection Attack

If an attacker enters:

用户名: admin' --
密码: anything

The SQL query becomes:


SELECT * FROM users WHERE username = 'admin' --' AND password = 'anything';

Here -- is the SQL comment symbol, which ignores the password condition and directly bypasses authentication.


Common SQL Injections

1. Basic SQL Injection

Malicious SQL code is embedded directly into user input and affects the query logic.


输入用户名:admin' OR '1'='1
输入密码:anything

The SQL query executed:

SELECT * FROM users WHERE username = 'admin' OR '1'='1' AND password = 'anything';

Result:

OR '1'='1' is always true and can bypass verification.

2. UNION Query Injection

Through UNION, the attacker merges the query result they constructed with the legitimate query result to obtain sensitive data.

Inputs:

' UNION SELECT null, username, password FROM users --

The SQL query executed:


SELECT id, name FROM products WHERE id = '' UNION SELECT null, username, password FROM users --';

Result:

The username and password data from the users table is returned as the result.

3. Error-Based SQL Injection

By deliberately triggering database errors, error messages are used to infer table names, column names, or data.

Inputs:

' AND 1=CONVERT(int, (SELECT @@version)) --

The SQL query executed:


SELECT * FROM users WHERE username = '' AND 1=CONVERT(int, (SELECT @@version)) --';

Result:

Error messages may expose the database version or other information.

4. Blind Injection

When the query result cannot be obtained directly, the attacker infers data step by step by judging the response of the returned page (such as a boolean value or a time delay).

Boolean-based blind injection, input:

' AND (SELECT 1 WHERE SUBSTRING((SELECT database()), 1, 1)='t') --

The SQL query executed:


SELECT * FROM users WHERE username = '' AND (SELECT 1 WHERE SUBSTRING((SELECT database()), 1, 1)='t') --';

Result:

Determine whether the first letter of the database name is t based on the returned result.

Time-based blind injection, input:

' AND IF(1=1, SLEEP(5), 0) --

The SQL query executed:


SELECT * FROM users WHERE username = '' AND IF(1=1, SLEEP(5), 0) --';

Result:

If the condition holds, the server delays its response by 5 seconds, thereby leaking information.

5. Stacked Query Injection

Allows multiple SQL statements to be executed at the same time.

Inputs:

'; DROP TABLE users; --

The SQL query executed:


SELECT * FROM users WHERE username = ''; DROP TABLE users; --';

Result:

The users table is deleted.

Some databases (such as MySQL) do not support multi-statement execution by default.

6. Stored Procedure Injection

Malicious SQL is injected through the input parameters of a stored procedure.

Inputs:

'; EXEC xp_cmdshell('dir'); --

SQL executed:


EXEC LoginProcedure 'username', ''; EXEC xp_cmdshell('dir'); --'

Result:

Execute system commands (such as listing a directory).

7. Cookie Injection

Injection is performed by modifying the Cookie values stored in the browser.


Cookie: session_id=' OR '1'='1;

The server executes malicious SQL when parsing the Cookie.


The Harm of SQL Injection


Prevention Measures

1. Parameterized Queries and Prepared Statements

Use parameterized queries or prepared statements to separate user input from SQL statements, preventing user input from being parsed directly as SQL code.

Java code:

Example

String

sql

=

"SELECT * FROM users WHERE username = ? AND password = ?"

;

PreparedStatement

pstmt

=

connection.

prepareStatement

(

sql

)

;

pstmt.

setString

(

1

, username

)

;

pstmt.

setString

(

2

, password

)

;

ResultSet

rs

=

pstmt.

executeQuery

(

)

;

Node.js (MySQL module):

Example

const

query

=

"SELECT * FROM users WHERE username = ? AND password = ?"

;

connection.

query

(

query

,

[

username

,

password

]

,

(

err

,

results

)

=>

{

   

if

(

err

)

throw

err

;

   

// Handle results

}

)

;

2. Using an ORM Framework

The core idea is that an ORM (such as Hibernate, Sequelize, etc.) automatically generates SQL queries, greatly reducing the chance of manually concatenating SQL and thus avoiding injection.

// 使用 Sequelize
const user = await User.findOne({
    where: { username: 'admin', password: 'password123' }
});

3. Input Validation

Strictly check whether user input meets expectations and reject input that does not follow the rules.

Use regular expressions for usernames, emails, etc., and allow only numeric input for numeric fields.

Escape special characters (such as escaping quotation marks).


const username = req.body.username.replace(/[^a-zA-Z0-9]/g, ''); // 清理特殊字符

4. Restricting Database Permissions

Assign minimum privileges to database users, allowing only necessary operations.

Create a read-only user:

CREATE USER 'readonly_user'@'%' IDENTIFIED BY 'secure_password';
GRANT SELECT ON database_name.* TO 'readonly_user'@'%';

5. Regular Security Testing

Use security scanning tools or manual testing to regularly check code for potential SQL injection vulnerabilities.

We can use the open-source tool SQLMap for testing.

SQLMap is a penetration testing tool specifically designed to automate SQL injection detection and exploitation.

SQLMap is widely used in network security assessment and penetration testing to help discover and fix SQL injection vulnerabilities.