Skip to content
SDETRole
SDETRole

Glossary · Security

SQL injection

Also called: SQLi, SQL injections, SQL injection attack

Definition

A vulnerability where user input is concatenated into a SQL query, letting an attacker change the query's logic to read, alter or delete data.

SQL injection (SQLi) occurs when an application builds a SQL statement by pasting user input into the query string. If the input contains SQL syntax, the database executes it as part of the query. Depending on the query and the database permissions, an attacker can bypass a login, read other users’ data, modify records or, in the worst cases, run commands on the server. It sits in A03 Injection in the OWASP Top 10 2021.

Example

Vulnerable Java code:

String sql = "SELECT * FROM users WHERE email = '" + email + "'";
ResultSet rs = conn.createStatement().executeQuery(sql);

If email is ' OR '1'='1, the query becomes:

SELECT * FROM users WHERE email = '' OR '1'='1'

The condition is always true, so the query returns every user. The fix is a parameterised query, where the input is sent separately from the SQL text and can never change its structure:

PreparedStatement ps = conn.prepareStatement("SELECT * FROM users WHERE email = ?");
ps.setString(1, email);
ResultSet rs = ps.executeQuery();

What a tester checks

With written authorisation, on a test environment:

  • Break the syntax. Submit a single quote ' in each text field, URL parameter, header and JSON value that might reach a query. A 500 error, a database error message or a changed result count suggests the input reaches SQL unescaped.
  • Change the logic. Compare value' AND '1'='1 with value' AND '1'='2. If the two responses differ in a way the plain value does not explain, the input is being interpreted.
  • Look at less obvious inputs. Sort columns, filter fields, search boxes and report parameters are often built dynamically, because column names cannot be bound as parameters.
  • Check error handling. Database errors, table names or stack traces in responses are a finding on their own.

Tools such as sqlmap automate deeper probing, but only run them against systems you are explicitly permitted to test, because they can modify or delete data.

Defences to verify

Parameterised queries or an ORM used correctly everywhere; allow-lists for dynamic identifiers such as sort columns; a database account with least privilege; and generic error messages. Input validation helps but is not a substitute for parameterisation.

Type to search across SDETRole.

Full-text search by Pagefind · runs in your browser Open search page →