ThinkPHP框架是國內(nèi)比較流行的PHP框架之一,雖然跟國外的那些個框架沒法比,但優(yōu)點在于,恩,中文手冊很全面。最近研究SQL注入,之前用TP框架的時候因為底層提供了安全功能,在開發(fā)過程中沒怎么考慮安全問題。
一、不得不說的I函數(shù)
TP系統(tǒng)提供了I函數(shù)用于輸入變量的過濾。整個函數(shù)主體的意義就是獲取各種格式的數(shù)據(jù),比如I('get.')、I('post.id'),然后用htmlspecialchars函數(shù)(默認情況下)進行處理。
如果需要采用其他的方法進行安全過濾,可以從/ThinkPHP/Conf/convention.php中設(shè)置:
- 'DEFAULT_FILTER' => 'strip_tags',
- //也可以設(shè)置多種過濾方法
- 'DEFAULT_FILTER' => 'strip_tags,stripslashes',
從/ThinkPHP/Common/functions.php中可以找到I函數(shù),源碼如下:
- /**
- * 獲取輸入?yún)?shù) 支持過濾和默認值
- * 使用方法:
- *
* I('id',0); 獲取id參數(shù) 自動判斷get或者post
* I('post.name','','htmlspecialchars'); 獲取$_POST['name']
* I('get.'); 獲取$_GET
*
- * @param string $name 變量的名稱 支持指定類型
- * @param mixed $default 不存在的時候默認值
- * @param mixed $filter 參數(shù)過濾方法
- * @param mixed $datas 要獲取的額外數(shù)據(jù)源
- * @return mixed
- */
- function I($name,$default='',$filter=null,$datas=null) {
- static $_PUT = null;
- if(strpos($name,'/')){ // 指定修飾符
- list($name,$type) = explode('/',$name,2);
- }elseif(C('VAR_AUTO_STRING')){ // 默認強制轉(zhuǎn)換為字符串
- $type = 's';
- }
- /*根據(jù)$name的格式獲取數(shù)據(jù):先判斷參數(shù)的來源,然后再根據(jù)各種格式獲取數(shù)據(jù)*/
- if(strpos($name,'.')) {list($method,$name) = explode('.',$name,2);} // 指定參數(shù)來源
- else{$method = 'param';}//設(shè)定為自動獲取
- switch(strtolower($method)) {
- case 'get' : $input =& $_GET;break;
- case 'post' : $input =& $_POST;break;
- case 'put' : /*此處省略*/
- case 'param' : /*此處省略*/
- case 'path' : /*此處省略*/
- }
- /*對獲取的數(shù)據(jù)進行過濾*/
- if('' // 獲取全部變量
- $data = $input;
- $filters = isset($filter)?$filter:C('DEFAULT_FILTER');
- if($filters) {
- if(is_string($filters)){$filters = explode(',',$filters);} //為多種過濾方法提供支持
- foreach($filters as $filter){
- $data = array_map_recursive($filter,$data); //循環(huán)過濾
- }
- }
- }elseif(isset($input[$name])) { // 取值操作
- $data = $input[$name];
- $filters = isset($filter)?$filter:C('DEFAULT_FILTER');
- if($filters) { /*對參數(shù)進行過濾,支持正則表達式驗證*/
- /*此處省略*/
- }
- if(!emptyempty($type)){ //如果設(shè)定了強制轉(zhuǎn)換類型
- switch(strtolower($type)){
- case 'a': $data = (array)$data;break; // 數(shù)組
- case 'd': $data = (int)$data;break; // 數(shù)字
- case 'f': $data = (float)$data;break; // 浮點
- case 'b': $data = (boolean)$data;break; // 布爾
- case 's': // 字符串
- default:$data = (string)$data;
- }
- }
- }else{ // 變量默認值
- $data = isset($default)?$default:null;
- //Vevb.com
- }
- is_array($data) && array_walk_recursive($data,'think_filter'); //如果$data是數(shù)組,那么用think_filter對數(shù)組過濾
- return $data;
- }
恩,函數(shù)基本分成三塊:
第一塊,獲取各種格式的數(shù)據(jù)。
第二塊,對獲取的數(shù)據(jù)進行循環(huán)編碼,不管是二維數(shù)組還是三維數(shù)組。
第三塊,也就是倒數(shù)第二行,調(diào)用了think_filter對數(shù)據(jù)進行了最后一步的神秘處理。
讓我們先來追蹤一下think_filter函數(shù):
- //1536行 版本3.2.3最新添加
- function think_filter(&$value){// 過濾查詢特殊字符
- if(preg_match('/^(EXP|NEQ|GT|EGT|LT|ELT|OR|XOR|LIKE|NOTLIKE|NOT BETWEEN|NOTBETWEEN|BETWEEN|NOTIN|NOT IN|IN)$/i',$value)){
- $value .= ' ';
- }
- }
這個函數(shù)很簡單,一眼就可以看出來,在一些特定的關(guān)鍵字后面加個空格。
但是這個叫think_filter的函數(shù),僅僅加了一個空格,到底起到了什么過濾的作用?
我們都知道重要的邏輯驗證,如驗證是否已登錄,用戶是否能購買某商品等,必須從服務(wù)器端驗證,如果從前端驗證的話,就很容易被繞過。同一個道理,在程序中,in/exp一類的邏輯結(jié)構(gòu),最好也是由服務(wù)器端來控制。
當(dāng)從傳遞到服務(wù)器端的數(shù)據(jù)是這樣:id[0]=in&id[1]=1,2,3,如果沒有think_filter函數(shù)的話,會被解析成下表中的1,也就會被當(dāng)成服務(wù)器端邏輯解析。但如果變成如下表2的樣子,因為多了一個空格,無法被匹配解析,也就避免了漏洞。
- $data['id']=array('in'=>'1,2,3')
- //經(jīng)過think_filter過濾之后,會變成介個樣子:
- $data['id']=array('in '=>'1,2,3')
二、SQL注入
相關(guān)的文件為:/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)用。
此次主要分析如下語句:
M('user')->where($map)->find(); //在user表根據(jù)$map的條件檢索出一條數(shù)據(jù)
大概說一下TP的處理思路:
首先將Model類實例化為一個user對象,然后調(diào)用user對象中的where函數(shù)處理$map,也就是將$map進行一些格式化處理之后賦值給user對象的成員變量$options(如果有其他的連貫操作,也是先賦值給user對象的對應(yīng)成員變量,而不是直接拼接SQL語句,所以在寫連貫操作的時候,無需像拼接SQL語句一樣考慮關(guān)鍵字的順序),接下來調(diào)用find函數(shù)。
find函數(shù)會調(diào)用底層的,也就是driver類中的函數(shù)——select來獲取數(shù)據(jù)。到了select函數(shù),又是另一個故事了。
select除了要處理curd操作,還要處理pdo綁定,我們這里只關(guān)心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這個復(fù)雜的典型來分析。
關(guān)于安全方面的,如果用I函數(shù)來獲取數(shù)據(jù),那么會默認進行htmlspecialchars處理,能有效抵御xss攻擊,但是對SQL注入沒有多大影響。
在過濾有關(guān)SQL注入有關(guān)的符號的時候,TP的做法很機智:先是按正常邏輯處理用戶的輸入,然后在最接近最終的SQL語句的parseWhere、parseHaving等函數(shù)中進行安全處理。這樣的順序避免了在處理的過程中出現(xiàn)注入。
當(dāng)然處理的方法是最普通的addslashes,根據(jù)死在沙灘上的前浪們說,推薦使用mysql_real_escape_string來進行過濾,但是這個函數(shù)只能在已經(jīng)連接了數(shù)據(jù)庫的前提下使用。
感覺TP在這個地方可以做一下優(yōu)化,畢竟走到這一步的都是連接了數(shù)據(jù)庫的。
恩,接下來,分析開始:
先說幾個Model對象中的成員變量:
- // 主鍵名稱
- protected $pk = 'id';
- // 字段信息
- protected $fields = array();
- // 數(shù)據(jù)信息
- protected $data = array();
- // 查詢表達式參數(shù)
- protected $options = array();
- // 鏈操作方法列表
- protected $methods = array('strict','order','alias','having','group','lock','distinct','auto','filter','validate','result','token','index','force')
- 接下來分析where函數(shù):
- public function where($where,$parse=null){
- //如果非數(shù)組格式,即where('id=%d&name=%s',array($id,$name)),對傳遞到字符串中的數(shù)組調(diào)用mysql里的escapeString進行處理
- if(!is_null($parse) && is_string($where)) {
- if(!is_array($parse)){ $parse = func_get_args();array_shift($parse);}
- $parse = array_map(array($this->db,'escapeString'),$parse);
- $where = vsprintf($where,$parse); //vsprintf() 函數(shù)把格式化字符串寫入變量中
- }elseif(is_object($where)){
- $where = get_object_vars($where);
- }
- if(is_string($where) && '' != $where){
- $map = array();
- $map['_string'] = $where;
- $where = $map;
- }
- //將$where賦值給$this->where
- if(isset($this->options['where'])){
- $this->options['where'] = array_merge($this->options['where'],$where);
- }else{
- $this->options['where'] = $where;
- }
- //Vevb.com
- 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ù):
- //model.class.php 行721 版本3.2.3
- public function find($options=array()) {
- if(is_numeric($options) || is_string($options)){ /*如果傳遞過來的數(shù)據(jù)是字符串,不是數(shù)組*/
- $where[$this->getPk()] = $options;
- $options = array();
- $options['where'] = $where; /*提取出查詢條件,并賦值*/
- }
- // 根據(jù)主鍵查找記錄
- $pk = $this->getPk();
- if (is_array($options) && (count($options) > 0) && is_array($pk)) {
- /*構(gòu)造復(fù)合主鍵查詢條件,此處省略*/
- }
- $options['limit'] = 1; // 總是查找一條記錄
- $options = $this->_parseOptions($options); // 分析表達式
- if(isset($options['cache'])){
- /*緩存查詢,此處省略*/
- }
- $resultSet = $this->db->select($options);
- if(false === $resultSet){ return false;}
- if(emptyempty($resultSet)) { return null; } // 查詢結(jié)果為空
- if(is_string($resultSet)){ return $resultSet;} //查詢結(jié)果為字符串
- // 讀取數(shù)據(jù)后的處理,此處省略簡寫
- $this->data = $this->_read_data($resultSet[0]);
- return $this->data;
- }
$Pk為主鍵,$options為表達式參數(shù),本函數(shù)的作用就是完善成員變量——options數(shù)組,然后調(diào)用db層的select函數(shù)查詢數(shù)據(jù),處理后返回數(shù)據(jù)。
跟進_parseOptions函數(shù):
- protected function _parseOptions($options=array()) { //分析表達式
- if(is_array($options)){
- $options = array_merge($this->options,$options);
- }
- /*獲取表名,此處省略*/
- /*添加數(shù)據(jù)表別名,此處省略*/
- $options['model'] = $this->name;// 記錄操作的模型名稱
- /*對數(shù)組查詢條件進行字段類型檢查,如果在合理范圍內(nèi),就進行過濾處理;否則拋出異常或者刪除掉對應(yīng)字段*/
- if(isset($options['where']) && is_array($options['where']) && !emptyempty($fields) && !isset($options['join'])){
- foreach ($options['where'] as $key=>$val){
- $key = trim($key);
- if(in_array($key,$fields,true)){ //如果$key在數(shù)據(jù)庫字段內(nèi),過濾以及強制類型轉(zhuǎn)換之
- if(is_scalar($val)) {
- /*is_scalar 檢測是否為標(biāo)量。標(biāo)量是指integer、float、string、boolean的變量,array則不是標(biāo)量。*/
- $this->_parseType($options['where'],$key);
- }
- }elseif(!is_numeric($key) && '_' != substr($key,0,1) && false === strpos($key,'.') && false === strpos($key,'(') && false === strpos($key,'|') && false === strpos($key,'&')){
- // 如果$key不是數(shù)字且第一個字符不是_,不存在.(|&等特殊字符
- if(!emptyempty($this->options['strict'])){ //如果是strict模式,拋出異常
- E(L('_ERROR_QUERY_EXPRESS_').':['.$key.'=>'.$val.']');
- }
- unset($options['where'][$key]); //unset掉對應(yīng)的值
- }
- }
- }
- //Vevb.com
- $this->options = array(); // 查詢過后清空sql表達式組裝 避免影響下次查詢
- $this->_options_filter($options); // 表達式過濾
- return $options;
- }
本函數(shù)的結(jié)構(gòu)大概是,先獲取了表名,模型名,再對數(shù)據(jù)進行處理:如果該條數(shù)據(jù)不在數(shù)據(jù)庫字段內(nèi),則做出異常處理或者刪除掉該條數(shù)據(jù)。否則,進行_parseType處理。parseType此處不再跟進,功能為:數(shù)據(jù)類型檢測,強制類型轉(zhuǎn)換包括int,float,bool型的三種數(shù)據(jù)。
函數(shù)運行到此處,就該把處理好的數(shù)據(jù)傳到db層的select函數(shù)里了。此時的查詢條件$options中的int,float,bool類型的數(shù)據(jù)都已經(jīng)進行了強制類型轉(zhuǎn)換,where()函數(shù)中的字符串(非數(shù)組格式的查詢)也進行了addslashes等處理。
繼續(xù)追蹤到select函數(shù),就到了driver對象中了,還是先列舉幾個有用的成員變量:
- // 數(shù)據(jù)庫表達式
- 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');
- // 查詢表達式
- protected $selectSql = 'SELECT%DISTINCT% %FIELD% FROM %TABLE%%FORCE%%JOIN%%WHERE%%GROUP%%HAVING%%ORDER%%LIMIT% %UNION%%LOCK%%COMMENT%';
- // 當(dāng)前SQL指令
- protected $queryStr = '';
- // 參數(shù)綁定
- protected $bind = array();
- select函數(shù):
- public function select($options=array()) {
- $this->model = $options['model'];
- $this->parseBind(!emptyempty($options['bind'])?$options['bind']:array());
- $sql = $this->buildSelectSql($options);
- $result = $this->query($sql,!emptyempty($options['fetch_sql']) ? true : false);
- return $result;
- }
版本3.2.3經(jīng)過改進之后,select精簡了不少。parseBind函數(shù)是綁定參數(shù),用于pdo查詢,此處不表。
buildSelectSql()函數(shù)及其后續(xù)調(diào)用如下:
- public function buildSelectSql($options=array()) {
- if(isset($options['page'])) {
- /*頁碼計算及處理,此處省略*/
- }
- $sql = $this->parseSql($this->selectSql,$options);
- return $sql;
- }
- /* 替換SQL語句中表達式*/
- public function parseSql($sql,$options=array()){
- $sql = str_replace(
- array('%TABLE%','%DISTINCT%','%FIELD%','%JOIN%','%WHERE%','%GROUP%','%HAVING%','%ORDER%','%LIMIT%','%UNION%','%LOCK%','%COMMENT%','%FORCE%'),
- array(
- $this->parseTable($options['table']),
- $this->parseDistinct(isset($options['distinct'])?$options['distinct']:false),
- $this->parseField(!emptyempty($options['field'])?$options['field']:'*'),
- $this->parseJoin(!emptyempty($options['join'])?$options['join']:''),
- $this->parseWhere(!emptyempty($options['where'])?$options['where']:''),
- $this->parseGroup(!emptyempty($options['group'])?$options['group']:''),
- $this->parseHaving(!emptyempty($options['having'])?$options['having']:''),
- $this->parseOrder(!emptyempty($options['order'])?$options['order']:''),
- $this->parseLimit(!emptyempty($options['limit'])?$options['limit']:''),
- $this->parseUnion(!emptyempty($options['union'])?$options['union']:''),
- $this->parseLock(isset($options['lock'])?$options['lock']:false),
- $this->parseComment(!emptyempty($options['comment'])?$options['comment']:''),
- //Vevb.com
- $this->parseForce(!emptyempty($options['force'])?$options['force']:'')
- ),$sql);
- return $sql;
- }
可以看到,在parseSql中用正則表達式拼接了sql語句,但并沒有直接的去處理各種插敘你的數(shù)據(jù)格式,而是在解析變量的過程中調(diào)用了多個函數(shù),此處拿parseWhere舉例子。
- protected function parseWhere($where) {
- $whereStr = '';
- if(is_string($where)) { // 直接使用字符串條件
- $whereStr = $where;
- }
- else{ // 使用數(shù)組表達式
- /*設(shè)定邏輯規(guī)則,如or and xor等,默認為and,此處省略*/
- $operate=' AND ';
- /*解析特殊格式的表達式并且格式化輸出*/
- foreach ($where as $key=>$val){
- if(0===strpos($key,'_')) { // 解析特殊條件表達式
- $whereStr .= $this->parseThinkWhere($key,$val);
- }
- else{ // 查詢字段的安全過濾
- $multi = is_array($val) && isset($val['_multi']); //判斷是否有復(fù)合查詢
- $key = trim($key);
- /*處理字段中包含的| &邏輯*/
- if(strpos($key,'|')) { // 支持 name|title|nickname 方式定義查詢字段
- /*將|換成or,并格式化輸出,此處省略*/
- }
- elseif(strpos($key,'&')){
- /*將&換成and,并格式化輸出,此處省略*/
- }
- else{
- $whereStr .= $this->parseWhereItem($this->parseKey($key),$val);
- }
- }
- $whereStr .= $operate;
- }
- $whereStr = substr($whereStr,0,-strlen($operate));
- }
- return emptyempty($whereStr)?'':' WHERE '.$whereStr;
- }
- // where子單元分析
- protected function parseWhereItem($key,$val) {
- $whereStr = '';
- if(is_array($val)){
- if(is_string($val[0])){
- $exp = strtolower($val[0]);
- //如果是$map['id']=array('eq',100)一類的結(jié)構(gòu),那么解析成數(shù)據(jù)庫可執(zhí)行格式
- if(preg_match('/^(eq|neq|gt|egt|lt|elt)$/',$exp)){
- $whereStr .= $key.' '.$this->exp[$exp].' '.$this->parseValue($val[1]);
- }
- //如果是模糊查找格式
- elseif(preg_match('/^(notlike|like)$/',$exp)){// 模糊查找,$map['name']=array('like','thinkphp%');
- if(is_array($val[1])) { //解析格式如下:$map['b'] =array('notlike',array('%thinkphp%','%tp'),'AND');
- $likeLogic = isset($val[2])?strtoupper($val[2]):'OR'; //如果沒有設(shè)定邏輯結(jié)構(gòu),則默認為OR
- if(in_array($likeLogic,array('AND','OR','XOR'))){
- /* 根據(jù)邏輯結(jié)構(gòu),組合語句,此處省略*/
- $whereStr .= '('.implode(' '.$likeLogic.' ',$like).')';
- }
- }
- else{
- $whereStr .= $key.' '.$this->exp[$exp].' '.$this->parseValue($val[1]);
- }
- }elseif('bind' == $exp ){ // 使用表達式,pdo數(shù)據(jù)綁定
- $whereStr .= $key.' = :'.$val[1];
- }elseif('exp' == $exp ){ // 使用表達式 $map['id'] = array('exp',' IN (1,3,8) ');
- $whereStr .= $key.' '.$val[1];
- }elseif(preg_match('/^(notin|not in|in)$/',$exp)){ //IN運算 $map['id'] = array('not in','1,5,8');
- if(isset($val[2]) && 'exp'==$val[2]){
- $whereStr .= $key.' '.$this->exp[$exp].' '.$val[1];
- }else{
- if(is_string($val[1])) {
- $val[1] = explode(',',$val[1]);
- }
- $zone = implode(',',$this->parseValue($val[1]));
- $whereStr .= $key.' '.$this->exp[$exp].' ('.$zone.')';
- }
- }elseif(preg_match('/^(notbetween|not between|between)$/',$exp)){ //BETWEEN運算
- $data = is_string($val[1])? explode(',',$val[1]):$val[1];
- $whereStr .= $key.' '.$this->exp[$exp].' '.$this->parseValue($data[0]).' AND '.$this->parseValue($data[1]);
- }else{ //否則拋出異常
- E(L('_EXPRESS_ERROR_').':'.$val[0]);
- }
- }
- else{ //解析如:$map['status&score&title'] =array('1',array('gt','0'),'thinkphp','_multi'=>true);
- $count = count($val);
- $rule = isset($val[$count-1]) ? (is_array($val[$count-1]) ? strtoupper($val[$count-1][0]) : strtoupper($val[$count-1]) ) : '' ;
- if(in_array($rule,array('AND','OR','XOR'))){
- $count = $count -1;
- }else{
- $rule = 'AND';
- }
- for($i=0;$i<$count;$i++){
- $data = is_array($val[$i])?$val[$i][1]:$val[$i];
- if('exp'==strtolower($val[$i][0])) {
- $whereStr .= $key.' '.$data.' '.$rule.' ';
- }else{
- $whereStr .= $this->parseWhereItem($key,$val[$i]).' '.$rule.' ';
- }
- }
- $whereStr = '( '.substr($whereStr,0,-4).' )';
- }
- }
- else {
- //對字符串類型字段采用模糊匹配
- $likeFields = $this->config['db_like_fields'];
- if($likeFields && preg_match('/^('.$likeFields.')$/i',$key)) {
- $whereStr .= $key.' LIKE '.$this->parseValue('%'.$val.'%');
- }else {
- $whereStr .= $key.' = '.$this->parseValue($val);
- }
- }
- return $whereStr;
- }
- protected function parseThinkWhere($key,$val) { //解析特殊格式的條件
- $whereStr = '';
- switch($key) {
- case '_string':$whereStr = $val;break; // 字符串模式查詢條件
- case '_complex':$whereStr = substr($this->parseWhere($val),6);break; // 復(fù)合查詢條件
- case '_query':// 字符串模式查詢條件
- /*處理邏輯結(jié)構(gòu),并且格式化輸出字符串,此處省略*/
- }
- return '( '.$whereStr.' )';
- }
上面的兩個函數(shù)很長,我們再精簡一些來看:parseWhere首先判斷查詢數(shù)據(jù)是不是字符串,如果是字符串,直接返回字符串,否則,遍歷查詢條件的數(shù)組,挨個解析。
由于TP支持_string,_complex之類的特殊查詢,調(diào)用了parseThinkWhere來處理,對于普通查詢,就調(diào)用了parseWhereItem。
在各自的處理過程中,都調(diào)用了parseValue,追蹤一下,其實是用了addslashes來過濾,雖然addslashes在非utf-8編碼的頁面中會造成寬字節(jié)注入,但是如果頁面和數(shù)據(jù)庫均正確編碼的話,還是沒什么問題的。
新聞熱點
疑難解答
圖片精選