CIDADAXSEC
← All topics
Apprentice

SQL injection

User input reaches a SQL query as code instead of data. The effect ranges from login bypass to reading an entire table.

Material

SQL injection happens when an application builds a query by joining user input into a string. The SQL engine cannot tell the part the developer wrote from the part the user typed, so it treats both the same way.

The vulnerable query

The example below builds a WHERE clause from two form fields. Nothing separates the values from the SQL syntax.

javascript
const query = `SELECT id, username, role FROM users
  WHERE username = '${username}' AND password = '${password}'`;

db.prepare(query).get();

Enter administrator' -- as the username with any password. The quote closes the string, then -- turns the rest of the query into a comment. The password clause disappears and the administrator row matches.

Attack shapes you practise

  • Login bypass: cutting the WHERE clause with a SQL comment.
  • UNION: appending a second SELECT to read another table through the same columns.
  • Blind boolean: inferring database contents from the difference between true and false responses.
  • Time-based: inferring data from response delay, used when there is no output at all.

Prevention

  • Use prepared statements with bound parameters. Values never become part of the query text.
  • Limit the privileges of the application database account. An account that only needs SELECT must not have DROP.
  • Never send SQL error messages to the browser.
  • Validate input types, but validation is not a substitute for bound parameters.
The Phase 1 lab runs a real SQLite engine inside the sandbox. The data is dummy and rebuilt every time you press Reset lab.

Labs in this topic

Labs run on a domain separate from this site, so a payload cannot reach your account session.

SQL injection: login bypassThe login form builds its query by joining strings. Get in as administrator without the password.
LevelApprentice
Not solved
SQL injection: UNIONPull extra columns through UNION to read another table.
LevelPractitioner
Not solved

Challenges in this category

Challenges from the PortSwigger Web Security Academy. The original labs run on PortSwigger domains, so the link opens there.