PHP's mysql_real_escape_string and MySQL Injec

2019-02-15 08:40发布

问题:

I have been trying to figure out how exactly \x00, \n, \r, \, or \x1a can cause an SQL Injection (as it is mentioned at http://nl3.php.net/manual/en/function.mysql-real-escape-string.php)

I understand the idea of single quote and double quotes, but how and why I need to take care of the other items to make my query safe?

回答1:

I was wondering about the same question and I found the answer in the C API documentation of MySQL, it states:

Characters encoded are “\”, “'”, “"”, NUL (ASCII 0), “\n”, “\r”, and Control+Z (\x1a). Strictly speaking, MySQL requires only that backslash and the quote character used to quote the string in the query be escaped. mysql_real_escape_string() quotes the other characters to make them easier to read in log files.

It is also explained in String Literals that:

The mysql client truncates quoted strings containing NUL characters if they are not escaped, and Control+Z may be taken for END-OF-FILE on Windows if not escaped.

The NUL character represents the end of a string in C language, so this can falsely terminate the input argument of the mysql client program. Same thing for \x1a, it marks the end-of-file under Windows (try type test.txt in a command prompt with a \x1a character in the middle of the file).

The main point is that an admin can miss important information in a log file if his log file reader doesn't show the data beyond one of these characters. But who still uses precarious type command or equivalent under Windows to read a log file anyway?

In other terms, there is no danger with \n, \r, \0 or \x1a in PHP, other than potentially making a log file difficult to read.

As for the backslash, \' OR 1==1 would be converted to \\' OR 1==1 if it was not escaped too, cancelling the effect of the escaping of the quote.



回答2:

let's assume you have

$SQL="select * from mytable where myfield='$uservalue'"

\ -> \:

try \' or 1=1; --', after escaping the quote, you would get \\' or 1=1; --' and the SQL would be select * from mytable where myfield='\\' or 1=1; --'

\x00

Not important for PHP, but for C

Sorry, too lazy for the rest.