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 Injection attacks and prevention
Sql Injection attacks and preventionSql Injection attacks and prevention
Sql Injection attacks and preventionhelloanand
 
Advanced Sql Injection ENG
Advanced Sql Injection ENGAdvanced Sql Injection ENG
Advanced Sql Injection ENGDmitry Evteev
 
Securing AEM webapps by hacking them
Securing AEM webapps by hacking themSecuring AEM webapps by hacking them
Securing AEM webapps by hacking themMikhail Egorov
 
Not a Security Boundary
Not a Security BoundaryNot a Security Boundary
Not a Security BoundaryWill Schroeder
 
Sql injections - with example
Sql injections - with exampleSql injections - with example
Sql injections - with examplePrateek Chauhan
 
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
 
Ppt on sql injection
Ppt on sql injectionPpt on sql injection
Ppt on sql injectionashish20012
 
A Brief Introduction in SQL Injection
A Brief Introduction in SQL InjectionA Brief Introduction in SQL Injection
A Brief Introduction in SQL InjectionSina Manavi
 
Time-Based Blind SQL Injection using Heavy Queries
Time-Based Blind SQL Injection using Heavy QueriesTime-Based Blind SQL Injection using Heavy Queries
Time-Based Blind SQL Injection using Heavy QueriesChema Alonso
 
The Unintended Risks of Trusting Active Directory
The Unintended Risks of Trusting Active DirectoryThe Unintended Risks of Trusting Active Directory
The Unintended Risks of Trusting Active DirectoryWill Schroeder
 
MySQL Indexing : Improving Query Performance Using Index (Covering Index)
MySQL Indexing : Improving Query Performance Using Index (Covering Index)MySQL Indexing : Improving Query Performance Using Index (Covering Index)
MySQL Indexing : Improving Query Performance Using Index (Covering Index)Hemant Kumar Singh
 
Sql Injection - Vulnerability and Security
Sql Injection - Vulnerability and SecuritySql Injection - Vulnerability and Security
Sql Injection - Vulnerability and SecuritySandip Chaudhari
 
Polyglot payloads in practice by avlidienbrunn at HackPra
Polyglot payloads in practice by avlidienbrunn at HackPraPolyglot payloads in practice by avlidienbrunn at HackPra
Polyglot payloads in practice by avlidienbrunn at HackPraMathias Karlsson
 
Client-side JavaScript
Client-side JavaScriptClient-side JavaScript
Client-side JavaScriptLilia Sfaxi
 

What's hot (20)

Sql Injection attacks and prevention
Sql Injection attacks and preventionSql Injection attacks and prevention
Sql Injection attacks and prevention
 
Advanced Sql Injection ENG
Advanced Sql Injection ENGAdvanced Sql Injection ENG
Advanced Sql Injection ENG
 
Sqlmap
SqlmapSqlmap
Sqlmap
 
Securing AEM webapps by hacking them
Securing AEM webapps by hacking themSecuring AEM webapps by hacking them
Securing AEM webapps by hacking them
 
Not a Security Boundary
Not a Security BoundaryNot a Security Boundary
Not a Security Boundary
 
Sql injections - with example
Sql injections - with exampleSql injections - with example
Sql injections - with example
 
Sqlmap
SqlmapSqlmap
Sqlmap
 
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
 
Ppt on sql injection
Ppt on sql injectionPpt on sql injection
Ppt on sql injection
 
A Brief Introduction in SQL Injection
A Brief Introduction in SQL InjectionA Brief Introduction in SQL Injection
A Brief Introduction in SQL Injection
 
Time-Based Blind SQL Injection using Heavy Queries
Time-Based Blind SQL Injection using Heavy QueriesTime-Based Blind SQL Injection using Heavy Queries
Time-Based Blind SQL Injection using Heavy Queries
 
The Unintended Risks of Trusting Active Directory
The Unintended Risks of Trusting Active DirectoryThe Unintended Risks of Trusting Active Directory
The Unintended Risks of Trusting Active Directory
 
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
 
Sql injection
Sql injectionSql injection
Sql injection
 
Sqlmap
SqlmapSqlmap
Sqlmap
 
MySQL Indexing : Improving Query Performance Using Index (Covering Index)
MySQL Indexing : Improving Query Performance Using Index (Covering Index)MySQL Indexing : Improving Query Performance Using Index (Covering Index)
MySQL Indexing : Improving Query Performance Using Index (Covering Index)
 
Sql Injection - Vulnerability and Security
Sql Injection - Vulnerability and SecuritySql Injection - Vulnerability and Security
Sql Injection - Vulnerability and Security
 
Polyglot payloads in practice by avlidienbrunn at HackPra
Polyglot payloads in practice by avlidienbrunn at HackPraPolyglot payloads in practice by avlidienbrunn at HackPra
Polyglot payloads in practice by avlidienbrunn at HackPra
 
Client-side JavaScript
Client-side JavaScriptClient-side JavaScript
Client-side JavaScript
 
Doing REST Right
Doing REST RightDoing REST Right
Doing REST Right
 

Viewers also liked

SQL Injections - A Powerpoint Presentation
SQL Injections - A Powerpoint PresentationSQL Injections - A Powerpoint Presentation
SQL Injections - A Powerpoint PresentationRapid Purple
 
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
Sql injectionSql injection
Sql injection
 
SQL Injections - A Powerpoint Presentation
SQL Injections - A Powerpoint PresentationSQL Injections - A Powerpoint Presentation
SQL Injections - A Powerpoint Presentation
 
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

Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
"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
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
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
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 

Recently uploaded (20)

Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
"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...
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
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
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 

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/