What Is an Injection Attack? Types and Defense
An injection attack occurs when an application passes untrusted input to an interpreter (a SQL engine, a shell, an LDAP directory, or a browser) in a way that lets the input change the command or query being run.
A login form asks for a username and password. An attacker types ' OR '1'='1 into the username field and leaves the password blank. The application takes that text and pastes it straight into a database query. What was meant to be a username is now part of the SQL logic, and the rewritten query returns the first user in the table, often an administrator. No password was guessed. No exploit was dropped. The application did exactly what its code told it to do, which was to treat attacker input as trusted instructions.
That is the whole of an injection attack in one line. An injection attack occurs when an application takes untrusted input and passes it to an interpreter, a SQL engine, a shell, an LDAP directory, an XML parser, a browser, in a way that lets the input change the command or query being run. The interpreter cannot tell the difference between the code the developer wrote and the code the attacker smuggled in through a data field, so it runs both. Injection is not one technique but a whole family, defined by a single root cause: data and code are mixed in the same channel.
This guide covers what an injection attack is, the main types a defender should be able to name, how the attack actually works under the hood, what it costs when it succeeds, and the controls that stop it. Cross-site scripting is part of this family and is covered here only in context; the dedicated article goes deeper on it.
What is an injection attack?
An injection attack is a class of cyberattack in which an attacker sends input that an application interprets as a command or query rather than as plain data. The application is supposed to treat what a user types as inert content, a name, a search term, a comment, but a flaw in how that input is handled lets the attacker's text break out of the data context and alter the instruction the application sends to a backend interpreter.
The defining flaw is the absence of separation between code and data. Whenever an application builds a command by gluing together trusted code and untrusted input as a single string, an attacker who controls part of that string can rewrite the whole instruction. This is why injection shows up against so many different backends: the same root cause applies whether the interpreter is a SQL database, a system shell, an LDAP server, or a web browser rendering a page.
Injection has been near the top of the industry's risk lists for two decades. In the OWASP Top 10:2025, the current edition, Injection is ranked A05:2025. It sat at A03 in the 2021 list and at A01, the single highest web application risk, in 2017. The drop in rank reflects better framework defaults and wider use of safe APIs, not a disappearance of the problem; injection flaws remain among the most tested and most exploited weaknesses in web applications.
One point of housekeeping that trips people up: as of the 2021 list, OWASP folds cross-site scripting (XSS) into the Injection category. XSS is injection into a web page that a victim's browser then executes, so it belongs to the same family as SQL and command injection even though the interpreter is the browser rather than a database.
The main types of injection attacks
Injection is named after the interpreter it targets. The mechanics differ, but the pattern is identical: untrusted input crosses into a place where it is treated as code.
| Type | Interpreter targeted | What the attacker gets | Classic payload shape | |
|---|---|---|---|---|
| SQL injection (SQLi) | A SQL database | Read, modify, or delete data; sometimes command execution | ' OR '1'='1 , '; DROP TABLE users; -- | |
| Command injection | The host operating system shell | Run arbitrary OS commands on the server | ; cat /etc/passwd , && whoami | |
| Cross-site scripting (XSS) | The victim's web browser | Run script in the victim's session; steal cookies or tokens | <script>...</script> in a reflected or stored field | |
| LDAP injection | An LDAP directory service | Bypass authentication; read or alter directory data | `*)(uid=*))( | (uid=*` |
| XML / XPath injection | An XML parser or XPath query | Read files, alter query logic, trigger XXE | crafted XML entities, ' or '1'='1 in XPath | |
| NoSQL injection | A NoSQL database query | Bypass auth; extract documents | operator payloads like {"$ne": null} |
A few of these carry most of the real-world weight.
SQL injection is the canonical case. The attacker supplies input that becomes part of a SQL statement, letting them read data they should not see, bypass authentication, modify or delete records, or in some configurations run commands on the database host. The ' OR '1'='1 trick in the opener turns a conditional into one that is always true; the '; DROP TABLE shape shows how a single field can append an entirely new statement.
Command injection targets applications that pass user input to a system shell, for example a tool that pings a hostname the user provided. If the application builds the shell command by concatenating that hostname, an attacker appends ; cat /etc/passwd or && whoami and the server runs it. The payoff is direct code execution on the server, which is why command injection is often the most damaging of the family.
Cross-site scripting (XSS) injects script into a web page rather than a backend interpreter. The malicious script is stored or reflected by the application, then executed by another user's browser in that user's session, which lets the attacker steal session cookies, capture keystrokes, or act as the victim. Because the interpreter is the browser, XSS is the one injection type whose direct victim is another user rather than the server. The mechanics, stored versus reflected versus DOM-based, are covered in the dedicated cross-site scripting article.
LDAP, XML, XPath, and NoSQL injection apply the same idea to directory services, XML parsers, and document databases. XML injection in particular can escalate to XML external entity (XXE) attacks, where a crafted document makes the parser read local files or reach internal systems.
How an injection attack works
Every injection follows the same four-beat sequence, whatever the interpreter. Seeing the sequence once makes every variant recognizable.
- Find an input that reaches an interpreter. The attacker probes form fields, URL parameters, HTTP headers, cookies, and API bodies for any value the application forwards to a database, shell, parser, or browser. A single quote, a semicolon, or an angle bracket that produces an error or a changed response is the tell.
- Craft a payload that breaks out of the data context. The input is shaped so part of it is read as code: a quote that closes a string literal, a semicolon that starts a new statement, a tag that opens a script. The goal is to escape the slot the developer intended and reach the surrounding instruction.
- The interpreter executes the mixed instruction. Because the application handed it one string of trusted code plus untrusted input, the interpreter parses and runs the whole thing. It has no way to know which characters came from the developer and which came from the attacker.
- The attacker reads the result or pivots. Returned data, an error message, a timing difference, or a new shell foothold tells the attacker what worked. From there they extract data, bypass authentication, or move deeper into the environment.
The reason the whole class exists is beat three. An interpreter executes whatever syntactically valid instruction it receives. The vulnerability is never in the database or the shell; it is in the application that built an instruction out of untrusted parts and trusted the result.
A practical detail worth knowing: not every injection returns data directly. In blind injection, the application does not echo results, so attackers infer them one bit at a time from boolean responses (a page that loads differently for true versus false) or from time delays (a payload that tells the database to sleep for ten seconds confirms the condition was true). Blind techniques are slower but just as effective, which is why a quiet application is not a safe one.
What injection attacks cost
When an injection succeeds, the impact tracks what the interpreter can do. The same flaw can mean a minor information leak or a full compromise depending on the backend and the application's privileges.
- Data exposure and breach. SQL and NoSQL injection are leading routes to mass data theft. An attacker can dump entire tables of customer records, credentials, or payment data, the raw material of a data breach and the extortion or resale that follows.
- Authentication bypass. Injection that rewrites a login query lets an attacker log in as another user, often an administrator, without a valid password.
- Remote code execution. Command injection, and SQL injection against permissive database accounts, can give the attacker the ability to run code on the server, turning a web flaw into a foothold in the network.
- Data integrity loss. Beyond reading data, an attacker can modify or delete it, corrupting records or destroying tables with a single payload.
- Account and session takeover. XSS lets an attacker hijack another user's session, acting as that user inside the application.
- Downstream cost. A successful injection drives the familiar tail of any serious incident: downtime, investigation and remediation effort, regulatory fines, legal exposure, and reputational damage.
The through-line is that injection sits at the front of an attack, not the end. It is frequently the initial access that a larger intrusion is built on, which is why a single unvalidated parameter can lead to a breach that takes months to clean up.
How to prevent injection attacks
The fix for injection is structural, not cosmetic. The root cause is mixing code and data in one channel, so the durable defenses are the ones that keep them separate. Treat the controls as layers; the first two do most of the work.
- Use parameterized queries and prepared statements. This is the single most effective control against SQL injection. Instead of building a query by concatenating strings, the application sends the query structure and the user data to the database separately, so the data can never be parsed as SQL. Use the safe, parameterized API of the database driver or ORM rather than assembling raw queries.
- Validate and sanitize all input. Treat every input as untrusted. Prefer allowlist validation, accept only the characters and formats a field legitimately needs, over trying to blocklist bad ones. Validation does not replace parameterization; it is a second layer that shrinks the attack surface.
- Encode output for its context. For XSS specifically, encode data when it is written into a page so the browser renders it as text rather than markup, and apply a Content Security Policy to limit what scripts can run.
- Avoid passing input to a shell. For command injection, call OS functionality through safe library APIs that take arguments as a list rather than building a shell string. If a shell is unavoidable, validate against a strict allowlist.
- Enforce least privilege on backends. Run the application's database and OS accounts with the minimum rights they need. A read-only database account cannot drop a table even if injection succeeds, which caps the blast radius.
- Test continuously. Static and dynamic application security testing, code review, and a web application firewall as a backstop all help. The WAF is a mitigation, not a fix; it can be bypassed, so it never substitutes for safe coding.
The order matters. Parameterized queries and context-aware output encoding remove the vulnerability at its source. Input validation, least privilege, and a WAF reduce what an attacker can do if something slips through. A team that does the first two well has solved most of the problem.
How to detect injection attempts
Because injection rides in over normal application traffic, detection leans on watching the inputs and the backend behavior rather than looking for malware. Useful signals include application and web server logs showing payload-like characters in parameters (stray quotes, semicolons, SQL keywords, script tags), database error messages surfacing to users, and unusual query patterns or volumes that suggest automated probing. A spike in failed queries, sudden large result sets, or repeated requests that differ only by a timing-control payload point to blind injection attempts.
Tying this together at scale means centralizing application, database, and web server logs and alerting on the patterns above, ideally correlated so a probe in the web logs and an anomaly in the database surface as one event. Detection does not replace prevention, but it shortens the time between a first probe and a response, which is the difference between a blocked attempt and a breach.
The bottom line
An injection attack is what happens when an application lets untrusted input cross the line from data into code. The interpreter, whether a SQL database, a shell, an LDAP directory, or a browser, runs whatever syntactically valid instruction it receives, so an attacker who controls part of that instruction controls the outcome. The family is broad, SQL injection, command injection, XSS, LDAP, XML, and NoSQL all share the same root cause, but the defense is narrow and well understood. Keep code and data in separate channels with parameterized queries and context-aware output encoding, validate input as a second layer, run backends with least privilege, and watch your logs for the payload patterns that signal a probe. Injection has fallen from the top of the OWASP list because those defenses work, not because attackers stopped trying.
Frequently asked questions
<p>An injection attack is a class of cyberattack in which an attacker sends input that an application treats as a command or query rather than as plain data. A flaw in how the input is handled lets the attacker's text break out of the data context and change the instruction the application sends to a backend interpreter, such as a SQL database, a shell, an LDAP directory, or a web browser. The interpreter then runs the attacker's code alongside the developer's.</p>
<p>The most common are SQL injection (against a database), command injection (against the host operating system shell), and cross-site scripting or XSS (against the victim's browser). Other types target other interpreters: LDAP injection against directory services, XML and XPath injection against XML parsers, and NoSQL injection against document databases. They share one root cause: untrusted input is mixed with code in the same channel.</p>
<p>It follows four beats. The attacker finds an input that reaches an interpreter, crafts a payload that breaks out of the data context (a quote that closes a string, a semicolon that starts a new statement, a tag that opens a script), and the interpreter executes the resulting mixed instruction because it cannot tell the developer's code from the attacker's. The attacker then reads the returned data or uses the foothold to move deeper.</p>
<p>Yes. As of the OWASP Top 10:2021, cross-site scripting (XSS) is folded into the Injection category, and it remains there in the 2025 edition. XSS injects script into a web page that a victim's browser then executes, so it shares the same root cause as SQL and command injection. The difference is the interpreter: the browser rather than a database or shell, which makes the direct victim another user rather than the server.</p>
<p>The durable fix is to keep code and data in separate channels. Use parameterized queries and prepared statements so user input can never be parsed as SQL, and encode output for its context to stop XSS. Add input validation with an allowlist as a second layer, call OS functionality through safe library APIs instead of building shell strings, and run database and OS accounts with least privilege so a successful injection has a limited blast radius. A web application firewall is a backstop, not a substitute for safe coding.</p>
<p>In the OWASP Top 10:2025, the current edition, Injection is ranked A05. It was A03 in the 2021 list and A01, the single highest web application risk, in 2017. The fall in rank reflects safer framework defaults and wider use of parameterized APIs, not the disappearance of the problem; injection flaws remain among the most tested and exploited weaknesses in web applications.</p>