Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

A SQL injection vulnerability arises when the original SQL query can be altered to form an altogether different query. Execution of this altered query may result in information leaks or data vulnerabilities arise in applications where elements of a SQL query originate from an untrusted source. Without precautions, the untrusted data may maliciously alter the query, resulting in information leaks or data modification. The primary means of preventing SQL injection are sanitizing and validating untrusted input and parameterizing queries sanitization and validation, which are typically implemented as parameterized queries and stored procedures.

Suppose a database contains user names and passwords used to authenticate users of the system. A SQL command to authenticate a user might take the following form:system authenticates users by issuing the following query to a SQL database. If the query returns any results, authentication succeeds; otherwise, authentication fails.

code
Code Block
languagesql
SELECT * FROM db_user WHERE username='<USERNAME>' AND 
                            password='<PASSWORD>'

If it returns any records, the user name and password are valid.

Suppose However, if an attacker can substitute arbitrary strings for <USERNAME> and <PASSWORD>, they can perform a SQL injection by using the following string for <USERNAME>. In that case, the authentication mechanism can be bypassed by supplying the following <USERNAME> with an arbitrary password:

Code Block
languagesql
validuser' OR '1'='1

When injected into the command, the command becomes

The authentication routine dynamically constructs the following query:

code
Code Block
languagesql
SELECT * FROM db_user WHERE username='validuser' OR '1'='1' AND password='<PASSWORD>'

If validuser is a valid user name, this SELECT statement selects yields the validuser record in the table. The password is never checked because username='validuser' is true; consequently, the items after the OR are not tested. As long as the components after the OR generate a syntactically correct SQL expression, the attacker is granted the access of validuser.

LikewiseSimilarly, an attacker could supply a the following string for <PASSWORD> such as with an arbitrary username:

Code Block
languagesql
' OR '1'='1

This would yield producing the following commandquery:

Code Block
languagesql
SELECT * FROM db_user WHERE username='<USERNAME>' AND password='' OR '1'='1'

This time, the '1'='1' tautology disables both user name and password validation, and the attacker is falsely logged in without a correct login ID  always evaluates to true, causing the query to yield every row in the database. In this scenario, the attacker would be authenticated without needing a valid username or password.

Noncompliant Code Example

This noncompliant code example shows JDBC code to authenticate a user to a system. The password is passed as a char array, the database connection is created, and then the passwords are hashed.

Unfortunately, this code example permits a SQL injection attack by incorporating the unsanitized input argument username into the SQL command, allowing an attacker to inject validuser' OR '1'='1. The password argument cannot be used to attack this program because it is passed to the hashPassword() function, which also sanitizes the input.

Code Block
bgColor#FFcccc
languagejava
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

class Login {
  public Connection getConnection() throws SQLException {
    DriverManager.registerDriver(new
            com.microsoft.sqlserver.jdbc.SQLServerDriver());
    String dbConnection = 
      PropertyManager.getProperty("db.connection");
    // Can hold some value like
    // "jdbc:microsoft:sqlserver://<HOST>:1433,<UID>,<PWD>"
    return DriverManager.getConnection(dbConnection);
  }

  String hashPassword(char[] password) {
    // Create hash of password
  }

  public void doPrivilegedAction(String username, char[] password)
                                 throws SQLException {
    Connection connection = getConnection();
    if (connection == null) {
      // Handle error
    }
    try {
      String pwd = hashPassword(password);

      String sqlString = "SELECT * FROM db_user WHERE username = '" 
                         + username +
                         "' AND password = '" + pwd + "'";
      Statement stmt = connection.createStatement();
      ResultSet rs = stmt.executeQuery(sqlString);

      if (!rs.next()) {
        throw new SecurityException(
          "User name or password incorrect"
        );
      }

      // Authenticated; proceed
    } finally {
      try {
        connection.close();
      } catch (SQLException x) {
        // Forward to handler
      }
    }
  }
}

Noncompliant Code Example (PreparedStatement)

The JDBC library provides an API for building SQL commands that sanitize untrusted data. The java.sql.PreparedStatement class properly escapes input strings, preventing SQL injection when used correctly.   This code example modifies the doPrivilegedAction() method to use a PreparedStatement instead of java.sql.Statement.   However, the prepared statement still permits a SQL injection attack by incorporating the unsanitized input argument username into the prepared statement.

Code Block
bgColor#FFcccc
languagejava
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

class Login {
  public Connection getConnection() throws SQLException {
    DriverManager.registerDriver(new
            com.microsoft.sqlserver.jdbc.SQLServerDriver());
    String dbConnection = 
      PropertyManager.getProperty("db.connection");
    // Can hold some value like
    // "jdbc:microsoft:sqlserver://<HOST>:1433,<UID>,<PWD>"
    return DriverManager.getConnection(dbConnection);
  }

  String hashPassword(char[] password) {
    // Create hash of password
  }

  public void doPrivilegedAction(
    String username, char[] password
  ) throws SQLException {
    Connection connection = getConnection();
    if (connection == null) {
      // Handle error
    }
    try {
      String pwd = hashPassword(password);
      String sqlString = "select * from db_user where username=" + 
        username + " and password =" + pwd;      
      PreparedStatement stmt = connection.prepareStatement(sqlString);

      ResultSet rs = stmt.executeQuery();
      if (!rs.next()) {
        throw new SecurityException("User name or password incorrect");
      }

      // Authenticated; proceed
    } finally {
      try {
        connection.close();
      } catch (SQLException x) {
        // Forward to handler
      }
    }
  }
}

Compliant Solution (PreparedStatement)

 This This compliant solution uses a parametric query with a  ꞌ?character as a placeholder for the argument. This code also validates the length of the username argument, preventing an attacker from submitting an arbitrarily long user name.

Code Block
bgColor#ccccff
languagejava
  public void doPrivilegedAction(
    String username, char[] password
  ) throws SQLException {
    Connection connection = getConnection();
    if (connection == null) {
      // Handle error
    }
    try {
      String pwd = hashPassword(password);

      // Validate username length
      if (username.length() > 8) {
        // Handle error
      }

      String sqlString = 
        "select * from db_user where username=? and password=?";
      PreparedStatement stmt = connection.prepareStatement(sqlString);
      stmt.setString(1, username);
      stmt.setString(2, pwd);
      ResultSet rs = stmt.executeQuery();
      if (!rs.next()) {
        throw new SecurityException("User name or password incorrect");
      }

      // Authenticated; proceed
    } finally {
      try {
        connection.close();
      } catch (SQLException x) {
        // Forward to handler
      }
    }
  }

Use the set*() methods of the PreparedStatement class to enforce strong type checking. This technique mitigates the SQL injection injection vulnerability because the input is properly escaped by automatic entrapment within double quotes. Note that prepared statements must be used even with queries that insert data into the database.

Risk Assessment

Failure to sanitize user input before processing or storing it can result in injection attacks.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

IDS00-J

High

Probable

Likely

Medium

P12

P18

L1

Automated Detection

ToolVersionCheckerDescription
The Checker Framework

Include Page
The Checker Framework_V
The Checker Framework_V

Tainting CheckerTrust and security errors (see Chapter 8)
CodeSonar
Include Page
CodeSonar_V
CodeSonar_V

JAVA.IO.INJ.SQL

SQL Injection (Java)

Coverity7.5

SQLI
FB.SQL_PREPARED_STATEMENT_GENERATED_

FB.SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE

Implemented
Findbugs1.0SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTEImplemented
Fortify1.0

HTTP_Response_Splitting
SQL_Injection__Persistence
SQL_Injection

Implemented
Klocwork
 

Include Page
Klocwork_V
Klocwork_V

SV.DATA.

BOUND

DB
SV.

DATA.DB

SQL
SV.

HTTP_SPLIT

SQL.DBSOURCE

Implemented
Parasoft Jtest
Include Page
Parasoft_V
Parasoft_V
CERT.IDS00.TDSQLProtect against SQL injection
SonarQube
Include Page
SonarQube_V
SonarQube_V

S2077

S3649

Executing SQL queries is security-sensitive

SQL queries should not be vulnerable to injection attacks

SpotBugs

Include Page
SpotBugs_V
SpotBugs_V

SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE
SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING


SV.PATH
SV.PATH.INJ
SV.SQL

Implemented

Related Vulnerabilities

CVE-2008-2370 describes a vulnerability in Apache Tomcat 4.1.0 through 4.1.37, 5.5.0 through 5.5.26, and 6.0.0 through 6.0.16. When a RequestDispatcher is used, Tomcat performs path normalization before removing the query string from the URI, which allows remote attackers to conduct directory traversal attacks and read arbitrary files via a .. (dot dot) in a request parameter.

Related Guidelines

Android Implementation Details

This rule uses MS Microsoft SQL Server as an example to show a database connection. However, on Android, DatabaseHelper from SQLite is used for a database connection. Because Android apps may receive receive untrusted data via network connections, the rule is applicable.

Bibliography

...


...

            Image Modified