Unsanitized external input in SQL query

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 external input in SQL queries. This practice can lead to SQL injection vulnerabilities.
    $sortingOrder = $_GET['untrusted'];
    $query = "SELECT id, name FROM products ORDER BY name LIMIT 20 $sortingOrder;"; // unsafe
  • Do validate all external input to ensure it meets the expected format before including it in SQL queries.
    $sortingOrder = $_GET['sortingOrder'] === 'DESC' ? 'DESC' : 'ASC';
  • Do use prepared statements for database queries to separate SQL logic from external input, significantly reducing the risk of SQL injection.
    $stmt = $pdo->prepare("SELECT * FROM products WHERE id LIKE ? ORDER BY price {$sortingOrder}");
    $stmt->execute(["%{$productId}%"]);
  • Do escape all external input using appropriate database-specific escaping functions before including it in SQL queries.
    $ok = mysqli_real_escape_string($conn, $_GET['ok']);

References

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_lang_sql_injection

To run only this rule during a scan, use the following flag

bearer scan /path/to/your-project/ --only-rule=php_lang_sql_injection