日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關咨詢
選擇下列產(chǎn)品馬上在線溝通
服務時間:8:30-17:00
你可能遇到了下面的問題
關閉右側工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
ThinkPHP框架安全實現(xiàn)分析

ThinkPHP框架是國內(nèi)比較流行的PHP框架之一,雖然跟國外的那些個框架沒法比,但優(yōu)點在于,恩,中文手冊很全面。最近研究SQL注入,之前用TP框架的時候因為底層提供了安全功能,在開發(fā)過程中沒怎么考慮安全問題。想知道TP到底是怎么實現(xiàn)防SQL注入的,所以看了一些源碼。結合phith0n大牛在烏云上發(fā)的漏洞,分析了一下,整理了一些思路~~

成都創(chuàng)新互聯(lián)長期為近1000家客戶提供的網(wǎng)站建設服務,團隊從業(yè)經(jīng)驗10年,關注不同地域、不同群體,并針對不同對象提供差異化的產(chǎn)品和服務;打造開放共贏平臺,與合作伙伴共同營造健康的互聯(lián)網(wǎng)生態(tài)環(huán)境。為隴川企業(yè)提供專業(yè)的成都網(wǎng)站建設、成都網(wǎng)站設計,隴川網(wǎng)站改版等技術服務。擁有10多年豐富建站經(jīng)驗和眾多成功案例,為您定制開發(fā)。

一、不得不說的I函數(shù)

TP系統(tǒng)提供了I函數(shù)用于輸入變量的過濾。整個函數(shù)主體的意義就是獲取各種格式的數(shù)據(jù),比如I('get.')、I('post.id'),然后用htmlspecialchars函數(shù)(默認情況下)進行處理。如果需要采用其他的方法進行安全過濾,可以從/ThinkPHP/Conf/convention.php中設置:

'DEFAULT_FILTER' => 'strip_tags',
//也可以設置多種過濾方法
'DEFAULT_FILTER' => 'strip_tags,stripslashes',

從/ThinkPHP/Common/functions.php中可以找到I函數(shù),源碼如下:

 
 
 
 
  1. /**  
  2.  * 獲取輸入?yún)?shù) 支持過濾和默認值  
  3.  * 使用方法:  
  4.  *   
  5.  * I('id',0); 獲取id參數(shù) 自動判斷get或者post  
  6.  * I('post.name','','htmlspecialchars'); 獲取$_POST['name']  
  7.  * I('get.'); 獲取$_GET  
  8.  *   
  9.  * @param string $name 變量的名稱 支持指定類型  
  10.  * @param mixed $default 不存在的時候默認值  
  11.  * @param mixed $filter 參數(shù)過濾方法  
  12.  * @param mixed $datas 要獲取的額外數(shù)據(jù)源  
  13.  * @return mixed  
  14.  */ 
  15. function I($name,$default='',$filter=null,$datas=null) {  
  16.     static $_PUT    =    null;  
  17.     if(strpos($name,'/')){ // 指定修飾符  
  18.         list($name,$type)     =    explode('/',$name,2);  
  19.     }elseif(C('VAR_AUTO_STRING')){ // 默認強制轉換為字符串  
  20.         $type   =   's';  
  21.     }  
  22.  
  23.     /*根據(jù)$name的格式獲取數(shù)據(jù):先判斷參數(shù)的來源,然后再根據(jù)各種格式獲取數(shù)據(jù)*/ 
  24.     if(strpos($name,'.')) {list($method,$name) =   explode('.',$name,2);} // 指定參數(shù)來源  
  25.     else{$method =   'param';}//設定為自動獲取  
  26.     switch(strtolower($method)) {  
  27.         case 'get'     :   $input =& $_GET;break;  
  28.         case 'post'    :   $input =& $_POST;break;  
  29.         case 'put'     :   /*此處省略*/ 
  30.         case 'param'   :   /*此處省略*/ 
  31.         case 'path'    :   /*此處省略*/ 
  32.     }  
  33.  
  34.     /*對獲取的數(shù)據(jù)進行過濾*/ 
  35.     if('' // 獲取全部變量  
  36.         $data       =   $input;  
  37.         $filters    =   isset($filter)?$filter:C('DEFAULT_FILTER');  
  38.         if($filters) {  
  39.             if(is_string($filters)){$filters    =   explode(',',$filters);} //為多種過濾方法提供支持  
  40.             foreach($filters as $filter){  
  41.                 $data   =   array_map_recursive($filter,$data); //循環(huán)過濾  
  42.             }  
  43.         }  
  44.     }elseif(isset($input[$name])) { // 取值操作  
  45.         $data       =   $input[$name];  
  46.         $filters    =   isset($filter)?$filter:C('DEFAULT_FILTER');  
  47.         if($filters) {      /*對參數(shù)進行過濾,支持正則表達式驗證*/ 
  48.             /*此處省略*/ 
  49.         }  
  50.         if(!emptyempty($type)){  //如果設定了強制轉換類型  
  51.             switch(strtolower($type)){  
  52.                 case 'a': $data = (array)$data;break;   // 數(shù)組    
  53.                 case 'd': $data = (int)$data;break;   // 數(shù)字   
  54.                 case 'f': $data = (float)$data;break;    // 浮點     
  55.                 case 'b': $data = (boolean)$data;break;    // 布爾  
  56.                 case 's':   // 字符串  
  57.                 default:$data   =   (string)$data;  
  58.             }  
  59.         }  
  60.     }else{ // 變量默認值  
  61.         $data       =    isset($default)?$default:null;  
  62.     }  
  63.  
  64.     is_array($data) && array_walk_recursive($data,'think_filter');  //如果$data是數(shù)組,那么用think_filter對數(shù)組過濾  
  65.     return $data;  

恩,函數(shù)基本分成三塊:第一塊,獲取各種格式的數(shù)據(jù)。第二塊,對獲取的數(shù)據(jù)進行循環(huán)編碼,不管是二維數(shù)組還是三維數(shù)組。第三塊,也就是倒數(shù)第二行,調(diào)用了think_filter對數(shù)據(jù)進行了最后一步的神秘處理。

讓我們先來追蹤一下think_filter函數(shù):

 
 
 
 
  1. //1536行 版本3.2.3最新添加  
  2. function think_filter(&$value){// 過濾查詢特殊字符      
  3.     if(preg_match('/^(EXP|NEQ|GT|EGT|LT|ELT|OR|XOR|LIKE|NOTLIKE|NOT BETWEEN|NOTBETWEEN|BETWEEN|NOTIN|NOT IN|IN)$/i',$value)){          
  4.         $value .= ' ';      
  5.     }  

這個函數(shù)很簡單,一眼就可以看出來,在一些特定的關鍵字后面加個空格。但是這個叫think_filter的函數(shù),僅僅加了一個空格,到底起到了什么過濾的作用?

我們都知道重要的邏輯驗證,如驗證是否已登錄,用戶是否能購買某商品等,必須從服務器端驗證,如果從前端驗證的話,就很容易被繞過。同一個道理,在程序中,in/exp一類的邏輯結構,最好也是由服務器端來控制。

當從傳遞到服務器端的數(shù)據(jù)是這樣:id[0]=in&id[1]=1,2,3,如果沒有think_filter函數(shù)的話,會被解析成下表中的1,也就會被當成服務器端邏輯解析。但如果變成如下表2的樣子,因為多了一個空格,無法被匹配解析,也就避免了漏洞。

 
 
 
 
  1. 1. $data['id']=array('in'=>'1,2,3')    
  2.  
  3. //經(jīng)過think_filter過濾之后,會變成介個樣子:  
  4. 2. $data['id']=array('in '=>'1,2,3') 

#p#

二、SQL注入

相關的文件為:/ThinkPHP/Library/Think/Db.class.php(在3.2.3中改為了/ThinkPHP/Library/Think/Db/Driver.class.php) 以及 /ThinkPHP/Library/Think/Model.class.php。其中Model.class.php文件提供的是curd直接調(diào)用的函數(shù),直接對外提供接口,Driver.class.php中的函數(shù)被curd操作間接調(diào)用。

 
 
 
 
  1. //此次主要分析如下語句:  
  2. M('user')->where($map)->find();    //在user表根據(jù)$map的條件檢索出一條數(shù)據(jù) 

 

大概說一下TP的處理思路。首先將Model類實例化為一個user對象,然后調(diào)用user對象中的where函數(shù)處理$map,也就是將$map進行一些格式化處理之后賦值給user對象的成員變量$options(如果有其他的連貫操作,也是先賦值給user對象的對應成員變量,而不是直接拼接SQL語句,所以在寫連貫操作的時候,無需像拼接SQL語句一樣考慮關鍵字的順序),接下來調(diào)用find函數(shù)。find函數(shù)會調(diào)用底層的,也就是driver類中的函數(shù)——select來獲取數(shù)據(jù)。到了select函數(shù),又是另一個故事了。

select除了要處理curd操作,還要處理pdo綁定,我們這里只關心curd操作,所以在select中調(diào)用了buildSelectSql,處理分頁信息,并且調(diào)用parseSQL按照既定的順序把SQL語句組裝進去。雖然拼接SQL語句所需要的參數(shù)已經(jīng)全部放在成員變量里了,但是格式不統(tǒng)一,有可能是字符串格式的,有可能是數(shù)組格式的,還有可能是TP提供的特殊查詢格式,比如:$data['id']=array('gt','100');,所以在拼接之前,還要調(diào)用各自的處理函數(shù),進行統(tǒng)一的格式化處理。我選取了parseWhere這個復雜的典型來分析。

關于安全方面的,如果用I函數(shù)來獲取數(shù)據(jù),那么會默認進行htmlspecialchars處理,能有效抵御xss攻擊,但是對SQL注入沒有多大影響。在過濾有關SQL注入有關的符號的時候,TP的做法很機智:先是按正常邏輯處理用戶的輸入,然后在最接近最終的SQL語句的parseWhere、parseHaving等函數(shù)中進行安全處理。這樣的順序避免了在處理的過程中出現(xiàn)注入。當然處理的方法是最普通的addslashes,根據(jù)死在沙灘上的前浪們說,推薦使用mysql_real_escape_string來進行過濾,但是這個函數(shù)只能在已經(jīng)連接了數(shù)據(jù)庫的前提下使用。感覺TP在這個地方可以做一下優(yōu)化,畢竟走到這一步的都是連接了數(shù)據(jù)庫的。

恩,接下來,分析開始:

先說幾個Model對象中的成員變量:

 
 
 
 
  1. // 主鍵名稱  
  2. protected $pk      = 'id';  
  3. // 字段信息  
  4. protected $fields  = array();  
  5. // 數(shù)據(jù)信息  
  6. protected $data    = array();  
  7. // 查詢表達式參數(shù)  
  8. protected $options = array();  
  9. // 鏈操作方法列表  
  10. protected $methods = array('strict','order','alias','having','group','lock','distinct','auto','filter','validate','result','token','index','force') 

接下來分析where函數(shù):

 
 
 
 
  1. public function where($where,$parse=null){  
  2.     //如果非數(shù)組格式,即where('id=%d&name=%s',array($id,$name)),對傳遞到字符串中的數(shù)組調(diào)用mysql里的escapeString進行處理  
  3.     if(!is_null($parse) && is_string($where)) {   
  4.         if(!is_array($parse)){  $parse = func_get_args();array_shift($parse);}  
  5.         $parse = array_map(array($this->db,'escapeString'),$parse);  
  6.         $where = vsprintf($where,$parse); //vsprintf() 函數(shù)把格式化字符串寫入變量中  
  7.     }elseif(is_object($where)){  
  8.         $where  =   get_object_vars($where);  
  9.     }  
  10.     if(is_string($where) && '' != $where){  
  11.         $map    =   array();  
  12.         $map['_string']   =   $where;  
  13.         $where  =   $map;  
  14.     }        
  15.  
  16.     //將$where賦值給$this->where  
  17.     if(isset($this->options['where'])){           
  18.         $this->options['where'] =   array_merge($this->options['where'],$where);  
  19.     }else{  
  20.         $this->options['where'] =   $where;  
  21.     }  
  22.       
  23.     return $this;  

where函數(shù)的邏輯很簡單,如果是where('id=%d&name=%s',array($id,$name))這種格式,那就對$id,$name變量調(diào)用mysql里的escapeString進行處理。escapeString的實質(zhì)是調(diào)用mysql_real_escape_string、addslashes等函數(shù)進行處理。最后將分析之后的數(shù)組賦值到Model對象的成員函數(shù)——$where中供下一步處理。

再分析find函數(shù):

 
 
 
 
  1. //model.class.php    行721    版本3.2.3  
  2. public function find($options=array()) {  
  3.     if(is_numeric($options) || is_string($options)){ /*如果傳遞過來的數(shù)據(jù)是字符串,不是數(shù)組*/ 
  4.         $where[$this->getPk()]  =   $options;  
  5.         $options                =   array();  
  6.         $options['where']       =   $where; /*提取出查詢條件,并賦值*/ 
  7.     }  
  8.  
  9.     // 根據(jù)主鍵查找記錄  
  10.     $pk  =  $this->getPk();  
  11.     if (is_array($options) && (count($options) > 0) && is_array($pk)) {  
  12.         /*構造復合主鍵查詢條件,此處省略*/ 
  13.     }  
  14.  
  15.     $options['limit']   =   1;                                  // 總是查找一條記錄  
  16.     $options            =   $this->_parseOptions($options);     // 分析表達式  
  17.  
  18.     if(isset($options['cache'])){  
  19.         /*緩存查詢,此處省略*/ 
  20.     }  
  21.     $resultSet = $this->db->select($options);  
  22.  
  23.     if(false === $resultSet){   return false;}  
  24.     if(emptyempty($resultSet)) {    return null; }           // 查詢結果為空         
  25.     if(is_string($resultSet)){   return $resultSet;}    //查詢結果為字符串  
  26.  
  27.     // 讀取數(shù)據(jù)后的處理,此處省略簡寫  
  28.     $this->data = $this->_read_data($resultSet[0]);  
  29.     return $this->data;  

$Pk為主鍵,$options為表達式參數(shù),本函數(shù)的作用就是完善成員變量——options數(shù)組,然后調(diào)用db層的select函數(shù)查詢數(shù)據(jù),處理后返回數(shù)據(jù)。

跟進_parseOptions函數(shù):

 
 
 
 
  1. protected function _parseOptions($options=array()) { //分析表達式  
  2.     if(is_array($options)){  
  3.         $options =  array_merge($this->options,$options);  
  4.     }  
  5.  
  6.     /*獲取表名,此處省略*/ 
  7.     /*添加數(shù)據(jù)表別名,此處省略*/ 
  8.  
  9.     $options['model']       =   $this->name;// 記錄操作的模型名稱  
  10.  
  11.     /*對數(shù)組查詢條件進行字段類型檢查,如果在合理范圍內(nèi),就進行過濾處理;否則拋出異?;蛘邉h除掉對應字段*/ 
  12.     if(isset($options['where']) && is_array($options['where']) && !emptyempty($fields) && !isset($options['join'])){  
  13.         foreach ($options['where'] as $key=>$val){  
  14.             $key = trim($key);  
  15.             if(in_array($key,$fields,true)){    //如果$key在數(shù)據(jù)庫字段內(nèi),過濾以及強制類型轉換之  
  16.                 if(is_scalar($val)) {    
  17.                 /*is_scalar 檢測是否為標量。標量是指integer、float、string、boolean的變量,array則不是標量。*/           
  18.                     $this->_parseType($options['where'],$key);  
  19.                 }  
  20.             }elseif(!is_numeric($key) && '_' != substr($key,0,1) && false === strpos($key,'.') && false === strpos($key,'(') && false === strpos($key,'|') && false === strpos($key,'&')){  
  21.                // 如果$key不是數(shù)字且第一個字符不是_,不存在.(|&等特殊字符  
  22.                 if(!emptyempty($this->options['strict'])){   //如果是strict模式,拋出異常  
  23.                     E(L('_ERROR_QUERY_EXPRESS_').':['.$key.'=>'.$val.']');  
  24.                 }     
  25.                 unset($options['where'][$key]); //unset掉對應的值  
  26.             }  
  27.         }  
  28.     }   
  29.     $this->options  =   array();            // 查詢過后清空sql表達式組裝 避免影響下次查詢  
  30.     $this->_options_filter($options);       // 表達式過濾  
  31.     return $options;  

本函數(shù)的結構大概是,先獲取了表名,模型名,再對數(shù)據(jù)進行處理:如果該條數(shù)據(jù)不在數(shù)據(jù)庫字段內(nèi),則做出異常處理或者刪除掉該條數(shù)據(jù)。否則,進行_parseType處理。parseType此處不再跟進,功能為:數(shù)據(jù)類型檢測,強制類型轉換包括int,float,bool型的三種數(shù)據(jù)。

函數(shù)運行到此處,就該把處理好的數(shù)據(jù)傳到db層的select函數(shù)里了。此時的查詢條件$options中的int,float,bool類型的數(shù)據(jù)都已經(jīng)進行了強制類型轉換,where()函數(shù)中的字符串(非數(shù)組格式的查詢)也進行了addslashes等處理。

繼續(xù)追蹤到select函數(shù),就到了driver對象中了,還是先列舉幾個有用的成員變量:

 
 
 
 
  1. // 數(shù)據(jù)庫表達式  
  2. protected $exp = array('eq'=>'=','neq'=>'<>','gt'=>'>','egt'=>'>=','lt'=>'<','elt'=>'<=','notlike'=>'NOT LIKE','like'=>'LIKE','in'=>'IN','notin'=>'NOT IN','not in'=>'NOT IN','between'=>'BETWEEN','not between'=>'NOT BETWEEN','notbetween'=>'NOT BETWEEN');  
  3. // 查詢表達式  
  4. protected $selectSql  = 'SELECT%DISTINCT% %FIELD% FROM %TABLE%%FORCE%%JOIN%%WHERE%%GROUP%%HAVING%%ORDER%%LIMIT% %UNION%%LOCK%%COMMENT%';  
  5. // 當前SQL指令  
  6. protected $queryStr   = '';  
  7. // 參數(shù)綁定  
  8. protected $bind         =   array(); 

select函數(shù):

 
 
 
 
  1. public function select($options=array()) {  
  2.     $this->model  =   $options['model'];  
  3.     $this->parseBind(!emptyempty($options['bind'])?$options['bind']:array());  
  4.     $sql    = $this->buildSelectSql($options);  
  5.     $result   = $this->query($sql,!emptyempty($options['fetch_sql']) ? true : false);  
  6.     return $result;  

版本3.2.3經(jīng)過改進之后,select精簡了不少。parseBind函數(shù)是綁定參數(shù),用于pdo查詢,此處不表。

buildSelectSql()函數(shù)及其后續(xù)調(diào)用如下:

 
 
 
 
  1. public function buildSelectSql($options=array()) {  
  2.     if(isset($options['page'])) {  
  3.         /*頁碼計算及處理,此處省略*/ 
  4.     }  
  5.     $sql  =   $this->parseSql($this->selectSql,$options);  
  6.     return $sql;  
  7. }  
  8.  
  9. /* 替換SQL語句中表達式*/ 
  10. public function parseSql($sql,$options=array()){  
  11.     $sql   = str_replace(  
  12.         array('%TABLE%','%DISTINCT%','%FIELD%','%JOIN%','%WHERE%','%GROUP%','%HAVING%','%ORDER%','%LIMIT%','%UNION%','%LOCK%','%COMMENT%','%FORCE%'),  
  13.         array(  
  14.             $this->parseTable($options['table']),  
  15.             $this->parseDistinct(isset($options['distinct'])?$options['distinct']:false),  
  16.             $this->parseField(!emptyempty($options['field'])?$options['field']:'*'),  
  17.             $this->parseJoin(!emptyempty($options['join'])?$options['join']:''),  
  18.             $this->parseWhere(!emptyempty($options['where'])?$options['where']:''),  
  19.             $this->parseGroup(!emptyempty($options['group'])?$options['group']:''),  
  20.             $this->parseHaving(!emptyempty($options['having'])?$options['having']:''),  
  21.             $this->parseOrder(!emptyempty($options['order'])?$options['order']:''),  
  22.             $this->parseLimit(!emptyempty($options['limit'])?$options['limit']:''),  
  23.             $this->parseUnion(!emptyempty($options['union'])?$options['union']:''),  
  24.             $this->parseLock(isset($options['lock'])?$options['lock']:false),  
  25.             $this->parseComment(!emptyempty($options['comment'])?$options['comment']:''),  
  26.             $this->parseForce(!emptyempty($options['force'])?$options['force']:'')  
  27.         ),$sql);  
  28.     return $sql;  

可以看到,在parseSql中用正則表達式拼接了sql語句,但并沒有直接的去處理各種插敘你的數(shù)據(jù)格式,而是在解析變量的過程中調(diào)用了多個函數(shù),此處拿parseWhere舉例子。

 
 
 
 
  1. protected function parseWhere($where) {  
  2.     $whereStr = '';  
  3.     if(is_string($where)) {     // 直接使用字符串條件  
  4.         $whereStr = $where;  
  5.     }  
  6.     else{                       // 使用數(shù)組表達式  
  7.         /*設定邏輯規(guī)則,如or and xor等,默認為and,此處省略*/ 
  8.         $operate=' AND ';  
  9.  
  10.         /*解析特殊格式的表達式并且格式化輸出*/ 
  11.         foreach ($where as $key=>$val){  
  12.             if(0===strpos($key,'_')) {    // 解析特殊條件表達式  
  13.                 $whereStr   .= $this->parseThinkWhere($key,$val);  
  14.             }  
  15.             else{                        // 查詢字段的安全過濾  
  16.                 $multi  = is_array($val) &&  isset($val['_multi']); //判斷是否有復合查詢  
  17.                 $key    = trim($key);  
  18.                 /*處理字段中包含的| &邏輯*/ 
  19.                 if(strpos($key,'|')) { // 支持 name|title|nickname 方式定義查詢字段  
  20.                     /*將|換成or,并格式化輸出,此處省略*/ 
  21.                 }  
  22.                 elseif(strpos($key,'&')){  
  23.                     /*將&換成and,并格式化輸出,此處省略*/ 
  24.                 }  
  25.                 else{  
  26.                     $whereStr .= $this->parseWhereItem($this->parseKey($key),$val);  
  27.                 }  
  28.             }  
  29.             $whereStr .= $operate;  
  30.         }  
  31.         $whereStr = substr($whereStr,0,-strlen($operate));  
  32.     }  
  33.  
  34.     return emptyempty($whereStr)?'':' WHERE '.$whereStr;  
  35. }  
  36.  
  37. // where子單元分析  
  38. protected function parseWhereItem($key,$val) {  
  39.     $whereStr = '';  
  40.     if(is_array($val)){  
  41.         if(is_string($val[0])){  
  42.             $exp    =   strtolower($val[0]);  
  43.             //如果是$map['id']=array('eq',100)一類的結構,那么解析成數(shù)據(jù)庫可執(zhí)行格式  
  44.             if(preg_match('/^(eq|neq|gt|egt|lt|elt)$/',$exp)){  
  45.                 $whereStr .= $key.' '.$this->exp[$exp].' '.$this->parseValue($val[1]);  
  46.             }  
  47.             //如果是模糊查找格式  
  48.             elseif(preg_match('/^(notlike|like)$/',$exp)){// 模糊查找,$map['name']=array('like','thinkphp%');  
  49.                 if(is_array($val[1])) { //解析格式如下:$map['b'] =array('notlike',array('%thinkphp%','%tp'),'AND');  
  50.                     $likeLogic  =   isset($val[2])?strtoupper($val[2]):'OR';    //如果沒有設定邏輯結構,則默認為OR  
  51.                     if(in_array($likeLogic,array('AND','OR','XOR'))){  
  52.                         /* 根據(jù)邏輯結構,組合語句,此處省略*/ 
  53.                         $whereStr .= '('.implode(' '.$likeLogic.' ',$like).')';                            
  54.                     }  
  55.                 }  
  56.                 else{  
  57.                     $whereStr .= $key.' '.$this->exp[$exp].' '.$this->parseValue($val[1]);  
  58.                 }  
  59.             }elseif('bind' == $exp ){ // 使用表達式,pdo數(shù)據(jù)綁定  
  60.                 $whereStr .= $key.' = :'.$val[1];  
  61.             }elseif('exp' == $exp ){ // 使用表達式 
    本文題目:ThinkPHP框架安全實現(xiàn)分析
    鏈接URL:http://www.5511xx.com/article/ccdjjpj.html