How SQL Injection Works

Let's get a deeper understanding of how SQL works with some examples.

Our code works under ideal inputs, but does it stand up to malicious use? The wildcard parameter to generateWildcardSQLForJournalEntrySearch is controlled by the attacker.

How much influence can the attacker have over the generated SQL by just controlling the wildcard parameter? Just like the knock-knock joke from the beginning of this chapter, this SQL statement was written with a mental model of a template where user input fits into one part and stays in its place to create a full statement. Can the attacker-controlled input break out of that template and alter the structure of the overall statement? What keeps the attacker-controlled wild card in its part of the statement? The answer is the percent signs. What would happen if the attacker-controlled wildcard contained a percent sign?

Calling this:

generateWildcardSQLForJournalEntrySearch(1, "lindy hop%");

will generate this response:

SELECT CreatedTimestamp, Body
FROM journal_entries
WHERE PersonId = 1 AND Body LIKE '%lindy hop%%';

This is valid SQL, but it looks kind of odd. That double % at the end looks funny. More importantly for the themes of this course, it shows us how the attacker can start to break out of the template. What if the attacker searched for something weird like this?

can't use a contraction

This ...