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

What's hot (20)

Ppt on sql injection
Ppt on sql injectionPpt on sql injection
Ppt on sql injection
 
Sql injection
Sql injectionSql injection
Sql injection
 
Sql injections - with example
Sql injections - with exampleSql injections - with example
Sql injections - with example
 
SQL Injection
SQL Injection SQL Injection
SQL Injection
 
seminar report on Sql injection
seminar report on Sql injectionseminar report on Sql injection
seminar report on Sql injection
 
Sql injection
Sql injectionSql injection
Sql injection
 
SQL injection
SQL injectionSQL injection
SQL injection
 
SQL Injections (Part 1)
SQL Injections (Part 1)SQL Injections (Part 1)
SQL Injections (Part 1)
 
Sql Injection Myths and Fallacies
Sql Injection Myths and FallaciesSql Injection Myths and Fallacies
Sql Injection Myths and Fallacies
 
Types of sql injection attacks
Types of sql injection attacksTypes of sql injection attacks
Types of sql injection attacks
 
Top 10 Web Security Vulnerabilities
Top 10 Web Security VulnerabilitiesTop 10 Web Security Vulnerabilities
Top 10 Web Security Vulnerabilities
 
Sql injection
Sql injectionSql injection
Sql injection
 
Secure Code Warrior - Cross site scripting
Secure Code Warrior - Cross site scriptingSecure Code Warrior - Cross site scripting
Secure Code Warrior - Cross site scripting
 
Sql injection
Sql injectionSql injection
Sql 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 INJECTIONSQL INJECTION
SQL INJECTION
 
Advanced Topics On Sql Injection Protection
Advanced Topics On Sql Injection ProtectionAdvanced Topics On Sql Injection Protection
Advanced Topics On Sql Injection Protection
 
Advanced SQL Injection
Advanced SQL InjectionAdvanced SQL Injection
Advanced SQL Injection
 
Sql injection
Sql injectionSql injection
Sql injection
 
Xss attack
Xss attackXss attack
Xss attack
 

Viewers also liked

SQL Injections - A Powerpoint Presentation
SQL Injections - A Powerpoint PresentationSQL Injections - A Powerpoint Presentation
SQL Injections - A Powerpoint PresentationRapid Purple
 
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
 
ヘルパー移送dm
ヘルパー移送dmヘルパー移送dm
ヘルパー移送dmfrumpy
 

Viewers also liked (19)

SQL Injections - A Powerpoint Presentation
SQL Injections - A Powerpoint PresentationSQL Injections - A Powerpoint Presentation
SQL Injections - A Powerpoint Presentation
 
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
 
ヘルパー移送dm
ヘルパー移送dmヘルパー移送dm
ヘルパー移送dm
 

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

The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
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
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
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
 

Recently uploaded (20)

The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
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
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
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
 

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/