liveBook · Manning

SQL injection

As explained in Grokking Web Application Security

SQL injection is an attack technique that alters a database command by supplying input containing characters or syntax interpreted as SQL.

SQL injection occurs when application input becomes part of a database command instead of remaining data. An attacker can use SQL syntax to alter what the database executes, with consequences ranging from login bypass to stolen, modified, or deleted data. section 4.10 section 12.4

The vulnerability appears when commands are assembled unsafely:

  • String concatenation or interpolation places untrusted HTTP input directly inside SQL. section 4.10 section 12.4
  • A quote can close a SQL string, while a semicolon can add another statement. section 4.10
  • A comment marker can cause the database driver to ignore the remaining conditions, potentially bypassing authentication. section 12.4

A destructive input

If an email value contains '; DROP TABLE USERS, the resulting command can close the original string and issue a DROP TABLE command. A related login attack uses a username containing a quote and SQL comment marker to bypass the password check. section 4.10 section 12.4

Connection conn = DriverManager.getConnection(
  URL, USER, PASS);
String     sql  = "SELECT * FROM users WHERE email = ?";

PreparedStatement stmt = conn.prepareStatement(sql); #1

statement.setString(1, email);                       #2

ResultSet results = stmt.executeQuery(sql);          #3

Use a prepared statement: keep the SQL command fixed, bind the email value separately, and let the database driver escape it safely. section 4.10

How Grokking Web Application Security covers it

How deep it goes
Explains vulnerable construction, authentication bypass, destructive commands, and parameterized mitigation.
Examples
Uses login lookups, a DROP TABLE payload, a comment-based password bypass, and prepared-statement listings.
What it assumes
Assumes basic web requests and database commands while defining SQL control characters through concrete examples.
What you can do after
Apply parameterized statements through a database driver to keep dynamic values separate from SQL commands.
How it connects
Connects SQL queries with HTTP input, database drivers, authentication, and parameterized statements.

Also explained in

Compare how 9 books explain SQL injection →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Grokking Web Application Security. The section links point to the parts of the book it draws on.