SQL Injection

SQL injection is a web security vulnerability that allows an attacker to interfere with the queries that an application makes to its database.

OWASP Top 10

  • A1:2017-Injection: Injection flaws, such as SQL, NoSQL, OS, and LDAP injection, occur when untrusted data is sent to an interpreter as part of a command or query. The attacker’s hostile data can trick the interpreter into executing unintended commands or accessing data without proper authorization.

Types of SQLi

  • In-Band (Classic) – Uses the same communication channel to attack and gather results
    • Error – Forces database to generate an error
    • Union – Leverages UNION SQL operator to combine results of two queries into a single result set
      • The number and order of columns must be the same in all queries
        • Attack using ORDER BY:
          • select title, cost from product where id =1 order by 1
          • Incrementally inject a series of ORDER BY clauses until you observe behavior changes
          • order by 1--
          • order by 2--
          • order by 3--
        • Attack using NULL VALUES:
          • select title, cost from product where id =1 UNION SELECT NULL--
          • ' UNION SELECT NULL--
          • ' UNION SELECT NULL, NULL--
      • The data types must be compatible
        • 'UNION SELECT 'a',NULL--
        • UNION SELECT NULL, 'a'
  • Inferential (Blind) – No actual transfer of data via the web application
    • Boolean – Uses boolean conditions to return a different results whether TRUE or FALSE
    • Time – Relies on the database pausing for a specified amount of time
  • Out-of-Band – Triggering an out-of-band network connection to a system that you control



  • Primary Defenses
    • Use of Prepared Statements (Parameterized Queries)
      • The application specifies the query’s structure with placeholders for each user input
      • The application specifies the content of each placeholder
    • Use of Stored Procedures (Partial) – Batch of statements grouped together and stored in the DB.
    • Whitelist Input Validation (Partial) – Defining what values are authorized.
    • Escaping all user supplied input (Partial)
  • Additional Defenses
    • Enforcing least privilege
    • Performing whitelist input validation

OWASP Prevention Cheat Sheet