SQL Injection
Description
SQL Injection (SQLi) is a code injection vulnerability that occurs when an application incorporates untrusted user input directly into SQL queries without proper validation or sanitization. Attackers exploit this weakness by inserting malicious SQL code through input fields, URL parameters, or other data entry points, allowing them to manipulate database queries and execute unauthorized commands against the application's database server.
Remediation
Implement parameterized queries (also known as prepared statements) as the primary defense against SQL Injection. Parameterized queries separate SQL code from user data by using placeholders for input values, ensuring the database treats user input as data rather than executable code.
Example using PHP PDO:
// Secure: Using parameterized query
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username AND password = :password');
$stmt->execute(['username' => $username, 'password' => $password]);
$user = $stmt->fetch();
// Insecure: Direct concatenation (DO NOT USE)
// $query = "SELECT * FROM users WHERE username = '" . $username . "'";Example using Java JDBC:// Secure: Using PreparedStatement String query = "SELECT * FROM users WHERE username = ? AND email = ?"; PreparedStatement stmt = connection.prepareStatement(query); stmt.setString(1, username); stmt.setString(2, email); ResultSet results = stmt.executeQuery();Additional recommendations:
- Use Object-Relational Mapping (ORM) frameworks that handle parameterization automatically
- Implement input validation with allowlists for expected data formats and types
- Apply the principle of least privilege to database accounts used by the application
- Employ Web Application Firewalls (WAF) as a defense-in-depth measure
- Conduct regular security testing including static and dynamic analysis to identify SQLi vulnerabilities