Executing SQL queries is security-sensitive. It has led in the past to the following vulnerabilities:
SQL injection is still one of the top 10 security vulnerabilities. Applications that execute SQL commands should neutralize any externally-provided values used in those commands. Failure to do so could allow an attacker to include input that changes the query so that unintended commands are executed, or sensitive data is exposed. Instead of trying to sanitize data by hand, SQL binding mechanisms should be used; they can be relied on to automatically perform a full sanitization.
This rule raises an issue when an execution of SQL queries might be susceptible to SQL injection. The goal is to guide security code reviews.
The following native database functions don't support prepared statements, thus their use is considered susceptible to injection.
mysql_query mysql_db_query mysql_unbuffered_query pg_update pg_query pg_send_query mssql_query mysqli_query and mysqli::query mysqli_real_query and mysqli::real_query mysqli_multi_query and mysqli::multi_query mysqli_send_query and mysqli::send_query PDO::query PDO::exec In addition, the following function call will also raise an issue if the provided query is a string with one or more interpolated variable (containing "$" sign).
PDO::prepare You are at risk if you answered yes to this question.
You can also reduce the impact of an attack by using a database account with low privileges.
$id = $_GET['id'];
mysql_connect('localhost', $username, $password) or die('Could not connect: ' . mysql_error());
mysql_select_db('myDatabase') or die('Could not select database');
$query = "SELECT * FROM myTable WHERE id = " + $id;
$result = mysql_query($query) or die('Query failed: ' . mysql_error()); // Questionable, seems to be susceptible to SQL injection
while ($row = mysql_fetch_object($result)) {
echo $row->name;
}
$id = $_GET['id'];
try {
$conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
$stmt->execute(array('id' => $id));
while($row = $stmt->fetch(PDO::FETCH_OBJ)) {
echo $row->name;
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
No issue will be raised if one of the functions is called with hard-coded string (no concatenation) and this string does not contain a "$" sign.
$result = mysql_query("SELECT * FROM myTable WHERE id = 42") or die('Query failed: ' . mysql_error()); // Compliant