SlideShare a Scribd company logo
4
Most read
10
Most read
16
Most read
SQL Injection Defense in Python

           Edgar Román
         emroman@pbs.org
          October 4, 2011
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
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))
• 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;
--‟
Security is about multiple layers
Multiple Layers

• Assume the worst and plan for it
• Coding protection is only one layer
  – Which we will focus on for this presentation
• Database lockdown
  – User partitioning
  – Password protection
• But there are other attacks too: Open Web
  Application Security Project (OWASP)
  – https://www.owasp.org/
General approaches to SQL Injection
                 Defense
•   Escape User Input
•   White Lists
•   Stored Procs
•   Parameterized Queries
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
Django ORM

• Automatically escapes all input parameters
• Be aware of extra() method – this is raw!
• More info
  – http://www.djangobook.com/en/2.0/chapter20/
Conclusions
• Use a db framework
• If possible, white list your inputs
• Be careful if writing raw SQL




                 http://xkcd.com/327/

More Related Content

PPT
Sql injection
Nitish Kumar
 
PDF
Sql Injection Myths and Fallacies
Karwin Software Solutions LLC
 
PPTX
seminar report on Sql injection
Jawhar Ali
 
PPTX
Web application security
Kapil Sharma
 
PPTX
Sql injections - with example
Prateek Chauhan
 
PDF
How to identify and prevent SQL injection
Eguardian Global Services
 
PDF
Sql Injection - Vulnerability and Security
Sandip Chaudhari
 
PPT
Advanced Sql Injection ENG
Dmitry Evteev
 
Sql injection
Nitish Kumar
 
Sql Injection Myths and Fallacies
Karwin Software Solutions LLC
 
seminar report on Sql injection
Jawhar Ali
 
Web application security
Kapil Sharma
 
Sql injections - with example
Prateek Chauhan
 
How to identify and prevent SQL injection
Eguardian Global Services
 
Sql Injection - Vulnerability and Security
Sandip Chaudhari
 
Advanced Sql Injection ENG
Dmitry Evteev
 

What's hot (20)

PPTX
Directory Traversal & File Inclusion Attacks
Raghav Bisht
 
PPTX
SQL injection prevention techniques
SongchaiDuangpan
 
PPT
Sql injection
Nikunj Dhameliya
 
PPTX
XSS Attacks Exploiting XSS Filter by Masato Kinugawa - CODE BLUE 2015
CODE BLUE
 
PDF
MongoDB Aggregation Framework
Caserta
 
PPTX
Ppt on sql injection
ashish20012
 
PPTX
Sqlmap
Rushikesh Kulkarni
 
PPTX
PowerShell for Penetration Testers
Nikhil Mittal
 
PDF
Offzone | Another waf bypass
Дмитрий Бумов
 
PPTX
Sql injection
Zidh
 
PDF
Secure Coding - Web Application Security Vulnerabilities and Best Practices
Websecurify
 
PPT
A Brief Introduction in SQL Injection
Sina Manavi
 
PPTX
SQL Functions
ammarbrohi
 
PDF
Sql injection with sqlmap
Herman Duarte
 
PPTX
Sql Injection attacks and prevention
helloanand
 
PDF
How to Shot Web - Jason Haddix at DEFCON 23 - See it Live: Details in Descrip...
bugcrowd
 
PDF
Introduction to Object-Oriented Programming & Design Principles (TCF 2014)
Michael Redlich
 
PDF
Exception handling in plsql
Arun Sial
 
PPT
Sql injection
Pallavi Biswas
 
Directory Traversal & File Inclusion Attacks
Raghav Bisht
 
SQL injection prevention techniques
SongchaiDuangpan
 
Sql injection
Nikunj Dhameliya
 
XSS Attacks Exploiting XSS Filter by Masato Kinugawa - CODE BLUE 2015
CODE BLUE
 
MongoDB Aggregation Framework
Caserta
 
Ppt on sql injection
ashish20012
 
PowerShell for Penetration Testers
Nikhil Mittal
 
Offzone | Another waf bypass
Дмитрий Бумов
 
Sql injection
Zidh
 
Secure Coding - Web Application Security Vulnerabilities and Best Practices
Websecurify
 
A Brief Introduction in SQL Injection
Sina Manavi
 
SQL Functions
ammarbrohi
 
Sql injection with sqlmap
Herman Duarte
 
Sql Injection attacks and prevention
helloanand
 
How to Shot Web - Jason Haddix at DEFCON 23 - See it Live: Details in Descrip...
bugcrowd
 
Introduction to Object-Oriented Programming & Design Principles (TCF 2014)
Michael Redlich
 
Exception handling in plsql
Arun Sial
 
Sql injection
Pallavi Biswas
 
Ad

Viewers also liked (20)

PPTX
SQL Injections - A Powerpoint Presentation
Rapid Purple
 
DOCX
Types of sql injection attacks
Respa Peter
 
PPTX
Social skills for those with autism
abagirl
 
PDF
Michael Bayer Introduction to SQLAlchemy @ Postgres Open
PostgresOpen
 
PDF
Sqlmap Analiz
B3mB4m Turk
 
PPTX
SQL Enjeksiyona karşi savunma
Nursultan Turdaliev
 
PPTX
Sql injection attack_analysis_py_vo
Jirka Vejrazka
 
PPT
Sql injection attacks
Nitish Kumar
 
PPTX
Protecting your data from SQL Injection attacks
Kevin Alcock
 
PPT
Sql Injection Attacks And Defense Presentatio (1)
guest32e5cfe
 
PDF
[Seoul cartoon] policy sharing makes cities around the world happier
simrc
 
PPTX
Tema liderazgo
Keliayadira
 
PDF
Olap scalability
lucboudreau
 
PPTX
Corporate gifts suppliers in gurgaon
vinay kumar
 
PPT
Frederic Arrouays, CFO Emerging Markets at SAP - The Finance transformation a...
Global Business Events
 
PPTX
2015 SaaS Industry Survey Results for Marketers
Matthew Howard
 
PPT
Digital marketing CK sinh vien kent international college
trung_1881
 
PDF
Follow me on Twitter
Paola Furlanetto
 
PPTX
Airfreight Trends: Still Sluggish, with Cargo Growth in Some Sectors
Craig Raucher New York
 
PDF
ヘルパー移送dm
frumpy
 
SQL Injections - A Powerpoint Presentation
Rapid Purple
 
Types of sql injection attacks
Respa Peter
 
Social skills for those with autism
abagirl
 
Michael Bayer Introduction to SQLAlchemy @ Postgres Open
PostgresOpen
 
Sqlmap Analiz
B3mB4m Turk
 
SQL Enjeksiyona karşi savunma
Nursultan Turdaliev
 
Sql injection attack_analysis_py_vo
Jirka Vejrazka
 
Sql injection attacks
Nitish Kumar
 
Protecting your data from SQL Injection attacks
Kevin Alcock
 
Sql Injection Attacks And Defense Presentatio (1)
guest32e5cfe
 
[Seoul cartoon] policy sharing makes cities around the world happier
simrc
 
Tema liderazgo
Keliayadira
 
Olap scalability
lucboudreau
 
Corporate gifts suppliers in gurgaon
vinay kumar
 
Frederic Arrouays, CFO Emerging Markets at SAP - The Finance transformation a...
Global Business Events
 
2015 SaaS Industry Survey Results for Marketers
Matthew Howard
 
Digital marketing CK sinh vien kent international college
trung_1881
 
Follow me on Twitter
Paola Furlanetto
 
Airfreight Trends: Still Sluggish, with Cargo Growth in Some Sectors
Craig Raucher New York
 
ヘルパー移送dm
frumpy
 
Ad

Similar to SQL Injection Defense in Python (20)

PDF
A Brief Introduction About Sql Injection in PHP and MYSQL
kobaitari
 
PPTX
Hack through Injections
Nazar Tymoshyk, CEH, Ph.D.
 
PPSX
Web application security
www.netgains.org
 
PPT
Sql Injection Adv Owasp
Aung Khant
 
PPT
Advanced SQL Injection
amiable_indian
 
PPTX
Database connectivity in python
baabtra.com - No. 1 supplier of quality freshers
 
PPT
PHP - Introduction to Advanced SQL
Vibrant Technologies & Computers
 
PPTX
Sql injection
Hemendra Kumar
 
PDF
Chapter 14 sql injection
newbie2019
 
PPTX
MySql Interface database in sql python my.pptx
UshimArora
 
PPT
Sql injection attack
RajKumar Rampelli
 
PPT
SQLSecurity.ppt
LokeshK66
 
PPT
SQLSecurity.ppt
CNSHacking
 
PPTX
Sql injection
Mehul Boghra
 
PDF
SQL Injection 101 : It is not just about ' or '1'='1 - Pichaya Morimoto
Pichaya Morimoto
 
PPT
Sql injection attacks
Kumar
 
PPTX
python db connection samples and program
usha raj
 
PDF
CNIT 129S Ch 9: Attacking Data Stores (Part 2 of 2)
Sam Bowne
 
PDF
CNIT 129S: 9: Attacking Data Stores (Part 2 of 2)
Sam Bowne
 
A Brief Introduction About Sql Injection in PHP and MYSQL
kobaitari
 
Hack through Injections
Nazar Tymoshyk, CEH, Ph.D.
 
Web application security
www.netgains.org
 
Sql Injection Adv Owasp
Aung Khant
 
Advanced SQL Injection
amiable_indian
 
Database connectivity in python
baabtra.com - No. 1 supplier of quality freshers
 
PHP - Introduction to Advanced SQL
Vibrant Technologies & Computers
 
Sql injection
Hemendra Kumar
 
Chapter 14 sql injection
newbie2019
 
MySql Interface database in sql python my.pptx
UshimArora
 
Sql injection attack
RajKumar Rampelli
 
SQLSecurity.ppt
LokeshK66
 
SQLSecurity.ppt
CNSHacking
 
Sql injection
Mehul Boghra
 
SQL Injection 101 : It is not just about ' or '1'='1 - Pichaya Morimoto
Pichaya Morimoto
 
Sql injection attacks
Kumar
 
python db connection samples and program
usha raj
 
CNIT 129S Ch 9: Attacking Data Stores (Part 2 of 2)
Sam Bowne
 
CNIT 129S: 9: Attacking Data Stores (Part 2 of 2)
Sam Bowne
 

More from Public Broadcasting Service (10)

PPTX
Cloud Orchestration is Broken
Public Broadcasting Service
 
PPT
Simplified Localization+ Presentation
Public Broadcasting Service
 
PPTX
PBS Localization+ API Webinar
Public Broadcasting Service
 
PPT
Mobile Presentation at PBS TECH CON 2011
Public Broadcasting Service
 
PPTX
PBS Presentation at AWS Summit 2012
Public Broadcasting Service
 
PPT
I've Got a Key to Your API, Now What? (Joint PBS and NPR API Presentation Giv...
Public Broadcasting Service
 
PPTX
Architecture at PBS
Public Broadcasting Service
 
PDF
PBS Tech Con 2011 API Workshop
Public Broadcasting Service
 
PPT
Fall2010 producer summit_openpbs_final
Public Broadcasting Service
 
Cloud Orchestration is Broken
Public Broadcasting Service
 
Simplified Localization+ Presentation
Public Broadcasting Service
 
PBS Localization+ API Webinar
Public Broadcasting Service
 
Mobile Presentation at PBS TECH CON 2011
Public Broadcasting Service
 
PBS Presentation at AWS Summit 2012
Public Broadcasting Service
 
I've Got a Key to Your API, Now What? (Joint PBS and NPR API Presentation Giv...
Public Broadcasting Service
 
Architecture at PBS
Public Broadcasting Service
 
PBS Tech Con 2011 API Workshop
Public Broadcasting Service
 
Fall2010 producer summit_openpbs_final
Public Broadcasting Service
 

Recently uploaded (20)

PDF
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
PDF
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
PDF
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
PDF
Doc9.....................................
SofiaCollazos
 
PDF
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
PPTX
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 
PPTX
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
PDF
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
PDF
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
PDF
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
PDF
Software Development Company | KodekX
KodekX
 
PDF
CIFDAQ'S Market Insight: BTC to ETH money in motion
CIFDAQ
 
PDF
This slide provides an overview Technology
mineshkharadi333
 
PDF
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
PDF
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
PPTX
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
PDF
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
PDF
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
Doc9.....................................
SofiaCollazos
 
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
Software Development Company | KodekX
KodekX
 
CIFDAQ'S Market Insight: BTC to ETH money in motion
CIFDAQ
 
This slide provides an overview Technology
mineshkharadi333
 
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
Presentation about Hardware and Software in Computer
snehamodhawadiya
 

SQL Injection Defense in Python

  • 1. SQL Injection Defense in Python Edgar Román [email protected] October 4, 2011
  • 2. 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
  • 3. 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))
  • 4. • 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; --‟
  • 5. Security is about multiple layers
  • 6. Multiple Layers • Assume the worst and plan for it • Coding protection is only one layer – Which we will focus on for this presentation • Database lockdown – User partitioning – Password protection • But there are other attacks too: Open Web Application Security Project (OWASP) – https://www.owasp.org/
  • 7. General approaches to SQL Injection Defense • Escape User Input • White Lists • Stored Procs • Parameterized Queries
  • 8. 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
  • 9. 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))
  • 10. 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; --‟
  • 12. 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
  • 13. 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
  • 14. 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
  • 15. 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!
  • 16. 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
  • 17. Django ORM • Automatically escapes all input parameters • Be aware of extra() method – this is raw! • More info – http://www.djangobook.com/en/2.0/chapter20/
  • 18. Conclusions • Use a db framework • If possible, white list your inputs • Be careful if writing raw SQL http://xkcd.com/327/