CAPEC

Common Attack Pattern Enumeration and Classification
Common Attack Pattern Enumeration and Classification

A Community Knowledge Resource for Building Secure Software

Home > CAPEC List > Individual CAPEC Dictionary Definition (Release 1.1)   View the CAPEC List

Individual CAPEC Dictionary Definition (Release 1.1)
Individual CAPEC Dictionary Definition (Release 1.1)

SQL Injection
Attack Pattern ID
Pattern Abstraction: Standard

66

Typical Severity

High

Description

Summary


        This attack exploits target software that constructs SQL statements based on user input.  An attacker crafts input strings so that when the target software constructs SQL statements based on the input, the resulting SQL statement performs actions other than those the application intended.
        
        SQL Injection results from failure of the application to appropriately validate input. When specially crafted user-controlled input consisting of SQL syntax is used without proper validation as part of SQL queries, it is possible to glean information from the database in ways not envisaged during application design. Depending upon the database and the design of the application, it may also be possible to leverage injection to have the database execute system-related commands of the attacker's choice. SQL Injection enables an attacker to talk directly to the database, thus bypassing the application completely. Sucessful injection can cause information disclosure as well as ability to add or modify data in the database. In order to successfully inject SQL and retrieve information from a database, an attacker:

Attack Execution Flow

Explore
  1. Survey application: The attacker first takes an inventory of the functionality exposed by the application.

    Attack Step Techniques
    DescriptionEnvironments
    Spider web sites for all available linksenv-Web
    Sniff network communications with application using a utility such as WireShark.env-ClientServer env-Peer2Peer env-CommProtocol
    Outcomes
    IDTypeDescription
    c66s0o1SuccessAt least one data input to application identified.
    c66s0o2FailureNo inputs to application identified. Note that just because no inputs are identified does not mean that the application will not accept any.
Experiment
  1. Determine user-controllable input susceptible to injection: Determine the user-controllable input susceptible to injection. For each user-controllable input that the attacker suspects is vulnerable to SQL injection, attempt to inject characters that have special meaning in SQL (such as a single quote character, a double quote character, two hyphens, a paranthesis, etc.). The goal is to create a SQL query with an invalid syntax.

    Attack Step Techniques
    DescriptionEnvironments
    Use web browser to inject input through text fields or through HTTP GET parameters.env-Web
    Use a web application debugging tool such as Tamper Data, TamperIE, WebScarab,etc. to modify HTTP POST parameters, hidden fields, non-freeform fields, etc.env-Web
    Use network-level packet injection tools such as netcat to inject inputenv-Web env-ClientServer env-Peer2Peer env-CommProtocol
    Use modified client (modified by reverse engineering) to inject input.env-ClientServer env-Peer2Peer env-CommProtocol
    Indicators of Susceptibility
    IDTypeDescriptionEnvironments
    c66s1i1NegativeAttacker receives normal response from server.env-Web env-ClientServer env-Peer2Peer env-CommProtocol
    c66s1i2PositiveAttacker receives an error message from server indicating that there was a problem with the SQL query.env-Web env-ClientServer env-Peer2Peer env-CommProtocol
    c66s1i3NegativeServer sends a specific error message that indicates programmatic parsing of the input data (e.g. NumberFormatException)env-Web env-ClientServer env-Peer2Peer env-CommProtocol
    Outcomes
    IDTypeDescription
    c66s1o1SuccessAt least one user-controllable input susceptible to injection found.
    c66s1o2FailureNo user-controllable input susceptible to injection found.
    Security Controls
    IDTypeDescription
    c66s1sc1DetectiveSearch for and alert on unexpected SQL keywords in application logs (e.g. SELECT, DROP, etc.).
    c66s1sc2PreventativeInput validation of user-controlled data before including it in a SQL query
    c66s1sc3PreventativeUse parameterized queries (e.g. PreparedStatement in Java, and Command.Parameters.Add() to set query parameters in .NET)
  2. Experiment and try to exploit SQL Injection vulnerability: After determining that a given input is vulnerable to SQL Injection, hypothesize what the underlying query looks like. Iteratively try to add logic to the query to extract information from the database, or to modify or delete information in the database.

    Attack Step Techniques
    DescriptionEnvironments
    Use public resources such as "SQL Injection Cheat Sheet" at http://ferruh.mavituna.com/makale/sql-injection-cheatsheet/, and try different approaches for adding logic to SQL queries.env-Web env-ClientServer env-Peer2Peer env-CommProtocol
    Add logic to query, and use detailed error messages from the server to debug the query. For example, if adding a single quote to a query causes an error message, try : "' OR 1=1; --", or something else that would syntactically complete a hypothesized query. Iteratively refine the query.env-Web env-ClientServer env-Peer2Peer env-CommProtocol
    Use "Blind SQL Injection" techniques to extract information about the database schema.env-Web env-ClientServer env-Peer2Peer env-CommProtocol
    If a denial of service attack is the goal, try stacking queries. This does not work on all platforms (most notably, it does not work on Oracle or MySQL). Examples of inputs to try include: "'; DROP TABLE SYSOBJECTS; --" and "'); DROP TABLE SYSOBJECTS; --". These particular queries will likely not work because the SYSOBJECTS table is generally protected.env-Web env-ClientServer env-Peer2Peer env-CommProtocol
    Indicators of Susceptibility
    IDTypeDescriptionEnvironments
    c66s2i1PositiveSuccess outcome in previous step.env-Web env-ClientServer env-Peer2Peer env-CommProtocol
    c66s2i2NegativeFailure outcome in previous step.env-Web env-ClientServer env-Peer2Peer env-CommProtocol
    Outcomes
    IDTypeDescription
    c66s2o1SuccessAttacker achieves goal of unauthorized system access, denial of service, etc.
    c66s2o2FailureAttacker unable to exploit SQL Injection vulnerability.
Attack Prerequisites

SQL queries used by the application to store, retrieve or modify data.

User-controllable input that is not properly validated by the application as part of SQL queries.

Typical Likelihood of Exploit

Very High

Methods of Attack
  • Injection
Examples-Instances

Description

With PHP-Nuke versions 7.9 and earlier, an attacker can successfully access and modify data, including sensitive contents such as usernames and password hashes, and compromise the application through SQL Injection. The protection mechanism against SQL Injection employs a blacklist approach to input validation. However, because of improper blacklisting, it is possible to inject content such as "foo'/**/UNION" or "foo UNION/**/" to bypass validation and glean sensitive information from the database.

Related Vulnerability

CVE-2006-5525

Attacker Skill or Knowledge Required

Low - It is fairly simple for someone with basic SQL knowledge to perform SQL injection, in general. In certain instances, however, specific knowledge of the database employed may be required.

Resources Required

None

Probing Techniques

The attacker tries to inject characters that can cause a SQL error, such as single-quote (') or keywords such as "UNION" and "OR". If the injection of such characters into the input causes a SQL error and the resulting error is displayed unfiltered, the attacker can begin to determine the nature of input validation and structure of SQL queries. A typical error resulting from such injection would look like: "You have an error in your SQL Syntax. Check your manual for the right syntax to use near ') FROM db_users.user_table"

With available design documentation and code, the attacker can determine whether all user-controllable inputs are being validated or not, and also the structure of SQL queries that such inputs feed into.

Indicators-Warnings of Attack

Too many false or invalid queries to the database, especially those caused by malformed input.

Solutions and Mitigations

Strong input validation - All user-controllable input must be validated and filtered for illegal characters as well as SQL content. Keywords such as UNION, SELECT or INSERT must be filtered in addition to characters such as a single-quote(') or SQL-comments (--) based on the context in which they appear.

Use of parameterized queries or stored procedures - Parameterization causes the input to be restricted to certain domains, such as strings or integers, and any input outside such domains is considered invalid and the query fails. Note that SQL Injection is possible even in the presence of stored procedures if the eventual query is constructed dynamically.

Use of custom error pages - Attackers can glean information about the nature of queries from descriptive error messages. Input validation must be coupled with customized error pages that inform about an error without disclosing information about the database or application.

Attack Motivation-Consequences
  • Data Modification
  • Information Leakage
  • Run Arbitrary Code
  • Privilege Escalation
Context Description

SQL Injection results from a combination of factors. The primary cause is lack of appropriate input validation. In the absence of such validation, it becomes possible to inject arbitrary content, such as code, into the input. The second most important reason is use of dynamic SQL queries. It is a misconception that use of stored procedures makes the application immune to SQL Injection. It is important that input be parameterized to provide an additional line of defense, should input validation fail. Another factor that lets attackers discern information about the structure of queries and the application is use of default error pages and improper error handling. Descriptive error pages must be used only for debugging purposes. The motive of an attacker is to inject spurious content into input that does not get properly validated and is used as part of SQL queries. When the resulting error page is displayed, the attacker can determine the structure of queries as well as internal system information, leading to SQL Injection being successful.
      
      An important distinction needs to be made concerning first-order and second-order SQL Injection. With first-order injection, the results of injection are observed immediately in the form of an error message or a successful query resulting in attaining the attacker's motive. However, there are instances when the results of a successful injection are observed when a different query is executed or a different user accesses the application. For example, an attacker may enter
      ';DELETE recipes;--
      as input to a favorite recipe question. When the application is subsequently requested to retrieve details of the attacker's favorite recipe, a query such as:
      "SELECT descr FROM recipes WHERE recipe='"+rs.getString("Favorite")+"'";
      results in the following being executed:
      "SELECT descr FROM recipes WHERE recipe='';DELETE recipes;--
      which is valid SQL syntax and results in deletion of an entire table.
      This method of SQL Injection that involves subsequent access to injected data is known as second-order SQL Injection.
    

Injection Vector

User-controllable input used as part of non-parameterized SQL queries: This may include input fields on web forms, data in user-accessible files or even command-line parameters.

Payload

SQL statements intended to reveal information or run malicious code

Activation Zone

Back-end database

Payload Activation Impact

When malicious SQL content is executed by the database, it can lead to arbitrary queries being executed, causing disclosure of information, unauthorized access, privilege escalation and possibly system compromise.

Related Weaknesses
CWE-IDWeakness NameWeakness Relationship Type
89Failure to Sanitize Data into SQL Queries (aka 'SQL Injection')Targeted
74Failure to Sanitize Data into a Different Plane (aka 'Injection')Secondary
20Insufficient Input ValidationSecondary
390Detection of Error Condition Without ActionSecondary
Related Attack Patterns
IDNameRelationship TypeRelationship Description
7Blind SQL InjectionMore Abstract
Relevant Security Requirements

Special characters in user-controllable input must be escaped before use by the application.

Only use parameterized stored procedures to query the database.

Input data must be revalidated in the parameterized stored procedures.

Custom error pages must be used to handle exceptions such that they do not reveal any information about the architecture of the application or the database.

Related Security Principles
  • Reluctance to Trust
  • Failing Securely
  • Defense in Depth
Related Guidelines
  • Never Use Input as Part of a Directive to any Internal Component
  • Handle All Errors Safely
Purpose

Penetration

Exploitation

CIA Impact
Confidentiality ImpactIntegrity ImpactAvailability Impact
HighHighHigh
Technical Context
Architectural ParadigmFrameworkPlatformLanguage
AllAllAllAll
References

CWE - SQL Injection

CWE - Input Validation

CWE - Improper Error Handling

Source
Submission(s)
SubmitterOrganizationDateComment
Chiradeep B Chhaya2007-01-12Second Draft
Modification(s)
ModifierOrganizationDateComment
Malik HamroCigital, Inc2007-02-27Reformat to new schema and review
Sean BarnumCigital, Inc2007-03-05Review and revise
Richard StruseVOXEM, Inc2007-03-26Review and feedback leading to changes in Description and Related Attack Patterns
Sean BarnumCigital, Inc2007-04-13Modified pattern content according to review and feedback
 
Page Last Updated: April 18, 2008