Skip to content
</> Mücahit TopalA developer's notebook

Blog/Siber Güvenlik

What Is SQL Injection, How Does It Work and How Do Prepared Statements Prevent It?

Mücahit Topal 7 min read 3 views TREN

What Is SQL Injection, How Does It Work and How Do Prepared Statements Prevent It?

SQL injection is one of the oldest security holes on the web and still one of the most common. The cause is not complicated: text coming from the user is pasted into the query text, and the database cannot tell the two apart. In this post I show how the hole works with a small example, then cover the permanent fix and why the "but I already use addslashes" defence does not hold.

One note up front: use the examples here only in your own development environment, to test your own code. Trying them without permission on a system that is not yours is a crime in most countries.

How does the hole appear?

The classic example is a login form. Suppose the code is written like this:

$email    = $_POST['email'];
$password = $_POST['password'];

$sql = "SELECT id FROM users
        WHERE email = '$email' AND password = '$password'";

A normal user types their address into the email field and the query comes out as expected. But if someone types this into the password field:

' OR '1'='1

the text that reaches the database becomes:

SELECT id FROM users
WHERE email = '[email protected]' AND password = '' OR '1'='1'

The single quote typed by the user closed the quote opened by the programmer; the rest is no longer data, it is SQL. Because OR '1'='1' is true for every row, the query returns every user in the table and the code will most likely log in with the first row, which is often the administrator account.

The problem is not the quote character; it is that data and command travel in the same piece of text. That is worth keeping in mind, because every wrong fix grows out of the idea "let me neutralise the quote".

Not just the login form

The hole can appear anywhere a user-supplied value enters a query: the id in the address bar, a search box, a sort option, a cookie, even HTTP headers. Consider a numeric field:

$id  = $_GET['id'];
$sql = "SELECT title, body FROM posts WHERE id = $id";

There is not even a quote here. If this is appended to the address:

?id=0 UNION SELECT email, password FROM users

the email and password columns of the users table are printed on the page instead of the post title and body. The attacker has just read a table they should never see. Data can be deleted or changed the same way; if the database user has broad privileges, the reach can extend to files on the server.

The hole can be exploited even when the page shows nothing. In so-called "blind" injection, the attacker extracts data one character at a time from the way the page behaves differently for a true and a false condition, or from a delay in the response. Tools that automate this are widespread, so "who would bother with my small site" is not a thought to rely on. Most scanning is not done by hand.

The permanent fix: prepared statements

With a prepared statement, the query text and the values are sent to the database separately. First the query with placeholders goes out; the database parses it and decides what will be done. The values arrive afterwards and are used purely as data. Whether they contain quotes, OR or UNION changes nothing; the structure of the query has already been fixed.

The correct version of the login example in PHP with PDO:

<?php
$pdo = new PDO(
    'mysql:host=localhost;dbname=app;charset=utf8mb4',
    'app_user',
    'app_password',
    [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES   => false,
    ]
);

$email    = $_POST['email'] ?? '';
$password = $_POST['password'] ?? '';

$stmt = $pdo->prepare('SELECT id, password_hash FROM users WHERE email = :email');
$stmt->execute(['email' => $email]);
$user = $stmt->fetch();

if ($user !== false && password_verify($password, $user['password_hash'])) {
    session_regenerate_id(true);
    $_SESSION['user_id'] = $user['id'];
} else {
    // Do not reveal which field was wrong
    $error = 'Incorrect email or password.';
}

There are two separate fixes here. The first is the injection: the email no longer enters the query text. The second is the password: the plain-text password is not compared inside the query; the database holds a hash produced with password_hash and the check happens on the PHP side with password_verify. Even with the injection closed, the code in the first example would still have been bad code because it stored passwords in plain text.

The same holds in other languages: SqlCommand parameters in C#, PreparedStatement in Java, the driver's parameter support in Python. The language changes, the principle does not: the value is never mixed into the query text.

Why is addslashes not enough?

The "fix" I see most often in legacy code is passing every input through addslashes or mysql_real_escape_string. There are several concrete reasons why that falls short:

  • Numeric fields have no quotes. Look at the WHERE id = $id example above. There is not a single quote to escape in 0 UNION SELECT ...; addslashes lets that text through untouched.
  • It does not know the character set. addslashes works at the byte level and is unaware of the connection's character set. In some multi-byte character sets the added backslash can merge with the byte before it into a single character, leaving the quote exposed again. mysql_real_escape_string only solves this if the connection charset was set the proper way.
  • It does not protect table and column names. If you take the sort column from the user and write ORDER BY $sort, none of the escaping functions help; there is no quoted value there.
  • It gets forgotten. Escaping is a step you have to remember for every variable in every query. Forgetting it in one query out of a hundred is enough. With prepared statements, the safe way is also the default way.

The magic_quotes setting PHP once had, which added backslashes to all input automatically, came from the same line of thinking; it was removed from the language because it did not work and it corrupted data.

Where placeholders are not enough

Placeholders are for values only. Parts that belong to the structure of the query, such as a table name, a column name or ASC/DESC, cannot be passed as placeholders. In that case you keep the allowed values fixed in code and use what the user sends only to choose among them:

$allowed = [
    'date'  => 'created_at',
    'title' => 'title',
    'views' => 'view_count',
];

$column    = $allowed[$_GET['sort'] ?? 'date'] ?? 'created_at';
$direction = ($_GET['dir'] ?? '') === 'asc' ? 'ASC' : 'DESC';

$stmt = $pdo->prepare(
    "SELECT id, title FROM posts WHERE category_id = :cat
     ORDER BY $column $direction LIMIT 20"
);
$stmt->execute(['cat' => (int) ($_GET['cat'] ?? 0)]);

The $column and $direction that enter the query are not text typed by the user; they are constants from your own array. Whatever the user sends, nothing other than these three column names and two directions can end up in the query.

One more trap: data you read from the database is not trustworthy either. A malicious string saved as a username triggers the same hole years later when it is pasted into another query. The rule is simple: do not look at where the value came from, always use a placeholder.

Additional layers of defence

Prepared statements are the real fix; the items below do not replace them, but they limit the damage when you make a mistake:

  • Least privilege. The application's database user should only be able to SELECT, INSERT, UPDATE and DELETE on the tables it needs. Do not connect the site as root; do not grant DROP and file privileges unless they are required.
  • Do not show errors to visitors. A SQL error printed on the page hands the attacker table and column names. Keep display_errors off in production and write errors to the log.
  • Validate input. If you expect a number, cast with (int) or check with filter_var; verify the format of fields such as email and date. This is not the fix for injection, but it turns nonsense away early.
  • Hash passwords. If the table leaks one day, passwords stored with password_hash cannot be used as easily as plain text or md5.
  • Take backups and test restoring them. The only thing that brings deleted data back is a backup.

How do you scan your own code?

To find out whether a project you have is vulnerable, look at the code first. Every line where a variable appears inside query text is suspect. A crude but useful search for PHP:

grep -rnE "(SELECT|INSERT|UPDATE|DELETE).*\\$" --include="*.php" .

For each line that comes up, ask this: does the variable go into the query text, or does it travel through execute? If it goes into the text and is not picked from a fixed list as above, add it to the list of things to fix. If you use a framework, the query builders protect you to a large extent, but the places where you write "raw queries" are subject to the same rule.

What makes SQL injection hard is not its technical depth but habit. Pasting the value into the query is two lines shorter and appears to work at first glance. Once prepared statements are your default way of writing queries, this class of vulnerability practically drops off your agenda.

,,,,,,,,,,,

Share X Facebook LinkedIn WhatsApp

More from this category

Comments 0

No comments yet.

Leave a comment

Comments appear after approval.