Provides various official and user-released code examples. For code reference, you are welcome to learn ThinkPHP 3.1.3 and earlier versions. The SQL injection vulnerability exists in ThinkPHP/Lib/Core/Model. class. php files
Explanation of the "SQL Injection prevention" approach (see http://doc.thinkphp1.cn/manual/ SQL _injection.html) according to the official documentation)
The use of query condition preprocessing can prevent SQL injection. That's right, it can be effective when the following code is used:
$Model->where("id=%d and username='%s' and xx='%f'",array($id,$username,$xx))->select();Or
$Model->where("id=%d and username='%s' and xx='%f'",$id,$username,$xx)->select();However, when you use the following code, it does not have the effect of "preventing SQL injection" (but the official document says it can prevent SQL injection ):
$model->query('select * from user where id=%d and status=%s',$id,$status);Or
$model->query('select * from user where id=%d and status=%s',array($id,$status));Cause:
The parseSql function in the ThinkPHP/Lib/Core/Model. class. php file does not implement SQL filtering.
Original function:
Protected function parseSql ($ SQL, $ parse ){
// Analysis expression
If (true ===$ parse ){
$ Options = $ this-> _ parseOptions ();
$ SQL = $ this-> db-> parseSql ($ SQL, $ options );
} Elseif (is_array ($ parse) {// SQL preprocessing
$ SQL = vsprintf ($ SQL, $ parse );
} Else {
$ SQL = strtr ($ SQL, array ('_ TABLE _' => $ this-> getTableName (), '_ PREFIX _' => C ('db _ prefix ')));
}
$ This-> db-> setModel ($ this-> name );
Return $ SQL;
}Vulnerability verification (example ):
Request address:
Http: // localhost/Main? Id = boo "or 1 =" 1
Or
Http: // localhost/Main? Id = boo % 22% 20or % 201 = % 221
Action Code:
$model=M('Peipeidui');
$m=$model->query('select * from peipeidui where name="%s"',$_GET['id']);
dump($m);exit;Or
$model=M('Peipeidui');
$m=$model->query('select * from peipeidui where name="%s"',array($_GET['id']));
dump($m);exit;Result:
All data in the peipeidui table is listed, and the SQL Injection statement takes effect.
Solution:
Modify the parseSql function:
Protected function parseSql ($ SQL, $ parse ){
// Analysis expression
If (true ===$ parse ){
$ Options = $ this-> _ parseOptions ();
$ SQL = $ this-> db-> parseSql ($ SQL, $ options );
} Elseif (is_array ($ parse) {// SQL preprocessing
$ Parse = array_map (array ($ this-> db, 'escapestring'), $ parse); // Add code for this behavior
$ SQL = vsprintf ($ SQL, $ parse );
} Else {
$ SQL = strtr ($ SQL, array ('_ TABLE _' => $ this-> getTableName (), '_ PREFIX _' => C ('db _ prefix ')));
}
$ This-> db-> setModel ($ this-> name );
Return $ SQL;
}Summary:
Do not rely too much on the underlying SQL filter of TP, and check the security of programmers.
We do not recommend using $ _ GET, $ _ POST directly.
AD: truly free, domain name + VM + enterprise mailbox = 0 RMB