MySQL and SQL Injection
If you obtain user input data through a web page and insert it into a MySQL database, SQL injection security issues may occur.
SQL injection is the act of inserting SQL commands into a web form submission, an input domain name, or the query string of a page request, ultimately deceiving the server into executing malicious SQL commands.
MySQL injection refers to an attacker successfully executing malicious SQL queries through maliciously constructed input. This usually occurs when user input is not properly validated or escaped, and the attacker attempts to insert SQL code into the input to execute unexpected queries or damage the database.
We should never trust user input. We must assume that all user input data is unsafe and that we need to filter it.
Suppose there is a login system where users authenticate by entering a username and password:
SELECT * FROM users WHERE username = 'input_username' AND password = 'input_password';
Without proper input validation and preventive measures, an attacker can enter a username similar to the following:
' OR '1'='1'; --
In this case, the SQL query becomes:
SELECT * FROM users WHERE username = '' OR '1'='1'; --' AND password = 'input_password';
This causes the query to return all users because 1=1 is always true, and the comment symbol -- is used to comment out the rest of the original query to ensure correct syntax.
Preventing SQL injection:
-
Use parameterized queries or prepared statements: Using parameterized queries (Prepared Statements) can effectively prevent SQL injection because they separate input data from the query statement before executing the query.
-
Input validation and escaping: Perform appropriate validation of user input and use suitable escaping functions (such as
mysqli_real_escape_string) to process the input and prevent malicious injection. -
Principle of least privilege: Give database users minimal permissions, ensuring they can only perform necessary operations to reduce potential damage.
-
Use an ORM framework: Using an Object-Relational Mapping (ORM) framework (such as Hibernate, Sequelize) can help abstract SQL queries, thereby reducing the risk of SQL injection.
-
Disable error message display: In production, disable the display of detailed error messages to prevent attackers from obtaining sensitive information about the database structure.
Application Example
In the following example, the input username must be a combination of letters, digits, and underscores, and the username length must be between 8 and 20 characters:
Example
IF
(
preg_match
(
"/^\w{8,20}$/"
,
$_GET
[
'username'
]
,
$matches
)
)
{
$result
=
mysqli_query
(
$conn
,
"SELECT * FROM users
WHERE username=$matches[0]"
)
;
}
ELSE
{
echo
"username input error"
;
}
Let's look at the SQL situation that occurs when special characters are not filtered:
// $name contains SQL statements we don't need
$name = "Qadir'; DELETE FROM users;";
mysqli_query($conn, "SELECT * FROM users WHERE name='{$name}'");
In the above injection statement, we did not filter the $name variable. Unwanted SQL statements were inserted into $name, which will delete all data in the users table.
mysqli_query() in PHP does not allow executing multiple SQL statements, but SQLite and PostgreSQL can execute multiple SQL statements at the same time, so we need to strictly validate such user data.
To prevent SQL injection, we need to pay attention to the following key points:
- 1. Never trust user input -- Validate user input, which can be done through regular expressions, limiting length, escaping single and double quotes, etc.
- 2. Never use dynamically assembled SQL -- You can use parameterized SQL or directly use stored procedures for data query and access.
- 3. Never use a database connection with administrator privileges -- Use a separate database connection with limited permissions for each application.
- 4. Do not store confidential information directly -- Use hashing to encrypt passwords and sensitive information.
- 5. Application error messages should reveal as little information as possible -- It is best to use custom error messages to wrap the original error messages.
- 6. SQL injection detection is generally carried out using auxiliary software or web platforms -- Use specialized vulnerability scanning tools (such as sqlmap, Acunetix, Netsparker) to perform automated SQL injection detection on applications.
Preventing SQL Injection
In scripting languages such as Perl and PHP, you can escape user input data to prevent SQL injection.
PHP's MySQL extension provides the mysqli_real_escape_string() function to escape special input characters.
Example
IF
(
get_magic_quotes_gpc
(
)
)
{
$name
=
stripslashes
(
$name
)
;
}
$name
=
mysqli_real_escape_string
(
$conn
,
$name
)
;
mysqli_query
(
$conn
,
"SELECT * FROM users WHERE name='{$name}'"
)
;
Injection in LIKE statements
In a LIKE query, if the value entered by the user contains _ and %, this situation occurs: the user only wanted to query abcd_, but the query results also contain " abcd_"、"abcde"、"abcdf" and so on; problems also arise when the user wants to query "30%" (note: thirty percent).
In PHP scripts we can use the addcslashes() function to handle the above situations, as shown in the following example:
Example
$sub
=
addcslashes
(
mysqli_real_escape_string
(
$conn
,
"%something_"
)
,
"%_"
)
;
// $sub == %something_
mysqli_query
(
$conn
,
"SELECT * FROM messages WHERE subject LIKE '{$sub}%'"
)
;
The addcslashes() function adds backslashes before the specified characters.
Syntax:
addcslashes(string,characters)
| Parameters | Description |
|---|---|
| string | Required. Specifies the string to check. |
| characters | Optional. Specifies the characters or character ranges affected by addcslashes(). |
For specific applications, see:PHP addcslashes() Function