UnixDroid

Lesson 4 of 5 · 9 min

SQL injection basics

See why gluing user input into a database query is dangerous, break DVWA in your lab, then learn the real fix.

Most websites keep their data in a database and talk to it using SQL. SQL injection happens when the app puts your input straight into a query, so your input becomes part of the command.

Practise only in your lab. Testing SQL injection on websites without permission is illegal.

Why it works

Imagine the app runs this, with your input in place of $id:

SELECT first_name, last_name FROM users WHERE user_id = '$id';

Type 1 and you get user 1. Now type 1' OR '1'='1. The query becomes:

SELECT first_name, last_name FROM users WHERE user_id = '1' OR '1'='1';

'1'='1' is always true, so the database returns every user.

The same input in a vulnerable query and in a parameterised query
The same input in a vulnerable query and in a parameterised query

Try it in DVWA

  1. Open http://192.168.56.102/dvwa/ from Kali and log in with admin / password.
  2. Go to DVWA Security, set it to low and submit.
  3. Open SQL Injection. Enter 1 and note the result.
  4. Enter a single '. An SQL error appears, which is a strong sign the input reaches the query unchanged.
  5. Enter 1' OR '1'='1 and watch every user appear.

The real fix: parameterised queries

Instead of building the query as text, the app sends the query and the input separately. The database then treats the input as data, never as code.

cur.execute("SELECT first_name FROM users WHERE user_id = %s", (user_id,))
$stmt = $pdo->prepare("SELECT first_name FROM users WHERE user_id = ?");
$stmt->execute([$id]);

With this, 1' OR '1'='1 is just a strange user ID that matches nothing.

Extra layers that help

  • Give the app's database user only the permissions it needs.
  • Validate input (an ID should be a number).
  • Don't show raw database errors to users.

Filtering out quotes is not a fix on its own. Attackers have many ways around it. Parameterised queries are the fix.

Try it yourself
  1. Complete the five DVWA steps above and screenshot each result.
  2. Set DVWA security to medium. Does the same input still work? Write down what changed.
  3. Open DVWA's View Source button on the low level and find the line that builds the query.

Quick check

One word: what kind of statements are the main fix for SQL injection?

Need a hint?

Also called parameterised queries.

Finished this lesson?

Done lessons keep your daily streak going 🔥

0 day streak

0 lessons done

best 0 days

Log in to keep your streak on every device →