Injection: SQL, Command and Beyond

Topics Covered

How Injection Works

Code and data in one channel

Why concatenation is tempting

Interpreters everywhere

Sources of untrusted input

Impact

Escaping is not a strategy

Allow lists versus deny lists

Where injection hides

Defence in depth

Injection in the threat model

Frameworks change the odds

Authorised testing

What this lesson covers

A vocabulary for the rest of the lesson

Injection is one of the oldest and most damaging classes of software vulnerability. It happens whenever untrusted input is combined with code or commands for an interpreter, such as a SQL database, an operating system shell or a template engine, in a way that lets the input change the meaning of the code. A single injectable query can expose every row in a database, and a single injectable command can hand an attacker the server. This lesson explains how injection works, how SQL and command injection arise, how to prevent them by construction and how to find and remove them across a large codebase.

Code and data in one channel

Every interpreter receives a string and parses it into a structure of operations and values. Injection happens when a program builds that string by gluing fixed code to user input, so the interpreter cannot tell which parts the developer wrote and which parts came from the user. If the input contains characters that the interpreter treats as syntax, such as a quote, a semicolon or a pipe, it stops being a value and becomes part of the program. The root cause is always the same: code and data share one channel.

Concatenation lets a quote in the input end the string and add new SQL. A parameterised query sends the input as a separate value, so it can never become code.

Why concatenation is tempting

String building is the most obvious way to produce a query or command, and it works perfectly with normal input. Tests written with ordinary names and numbers pass, code reviews see readable SQL and the feature ships. The bug only appears when someone sends input containing syntax characters, which ordinary users rarely do. This is why injection persists decades after it was first described: the unsafe pattern is the natural one, and its failure is invisible until someone looks for it.

Interpreters everywhere

SQL databases and shells are the best known targets, but any interpreter can be injected. Document databases accept query operators, directory services parse LDAP filters, XML processors evaluate XPath, template engines execute expressions, spreadsheet programs run formulas and logging systems interpret control characters. Each has its own syntax and escaping rules, which is part of why hand written escaping fails: developers must know every special character of every interpreter their data might reach.

Sources of untrusted input

Untrusted input is anything an attacker can influence, which is far more than form fields. URL paths and query strings, headers, cookies, JSON bodies, uploaded file names and contents, data from third party APIs, messages from queues and even values previously stored in your own database can all carry attacker controlled text. Second order injection happens when input is stored safely and later used unsafely, such as a username saved correctly and then concatenated into a report query months later.

Impact

The consequences depend on the interpreter and its privileges. SQL injection can read any table the database account can reach, modify or delete data, bypass login checks and, in some configurations, read files or run operating system commands. Command injection usually gives code execution with the privileges of the application process. Template injection often leads to code execution as well. Because the impact is so broad, injection findings are typically rated critical, and attackers scan the internet constantly for them.

Escaping is not a strategy

Escaping replaces special characters so the interpreter treats them as data. It can work, but it is fragile: each interpreter needs different escaping, character encodings can smuggle special characters past naive filters, contexts change within a single statement and one forgotten call reopens the hole. Escaping is a last resort for the rare cases where no structured interface exists. The primary defence is to use interfaces that keep code and data separate, so there is nothing to escape.

Allow lists versus deny lists

Some teams try to block dangerous input with deny lists of keywords such as SELECT or DROP. These filters break legitimate input, such as a user named Drop Shipping Ltd, and attackers bypass them with case changes, comments, encodings or alternate syntax. Allow lists, which accept only input matching a strict expected form, are more effective for fields with a known shape, such as numeric identifiers, ISO dates or sort directions. Allow lists complement safe interfaces but do not replace them.

SQL accounted for 24 of 60 confirmed injection findings, but command, NoSQL, template and LDAP injection together made up 30. Any interpreter that parses strings can be injected.

Where injection hides

Injection rarely appears in the main code paths, which use the framework safely. It hides in admin reports with custom filters, search and sort features that build dynamic queries, data export tools, scripts that shell out to command line utilities, migration jobs, legacy endpoints and internal tools that were never expected to face hostile input. Security reviews that focus on these less travelled paths find most of the remaining injection in mature codebases.

Defence in depth

Safe interfaces prevent injection, and other controls limit the damage if one slips through. The database account used by the application should have only the permissions it needs, never administrative rights. Application processes should run with minimal operating system privileges inside containers with restricted capabilities. Network egress controls can block data exfiltration and callbacks. Error messages should not reveal query text or stack traces. Each layer turns a potential breach into a smaller incident.

Injection in the threat model

During threat modelling, every point where data crosses into an interpreter is a trust boundary worth noting. A data flow diagram that shows the web tier calling the database, a worker invoking an image tool and a reporting service rendering templates makes these boundaries visible. For each one, the team should name the safe interface in use and the privileges of the interpreter. Boundaries without a safe interface become review priorities.

Frameworks change the odds

Modern frameworks make injection less likely by default. ORMs and query builders parameterise values automatically, template engines escape output by default and process libraries accept argument arrays. Developers still reach for raw queries, string formatting and shell commands when the framework feels limiting, and those escape hatches are where injection returns. Making the safe path convenient, and the unsafe path visibly unusual, is one of the most effective controls a platform team can provide.

Authorised testing

Injection testing must only be performed against systems you own or have written permission to test, within an agreed scope. In development, tests can use crafted inputs containing syntax characters to confirm that features handle them as data. Production testing belongs to authorised security assessments and bug bounty programs, covered later in the course. Uncontrolled testing can corrupt data or cause outages even when well intentioned.

What this lesson covers

The following sections look at SQL injection in detail, then at preventing it with parameterised queries and safe dynamic SQL, then at command and other interpreter injection, and finally at finding and removing injection across a codebase with static analysis, review, testing and monitoring. Throughout, the goal is structural prevention: designs in which injection cannot happen, rather than code that tries to clean up dangerous input.

A vocabulary for the rest of the lesson

A few terms recur throughout. A source is where untrusted data enters, such as a request parameter or a queue message. A sink is where data reaches an interpreter, such as a query execution call or a process launch. A sanitiser or safe API is anything that guarantees data stays data on its way from source to sink, such as parameter binding or an argument array. Injection is a path from a source to a sink that bypasses every safe API. Thinking in these terms makes review systematic: list the sinks, trace back to sources and confirm a safe API sits on every path between them.

Keep code and data apart

Injection happens when input is mixed into code for an interpreter. Use interfaces that send data separately from code, treat every external and stored value as untrusted, prefer allow lists for constrained fields, run interpreters with least privilege and focus reviews on reports, exports, scripts and other rarely travelled paths.