Using character encoding issues to bypass mysql_real_escape_string()
’s SQL injection
Although the mysql_real_escape_string()
function protects against SQL injection, it may be bypassed under certain circumstances.
Consider the following PHP code:
<code class="language-php">$login = mysql_real_escape_string(GetFromPost('login')); $password = mysql_real_escape_string(GetFromPost('password')); $sql = "SELECT * FROM table WHERE login='$login' AND password='$password'";</code>
This code appears to be safe, but it can be exploited due to edge cases in character set encoding.
Attack method:
The attack relies on the following steps:
mysql_real_escape_string()
: The client thinks the connection is using a different character set (e.g., latin1), so mysql_real_escape_string()
inserts a backslash before the single quote, resulting in a syntactically valid string. How it works:
The key problem is that the character set expected by the server does not match what the client thinks it is. Although mysql_real_escape_string()
is escaped according to the connection encoding set by the client, it will treat invalid multi-byte characters as single bytes in some cases, including cases where SET NAMES
is used instead of mysql_set_charset()
.
Consequences:
This attack can bypass PDO's simulated prepared statements even if simulated prepared statements are disabled.
Remedy:
Using a non-vulnerable character set, such as utf8mb4 or utf8, can mitigate this problem. Enabling NO_BACKSLASH_ESCAPES SQL mode also provides protection.
Safe example:
Always set the charset correctly using mysql_set_charset()
or PDO's DSN charset parameter. Real prepared statements in MySQLi are also immune to this attack.
Conclusion:
While mysql_real_escape_string()
generally provides strong protection, it is important to be aware of potential edge cases like this to ensure complete protection against SQL injection.
The above is the detailed content of Can SQL Injection Bypass `mysql_real_escape_string()` Due to Character Encoding Issues?. For more information, please follow other related articles on the PHP Chinese website!