User provided data, such as URL parameters, should always be considered untrusted and tainted. Constructing SQL queries directly from tainted data enables attackers to inject specially crafted values that change the initial meaning of the query itself. Successful database query injection attacks can read, modify, or delete sensitive information from the database and sometimes even shut it down or execute arbitrary operating system commands.


Typically, the solution is to use prepared statements and to bind variables to SQL query parameters with dedicated methods like ``++bindParam++``, which ensures that user provided data will be properly escaped. Another solution is to validate every parameter used to build the query. This can be achieved by transforming string values to primitive types or by validating them against a white list of accepted values.


This rule supports: Native Database Extensions, PDO, Symfony/Doctrine, Laravel/Eloquent.

== Noncompliant Code Example

----
function authenticate() {
  if( isset( $_POST[ 'Connect' ] ) ) {
    $login = $_POST[ 'login' ];
    $pass = $_POST[ 'pass' ];

    $query = "SELECT * FROM users WHERE login = '" . $login . "' AND pass = '" . $pass . "'"; // Unsafe

    // If the special value "foo' OR 1=1 --" is passed as either the user or pass, authentication is bypassed 
    // Indeed, if it is passed as a user, the query becomes: 
    // SELECT * FROM users WHERE user = 'foo' OR 1=1 --' AND pass = '...' 
    // As '--' is the comment till end of line syntax in SQL, this is equivalent to: 
    // SELECT * FROM users WHERE user = 'foo' OR 1=1 
    // which is equivalent to: 
    // SELECT * FROM users WHERE 1=1 
    // which is equivalent to: 
    // SELECT * FROM users 

    $con = getDatabaseConnection();
    $result = mysqli_query($con, $query);

    $authenticated = false;
    if ( $row = mysqli_fetch_row( $result ) ) {
      $authenticated = true;
    }
    mysqli_free_result( $result );
    return $authenticated;
  }
}
----

== Compliant Solution

----
function authenticate() {
  if( isset( $_POST[ 'Connect' ] ) ) {
    $login = $_POST[ 'login' ];
    $pass = $_POST[ 'pass' ];

    $query = "SELECT * FROM users WHERE login = :login AND pass = :pass"; // Safe regarding sql injection

    $stmt = $pdo->prepare($query);
    $stmt->bindParam(":login", $login);
    $stmt->bindParam(":pass", $pass);
    $stmt->execute();

    $authenticated = false;
    if ( $stmt->rowCount() == 1 ) {
      $authenticated = true;
    }

    return $authenticated;
  }
}
----

include::../see.adoc[]

ifdef::env-github,rspecator-view[]
'''
== Comments And Links
(visible only on this page)

include::../comments-and-links.adoc[]
endif::env-github,rspecator-view[]
