neven@dimitri-dev:~$
cd ../hacknite-2021

$cat searching.mdWebHacknite 2.0

Searching

The animal search drops whatever you type straight into a database query, so a crafted search makes it return every row, flag included.

  • #sql-injection
  • #database

$man searching

What this one teaches:

  • What SQL is and how a site turns a search box into a database query.
  • What SQL injection is, why it happens, and the idea behind a payload that always matches.
  • Why queries must keep user input separate from the command (parameterised queries).

Task description

Petra has to build a site for a “Web pages” class. She loves animals, so she made one with facts about wild animals, kept in a database. She’d never used a database before, so she did her best. She added a search box, and although it sometimes throws an error, it mostly works.

The original was in Croatian; this is my translation.

The site lists animal facts and has a search page. Type an animal, submit, and it looks the term up in the database and shows what it finds. The task mentions that searching “sometimes throws an error”, which is the tell: a well-built search doesn’t break on odd input.

How the search becomes a query

Most sites keep their data in a database and ask for it using SQL, a language for querying data. A search for “lion” turns into something like:

SELECT * FROM animals WHERE name = 'lion'

The word you typed goes inside the quotes. The danger is when the site builds that line by gluing your text straight into it. If your text contains a quote, it ends the string early, and anything after it is read as part of the command rather than as data. That’s SQL injection: making the database run input that was supposed to be just a search term.

A search that always matches

The standard first payload is one that makes the condition always true:

' or true --

Pasted into the search, the query becomes, in effect, “return rows where the name is empty, OR where true”. Since true is always true, every row matches. The -- starts a comment, which tells the database to ignore the rest of the original line so the leftover quote doesn’t cause an error.

With every row returned, the flag came back among the results. (A cheat sheet of these payloads is worth keeping; this one is on every SQL injection reference.)

The real fix is a parameterised query, where the database is told “this is the command, and this is the data, keep them apart”. Then a quote in the search is just a quote, never part of the command.

$cat flag.txt revealCTF2021[499262524784]

Written by Neven Marić. This writeup was written with the help of Claude Code (Anthropic).