SQL Injection Prevention
Techniques to prevent attackers from inserting malicious SQL statements into application queries.
Description
SQL injection is a code injection technique that exploits vulnerabilities in the data layer of an application by inserting malicious SQL code into queries. When user input is concatenated directly into SQL statements without proper sanitization, attackers can manipulate query logic to bypass authentication, extract sensitive data, modify or delete records, and in severe cases execute operating system commands on the database server.
The attack surface for SQL injection extends beyond simple login forms. It includes any application input that feeds into a database query: URL parameters, cookie values, HTTP headers, file uploads with metadata, and JSON/XML payloads. Blind SQL injection techniques allow attackers to extract data even when error messages are suppressed, using boolean-based or time-based inference.
Prevention centers on parameterized queries (prepared statements) as the primary defense, where SQL code and data are sent to the database separately. ORMs like Prisma, Sequelize, or Drizzle provide this by default. Additional layers include input validation with strict type checking, stored procedures with parameterized inputs, least-privilege database accounts, and Web Application Firewalls (WAFs) as a final safety net. Never construct SQL strings through concatenation or template literals with user-supplied values.
Prompt Snippet
Use parameterized queries or prepared statements exclusively -- never concatenate user input into SQL strings. With raw SQL drivers (pg, mysql2, better-sqlite3), always use parameter placeholders ($1, ?, :param). When using ORMs like Prisma or Drizzle, avoid raw query escape hatches (prisma.$queryRawUnsafe, sql.raw()) unless inputs are validated. Apply database-level least privilege by granting only SELECT/INSERT/UPDATE on specific tables to the application role, and revoke DROP/ALTER/GRANT permissions entirely. Enable query logging in staging to detect anomalous patterns.
Tags
Related Terms
Input Validation & Sanitization
The practice of verifying and cleaning all user-supplied data before processing to prevent injection attacks and data corruption.
OWASP Top 10
A standard awareness document listing the ten most critical web application security risks, maintained by the Open Web Application Security Project.
Principle of Least Privilege
A security principle requiring that every user, process, and system component be granted only the minimum permissions necessary to perform its function.