Is htmlspecialchars enough to prevent an SQL injection on a variable enclosed in single quotes?

别说谁变了你拦得住时间么 提交于 2019-11-26 18:30:34

问题


Although many sources quote the htmlspecialchars function with ENT_QUOTES to be not enough to prevent SQL injection, none of them provide a proof of the concept. I cannot think of any possibility myself.

Let us consider the following example:

$username = htmlspecialchars($_GET['name'], ENT_QUOTES, 'UTF-8');
$sql = "SELECT * from user WHERE name='$username'";
mysql_query($sql,...);

Can any one provide an example, OTHER than ones covered by the case when SQL injection gets around mysql_real_escape_string()?


回答1:


The character that htmlspecialchars fails to encode the critical character \0 (NUL byte), \b (backspace), as well as the \ character.

In order to exploit this, you need a statement with multiple injection points. With this you can escape the closing delimiter of one string literal and thus expand it up to the next starting delimiter of the next string literal. Three string literals each with an injection point can then be transformed into two string literals.

For example:

SELECT * from user WHERE (name='$login' OR email='$login') AND password='$password'

Now with the following values:

login:    ) OR 1=1 /*\
password: */--

The resulting statement looks like this:

SELECT * from user WHERE (name=') OR 1=1 /*\' OR email=') OR 1=1 /*\') AND password='*/--'

Which is equivalent to:

SELECT * from user WHERE (name=') OR 1=1 /*\' OR email=') OR 1=1



回答2:


Strings aren't the only thing SQL interacts with.

$result = "SELECT * FROM user WHERE id = " . htmlspecialchars($_GET['id']);

This is where parameterized queries come in very handy.



来源:https://stackoverflow.com/questions/22116934/is-htmlspecialchars-enough-to-prevent-an-sql-injection-on-a-variable-enclosed-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!