SlideShare a Scribd company logo
1 of 18
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

What's hot

SQL Injections - A Powerpoint Presentation
SQL Injections - A Powerpoint PresentationSQL Injections - A Powerpoint Presentation
SQL Injections - A Powerpoint PresentationRapid Purple
 
Sql injection
Sql injectionSql injection
Sql injectionZidh
 
SQL INJECTION
SQL INJECTIONSQL INJECTION
SQL INJECTIONAnoop T
 
Advanced SQL Injection
Advanced SQL InjectionAdvanced SQL Injection
Advanced SQL Injectionamiable_indian
 
Sql injections - with example
Sql injections - with exampleSql injections - with example
Sql injections - with examplePrateek Chauhan
 
Offensive PowerShell Cheat Sheet
Offensive	PowerShell Cheat SheetOffensive	PowerShell Cheat Sheet
Offensive PowerShell Cheat SheetRahmat Nurfauzi
 
Sql Injection attacks and prevention
Sql Injection attacks and preventionSql Injection attacks and prevention
Sql Injection attacks and preventionhelloanand
 
Neat tricks to bypass CSRF-protection
Neat tricks to bypass CSRF-protectionNeat tricks to bypass CSRF-protection
Neat tricks to bypass CSRF-protectionMikhail Egorov
 
SQLMAP Tool Usage - A Heads Up
SQLMAP Tool Usage - A  Heads UpSQLMAP Tool Usage - A  Heads Up
SQLMAP Tool Usage - A Heads UpMindfire Solutions
 
Sql injection attack
Sql injection attackSql injection attack
Sql injection attackRaghav Bisht
 
Introduction to Web Application Penetration Testing
Introduction to Web Application Penetration TestingIntroduction to Web Application Penetration Testing
Introduction to Web Application Penetration TestingAnurag Srivastava
 
SQL injection prevention techniques
SQL injection prevention techniquesSQL injection prevention techniques
SQL injection prevention techniquesSongchaiDuangpan
 

What's hot (20)

SQL Injections - A Powerpoint Presentation
SQL Injections - A Powerpoint PresentationSQL Injections - A Powerpoint Presentation
SQL Injections - A Powerpoint Presentation
 
Sql injection
Sql injectionSql injection
Sql injection
 
SQL INJECTION
SQL INJECTIONSQL INJECTION
SQL INJECTION
 
Advanced SQL Injection
Advanced SQL InjectionAdvanced SQL Injection
Advanced SQL Injection
 
SQL Injections (Part 1)
SQL Injections (Part 1)SQL Injections (Part 1)
SQL Injections (Part 1)
 
Sql injections - with example
Sql injections - with exampleSql injections - with example
Sql injections - with example
 
Sql injection
Sql injectionSql injection
Sql injection
 
Offensive PowerShell Cheat Sheet
Offensive	PowerShell Cheat SheetOffensive	PowerShell Cheat Sheet
Offensive PowerShell Cheat Sheet
 
SQL injection
SQL injectionSQL injection
SQL injection
 
Sql Injection attacks and prevention
Sql Injection attacks and preventionSql Injection attacks and prevention
Sql Injection attacks and prevention
 
Neat tricks to bypass CSRF-protection
Neat tricks to bypass CSRF-protectionNeat tricks to bypass CSRF-protection
Neat tricks to bypass CSRF-protection
 
Command injection
Command injectionCommand injection
Command injection
 
SQLMAP Tool Usage - A Heads Up
SQLMAP Tool Usage - A  Heads UpSQLMAP Tool Usage - A  Heads Up
SQLMAP Tool Usage - A Heads Up
 
SQL Injection
SQL Injection SQL Injection
SQL Injection
 
Sql injection attack
Sql injection attackSql injection attack
Sql injection attack
 
How to identify and prevent SQL injection
How to identify and prevent SQL injection  How to identify and prevent SQL injection
How to identify and prevent SQL injection
 
Introduction to Web Application Penetration Testing
Introduction to Web Application Penetration TestingIntroduction to Web Application Penetration Testing
Introduction to Web Application Penetration Testing
 
Sql injection
Sql injectionSql injection
Sql injection
 
SQL injection prevention techniques
SQL injection prevention techniquesSQL injection prevention techniques
SQL injection prevention techniques
 
Sql injection attack
Sql injection attackSql injection attack
Sql injection attack
 

Viewers also liked

Types of sql injection attacks
Types of sql injection attacksTypes of sql injection attacks
Types of sql injection attacksRespa Peter
 
Social skills for those with autism
Social skills for those with autismSocial skills for those with autism
Social skills for those with autismabagirl
 
Michael Bayer Introduction to SQLAlchemy @ Postgres Open
Michael Bayer Introduction to SQLAlchemy @ Postgres OpenMichael Bayer Introduction to SQLAlchemy @ Postgres Open
Michael Bayer Introduction to SQLAlchemy @ Postgres OpenPostgresOpen
 
Sql injection attack_analysis_py_vo
Sql injection attack_analysis_py_voSql injection attack_analysis_py_vo
Sql injection attack_analysis_py_voJirka Vejrazka
 
Sql injection attacks
Sql injection attacksSql injection attacks
Sql injection attacksNitish Kumar
 
Protecting your data from SQL Injection attacks
Protecting your data from SQL Injection attacksProtecting your data from SQL Injection attacks
Protecting your data from SQL Injection attacksKevin Alcock
 
Sql Injection Attacks And Defense Presentatio (1)
Sql Injection Attacks And Defense Presentatio (1)Sql Injection Attacks And Defense Presentatio (1)
Sql Injection Attacks And Defense Presentatio (1)guest32e5cfe
 
[Seoul cartoon] policy sharing makes cities around the world happier
[Seoul cartoon] policy sharing makes cities around the world happier[Seoul cartoon] policy sharing makes cities around the world happier
[Seoul cartoon] policy sharing makes cities around the world happiersimrc
 
Olap scalability
Olap scalabilityOlap scalability
Olap scalabilitylucboudreau
 
Corporate gifts suppliers in gurgaon
Corporate gifts suppliers in gurgaonCorporate gifts suppliers in gurgaon
Corporate gifts suppliers in gurgaonvinay kumar
 
Frederic Arrouays, CFO Emerging Markets at SAP - The Finance transformation a...
Frederic Arrouays, CFO Emerging Markets at SAP - The Finance transformation a...Frederic Arrouays, CFO Emerging Markets at SAP - The Finance transformation a...
Frederic Arrouays, CFO Emerging Markets at SAP - The Finance transformation a...Global Business Events
 
2015 SaaS Industry Survey Results for Marketers
2015 SaaS Industry Survey Results for Marketers2015 SaaS Industry Survey Results for Marketers
2015 SaaS Industry Survey Results for MarketersMatthew Howard
 
Digital marketing CK sinh vien kent international college
Digital marketing CK sinh vien kent international collegeDigital marketing CK sinh vien kent international college
Digital marketing CK sinh vien kent international collegetrung_1881
 
Airfreight Trends: Still Sluggish, with Cargo Growth in Some Sectors
Airfreight Trends: Still Sluggish, with Cargo Growth in Some Sectors Airfreight Trends: Still Sluggish, with Cargo Growth in Some Sectors
Airfreight Trends: Still Sluggish, with Cargo Growth in Some Sectors Craig Raucher New York
 

Viewers also liked (20)

Sql Injection Myths and Fallacies
Sql Injection Myths and FallaciesSql Injection Myths and Fallacies
Sql Injection Myths and Fallacies
 
Sql injection
Sql injectionSql injection
Sql injection
 
Types of sql injection attacks
Types of sql injection attacksTypes of sql injection attacks
Types of sql injection attacks
 
Social skills for those with autism
Social skills for those with autismSocial skills for those with autism
Social skills for those with autism
 
Michael Bayer Introduction to SQLAlchemy @ Postgres Open
Michael Bayer Introduction to SQLAlchemy @ Postgres OpenMichael Bayer Introduction to SQLAlchemy @ Postgres Open
Michael Bayer Introduction to SQLAlchemy @ Postgres Open
 
Sqlmap Analiz
Sqlmap AnalizSqlmap Analiz
Sqlmap Analiz
 
SQL Enjeksiyona karşi savunma
SQL Enjeksiyona karşi savunmaSQL Enjeksiyona karşi savunma
SQL Enjeksiyona karşi savunma
 
Sql injection attack_analysis_py_vo
Sql injection attack_analysis_py_voSql injection attack_analysis_py_vo
Sql injection attack_analysis_py_vo
 
Sql injection attacks
Sql injection attacksSql injection attacks
Sql injection attacks
 
Protecting your data from SQL Injection attacks
Protecting your data from SQL Injection attacksProtecting your data from SQL Injection attacks
Protecting your data from SQL Injection attacks
 
Sql Injection Attacks And Defense Presentatio (1)
Sql Injection Attacks And Defense Presentatio (1)Sql Injection Attacks And Defense Presentatio (1)
Sql Injection Attacks And Defense Presentatio (1)
 
[Seoul cartoon] policy sharing makes cities around the world happier
[Seoul cartoon] policy sharing makes cities around the world happier[Seoul cartoon] policy sharing makes cities around the world happier
[Seoul cartoon] policy sharing makes cities around the world happier
 
Tema liderazgo
Tema liderazgoTema liderazgo
Tema liderazgo
 
Olap scalability
Olap scalabilityOlap scalability
Olap scalability
 
Corporate gifts suppliers in gurgaon
Corporate gifts suppliers in gurgaonCorporate gifts suppliers in gurgaon
Corporate gifts suppliers in gurgaon
 
Frederic Arrouays, CFO Emerging Markets at SAP - The Finance transformation a...
Frederic Arrouays, CFO Emerging Markets at SAP - The Finance transformation a...Frederic Arrouays, CFO Emerging Markets at SAP - The Finance transformation a...
Frederic Arrouays, CFO Emerging Markets at SAP - The Finance transformation a...
 
2015 SaaS Industry Survey Results for Marketers
2015 SaaS Industry Survey Results for Marketers2015 SaaS Industry Survey Results for Marketers
2015 SaaS Industry Survey Results for Marketers
 
Digital marketing CK sinh vien kent international college
Digital marketing CK sinh vien kent international collegeDigital marketing CK sinh vien kent international college
Digital marketing CK sinh vien kent international college
 
Follow me on Twitter
Follow me on TwitterFollow me on Twitter
Follow me on Twitter
 
Airfreight Trends: Still Sluggish, with Cargo Growth in Some Sectors
Airfreight Trends: Still Sluggish, with Cargo Growth in Some Sectors Airfreight Trends: Still Sluggish, with Cargo Growth in Some Sectors
Airfreight Trends: Still Sluggish, with Cargo Growth in Some Sectors
 

Similar to SQL Injection Defense in Python

ShmooCON 2009 : Re-playing with (Blind) SQL Injection
ShmooCON 2009 : Re-playing with (Blind) SQL InjectionShmooCON 2009 : Re-playing with (Blind) SQL Injection
ShmooCON 2009 : Re-playing with (Blind) SQL InjectionChema Alonso
 
Hack your db before the hackers do
Hack your db before the hackers doHack your db before the hackers do
Hack your db before the hackers dofangjiafu
 
Rails Tips and Best Practices
Rails Tips and Best PracticesRails Tips and Best Practices
Rails Tips and Best PracticesDavid Keener
 
Oracle forensics 101
Oracle forensics 101Oracle forensics 101
Oracle forensics 101fangjiafu
 
Web hacking series part 3
Web hacking series part 3Web hacking series part 3
Web hacking series part 3Aditya Kamat
 
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
 
Different waysconnect
Different waysconnectDifferent waysconnect
Different waysconnectmyrajendra
 
DjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling DisqusDjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling Disquszeeg
 
Appsec usa2013 js_libinsecurity_stefanodipaola
Appsec usa2013 js_libinsecurity_stefanodipaolaAppsec usa2013 js_libinsecurity_stefanodipaola
Appsec usa2013 js_libinsecurity_stefanodipaoladrewz lin
 
Developing on SQL Azure
Developing on SQL AzureDeveloping on SQL Azure
Developing on SQL AzureIke Ellis
 
Scala Frustrations
Scala FrustrationsScala Frustrations
Scala Frustrationstakezoe
 
GreenDao Introduction
GreenDao IntroductionGreenDao Introduction
GreenDao IntroductionBooch Lin
 
Practical Approach towards SQLi ppt
Practical Approach towards SQLi pptPractical Approach towards SQLi ppt
Practical Approach towards SQLi pptAhamed Saleem
 

Similar to SQL Injection Defense in Python (20)

Hack through Injections
Hack through InjectionsHack through Injections
Hack through Injections
 
null Bangalore meet - Php Security
null Bangalore meet - Php Securitynull Bangalore meet - Php Security
null Bangalore meet - Php Security
 
Rails Security
Rails SecurityRails Security
Rails Security
 
ShmooCON 2009 : Re-playing with (Blind) SQL Injection
ShmooCON 2009 : Re-playing with (Blind) SQL InjectionShmooCON 2009 : Re-playing with (Blind) SQL Injection
ShmooCON 2009 : Re-playing with (Blind) SQL Injection
 
Not so blind SQL Injection
Not so blind SQL InjectionNot so blind SQL Injection
Not so blind SQL Injection
 
Hack your db before the hackers do
Hack your db before the hackers doHack your db before the hackers do
Hack your db before the hackers do
 
06.1 .Net memory management
06.1 .Net memory management06.1 .Net memory management
06.1 .Net memory management
 
Rails Tips and Best Practices
Rails Tips and Best PracticesRails Tips and Best Practices
Rails Tips and Best Practices
 
Oracle forensics 101
Oracle forensics 101Oracle forensics 101
Oracle forensics 101
 
Web hacking series part 3
Web hacking series part 3Web hacking series part 3
Web hacking series part 3
 
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
 
Different waysconnect
Different waysconnectDifferent waysconnect
Different waysconnect
 
DjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling DisqusDjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling Disqus
 
Appsec usa2013 js_libinsecurity_stefanodipaola
Appsec usa2013 js_libinsecurity_stefanodipaolaAppsec usa2013 js_libinsecurity_stefanodipaola
Appsec usa2013 js_libinsecurity_stefanodipaola
 
Developing on SQL Azure
Developing on SQL AzureDeveloping on SQL Azure
Developing on SQL Azure
 
Orms vs Micro-ORMs
Orms vs Micro-ORMsOrms vs Micro-ORMs
Orms vs Micro-ORMs
 
Scala Frustrations
Scala FrustrationsScala Frustrations
Scala Frustrations
 
GreenDao Introduction
GreenDao IntroductionGreenDao Introduction
GreenDao Introduction
 
MYSQL - PHP Database Connectivity
MYSQL - PHP Database ConnectivityMYSQL - PHP Database Connectivity
MYSQL - PHP Database Connectivity
 
Practical Approach towards SQLi ppt
Practical Approach towards SQLi pptPractical Approach towards SQLi ppt
Practical Approach towards SQLi ppt
 

More from Public Broadcasting Service (10)

Cloud Orchestration is Broken
Cloud Orchestration is BrokenCloud Orchestration is Broken
Cloud Orchestration is Broken
 
Pycon2013
Pycon2013Pycon2013
Pycon2013
 
Simplified Localization+ Presentation
Simplified Localization+ PresentationSimplified Localization+ Presentation
Simplified Localization+ Presentation
 
PBS Localization+ API Webinar
PBS Localization+ API WebinarPBS Localization+ API Webinar
PBS Localization+ API Webinar
 
Mobile Presentation at PBS TECH CON 2011
Mobile Presentation at PBS TECH CON 2011Mobile Presentation at PBS TECH CON 2011
Mobile Presentation at PBS TECH CON 2011
 
PBS Presentation at AWS Summit 2012
PBS Presentation at AWS Summit 2012PBS Presentation at AWS Summit 2012
PBS Presentation at AWS Summit 2012
 
I've Got a Key to Your API, Now What? (Joint PBS and NPR API Presentation Giv...
I've Got a Key to Your API, Now What? (Joint PBS and NPR API Presentation Giv...I've Got a Key to Your API, Now What? (Joint PBS and NPR API Presentation Giv...
I've Got a Key to Your API, Now What? (Joint PBS and NPR API Presentation Giv...
 
Architecture at PBS
Architecture at PBSArchitecture at PBS
Architecture at PBS
 
PBS Tech Con 2011 API Workshop
PBS Tech Con 2011 API WorkshopPBS Tech Con 2011 API Workshop
PBS Tech Con 2011 API Workshop
 
Fall2010 producer summit_openpbs_final
Fall2010 producer summit_openpbs_finalFall2010 producer summit_openpbs_final
Fall2010 producer summit_openpbs_final
 

Recently uploaded

Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...apidays
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusZilliz
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 

Recently uploaded (20)

Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 

SQL Injection Defense in Python

  • 1. SQL Injection Defense in Python Edgar Román emroman@pbs.org 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/