HACKORY
Language · English
← All chapters
HACKORY / Open library

SQL injection

A database stores an app’s information in tables. To ask it for data, the app writes it a statement in SQL, such as SELECT titulo FROM libros WHERE autor = ?. SQL injection happens when text someone typed ends up becoming part of that command.

New here? Try the first lesson without an account

How it works

Quick review: SELECT says which columns to read, FROM which table, and WHERE which rows to keep. The ? sign marks the place of a value that travels separately (you saw it in /primeros-pasos#resultados). If instead of using ? the app pastes the user’s text inside the statement, a quote mark or an SQL word in that text can change the condition or the structure of the query.

Expected behavior

The app runs SELECT ... WHERE id = ? and passes 101 separately, as a value: the database never reads it as part of the command.

What can go wrong

The app pastes the value of the id field inside the statement; the database reads part of that input as if it were SQL.

What to observe

Compare a normal query, a true condition, and a false condition; observe data and errors.

Common false positive

A quote mark that causes a 500 suggests the app handles input badly, but it does not confirm that data can be read.

Why it matters

Whoever manages to change the statement may read or modify data that does not belong to them. A quote mark that only causes an error does not, on its own, confirm that impact.

How to fix it

Use parameterized queries, with ? and the value sent separately, and give the database account only the permissions it needs.

Understand it step by step

What a statement is

A statement is a complete command for the database. SELECT * FROM usuarios WHERE nombre = ? AND clave = ? asks for the rows of the usuarios table that meet two conditions: the asterisk means “all columns” and AND means “and also.” Each ? is a place the app fills with a value sent separately; the database never interprets that value as new SQL words.

Why a quote mark changes something

In a badly built query, the server pastes the name between quote marks: WHERE nombre = '...' AND clave = '...'. Quote marks show where a text begins and ends. If the name contains a quote mark, that mark closes the text too early and whatever follows is read as SQL. The word next to it is nothing special: what matters is that a character typed by the user became part of the command.

What the comment does

In SQL, two hyphens (--) start a comment: the database ignores the rest of the line. That is why, in the lab, a name that closes the quote and adds a comment leaves out the password condition, and the statement that reaches SQLite no longer asks for the password. The fix uses parameters: the full text travels as a single value and the structure of the statement does not change, whatever the person types.

Recommend this chapter to a friend