消除危险字符是否可以避免 SQL 注入? [英] Does eliminating dangerous characters avoid SQL-injection?

查看:64
本文介绍了消除危险字符是否可以避免 SQL 注入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

避免 SQL 注入有很多方法 如何预防PHP 中的 SQL 注入?.

Avoiding SQL-injections there are many ways How to prevent SQL injection in PHP?.

问题是,如何通过removeBadCharacters进行sql注入?

The question is, how is it possible to sql-inject through removeBadCharacters?

function removeBadCharacters($s)
{
   return str_replace(array('&','<','>','/','\\','"',"'",'?','+'), '', $s);
}

它试图丢弃危险字符(应用程序不需要这些字符):

$x = removeBadCharacters($_POST['data']);

mysql_query("insert into table (x) values ('".$x."');");

// or

mysql_query("select * from into where name = '".$x."';"); 

推荐答案

能够从 字符串文字,需要保留该字符串文字.这只能通过引入字符串结束分隔符来实现,在这种情况下是单个 ',或者通过将字符串文字扩展到前面的 ',例如,通过使用转义符字符 \:

To be able to inject arbitrary SQL from the context of a string literal, that string literal needs to be left. This is only possible by introducing a string end delimiter, in this case a single ', or by expand the a string literal to a preceding ', e.g., by using the escapes character \:

$a = '\\';
$b = ' OR 1=1 OR ';
$c = ' --';

$query = "SELECT * FROM t1 WHERE a='$a' AND b='$b' AND c='$c'";
// result:
// SELECT * FROM t1 WHERE a='\' AND b=' OR 1=1 OR ' AND c=' --'
//                          \_________/           \_______/

现在,由于您的函数删除了任何 '\似乎 不可能离开或扩展字符串文字,因此不可能注入任意 SQL.

Now as your function removes any ' and \, it seems to be impossible to leave or expand the string literal and thus not possible to inject arbitrary SQL.

但是,由于你的函数没有考虑实际的字符编码,如果MySQL的字符编码是GBK,类似当使用 addslashes 而不是 mysql_real_escape_string:

However, since your function does not take the actual character encoding into account, it is possible to exploit this if the MySQL’s character encoding is GBK, similar to how it can be exploited when using addslashes instead of mysql_real_escape_string:

$a = "\xbf";
$b = " OR 1=1 OR ";
$c = " --";

$query = "SELECT * FROM t1 WHERE a='$a' AND b='$b' AND c='$c'";
// result:
// SELECT * FROM t1 WHERE a='縗 AND b=' OR 1=1 OR ' AND c=' --'
//                          \_________/           \_______/

所以为了安全起见,使用mysql_real_escape_string 或其他经过验证的方法来防止 SQL 注入.

So to play safe, use mysql_real_escape_string or other proven methods to prevent SQL injections.

这篇关于消除危险字符是否可以避免 SQL 注入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆