ThinkPHP框架通殺全部版本的一個SQL注入漏洞詳細分析及測試方法

ThinkPHP 3.1.3及以前的版本存在一個SQL注入漏洞,漏洞存在於ThinkPHP/Lib/Core/Model.class.php 文件php

根據官方文檔對"防止SQL注入"的方法解釋(見http://doc.thinkphp.cn/manual/sql_injection.html)使用查詢條件預處理能夠防止SQL注入,沒錯,當使用以下代碼時能夠起到效果:   
$Model->where("id=%d and username='%s' and xx='%f'",array($id,$username,$xx))->select();  
或者  $Model->where("id=%d and username='%s' and xx='%f'",$id,$username,$xx)->select();    
可是,當你使用以下代碼時,卻沒有"防止SQL注入"效果(而官方文檔卻說能夠防止SQL注入):  
$model->query('select * from user where id=%d and status=%s',$id,$status);   
或者   $model->query('select * from user where id=%d and status=%s',array($id,$status));   
緣由:
ThinkPHP/Lib/Core/Model.class.php 文件裏的parseSql函數沒有實現SQL過濾.html

原函數: sql

  1. protected function parseSql($sql,$parse) {
  2.         // 分析表達式
  3.         if(true === $parse) {
  4.             $options =  $this->_parseOptions();
  5.             $sql  =   $this->db->parseSql($sql,$options);
  6.         }elseif(is_array($parse)){ // SQL預處理
  7.             $sql  = vsprintf($sql,$parse);
  8.         }else{
  9.             $sql    =   strtr($sql,array('__TABLE__'=>$this->getTableName(),'__PREFIX__'=>C('DB_PREFIX')));
  10.         }
  11.         $this->db->setModel($this->name);
  12.         return $sql;
  13.     }

 

驗證漏洞(舉例):thinkphp

請求地址:http://localhost/Main?id=boo" or 1="1或http://localhost/Main?id=boo%22%20or%201=%221函數

action代碼: ui

  1. $model=M('Peipeidui');
  2. $m=$model->query('select * from peipeidui where name="%s"',$_GET['id']);
  3. dump($m);exit;

    或者
  4. $model=M('Peipeidui');
  5. $m=$model->query('select * from peipeidui where name="%s"',array($_GET['id']));
  6. dump($m);exit;

結果:this

表peipeidui全部數據被列出,SQL注入語句起效.htm

解決辦法:ip

將parseSql函數修改成: 文檔

  1. protected function parseSql($sql,$parse) {
  2.     // 分析表達式
  3.     if(true === $parse) {
  4.         $options =  $this->_parseOptions();
  5.         $sql  =   $this->db->parseSql($sql,$options);
  6.     }elseif(is_array($parse)){ // SQL預處理
  7.         $parse = array_map(array($this->db,'escapeString'),$parse);//此行爲新增代碼
  8.         $sql  = vsprintf($sql,$parse);
  9.     }else{
  10.         $sql    =   strtr($sql,array('__TABLE__'=>$this->getTableName(),'__PREFIX__'=>C('DB_PREFIX')));
  11.     }
  12.     $this->db->setModel($this->name);
  13.     return $sql;
  14. }
相關文章
相關標籤/搜索