Unsanitized external input in SQL query
- Rule ID: php_symfony_sql_injection
- Languages: php
- Source: sql_injection.yml
Description
Using unsanitized data, such as user input or request data, or externally influenced data passed to a function, in SQL query exposes your application to SQL injection attacks. This vulnerability arises when externally controlled data is directly included in SQL statements without proper sanitation, allowing attackers to manipulate queries and access or modify data.
Remediations
- Do not include raw input in SQL queries. This practice can lead to SQL injection vulnerabilities.
$sql = "SELECT * FROM foo WHERE foo.bar > " . $_GET['untrusted']. " ORDER BY foo.bar ASC";
- Do validate all external input to ensure it meets the expected format before including it in SQL queries.
$sql = "SELECT * FROM foo WHERE bar = '" . $conn->quote($_GET['bar']) . "'";
- Do use safe lists to validate external input, if dynamic input is required.
private function validatedTableName($table_name)
{
if in_array($table_name, $ALLOWED_TABLE_NAMES) {
return $table_name
}
// handle invalid table name
} - Do use prepared statements with bound parameters to safely include external data in SQL queries. This method ensures that external input is treated as data and not as part of the SQL command.
$sql = "SELECT * FROM users WHERE username = :user";
$stmt = $connection->prepare($sql);
$stmt->bindValue("user", $_GET['username']); - Do employ an Object-Relational Mapping (ORM) tool or a database abstraction layer that automatically handles input sanitization and prepared statements.
$dql = "SELECT * FROM Foo WHERE bar = :bar";
$query = $em->createQuery($dql);
$query->setParameter("bar", $_GET['bar']);
References
- Doctrine DBAL Security
- Doctrine SQL Query Builder Security
- OWASP SQL injection explained
- OWASP SQL injection prevention cheat sheet
Associated CWE
OWASP Top 10
Configuration
To skip this rule during a scan, use the following flag
bearer scan /path/to/your-project/ --skip-rule=php_symfony_sql_injection
To run only this rule during a scan, use the following flag
bearer scan /path/to/your-project/ --only-rule=php_symfony_sql_injection