SlideShare ist ein Scribd-Unternehmen logo
1 von 28
CHAPTER 8
 SQL Injection

Slides adapted from "Foundations of Security: What Every Programmer
Needs To Know" by Neil Daswani, Christoph Kern, and Anita Kesavan
(ISBN 1590597842; http://www.foundationsofsecurity.com). Except as
otherwise noted, the content of this presentation is licensed under the
Creative Commons 3.0 License.
Agenda
   Command injection vulnerability - untrusted input
    inserted into query or command
     Attackstring alters intended semantics of command
     Ex: SQL Injection - unsanitized data used in query to
      back-end database (DB)

   SQL Injection Examples & Solutions
     Type 1: compromises user data
     Type 2: modifies critical data
     Whitelisting over Blacklisting
     Escaping
     Prepared Statements and Bind Variables
SQL Injection Impact in
the Real World
   CardSystems, credit card payment processing
   Ruined by SQL Injection attack in June 2005

   263,000 credit card #s stolen from its DB

   #s stored unencrypted, 40 million exposed

   Awareness Increasing: # of reported SQL
    injection vulnerabilities tripled from 2004 to 2005
8.1. Attack Scenario (1)
   Ex: Pizza Site Reviewing Orders
     Form   requesting month # to view orders for




     HTTP   request:
      https://www.deliver-me-pizza.com/show_orders?month=10
8.1. Attack Scenario (2)
     App constructs SQL query from parameter:
  sql_query = "SELECT pizza, toppings, quantity, order_day " +
              "FROM orders " +
              "WHERE userid=" + session.getCurrentUserId() + " " +
              "AND order_month=" + request.getParamenter("month");


      Normal     SELECT pizza, toppings, quantity, order_day
                 FROM orders
                 WHERE userid=4123
       SQL       AND order_month=10

      Query
     Type 1 Attack: inputs month='0 OR 1=1' !
     Goes to encoded URL: (space -> %20, = -> %3D)
https://www.deliver-me-pizza.com/show_orders?month=0%20OR%201%3D1
8.1. Attack Scenario (3)
Malicious SELECT pizza,
          FROM orders
                          toppings, quantity, order_day

           WHERE userid=4123
  Query    AND order_month=0 OR 1=1

  WHERE condition is
   always true!
    OR  precedes AND
    Type 1 Attack:
     Gains access to
     other users’
     private data!
     All User Data
     Compromised
8.1. Attack Scenario (4)
   More damaging attack: attacker sets month=
    0 AND 1=0
    UNION SELECT cardholder, number, exp_month, exp_year
    FROM creditcards

   Attacker is able to
     Combine    2 queries
     1st query: empty
      table (where fails)
     2nd query: credit
      card #s of all users
8.1. Attack Scenario (4)
   Even worse, attacker sets         month=0;
                                      DROP TABLE creditcards;

   Then DB executes                SELECT pizza, toppings,
     Type 2 Attack:                quantity, order_day
      Removes creditcards           FROM orders
      from schema!                  WHERE userid=4123
     Future orders fail: DoS!      AND order_month=0;
                                    DROP TABLE creditcards;

   Problematic Statements:
     Modifiers: INSERT INTO admin_users VALUES ('hacker',...)
     Administrative: shut down DB, control OS…
8.1. Attack Scenario (5)
   Injecting String Parameters: Topping Search
sql_query =
  "SELECT pizza, toppings, quantity, order_day " +
  "FROM orders " +
  "WHERE userid=" + session.getCurrentUserId() + " " +
  "AND topping LIKE '%" + request.getParamenter("topping") + "%' ";

   Attacker sets: topping=brzfg%';   DROP table creditcards; --



   Query evaluates as:              SELECT pizza, toppings,
                                     quantity, order_day
     SELECT:   empty table          FROM orders
     -- comments out end            WHERE userid=4123
                                     AND topping LIKE '%brzfg%';
     Credit card info dropped       DROP table creditcards; --%'
8.1. Attack Scenario (6)




          Source: http://xkcd.com/327/
8.2. Solutions
   Variety of Techniques: Defense-in-depth

   Whitelisting over Blacklisting

   Input Validation & Escaping

   Use Prepared Statements & Bind Variables

   Mitigate Impact
8.2.1. Why Blacklisting Does
Not Work
   Eliminating quotes enough (blacklist them)?
      sql_query =
      "SELECT pizza, toppings, quantity, order_day " +
      "FROM orders " +
      "WHERE userid=" + session.getCurrentUserId() + " " +
      "AND topping LIKE
      'kill_quotes(request.getParamenter("topping")) + "%'";

   kill_quotes (Java) removes single quotes:
      String kill_quotes(String str) {
        StringBuffer result = new    StringBuffer(str.length());
        for (int i = 0; i < str.length(); i++) {
          if (str.charAt(i) != ''')
            result.append(str.charAt(i));
        }
        return result.toString();
      }
8.2.1. Pitfalls of Blacklisting
   Filter quotes, semicolons, whitespace, and…?
     Could  always miss a dangerous character
     Blacklisting not comprehensive solution
     Ex: kill_quotes() can’t prevent attacks against
      numeric parameters


   May conflict with functional requirements
   How to store O’Brien in DB if quotes blacklisted?
8.2.2. Whitelisting-Based Input
Validation
   Whitelisting – only allow input within well-defined
    set of safe values
     setimplicitly defined through regular expressions
     RegExp – pattern to match strings against


   Ex: month parameter: non-negative integer
     RegExp:  ^[0-9]*$ - 0 or more digits, safe subset
     The ^, $ match beginning and end of string
     [0-9] matches a digit, * specifies 0 or more
8.2.3. Escaping
   Could escape quotes instead of blacklisting
   Ex: insert user o'connor, password terminator
         sql = "INSERT INTO USERS(uname,passwd) " +
               "VALUES (" + escape(uname)+ "," +
               escape(password) +")";

     escape(o'connor)        = o''connor
INSERT INTO USERS(uname,passwd) VALUES ('o''connor','terminator');



   Like kill_quotes, only works for string inputs
   Numeric parameters could still be vulnerable
8.2.4. Second-Order
SQL Injection (1)
   Second-Order SQL Injection: data stored in
    database is later used to conduct SQL injection
     Common  if string escaping is applied inconsistently
     Ex: o'connor updates passwd to SkYn3t
     new_passwd = request.getParameter("new_passwd");
     uname = session.getUsername();
     sql = "UPDATE USERS SET passwd='"+ escape(new_passwd) +
           "' WHERE uname='" + uname + "'";
     Username  not escaped, b/c originally escaped before
      entering DB, now inside our trust zone:
       UPDATE USERS SET passwd='SkYn3t' WHERE uname='o'connor'

     Query   fails b/c ' after o ends command prematurely
8.2.4. Second-Order
SQL Injection (2)
   Even Worse: What if user set
    uname=admin'-- !?
    UPDATE USERS SET passwd='cracked' WHERE uname='admin' --'

      Attacker  changes admin’s password to cracked
      Has full access to admin account
      Username avoids collision with real admin
      -- comments out trailing quote



   All parameters dangerous: escape(uname)
8.2.5. Prepared Statements &
Bind Variables
   Metachars (e.g. quotes) provide distinction
    between data & control in queries
     most  attacks: data interpreted as control
     alters the semantics of a query


   Bind Variables: ? placeholders guaranteed to be
    data (not control)

   Prepared Statements allow creation of static
    queries with bind variables
     Preservesthe structure of intended query
     Parameters not involved in query parsing/compiling
8.2.5. Java Prepared
Statements
PreparedStatement ps =
db.prepareStatement("SELECT pizza, toppings, quantity, order_day "
                + "FROM orders WHERE userid=? AND order_month=?");
ps.setInt(1, session.getCurrentUserId());
ps.setInt(2, Integer.parseInt(request.getParamenter("month")));
ResultSet res = ps.executeQuery();

                                                 Bind Variable:
                                                      Data
                                                  Placeholder
   Query parsed without parameters

   Bind variables are typed: input must be of
    expected type (e.g. int, string)
8.2.5. PHP Prepared
Statements
     $ps = $db->prepare(
           'SELECT pizza, toppings, quantity, order_day '.
           'FROM orders WHERE userid=? AND order_month=?');
     $ps->execute(array($current_user_id, $month));


   No explicit typing of parameters like in Java
   Apply consistently: adding $year parameter
    directly to query still creates SQL injection threat

   Have separate module for DB access
     Do prepared statements here
     Gateway to DB for rest of code
8.2.5. SQL Stored Procedures
   Stored procedure: sequence of SQL statements
    executing on specified inputs

            CREATE PROCEDURE change_password
   Ex:                      @username VARCHAR(25),
                             @new_passwd VARCHAR(25) AS
            UPDATE USERS SET passwd=new_passwd WHERE uname=username

   Vulnerable use:
          $db->exec("change_password '"+$uname+"','"+new_passwd+"'");


   Instead use bind variables w/ stored procedure:
              $ps = $db->prepare("change_password ?, ?");
              $ps->execute(array($uname, $new_passwd));
8.2.6. Mitigating the Impact of
SQL Injection Attacks
   Prevent Schema & Information Leaks

   Limit Privileges (Defense-in-Depth)

   Encrypt Sensitive Data stored in Database

   Harden DB Server and Host O/S

   Apply Input Validation
8.2.6. Prevent Schema &
Information Leaks
   Knowing database schema makes attacker’s job
    easier

   Blind SQL Injection: attacker attempts to
    interrogate system to figure out schema

   Prevent leakages of schema information

   Don’t display detailed error messages and stack
    traces to external users
8.2.6. Limiting Privileges
   Apply Principle of Least Privilege! Limit
     Readaccess, tables/views user can query
     Commands (are updates/inserts ok?)


   No more privileges than typical user needs

   Ex: could prevent attacker from executing
    INSERT and DROP statements
     But could still be able do SELECT attacks and
      compromise user data
     Not a complete fix, but less damage
8.2.6. Encrypting Sensitive Data
   Encrypt data stored in the database
     second line of defense
     w/o key, attacker can’t read sensitive info


   Key management precautions: don’t store key
    in DB, attacker just SQL injects again to get it

   Some databases allow automatic encryption,
    but these still return plaintext queries!
8.2.6. Hardening DB Server and
Host O/S
   Dangerous functions could be on by default

   Ex: Microsoft SQL Server
     Allows  users to open inbound/outbound sockets
     Attacker could steal data, upload binaries, port scan
      victim’s network


   Disable unused services and accounts on OS
    (Ex: No need for web server on DB host)
8.2.6. Applying Input Validation
   Validation of query parameters not enough

   Validate all input early at entry point into code

   Reject overly long input (could prevent unknown
    buffer overflow exploit in SQL parser)

   Redundancy helps protect systems
     E.g.if programmer forgets to apply validation for
      query input
     Two lines of defense
Summary
   SQL injection attacks are important security
    threat that can
     Compromise   sensitive user data
     Alter or damage critical data
     Give an attacker unwanted access to DB


   Key Idea: Use diverse solutions, consistently!
     Whitelisting
                 input validation & escaping
     Prepared Statements with bind variables

Weitere ähnliche Inhalte

Was ist angesagt?

Client-side Auth with Ember.js
Client-side Auth with Ember.jsClient-side Auth with Ember.js
Client-side Auth with Ember.jsMatthew Beale
 
Modern Android Architecture
Modern Android ArchitectureModern Android Architecture
Modern Android ArchitectureEric Maxwell
 
Tame Accidental Complexity with Ruby and MongoMapper
Tame Accidental Complexity with Ruby and MongoMapperTame Accidental Complexity with Ruby and MongoMapper
Tame Accidental Complexity with Ruby and MongoMapperGiordano Scalzo
 
TDC2017 | São Paulo - Trilha Java EE How we figured out we had a SRE team at ...
TDC2017 | São Paulo - Trilha Java EE How we figured out we had a SRE team at ...TDC2017 | São Paulo - Trilha Java EE How we figured out we had a SRE team at ...
TDC2017 | São Paulo - Trilha Java EE How we figured out we had a SRE team at ...tdc-globalcode
 
Webit expo Standard Product
Webit expo Standard ProductWebit expo Standard Product
Webit expo Standard ProductBoji Ditcheva
 
.NET Fest 2017. Михаил Щербаков. Механизмы предотвращения атак в ASP.NET Core
.NET Fest 2017. Михаил Щербаков. Механизмы предотвращения атак в ASP.NET Core.NET Fest 2017. Михаил Щербаков. Механизмы предотвращения атак в ASP.NET Core
.NET Fest 2017. Михаил Щербаков. Механизмы предотвращения атак в ASP.NET CoreNETFest
 
Top Ten Web Defenses - DefCamp 2012
Top Ten Web Defenses  - DefCamp 2012Top Ten Web Defenses  - DefCamp 2012
Top Ten Web Defenses - DefCamp 2012DefCamp
 
Nagios Conference 2014 - Troy Lea - JavaScript and jQuery - Nagios XI Tips, T...
Nagios Conference 2014 - Troy Lea - JavaScript and jQuery - Nagios XI Tips, T...Nagios Conference 2014 - Troy Lea - JavaScript and jQuery - Nagios XI Tips, T...
Nagios Conference 2014 - Troy Lea - JavaScript and jQuery - Nagios XI Tips, T...Nagios
 
Open Selector
Open SelectorOpen Selector
Open Selectorjjdelc
 
WordPress as an application framework
WordPress as an application frameworkWordPress as an application framework
WordPress as an application frameworkDustin Filippini
 
Hacking Your Way to Better Security - PHP South Africa 2016
Hacking Your Way to Better Security - PHP South Africa 2016Hacking Your Way to Better Security - PHP South Africa 2016
Hacking Your Way to Better Security - PHP South Africa 2016Colin O'Dell
 
Hacking Your Way To Better Security
Hacking Your Way To Better SecurityHacking Your Way To Better Security
Hacking Your Way To Better SecurityColin O'Dell
 
Taming forms with React
Taming forms with ReactTaming forms with React
Taming forms with ReactGreeceJS
 
Modularized Persistence - B Zsoldos
Modularized Persistence - B ZsoldosModularized Persistence - B Zsoldos
Modularized Persistence - B Zsoldosmfrancis
 
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)Carles Farré
 
Integrating OAuth and Social Login Into Wordpress
Integrating OAuth and Social Login Into WordpressIntegrating OAuth and Social Login Into Wordpress
Integrating OAuth and Social Login Into WordpressWilliam Tam
 
Présentation et bonnes pratiques du pattern MVVM - MIC Belgique
Présentation et bonnes pratiques du pattern MVVM - MIC BelgiquePrésentation et bonnes pratiques du pattern MVVM - MIC Belgique
Présentation et bonnes pratiques du pattern MVVM - MIC BelgiqueDenis Voituron
 
FormsKit: reactive forms driven by state. UA Mobile 2017.
FormsKit: reactive forms driven by state. UA Mobile 2017.FormsKit: reactive forms driven by state. UA Mobile 2017.
FormsKit: reactive forms driven by state. UA Mobile 2017.UA Mobile
 
Detroit ELEVATE Track 2
Detroit ELEVATE Track 2Detroit ELEVATE Track 2
Detroit ELEVATE Track 2Joshua Birk
 

Was ist angesagt? (19)

Client-side Auth with Ember.js
Client-side Auth with Ember.jsClient-side Auth with Ember.js
Client-side Auth with Ember.js
 
Modern Android Architecture
Modern Android ArchitectureModern Android Architecture
Modern Android Architecture
 
Tame Accidental Complexity with Ruby and MongoMapper
Tame Accidental Complexity with Ruby and MongoMapperTame Accidental Complexity with Ruby and MongoMapper
Tame Accidental Complexity with Ruby and MongoMapper
 
TDC2017 | São Paulo - Trilha Java EE How we figured out we had a SRE team at ...
TDC2017 | São Paulo - Trilha Java EE How we figured out we had a SRE team at ...TDC2017 | São Paulo - Trilha Java EE How we figured out we had a SRE team at ...
TDC2017 | São Paulo - Trilha Java EE How we figured out we had a SRE team at ...
 
Webit expo Standard Product
Webit expo Standard ProductWebit expo Standard Product
Webit expo Standard Product
 
.NET Fest 2017. Михаил Щербаков. Механизмы предотвращения атак в ASP.NET Core
.NET Fest 2017. Михаил Щербаков. Механизмы предотвращения атак в ASP.NET Core.NET Fest 2017. Михаил Щербаков. Механизмы предотвращения атак в ASP.NET Core
.NET Fest 2017. Михаил Щербаков. Механизмы предотвращения атак в ASP.NET Core
 
Top Ten Web Defenses - DefCamp 2012
Top Ten Web Defenses  - DefCamp 2012Top Ten Web Defenses  - DefCamp 2012
Top Ten Web Defenses - DefCamp 2012
 
Nagios Conference 2014 - Troy Lea - JavaScript and jQuery - Nagios XI Tips, T...
Nagios Conference 2014 - Troy Lea - JavaScript and jQuery - Nagios XI Tips, T...Nagios Conference 2014 - Troy Lea - JavaScript and jQuery - Nagios XI Tips, T...
Nagios Conference 2014 - Troy Lea - JavaScript and jQuery - Nagios XI Tips, T...
 
Open Selector
Open SelectorOpen Selector
Open Selector
 
WordPress as an application framework
WordPress as an application frameworkWordPress as an application framework
WordPress as an application framework
 
Hacking Your Way to Better Security - PHP South Africa 2016
Hacking Your Way to Better Security - PHP South Africa 2016Hacking Your Way to Better Security - PHP South Africa 2016
Hacking Your Way to Better Security - PHP South Africa 2016
 
Hacking Your Way To Better Security
Hacking Your Way To Better SecurityHacking Your Way To Better Security
Hacking Your Way To Better Security
 
Taming forms with React
Taming forms with ReactTaming forms with React
Taming forms with React
 
Modularized Persistence - B Zsoldos
Modularized Persistence - B ZsoldosModularized Persistence - B Zsoldos
Modularized Persistence - B Zsoldos
 
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)
 
Integrating OAuth and Social Login Into Wordpress
Integrating OAuth and Social Login Into WordpressIntegrating OAuth and Social Login Into Wordpress
Integrating OAuth and Social Login Into Wordpress
 
Présentation et bonnes pratiques du pattern MVVM - MIC Belgique
Présentation et bonnes pratiques du pattern MVVM - MIC BelgiquePrésentation et bonnes pratiques du pattern MVVM - MIC Belgique
Présentation et bonnes pratiques du pattern MVVM - MIC Belgique
 
FormsKit: reactive forms driven by state. UA Mobile 2017.
FormsKit: reactive forms driven by state. UA Mobile 2017.FormsKit: reactive forms driven by state. UA Mobile 2017.
FormsKit: reactive forms driven by state. UA Mobile 2017.
 
Detroit ELEVATE Track 2
Detroit ELEVATE Track 2Detroit ELEVATE Track 2
Detroit ELEVATE Track 2
 

Andere mochten auch

Sql injection - security testing
Sql injection - security testingSql injection - security testing
Sql injection - security testingNapendra Singh
 
Seminar rus
Seminar rusSeminar rus
Seminar rusgayanep
 
Cyber crime an eye opener 144 te 2 t-7
Cyber crime an eye opener  144 te 2 t-7Cyber crime an eye opener  144 te 2 t-7
Cyber crime an eye opener 144 te 2 t-7Gargee Hiray
 
DefCon 2012 - Near-Field Communication / RFID Hacking - Lee
DefCon 2012 - Near-Field Communication / RFID Hacking - LeeDefCon 2012 - Near-Field Communication / RFID Hacking - Lee
DefCon 2012 - Near-Field Communication / RFID Hacking - LeeMichael Smith
 
DEFCON 17 Presentation: CSRF - Yeah, It Still Works
DEFCON 17 Presentation: CSRF - Yeah, It Still WorksDEFCON 17 Presentation: CSRF - Yeah, It Still Works
DEFCON 17 Presentation: CSRF - Yeah, It Still WorksRuss McRee
 
Black hat and defcon 2014
Black hat and defcon 2014Black hat and defcon 2014
Black hat and defcon 2014Peter Swedin
 
Defcon 17 Tactical Fingerprinting using Foca
Defcon 17   Tactical Fingerprinting using FocaDefcon 17   Tactical Fingerprinting using Foca
Defcon 17 Tactical Fingerprinting using FocaChema Alonso
 
Advanced cfg bypass on adobe flash player 18 defcon russia 23
Advanced cfg bypass on adobe flash player 18 defcon russia 23Advanced cfg bypass on adobe flash player 18 defcon russia 23
Advanced cfg bypass on adobe flash player 18 defcon russia 23DefconRussia
 
Art of Trolling Defcon 19
Art of Trolling Defcon 19Art of Trolling Defcon 19
Art of Trolling Defcon 19openfly
 
Defcon 18 "Hacking Electronic Door Access Controllers"
Defcon 18  "Hacking Electronic Door Access Controllers" Defcon 18  "Hacking Electronic Door Access Controllers"
Defcon 18 "Hacking Electronic Door Access Controllers" shawn_merdinger
 
New techniques in sql obfuscation, from DEFCON 20
New techniques in sql obfuscation, from DEFCON 20New techniques in sql obfuscation, from DEFCON 20
New techniques in sql obfuscation, from DEFCON 20Nick Galbreath
 
[Defcon] Hardware backdooring is practical
[Defcon] Hardware backdooring is practical[Defcon] Hardware backdooring is practical
[Defcon] Hardware backdooring is practicalMoabi.com
 
DEFCON17 - Your Mind: Legal Status, Rights and Securing Yourself
DEFCON17 - Your Mind: Legal Status, Rights and Securing YourselfDEFCON17 - Your Mind: Legal Status, Rights and Securing Yourself
DEFCON17 - Your Mind: Legal Status, Rights and Securing YourselfJames Arlen
 
Defcon 22-anton-sapozhnikov-acquire-current-user-hashes-with
Defcon 22-anton-sapozhnikov-acquire-current-user-hashes-withDefcon 22-anton-sapozhnikov-acquire-current-user-hashes-with
Defcon 22-anton-sapozhnikov-acquire-current-user-hashes-withPriyanka Aash
 
Web Security: SQL Injection
Web Security: SQL InjectionWeb Security: SQL Injection
Web Security: SQL InjectionVortana Say
 
Am I being spied on: Low-tech ways of detecting high-tech surveillance (DEFCO...
Am I being spied on: Low-tech ways of detecting high-tech surveillance (DEFCO...Am I being spied on: Low-tech ways of detecting high-tech surveillance (DEFCO...
Am I being spied on: Low-tech ways of detecting high-tech surveillance (DEFCO...Philip Polstra
 
Defcon 22-quaddi-r3plicant-hefley-hacking-911
Defcon 22-quaddi-r3plicant-hefley-hacking-911Defcon 22-quaddi-r3plicant-hefley-hacking-911
Defcon 22-quaddi-r3plicant-hefley-hacking-911Priyanka Aash
 
THE EFFECTS OF SOCIAL NETWORKING SITES ON THE ACADEMIC PERFORMANCE OF STUDENT...
THE EFFECTS OF SOCIAL NETWORKING SITES ON THE ACADEMIC PERFORMANCE OF STUDENT...THE EFFECTS OF SOCIAL NETWORKING SITES ON THE ACADEMIC PERFORMANCE OF STUDENT...
THE EFFECTS OF SOCIAL NETWORKING SITES ON THE ACADEMIC PERFORMANCE OF STUDENT...Kasthuripriya Nanda Kumar
 

Andere mochten auch (20)

Sql injection - security testing
Sql injection - security testingSql injection - security testing
Sql injection - security testing
 
Seminar rus
Seminar rusSeminar rus
Seminar rus
 
Cyber crime an eye opener 144 te 2 t-7
Cyber crime an eye opener  144 te 2 t-7Cyber crime an eye opener  144 te 2 t-7
Cyber crime an eye opener 144 te 2 t-7
 
DefCon 2012 - Near-Field Communication / RFID Hacking - Lee
DefCon 2012 - Near-Field Communication / RFID Hacking - LeeDefCon 2012 - Near-Field Communication / RFID Hacking - Lee
DefCon 2012 - Near-Field Communication / RFID Hacking - Lee
 
DEFCON 17 Presentation: CSRF - Yeah, It Still Works
DEFCON 17 Presentation: CSRF - Yeah, It Still WorksDEFCON 17 Presentation: CSRF - Yeah, It Still Works
DEFCON 17 Presentation: CSRF - Yeah, It Still Works
 
Black hat and defcon 2014
Black hat and defcon 2014Black hat and defcon 2014
Black hat and defcon 2014
 
Defcon 17 Tactical Fingerprinting using Foca
Defcon 17   Tactical Fingerprinting using FocaDefcon 17   Tactical Fingerprinting using Foca
Defcon 17 Tactical Fingerprinting using Foca
 
Advanced cfg bypass on adobe flash player 18 defcon russia 23
Advanced cfg bypass on adobe flash player 18 defcon russia 23Advanced cfg bypass on adobe flash player 18 defcon russia 23
Advanced cfg bypass on adobe flash player 18 defcon russia 23
 
Art of Trolling Defcon 19
Art of Trolling Defcon 19Art of Trolling Defcon 19
Art of Trolling Defcon 19
 
Defcon 18 "Hacking Electronic Door Access Controllers"
Defcon 18  "Hacking Electronic Door Access Controllers" Defcon 18  "Hacking Electronic Door Access Controllers"
Defcon 18 "Hacking Electronic Door Access Controllers"
 
New techniques in sql obfuscation, from DEFCON 20
New techniques in sql obfuscation, from DEFCON 20New techniques in sql obfuscation, from DEFCON 20
New techniques in sql obfuscation, from DEFCON 20
 
[Defcon] Hardware backdooring is practical
[Defcon] Hardware backdooring is practical[Defcon] Hardware backdooring is practical
[Defcon] Hardware backdooring is practical
 
DEFCON17 - Your Mind: Legal Status, Rights and Securing Yourself
DEFCON17 - Your Mind: Legal Status, Rights and Securing YourselfDEFCON17 - Your Mind: Legal Status, Rights and Securing Yourself
DEFCON17 - Your Mind: Legal Status, Rights and Securing Yourself
 
Defcon 22-anton-sapozhnikov-acquire-current-user-hashes-with
Defcon 22-anton-sapozhnikov-acquire-current-user-hashes-withDefcon 22-anton-sapozhnikov-acquire-current-user-hashes-with
Defcon 22-anton-sapozhnikov-acquire-current-user-hashes-with
 
Web Security: SQL Injection
Web Security: SQL InjectionWeb Security: SQL Injection
Web Security: SQL Injection
 
Am I being spied on: Low-tech ways of detecting high-tech surveillance (DEFCO...
Am I being spied on: Low-tech ways of detecting high-tech surveillance (DEFCO...Am I being spied on: Low-tech ways of detecting high-tech surveillance (DEFCO...
Am I being spied on: Low-tech ways of detecting high-tech surveillance (DEFCO...
 
Defcon 22-quaddi-r3plicant-hefley-hacking-911
Defcon 22-quaddi-r3plicant-hefley-hacking-911Defcon 22-quaddi-r3plicant-hefley-hacking-911
Defcon 22-quaddi-r3plicant-hefley-hacking-911
 
Sql Injection Myths and Fallacies
Sql Injection Myths and FallaciesSql Injection Myths and Fallacies
Sql Injection Myths and Fallacies
 
THE EFFECTS OF SOCIAL NETWORKING SITES ON THE ACADEMIC PERFORMANCE OF STUDENT...
THE EFFECTS OF SOCIAL NETWORKING SITES ON THE ACADEMIC PERFORMANCE OF STUDENT...THE EFFECTS OF SOCIAL NETWORKING SITES ON THE ACADEMIC PERFORMANCE OF STUDENT...
THE EFFECTS OF SOCIAL NETWORKING SITES ON THE ACADEMIC PERFORMANCE OF STUDENT...
 
Ethics
EthicsEthics
Ethics
 

Ähnlich wie 8 sql injection

20111204 web security_livshits_lecture01
20111204 web security_livshits_lecture0120111204 web security_livshits_lecture01
20111204 web security_livshits_lecture01Computer Science Club
 
03. sql and other injection module v17
03. sql and other injection module v1703. sql and other injection module v17
03. sql and other injection module v17Eoin Keary
 
Php Security - OWASP
Php  Security - OWASPPhp  Security - OWASP
Php Security - OWASPMizno Kruge
 
Advanced Topics On Sql Injection Protection
Advanced Topics On Sql Injection ProtectionAdvanced Topics On Sql Injection Protection
Advanced Topics On Sql Injection Protectionamiable_indian
 
SQL Injections - 2016 - Huntington Beach
SQL Injections - 2016 - Huntington BeachSQL Injections - 2016 - Huntington Beach
SQL Injections - 2016 - Huntington BeachJeff Prom
 
How "·$% developers defeat the web vulnerability scanners
How "·$% developers defeat the web vulnerability scannersHow "·$% developers defeat the web vulnerability scanners
How "·$% developers defeat the web vulnerability scannersChema Alonso
 
Chapter 14 sql injection
Chapter 14 sql injectionChapter 14 sql injection
Chapter 14 sql injectionnewbie2019
 
Securing the Web@VoxxedDays2017
Securing the Web@VoxxedDays2017Securing the Web@VoxxedDays2017
Securing the Web@VoxxedDays2017Sumanth Damarla
 
Application Security around OWASP Top 10
Application Security around OWASP Top 10Application Security around OWASP Top 10
Application Security around OWASP Top 10Sastry Tumuluri
 
Code injection and green sql
Code injection and green sqlCode injection and green sql
Code injection and green sqlKaustav Sengupta
 
07 application security fundamentals - part 2 - security mechanisms - data ...
07   application security fundamentals - part 2 - security mechanisms - data ...07   application security fundamentals - part 2 - security mechanisms - data ...
07 application security fundamentals - part 2 - security mechanisms - data ...appsec
 
Asegúr@IT IV - Remote File Downloading
Asegúr@IT IV - Remote File DownloadingAsegúr@IT IV - Remote File Downloading
Asegúr@IT IV - Remote File DownloadingChema Alonso
 
Understanding and preventing sql injection attacks
Understanding and preventing sql injection attacksUnderstanding and preventing sql injection attacks
Understanding and preventing sql injection attacksKevin Kline
 
Types of sql injection attacks
Types of sql injection attacksTypes of sql injection attacks
Types of sql injection attacksRespa Peter
 

Ähnlich wie 8 sql injection (20)

20111204 web security_livshits_lecture01
20111204 web security_livshits_lecture0120111204 web security_livshits_lecture01
20111204 web security_livshits_lecture01
 
Sql injection
Sql injectionSql injection
Sql injection
 
03. sql and other injection module v17
03. sql and other injection module v1703. sql and other injection module v17
03. sql and other injection module v17
 
Php Security - OWASP
Php  Security - OWASPPhp  Security - OWASP
Php Security - OWASP
 
Advanced Topics On Sql Injection Protection
Advanced Topics On Sql Injection ProtectionAdvanced Topics On Sql Injection Protection
Advanced Topics On Sql Injection Protection
 
Sql Injection V.2
Sql Injection V.2Sql Injection V.2
Sql Injection V.2
 
Sql injection
Sql injectionSql injection
Sql injection
 
SQL Injections - 2016 - Huntington Beach
SQL Injections - 2016 - Huntington BeachSQL Injections - 2016 - Huntington Beach
SQL Injections - 2016 - Huntington Beach
 
Sql injection
Sql injectionSql injection
Sql injection
 
How "·$% developers defeat the web vulnerability scanners
How "·$% developers defeat the web vulnerability scannersHow "·$% developers defeat the web vulnerability scanners
How "·$% developers defeat the web vulnerability scanners
 
Chapter 14 sql injection
Chapter 14 sql injectionChapter 14 sql injection
Chapter 14 sql injection
 
Securing the Web@VoxxedDays2017
Securing the Web@VoxxedDays2017Securing the Web@VoxxedDays2017
Securing the Web@VoxxedDays2017
 
Application Security around OWASP Top 10
Application Security around OWASP Top 10Application Security around OWASP Top 10
Application Security around OWASP Top 10
 
Code injection and green sql
Code injection and green sqlCode injection and green sql
Code injection and green sql
 
Greensql2007
Greensql2007Greensql2007
Greensql2007
 
07 application security fundamentals - part 2 - security mechanisms - data ...
07   application security fundamentals - part 2 - security mechanisms - data ...07   application security fundamentals - part 2 - security mechanisms - data ...
07 application security fundamentals - part 2 - security mechanisms - data ...
 
Asegúr@IT IV - Remote File Downloading
Asegúr@IT IV - Remote File DownloadingAsegúr@IT IV - Remote File Downloading
Asegúr@IT IV - Remote File Downloading
 
Understanding and preventing sql injection attacks
Understanding and preventing sql injection attacksUnderstanding and preventing sql injection attacks
Understanding and preventing sql injection attacks
 
Types of sql injection attacks
Types of sql injection attacksTypes of sql injection attacks
Types of sql injection attacks
 
2nd-Order-SQLi-Josh
2nd-Order-SQLi-Josh2nd-Order-SQLi-Josh
2nd-Order-SQLi-Josh
 

Mehr von drewz lin

Web security-–-everything-we-know-is-wrong-eoin-keary
Web security-–-everything-we-know-is-wrong-eoin-kearyWeb security-–-everything-we-know-is-wrong-eoin-keary
Web security-–-everything-we-know-is-wrong-eoin-kearydrewz lin
 
Via forensics appsecusa-nov-2013
Via forensics appsecusa-nov-2013Via forensics appsecusa-nov-2013
Via forensics appsecusa-nov-2013drewz lin
 
Phu appsec13
Phu appsec13Phu appsec13
Phu appsec13drewz lin
 
Owasp2013 johannesullrich
Owasp2013 johannesullrichOwasp2013 johannesullrich
Owasp2013 johannesullrichdrewz lin
 
Owasp advanced mobile-application-code-review-techniques-v0.2
Owasp advanced mobile-application-code-review-techniques-v0.2Owasp advanced mobile-application-code-review-techniques-v0.2
Owasp advanced mobile-application-code-review-techniques-v0.2drewz lin
 
I mas appsecusa-nov13-v2
I mas appsecusa-nov13-v2I mas appsecusa-nov13-v2
I mas appsecusa-nov13-v2drewz lin
 
Defeating xss-and-xsrf-with-my faces-frameworks-steve-wolf
Defeating xss-and-xsrf-with-my faces-frameworks-steve-wolfDefeating xss-and-xsrf-with-my faces-frameworks-steve-wolf
Defeating xss-and-xsrf-with-my faces-frameworks-steve-wolfdrewz lin
 
Csrf not-all-defenses-are-created-equal
Csrf not-all-defenses-are-created-equalCsrf not-all-defenses-are-created-equal
Csrf not-all-defenses-are-created-equaldrewz lin
 
Chuck willis-owaspbwa-beyond-1.0-app secusa-2013-11-21
Chuck willis-owaspbwa-beyond-1.0-app secusa-2013-11-21Chuck willis-owaspbwa-beyond-1.0-app secusa-2013-11-21
Chuck willis-owaspbwa-beyond-1.0-app secusa-2013-11-21drewz lin
 
Appsec usa roberthansen
Appsec usa roberthansenAppsec usa roberthansen
Appsec usa roberthansendrewz lin
 
Appsec usa2013 js_libinsecurity_stefanodipaola
Appsec usa2013 js_libinsecurity_stefanodipaolaAppsec usa2013 js_libinsecurity_stefanodipaola
Appsec usa2013 js_libinsecurity_stefanodipaoladrewz lin
 
Appsec2013 presentation-dickson final-with_all_final_edits
Appsec2013 presentation-dickson final-with_all_final_editsAppsec2013 presentation-dickson final-with_all_final_edits
Appsec2013 presentation-dickson final-with_all_final_editsdrewz lin
 
Appsec2013 presentation
Appsec2013 presentationAppsec2013 presentation
Appsec2013 presentationdrewz lin
 
Appsec 2013-krehel-ondrej-forensic-investigations-of-web-exploitations
Appsec 2013-krehel-ondrej-forensic-investigations-of-web-exploitationsAppsec 2013-krehel-ondrej-forensic-investigations-of-web-exploitations
Appsec 2013-krehel-ondrej-forensic-investigations-of-web-exploitationsdrewz lin
 
Appsec2013 assurance tagging-robert martin
Appsec2013 assurance tagging-robert martinAppsec2013 assurance tagging-robert martin
Appsec2013 assurance tagging-robert martindrewz lin
 
Amol scadaowasp
Amol scadaowaspAmol scadaowasp
Amol scadaowaspdrewz lin
 
Agile sdlc-v1.1-owasp-app sec-usa
Agile sdlc-v1.1-owasp-app sec-usaAgile sdlc-v1.1-owasp-app sec-usa
Agile sdlc-v1.1-owasp-app sec-usadrewz lin
 
Vulnex app secusa2013
Vulnex app secusa2013Vulnex app secusa2013
Vulnex app secusa2013drewz lin
 
基于虚拟化技术的分布式软件测试框架
基于虚拟化技术的分布式软件测试框架基于虚拟化技术的分布式软件测试框架
基于虚拟化技术的分布式软件测试框架drewz lin
 
新浪微博稳定性经验谈
新浪微博稳定性经验谈新浪微博稳定性经验谈
新浪微博稳定性经验谈drewz lin
 

Mehr von drewz lin (20)

Web security-–-everything-we-know-is-wrong-eoin-keary
Web security-–-everything-we-know-is-wrong-eoin-kearyWeb security-–-everything-we-know-is-wrong-eoin-keary
Web security-–-everything-we-know-is-wrong-eoin-keary
 
Via forensics appsecusa-nov-2013
Via forensics appsecusa-nov-2013Via forensics appsecusa-nov-2013
Via forensics appsecusa-nov-2013
 
Phu appsec13
Phu appsec13Phu appsec13
Phu appsec13
 
Owasp2013 johannesullrich
Owasp2013 johannesullrichOwasp2013 johannesullrich
Owasp2013 johannesullrich
 
Owasp advanced mobile-application-code-review-techniques-v0.2
Owasp advanced mobile-application-code-review-techniques-v0.2Owasp advanced mobile-application-code-review-techniques-v0.2
Owasp advanced mobile-application-code-review-techniques-v0.2
 
I mas appsecusa-nov13-v2
I mas appsecusa-nov13-v2I mas appsecusa-nov13-v2
I mas appsecusa-nov13-v2
 
Defeating xss-and-xsrf-with-my faces-frameworks-steve-wolf
Defeating xss-and-xsrf-with-my faces-frameworks-steve-wolfDefeating xss-and-xsrf-with-my faces-frameworks-steve-wolf
Defeating xss-and-xsrf-with-my faces-frameworks-steve-wolf
 
Csrf not-all-defenses-are-created-equal
Csrf not-all-defenses-are-created-equalCsrf not-all-defenses-are-created-equal
Csrf not-all-defenses-are-created-equal
 
Chuck willis-owaspbwa-beyond-1.0-app secusa-2013-11-21
Chuck willis-owaspbwa-beyond-1.0-app secusa-2013-11-21Chuck willis-owaspbwa-beyond-1.0-app secusa-2013-11-21
Chuck willis-owaspbwa-beyond-1.0-app secusa-2013-11-21
 
Appsec usa roberthansen
Appsec usa roberthansenAppsec usa roberthansen
Appsec usa roberthansen
 
Appsec usa2013 js_libinsecurity_stefanodipaola
Appsec usa2013 js_libinsecurity_stefanodipaolaAppsec usa2013 js_libinsecurity_stefanodipaola
Appsec usa2013 js_libinsecurity_stefanodipaola
 
Appsec2013 presentation-dickson final-with_all_final_edits
Appsec2013 presentation-dickson final-with_all_final_editsAppsec2013 presentation-dickson final-with_all_final_edits
Appsec2013 presentation-dickson final-with_all_final_edits
 
Appsec2013 presentation
Appsec2013 presentationAppsec2013 presentation
Appsec2013 presentation
 
Appsec 2013-krehel-ondrej-forensic-investigations-of-web-exploitations
Appsec 2013-krehel-ondrej-forensic-investigations-of-web-exploitationsAppsec 2013-krehel-ondrej-forensic-investigations-of-web-exploitations
Appsec 2013-krehel-ondrej-forensic-investigations-of-web-exploitations
 
Appsec2013 assurance tagging-robert martin
Appsec2013 assurance tagging-robert martinAppsec2013 assurance tagging-robert martin
Appsec2013 assurance tagging-robert martin
 
Amol scadaowasp
Amol scadaowaspAmol scadaowasp
Amol scadaowasp
 
Agile sdlc-v1.1-owasp-app sec-usa
Agile sdlc-v1.1-owasp-app sec-usaAgile sdlc-v1.1-owasp-app sec-usa
Agile sdlc-v1.1-owasp-app sec-usa
 
Vulnex app secusa2013
Vulnex app secusa2013Vulnex app secusa2013
Vulnex app secusa2013
 
基于虚拟化技术的分布式软件测试框架
基于虚拟化技术的分布式软件测试框架基于虚拟化技术的分布式软件测试框架
基于虚拟化技术的分布式软件测试框架
 
新浪微博稳定性经验谈
新浪微博稳定性经验谈新浪微博稳定性经验谈
新浪微博稳定性经验谈
 

8 sql injection

  • 1. CHAPTER 8 SQL Injection Slides adapted from "Foundations of Security: What Every Programmer Needs To Know" by Neil Daswani, Christoph Kern, and Anita Kesavan (ISBN 1590597842; http://www.foundationsofsecurity.com). Except as otherwise noted, the content of this presentation is licensed under the Creative Commons 3.0 License.
  • 2. Agenda  Command injection vulnerability - untrusted input inserted into query or command  Attackstring alters intended semantics of command  Ex: SQL Injection - unsanitized data used in query to back-end database (DB)  SQL Injection Examples & Solutions  Type 1: compromises user data  Type 2: modifies critical data  Whitelisting over Blacklisting  Escaping  Prepared Statements and Bind Variables
  • 3. SQL Injection Impact in the Real World  CardSystems, credit card payment processing  Ruined by SQL Injection attack in June 2005  263,000 credit card #s stolen from its DB  #s stored unencrypted, 40 million exposed  Awareness Increasing: # of reported SQL injection vulnerabilities tripled from 2004 to 2005
  • 4. 8.1. Attack Scenario (1)  Ex: Pizza Site Reviewing Orders  Form requesting month # to view orders for  HTTP request: https://www.deliver-me-pizza.com/show_orders?month=10
  • 5. 8.1. Attack Scenario (2)  App constructs SQL query from parameter: sql_query = "SELECT pizza, toppings, quantity, order_day " + "FROM orders " + "WHERE userid=" + session.getCurrentUserId() + " " + "AND order_month=" + request.getParamenter("month"); Normal SELECT pizza, toppings, quantity, order_day FROM orders WHERE userid=4123 SQL AND order_month=10 Query  Type 1 Attack: inputs month='0 OR 1=1' !  Goes to encoded URL: (space -> %20, = -> %3D) https://www.deliver-me-pizza.com/show_orders?month=0%20OR%201%3D1
  • 6. 8.1. Attack Scenario (3) Malicious SELECT pizza, FROM orders toppings, quantity, order_day WHERE userid=4123 Query AND order_month=0 OR 1=1  WHERE condition is always true!  OR precedes AND  Type 1 Attack: Gains access to other users’ private data! All User Data Compromised
  • 7. 8.1. Attack Scenario (4)  More damaging attack: attacker sets month= 0 AND 1=0 UNION SELECT cardholder, number, exp_month, exp_year FROM creditcards  Attacker is able to  Combine 2 queries  1st query: empty table (where fails)  2nd query: credit card #s of all users
  • 8. 8.1. Attack Scenario (4)  Even worse, attacker sets month=0; DROP TABLE creditcards;  Then DB executes SELECT pizza, toppings,  Type 2 Attack: quantity, order_day Removes creditcards FROM orders from schema! WHERE userid=4123  Future orders fail: DoS! AND order_month=0; DROP TABLE creditcards;  Problematic Statements:  Modifiers: INSERT INTO admin_users VALUES ('hacker',...)  Administrative: shut down DB, control OS…
  • 9. 8.1. Attack Scenario (5)  Injecting String Parameters: Topping Search sql_query = "SELECT pizza, toppings, quantity, order_day " + "FROM orders " + "WHERE userid=" + session.getCurrentUserId() + " " + "AND topping LIKE '%" + request.getParamenter("topping") + "%' ";  Attacker sets: topping=brzfg%'; DROP table creditcards; --  Query evaluates as: SELECT pizza, toppings, quantity, order_day  SELECT: empty table FROM orders  -- comments out end WHERE userid=4123 AND topping LIKE '%brzfg%';  Credit card info dropped DROP table creditcards; --%'
  • 10. 8.1. Attack Scenario (6) Source: http://xkcd.com/327/
  • 11. 8.2. Solutions  Variety of Techniques: Defense-in-depth  Whitelisting over Blacklisting  Input Validation & Escaping  Use Prepared Statements & Bind Variables  Mitigate Impact
  • 12. 8.2.1. Why Blacklisting Does Not Work  Eliminating quotes enough (blacklist them)? sql_query = "SELECT pizza, toppings, quantity, order_day " + "FROM orders " + "WHERE userid=" + session.getCurrentUserId() + " " + "AND topping LIKE 'kill_quotes(request.getParamenter("topping")) + "%'";  kill_quotes (Java) removes single quotes: String kill_quotes(String str) { StringBuffer result = new StringBuffer(str.length()); for (int i = 0; i < str.length(); i++) { if (str.charAt(i) != ''') result.append(str.charAt(i)); } return result.toString(); }
  • 13. 8.2.1. Pitfalls of Blacklisting  Filter quotes, semicolons, whitespace, and…?  Could always miss a dangerous character  Blacklisting not comprehensive solution  Ex: kill_quotes() can’t prevent attacks against numeric parameters  May conflict with functional requirements  How to store O’Brien in DB if quotes blacklisted?
  • 14. 8.2.2. Whitelisting-Based Input Validation  Whitelisting – only allow input within well-defined set of safe values  setimplicitly defined through regular expressions  RegExp – pattern to match strings against  Ex: month parameter: non-negative integer  RegExp: ^[0-9]*$ - 0 or more digits, safe subset  The ^, $ match beginning and end of string  [0-9] matches a digit, * specifies 0 or more
  • 15. 8.2.3. Escaping  Could escape quotes instead of blacklisting  Ex: insert user o'connor, password terminator sql = "INSERT INTO USERS(uname,passwd) " + "VALUES (" + escape(uname)+ "," + escape(password) +")";  escape(o'connor) = o''connor INSERT INTO USERS(uname,passwd) VALUES ('o''connor','terminator');  Like kill_quotes, only works for string inputs  Numeric parameters could still be vulnerable
  • 16. 8.2.4. Second-Order SQL Injection (1)  Second-Order SQL Injection: data stored in database is later used to conduct SQL injection  Common if string escaping is applied inconsistently  Ex: o'connor updates passwd to SkYn3t new_passwd = request.getParameter("new_passwd"); uname = session.getUsername(); sql = "UPDATE USERS SET passwd='"+ escape(new_passwd) + "' WHERE uname='" + uname + "'";  Username not escaped, b/c originally escaped before entering DB, now inside our trust zone: UPDATE USERS SET passwd='SkYn3t' WHERE uname='o'connor'  Query fails b/c ' after o ends command prematurely
  • 17. 8.2.4. Second-Order SQL Injection (2)  Even Worse: What if user set uname=admin'-- !? UPDATE USERS SET passwd='cracked' WHERE uname='admin' --'  Attacker changes admin’s password to cracked  Has full access to admin account  Username avoids collision with real admin  -- comments out trailing quote  All parameters dangerous: escape(uname)
  • 18. 8.2.5. Prepared Statements & Bind Variables  Metachars (e.g. quotes) provide distinction between data & control in queries  most attacks: data interpreted as control  alters the semantics of a query  Bind Variables: ? placeholders guaranteed to be data (not control)  Prepared Statements allow creation of static queries with bind variables  Preservesthe structure of intended query  Parameters not involved in query parsing/compiling
  • 19. 8.2.5. Java Prepared Statements PreparedStatement ps = db.prepareStatement("SELECT pizza, toppings, quantity, order_day " + "FROM orders WHERE userid=? AND order_month=?"); ps.setInt(1, session.getCurrentUserId()); ps.setInt(2, Integer.parseInt(request.getParamenter("month"))); ResultSet res = ps.executeQuery(); Bind Variable: Data Placeholder  Query parsed without parameters  Bind variables are typed: input must be of expected type (e.g. int, string)
  • 20. 8.2.5. PHP Prepared Statements $ps = $db->prepare( 'SELECT pizza, toppings, quantity, order_day '. 'FROM orders WHERE userid=? AND order_month=?'); $ps->execute(array($current_user_id, $month));  No explicit typing of parameters like in Java  Apply consistently: adding $year parameter directly to query still creates SQL injection threat  Have separate module for DB access  Do prepared statements here  Gateway to DB for rest of code
  • 21. 8.2.5. SQL Stored Procedures  Stored procedure: sequence of SQL statements executing on specified inputs CREATE PROCEDURE change_password  Ex: @username VARCHAR(25), @new_passwd VARCHAR(25) AS UPDATE USERS SET passwd=new_passwd WHERE uname=username  Vulnerable use: $db->exec("change_password '"+$uname+"','"+new_passwd+"'");  Instead use bind variables w/ stored procedure: $ps = $db->prepare("change_password ?, ?"); $ps->execute(array($uname, $new_passwd));
  • 22. 8.2.6. Mitigating the Impact of SQL Injection Attacks  Prevent Schema & Information Leaks  Limit Privileges (Defense-in-Depth)  Encrypt Sensitive Data stored in Database  Harden DB Server and Host O/S  Apply Input Validation
  • 23. 8.2.6. Prevent Schema & Information Leaks  Knowing database schema makes attacker’s job easier  Blind SQL Injection: attacker attempts to interrogate system to figure out schema  Prevent leakages of schema information  Don’t display detailed error messages and stack traces to external users
  • 24. 8.2.6. Limiting Privileges  Apply Principle of Least Privilege! Limit  Readaccess, tables/views user can query  Commands (are updates/inserts ok?)  No more privileges than typical user needs  Ex: could prevent attacker from executing INSERT and DROP statements  But could still be able do SELECT attacks and compromise user data  Not a complete fix, but less damage
  • 25. 8.2.6. Encrypting Sensitive Data  Encrypt data stored in the database  second line of defense  w/o key, attacker can’t read sensitive info  Key management precautions: don’t store key in DB, attacker just SQL injects again to get it  Some databases allow automatic encryption, but these still return plaintext queries!
  • 26. 8.2.6. Hardening DB Server and Host O/S  Dangerous functions could be on by default  Ex: Microsoft SQL Server  Allows users to open inbound/outbound sockets  Attacker could steal data, upload binaries, port scan victim’s network  Disable unused services and accounts on OS (Ex: No need for web server on DB host)
  • 27. 8.2.6. Applying Input Validation  Validation of query parameters not enough  Validate all input early at entry point into code  Reject overly long input (could prevent unknown buffer overflow exploit in SQL parser)  Redundancy helps protect systems  E.g.if programmer forgets to apply validation for query input  Two lines of defense
  • 28. Summary  SQL injection attacks are important security threat that can  Compromise sensitive user data  Alter or damage critical data  Give an attacker unwanted access to DB  Key Idea: Use diverse solutions, consistently!  Whitelisting input validation & escaping  Prepared Statements with bind variables

Hinweis der Redaktion

  1. Welcome to SEC103 on Secure Programming Techniques. In this course, I assume that you have some background in computer security, but now you want to put that background to use. For example, in the Computer Security Principles and Introduction To Cryptography courses, we cover topics such concerning trust and encryption. In this course, we put these principles into to practice, and I’ll show you have to write secure code that builds security into your applications from the ground up.