QA Interview Hub · Knowledge base · Quizzes · Українська

Penetration Testing

Injections: SQL, commands, templates

SQL injection: how input becomes a command

SQL injection is when user input becomes part of an SQL command, because the query is built as a string and the boundary between code and data disappears. The result is seen through errors, UNION or blind conditions and delays. It is tested with safe probes: a quote, a true and a false condition, a controlled delay, no destructive commands. The defence is parameterized queries.

Pentest · Injections

The search field fails with a database error when you type an apostrophe. Just a bug or already a hole?

A tester types a single quote into the catalogue search and instead of a product list sees an error page with syntax error at or near. It is not necessarily SQL injection, but it is a strong signal: the typed text reached the database as part of a command. The lesson shows how it works, which kinds exist (including "blind" ones, when no errors are visible) and how to check them without breaking anything.

Mechanism. The application builds SQL as a string and inserts the user’s input into it:

const sql =
  "SELECT * FROM products WHERE name = '" + term + "'";

For term = laptop this is an ordinary query. For term = ' OR '1'='1 the database receives WHERE name = '' OR '1'='1': the condition is always true, the whole catalogue is returned. The user did not pass data, he changed the structure of the command. This is what separates injection from incorrect input: the border between code and data is gone.

Building a query: a string or parameters

Concatenation: input becomes codeWHERE name = ’’ OR 1=1 --’always true, the tail is commented outParameterization: input is only dataWHERE name = $1’ OR 1=1 --the input does not change the query structure
Figure 1. In the first row the input becomes part of the SQL, in the second it stays a parameter value.

Kinds.

  • Error-based: the database error is shown in the response and reveals the query structure;
  • UNION-based: UNION SELECT … is appended to the query and the result of another table appears in the same response. First the number of columns of the original query is found;
  • Blind boolean: data is not visible, but a condition changes the response (a product is there or not, the page differs);
  • Blind time-based: the response is the same, but the injected command delays it (pg_sleep(5) in PostgreSQL, SLEEP(5) in MySQL);
  • Out-of-band: the database itself contacts an external address; used when there are no other channels.

For "blind" kinds the check is like an experiment with a control. Two responses differ only in the condition:

GET /products?name=laptop' AND '1'='1   ->  list of laptops
GET /products?name=laptop' AND '1'='2   ->  empty list

GET /products?name=laptop'; SELECT pg_sleep(5)--  ->  5 s delay

If the first and the second responses differ consistently while the request format and the network do not, the input reaches an SQL condition. A delay of exactly five seconds on repeats also points to command execution rather than a slow network: repeat with 2 and 8 seconds and compare. Note that a tester uses no DROP, UPDATE or data extraction, even on a test environment: a condition and a delay are enough as proof.

Where input goes. Not only in a search string: filters and sorting, numeric parameters (?id=5), JSON fields, cookies, headers (User-Agent, X-Forwarded-For), previously stored values (second-order). One place where a query is built by string is enough.

A real case. In May 2023 the web application MOVEit Transfer (Progress Software, a file transfer system) turned out to have the SQL injection CVE-2023-34362. According to CISA, exploitation began around 27 May, before a fix existed. The CL0P group used the injection to install the web shell LEMURLOOT: through it they ran commands on the server, read settings and files and stole data. On 2 June CISA added the vulnerability to the KEV catalogue and on 7 June published the advisory AA23-158A. The lesson: SQL injection is not only "showing extra rows": it leads to command execution and data theft from many customers of a product.

How QA checks it. Only on an authorized environment or in a training lab (PortSwigger Web Security Academy, OWASP Juice Shop, DVWA). Start with the harmless: a single quote, a pair of "true/false conditions", a delay. Extra caution with requests that change data (UPDATE behind a form, deletion): OR 1=1 in such a query would affect every row. sqlmap can automate this, but with low risk and only within the scope.

Common mistakes.

  • Considering only the situation with a visible error as injection. Blind kinds stay silent;
  • Considering a query behind a login safe: after authentication the input reaches SQL just the same;
  • Checking only GET parameters and forgetting JSON, headers and cookies.

Check yourself

The request ?name=laptop' AND '1'='1 returns laptops and ?name=laptop' AND '1'='2 returns an empty list. There are no errors. What does it mean?

Answer

The input reaches an SQL condition: the response depends on the truth of the added expression. This is boolean-based blind SQL injection. It is confirmed further with a delay or another pair of conditions and fixed with parameterization.

Why does a tester not add DROP TABLE to the injection even on a test environment?

Answer

A safe condition or delay is enough to prove the flaw, while a destructive command would destroy data, spoil the environment for other people and add no evidence. The pentest principle: the minimal action that proves the impact, within the permission.

In an interview. Junior: SQL injection is when user input becomes part of an SQL command. Visible errors, UNION and blind conditions or delays are different ways to see the result; the defence is parameterized queries. Middle/Senior: I check with safe probes: a quote, a pair of a true and a false condition, a controlled delay with several values, in every input place, not just search. Consequences can reach command execution, as in MOVEit, so I rate severity by the reachable data and the database account’s rights.

Parameterization, ORMs and why escaping does not save you

SQL injection is prevented by parameterized queries, not escaping: the command text and the values go to the database separately. Escaping and keyword blocklists depend on dialect and context and can be bypassed, for example in a numeric parameter. Column names and ORDER BY are not parameterized but matched against an allowlist. Raw ORM methods and second-order data remain a risk.

Pentest · Injections

A developer escapes apostrophes and considers SQL injection closed. What did he miss?

After a vulnerability report a developer added a function that replaces ' with \' and asks to close the defect. The tester switches from a search by string to a search by number ?id=1 OR 1=1, and the injection works again: there are no quotes in a numeric context, so there is nothing to escape. The lesson explains why reliable protection is not cleaning input but separating the command from the data.

Mechanism. In a parameterized (prepared) query the SQL text with placeholders ($1, ?, :name) is sent to the database separately from the values. The database parses and plans the command without the data and then substitutes the values as values. Even if a value contains ' OR 1=1 --, it is only a string to compare, not a fragment of the command. So there is no need to know which characters are dangerous in this dialect, encoding and context: the question "what to escape" disappears.

// before: a string is a command
db.query("SELECT * FROM users WHERE id = " + id);

// after: a command and a value are separate
db.query("SELECT * FROM users WHERE id = $1", [id]);

A numeric parameter: where escaping is powerless

Typical

"… WHERE id = " + escapeQuotes(id)

The input 1 OR 1=1 contains no quotes. Escaping changes nothing and the condition becomes always true.

Better

"… WHERE id = $1", [id]

The value 1 OR 1=1 does not become a number: PostgreSQL rejects it as not a number, and the request ends with an error, not a leak.

Figure 1. Escaping depends on the context (quotes, numbers, identifiers), a parameter does not.

Why "cleaning input" does not work.

ApproachReliable?Why
Escaping quotesnonumbers, encodings
Word blacklistnocase, comments
Parametersyesdata apart

A word blacklist (SELECT, UNION) is bypassed with case (SeLeCt), comments inside a word or encoding. Escaping depends on the dialect and character set: a mistake in one place leaves a hole. Besides, they work only where someone remembered them, while parameters become the default way.

What cannot be a parameter. A parameter substitutes a value, not a table or column name. So user-chosen sorting (ORDER BY) is not parameterized. The right way is to map the permitted options to a fixed set:

const SORT = { price: "price", name: "name" };
const col = SORT[req.query.sort] ?? "name";
const dir = req.query.dir === "desc" ? "DESC" : "ASC";
db.query("SELECT * FROM products ORDER BY " + col + " " + dir);

Only a string from our own dictionary reaches SQL, not the input. The same goes for column names in filters and dynamic reports.

ORMs and "raw" queries. An ORM parameterizes ordinary calls by default (findMany({ where })). The flaw appears in "raw" methods: in Prisma $queryRawUnsafe with an assembled string is vulnerable, while $queryRaw with a template literal is parameterized. Similar traps exist in Sequelize (query with concatenation), Django (raw, extra) and Hibernate (HQL strings). In code review look for SQL assembled with + or interpolation.

Second order. A value may have entered the database safely (a parameterized INSERT), but later other code takes it from the database and inserts it into SQL as a string, for example in an administrator report. The database does not "clean" what is stored: it is dangerous where it is used as code. Parameterization is needed in every query, whatever the source of the value.

Extra layers. An application account with only the needed rights (no DROP, no file system access, a separate account for reading), hidden database error messages (only a generic error and an identifier for the logs in the response), a WAF as a temporary shield. This reduces the consequences but does not replace the fix: a WAF is bypassed, and account rights do not stop reading data the account can access.

A real case. In August 2009 the US Department of Justice published charges against Albert Gonzalez: according to the indictment, SQL injections were the start of intrusions into the networks of several large companies, among them Heartland Payment Systems and Hannaford, involving about 130 million payment card numbers. The technique was already old and the reliable defence known. That injections still occur about fifteen years later (MOVEit, 2023) shows that the problem is not ignorance of the technique but discipline: one line assembled by concatenation undoes everything else.

Common mistakes.

  • Parameterizing values while taking the sort column name from input as is;
  • Treating an ORM as a guarantee: a raw method with concatenation stays vulnerable;
  • Trusting "already stored" data and assembling SQL from it as a string (second order).

Check yourself

The query ORDER BY $1 with the parameter price does not sort by price. Why and how to do it right?

Answer

A parameter passes a value (the string "price"), not a column name, so the database sorts by a constant. The right way is a dictionary of permitted columns and substituting only the matching string from it.

Does the rule "the database never receives the words SELECT and UNION from a user" protect against SQL injection?

Answer

No. Bypasses are easy (case, comments inside a word, encoding), and changing a condition needs no such keywords: OR 1=1 or a delay does not contain them. Reliable protection does not depend on the words in the input.

In an interview. Junior: The defence against SQL injection is parameterized queries: the command and the data go separately, so input does not become part of SQL. Escaping and blacklists are unreliable. Middle/Senior: Separately I look at what cannot be parameterized (column names, ORDER BY): an allowlist is needed there. Also raw ORM methods, second order, minimal database account rights and hidden errors; I treat a WAF as a temporary mitigation.

Command and template injection

OS command and template injection (SSTI) share the SQL principle that input becomes code, but the consequence is often RCE. In one case input lands in a string for the shell, in the other it becomes the template itself. The defence: do not build a command or template from input, call the program without a shell using an argument array, and pass input only as a variable value.

Pentest · Injections

A service converts a file with an external utility. What if the file name contains a semicolon?

The same principle "input becomes code" works not only in SQL. When an application builds a string for a command shell or for a template engine, the user’s input can change the command or expression the server executes. The consequences are often heavier than with SQL injection: execution of arbitrary commands on the server (RCE). The lesson covers OS command injection and template injection (SSTI) and what they have in common.

OS command injection. The application calls a utility through a shell:

exec("convert " + name + " out.png");

A shell understands special characters: ;, |, &&, $(…), backticks, a line break. If name equals a.png; id, the shell executes two commands, and the second runs as the application’s process. A safe probe for a test environment: ; sleep 5 gives a delay and ; id shows a line with uid= in the response. For the "blind" case, when no output is visible, a delay or a request to a controlled test host remains.

A string for the shell or an argument array

Typical

exec("convert " + name)

Everything goes as one string to a shell, which parses special characters in the input.

Better

execFile("convert", [name])

Arguments are passed as an array without a shell: ; stays part of the file name.

Figure 1. The fix removes the shell instead of "cleaning" characters.

Also: generate the file name on the server, check permitted formats against a list, and -- before the argument stops a name that starts with a hyphen from becoming a flag (argument injection).

A real case. CVE-2023-2868 in the Barracuda Email Security Gateway appliance (firmware 5.1.3.001–9.2.0.006): according to the NVD description, a specially formatted file name inside a TAR attachment reached the Perl operator qx and the system executed a command with the appliance’s rights. So an email with an attachment gave remote command execution. The vulnerability is in the CISA KEV catalogue; according to the vendor as cited by Rapid7 analysts, it had been exploited since October 2022. The same rule: a name from an attachment is input and must not be passed to a shell.

SSTI (Server-Side Template Injection). Template engines (Jinja2, Twig, FreeMarker, Velocity, Thymeleaf) insert values into a ready template: input is only data there. The flaw appears when input becomes the template itself:

# safe: the input is a value
render_template("hello.html", name=name)

# vulnerable: the input is the template text
render_template_string("Hello " + name)

A probe: send {{7*7}}. If the raw server response (not just the DOM in the browser) already contains Hello 49, the server evaluated the expression, and it is SSTI, not XSS (evaluation only in the DOM comes from a client-side template framework: that is CSTI, a kind of XSS): with HTML reflection you would see literally {{7*7}}. Other engines take ${7*7} or <%= 7*7 %>. To identify the engine a second evaluation is used:

ExpressionTwigJinja2
{{7*7}}4949
{{7*'7'}}497777777

Jinja2 (Python) repeats the string, Twig (PHP) turns "7" into a number. The following steps (access to the engine’s objects and command execution) are practised in a training lab on the PortSwigger Web Security Academy, while in a real test one stops here: a safe probe is enough as proof. The method was described by James Kettle (PortSwigger, 2015), who showed vulnerable cases in enterprise products (Alfresco, XWiki): when users edit a template "for convenience", the input is the code.

Fixes and limits.

  • Do not build a template from input; pass input only as a variable value. If users need formatting, take "logic-less" languages (Markdown, Mustache) with sanitization;
  • A template engine sandbox helps as an extra layer, but historically it was bypassed, so it is not the main fix;
  • For commands: no shell, an argument array, an allowlist of values, a process with minimal rights.

Other injections of the same kind. NoSQL ({"$ne": null} instead of a password in JSON), LDAP, XPath, headers (CRLF in a header value), logs (forged lines). The principle is one: the command structure must not depend on input, use an API that takes data separately.

Common mistakes.

  • Stripping ; and | from input: &, $(), a line break remain;
  • Mixing up SSTI with XSS: reflecting {{7*7}} without evaluation is not SSTI;
  • Proving the flaw with destructive commands instead of id, sleep or a calculation.

Check yourself

A service calls exec("ping " + host). The developer removed the ; character from host. Is it safe?

Answer

No. A shell has other separators: |, &&, $(…), backticks, a line break. The reliable option is a call without a shell with an argument array and a check that host is a host name or an IP address.

A search answers Nothing found for {{7*7}}. Is this SSTI?

Answer

No, the expression is shown as text: it was not evaluated. If the raw server response said "for 49", the server evaluated the expression and it would be SSTI. Reflected text without execution is checked for XSS separately.

In an interview. Junior: Command injection is when input reaches a string for a shell, SSTI is when input becomes a template. Both give code execution; the defence is not to build a command or a template from input. Middle/Senior: Probes: a delay or id for commands, {{7*7}} and a second check for the engine in SSTI, with no destructive actions. The fix is a call without a shell with an argument array and an allowlist; I treat a template sandbox only as an extra layer.