SQL Injection Explained: How to Detect and Fix It
SQL injection is one of the oldest web vulnerabilities and it still shows up in new code. The cause is almost always the same: user input becomes part of the SQL text instead of being passed as data. This guide explains how to fix SQL injection properly, how to find it in your own code before anyone else does, and how to verify the fix. It is written for defenders, so there are no attack strings…
SQL injection remains a prevalent web vulnerability despite being an old one. It occurs when user input is inadvertently included in SQL queries instead of being passed as data, allowing attackers to alter the query's meaning and potentially access sensitive data or perform unauthorized actions. This guide explains how to identify and correct SQL injection vulnerabilities, as well as how to validate the corrections.
It is intended for defenders and focuses on recognizing patterns and addressing them rather than providing attack strings.
In simple terms, SQL injection happens when a database receives a query as text and tries to parse it. If your application builds that text by inserting user input, the database cannot distinguish between the user's input and the code's own SQL. Consequently, input containing SQL syntax can change the query's meaning, enabling read, write, or other malicious actions. The weakness is documented as CWE-89.
To prevent SQL injection, keep code and data separate, ensuring that input is never parsed as SQL. This can be achieved by avoiding string building, which is the classic pattern where input is directly included in the SQL text. Instead, use parameterized queries, allow-list input validation, and other defensive measures. These practices aim to keep SQL text fixed and values separate, thereby preventing the database from parsing user input as SQL.
Several common scenarios can lead to SQL injection. These include string concatenation or template literals in any programming language, ORM escape hatches like raw query methods or custom WHERE snippets, dynamic ORDER BY columns, and stored procedures that build and execute SQL strings. Reporting and admin screens, which might receive less scrutiny than the main application, are also susceptible.
To effectively address SQL injection, follow these four habits. First, use parameterized queries everywhere; this separates SQL text from values, preventing the database from parsing user input as SQL. Second, allow-list anything that cannot be a parameter, such as table names, column names, or SQL keywords. When users choose a sort column, map their choice to a value owned by your code and reject any other input.
Third, do not rely on manual escaping, as it depends on the database, its version, and its settings, making it error-prone. Instead, use parameter binding as recommended by OWASP. Lastly, limit the damage with least privilege by giving each application its own database account with only the permissions it needs. This does not eliminate the risk of injection but limits the potential impact of a successful attack.
In addition to the primary defenses, input validation (such as types, lengths, and formats) is still valuable as part of a defense-in-depth strategy. A web application firewall can also provide an extra layer of protection, but neither of these should replace parameterized queries.
Detecting SQL injection before it reaches production is crucial. Detection methods should include a combination of code review and search for SQL keywords next to string formatting, integration of static analysis tools (such as Semgrep or CodeQL) into CI pipelines, and running authorized dynamic scans like OWASP ZAP against staging or production environments with proper authorization and within agreed limits.
Monitoring database syntax errors, unusual query patterns, and Web Application Firewall (WAF) alerts can also signal potential SQL injection attempts.
Once a fix is implemented, it must be verified to ensure its effectiveness. This involves writing unit tests with awkward but legitimate input, such as names with apostrophes or values containing quotes and semicolons. Run the scan that initially found the issue against the same endpoint and confirm that the finding has been resolved. Additionally, search for similar vulnerabilities in other parts of the codebase and add CI rules to prevent their recurrence.
Preventing SQL injection should be a routine practice for all development teams. Teams that rarely encounter SQL injection typically use parameterized queries by default, carefully review raw SQL, run static analysis on every change, schedule regular dynamic scans, and retest after implementing fixes. For those managing multiple applications or clients, tools like CerberusGuard can assist with scanning and retesting processes, using Nuclei and OWASP ZAP for web and API scans, including OpenAPI-driven scans.
Rewritten by urgent.news; may contain errors — check the original.
Source: dev.to