PDO防注入原理分析以及使用PDO的注意事项 (转)

咱们都知道,只要合理正确使用PDO,能够基本上防止SQL注入的产生,本文主要回答如下两个问题:php

为何要使用PDO而不是mysql_connect?html

为什么PDO能防注入?mysql

使用PDO防注入的时候应该特别注意什么?sql

 

1、为什么要优先使用PDO?数据库

PHP手册上说得很清楚:安全

Prepared statements and stored procedures
Many of the more mature databases support the concept of prepared statements. What are they? They can be thought of as a kind of compiled template for the SQL that an application wants to run, that can be customized using variable parameters. Prepared statements offer two major benefits:

The query only needs to be parsed (or prepared) once, but can be executed multiple times with the same or different parameters. When the query is prepared, the database will analyze, compile and optimize its plan for executing the query. For complex queries this process can take up enough time that it will noticeably slow down an application if there is a need to repeat the same query many times with different parameters. By using a prepared statement the application avoids repeating the analyze/compile/optimize cycle. This means that prepared statements use fewer resources and thus run faster.网络

 


The parameters to prepared statements don't need to be quoted; the driver automatically handles this. If an application exclusively uses prepared statements, the developer can be sure that no SQL injection will occur (however, if other portions of the query are being built up with unescaped input, SQL injection is still possible).app

 

即便用PDO的prepare方式,主要是提升相同SQL模板查询性能、阻止SQL注入框架

同时,PHP手册中给出了警告信息tcp

Prior to PHP 5.3.6, this element was silently ignored. The same behaviour can be partly replicated with the PDO::MYSQL_ATTR_INIT_COMMAND driver option, as the following example shows.
Warning

The method in the below example can only be used with character sets that share the same lower 7 bit representation as ASCII, such as ISO-8859-1 and UTF-8. Users using character sets that have different representations (such as UTF-16 or Big5) must use the charset option provided in PHP 5.3.6 and later versions.

 

意思是说,在PHP 5.3.6及之前版本中,并不支持在DSN中的charset定义,而应该使用PDO::MYSQL_ATTR_INIT_COMMAND设置初始SQL, 即咱们经常使用的 set names gbk指令。

 

我看到一些程序,还在尝试使用addslashes达到防注入的目的,却不知这样其实问题更多, 详情请看http://www.lorui.com/addslashes-mysql_escape_string-mysql_real_eascape_string.html

还有一些作法:在执行数据库查询前,将SQL中的select, union, ....之类的关键词清理掉。这种作法显然是很是错误的处理方式,若是提交的正文中确实包含 the students's union , 替换后将篡改原本的内容,滥杀无辜,不可取。

 

2、为什么PDO能防SQL注入?
请先看如下PHP代码:

<?php

$pdo = new PDO("mysql:host=192.168.0.1;dbname=test;charset=utf8","root");

$st = $pdo->prepare("select * from info where id =? and name = ?");

 

$id = 21;

$name = 'zhangsan';

$st->bindParam(1,$id);

$st->bindParam(2,$name);

 

$st->execute();

$st->fetchAll();

?>

 

环境以下:

PHP 5.4.7

Mysql 协议版本 10

MySQL Server 5.5.27

 

为了完全搞清楚php与mysql server通信的细节,我特别使用了wireshark抓包进行研究之,安装wireshak以后,咱们设置过滤条件为tcp.port==3306, 以下图:

 

 

 

 

如此只显示与mysql 3306端口的通讯数据,避免没必要要的干扰。

特别要注意的是wireshak基于wincap驱动,不支持本地环回接口的侦听(即便用php链接本地mysql的方法是没法侦听的),请链接其它机器(桥接网络的虚拟机也可)的MySQL进行测试。

 

而后运行咱们的PHP程序,侦听结果以下,咱们发现,PHP只是简单地将SQL直接发送给MySQL Server :

 


 

 

 

其实,这与咱们平时使用mysql_real_escape_string将字符串进行转义,再拼接成SQL语句没有差异(只是由PDO本地驱动完成转义的),显然这种状况下仍是有可能形成SQL注入的,也就是说在php本地调用pdo prepare中的mysql_real_escape_string来操做query,使用的是本地单字节字符集,而咱们传递多字节编码的变量时,有可能仍是会形成SQL注入漏洞(php 5.3.6之前版本的问题之一,这也就解释了为什么在使用PDO时,建议升级到php 5.3.6+,并在DSN字符串中指定charset的缘由。

 

针对php 5.3.6之前版本,如下代码仍然可能形成SQL注入问题:

$pdo->query('SET NAMES GBK'); 

$var = chr(0xbf) . chr(0x27) . " OR 1=1 /*"; 

$query = "SELECT * FROM info WHERE name = ?"; 

$stmt = $pdo->prepare($query); 

$stmt->execute(array($var)); 

 

缘由与上面的分析是一致的。

 

而正确的转义应该是给mysql Server指定字符集,并将变量发送给MySQL Server完成根据字符转义。

 

那么,如何才能禁止PHP本地转义而交由MySQL Server转义呢?

PDO有一项参数,名为PDO::ATTR_EMULATE_PREPARES ,表示是否使用PHP本地模拟prepare,此项参数默认值未知。并且根据咱们刚刚抓包分析结果来看,php 5.3.6+默认仍是使用本地变量转,拼接成SQL发送给MySQL Server的,咱们将这项值设置为false, 试试效果,如如下代码:

<?php

$pdo = new PDO("mysql:host=192.168.0.1;dbname=test;","root");

$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

 

$st = $pdo->prepare("select * from info where id =? and name = ?");

$id = 21;

$name = 'zhangsan';

 

$st->bindParam(1,$id);

$st->bindParam(2,$name);

$st->execute();

$st->fetchAll();

?>

 

红色行是咱们刚加入的内容,运行如下程序,使用wireshark抓包分析,得出的结果以下:

 



 

 

看到了吗?这就是神奇之处,可见此次PHP是将SQL模板和变量是分两次发送给MySQL的,由MySQL完成变量的转义处理,既然变量和SQL模板是分两次发送的,那么就不存在SQL注入的问题了,但须要在DSN中指定charset属性,如:

$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'root');

 

如此,便可从根本上杜绝SQL注入的问题。若是你对此不是很清楚,能够发邮件至zhangxugg@163.com, 一块儿探讨。

 

3、使用PDO的注意事项

知道以上几点以后,咱们就能够总结使用PDO杜绝SQL注入的几个注意事项:

1.  php升级到5.3.6+,生产环境强烈建议升级到php 5.3.9+ php 5.4+,php 5.3.8存在致命的hash碰撞漏洞。

 

2. 若使用php 5.3.6+, 请在在PDO的DSN中指定charset属性

3. 若是使用了PHP 5.3.6及之前版本,设置PDO::ATTR_EMULATE_PREPARES参数为false(即由MySQL进行变量处理),php 5.3.6以上版本已经处理了这个问题,不管是使用本地模拟prepare仍是调用mysql server的prepare都可。在DSN中指定charset是无效的,同时set names <charset>的执行是必不可少的。

 

4. 若是使用了PHP 5.3.6及之前版本, 因Yii框架默认并未设置ATTR_EMULATE_PREPARES的值,请在数据库配置文件中指定emulatePrepare的值为false。

 

那么,有个问题,若是在DSN中指定了charset, 是否还须要执行set names <charset>呢?

是的,不能省。set names <charset>其实有两个做用:

A.  告诉mysql server, 客户端(PHP程序)提交给它的编码是什么

B.  告诉mysql server, 客户端须要的结果的编码是什么

也就是说,若是数据表使用gbk字符集,而PHP程序使用UTF-8编码,咱们在执行查询前运行set names utf8, 告诉mysql server正确编码便可,无须在程序中编码转换。这样咱们以utf-8编码提交查询到mysql server, 获得的结果也会是utf-8编码。省却了程序中的转换编码问题,不要有疑问,这样作不会产生乱码。

 

那么在DSN中指定charset的做用是什么? 只是告诉PDO, 本地驱动转义时使用指定的字符集(并非设定mysql server通讯字符集),设置mysql server通讯字符集,还得使用set names <charset>指令。

 

若是图片丢失,能够发邮件至zhangxugg@163.com, 索取PDF版本。

 

我真想不通,一些新的项目,为什么不使用PDO而使用传统的mysql_XXX函数库呢?若是正确使用PDO,能够从根本上杜绝SQL注入,我强烈建议各个公司的技术负责人、一线技术研发人员,要对这个问题引发重视,尽量使用PDO加快项目进度和安全质量。

 

不要再尝试本身编写SQL注入过滤函数库了(又繁琐并且很容易产生未知的漏洞)。

相关文章
相关标签/搜索