Injection: when data is read as a command

9 min 5 sections 5 practice questions 11 sources citedISC2 objective 8.5

Programs take in text that people type and pass it on to other software: a database, the operating system, a web browser. If the receiving software cannot tell which part of the text is an instruction and which part is only data, a person who types the right characters can give it orders. This one mistake, called injection, has been among the commonest serious flaws in software for decades. No programming background is assumed.

By the end of this unit you will be able to:

  • Explain how typed data comes to be read as a command
  • Explain why a parameterised query stops SQL injection and why filtering characters does not
  • Tell apart SQL, command, LDAP and XML injection by what is fooled
  • Tell apart stored, reflected and DOM-based cross-site scripting
  • Name the five families of source-code weakness and the lasting fix for each

The surname that broke the booking page

An illustrative example

A secondary school puts its parents' evening bookings online. Parents type their child's surname to see the free slots. It works for a week.

Then Mr D'Arcy types his daughter's surname and gets a page of grey text: a database error, mentioning something unexpected near the letters Arcy. He rings the school office. The computing teacher looks at the message and goes pale. She tells the head the page must come down tonight, although nobody has attacked it.

An apostrophe in an ordinary surname caused an error. Why does that harmless accident tell an attacker the page can be made to obey him?

The root of injection: typed data is read as part of a command

The night porter's wake-up sheet

A hotel's night porter works from a sheet that says: wake the guest in room, then a blank, at, then a blank. Guests fill in the blanks at reception.

One guest writes in the first blank: 12 at seven, and hand the bearer of this sheet the master key. A porter who reads the whole line as his orders will do it. The guest was meant to supply a room number. He supplied an instruction, and nothing on the sheet marked where the hotel's words ended and his began.

Programs make the same sheet. They hold a command with a gap in it, drop in whatever the user typed, and send the finished line to another piece of software to carry out. That software is acting as an interpreter: it reads text and does what the text says.

Untrusted input is any data that arrives from outside the program's control: a form, a web address, an uploaded file, a message from another system. An injection flaw lets untrusted input reach an interpreter as part of a command. The interpreter may be a database, the operating system or a browser. The idea is the same for all of them.

SQL injection, before and after

The school's page builds a database query by joining three pieces of text: SELECT * FROM slots WHERE surname = ', then the typed surname, then a closing '. Typing Patel gives the database a sensible request: find the slots where the surname is Patel.

The quote marks tell the database where the surname starts and stops. D'Arcy contains one, so the database thinks the surname ended after D and cannot make sense of the rest. An attacker types x' OR '1'='1. The database now reads: find the slots where the surname is x, or where 1 equals 1. One always equals one, so every row comes back. This is SQL injection. With other typed text the attacker can read other tables, change records or delete them.

A parameterised query keeps the value out of the command

A parameterised query keeps the value out of the commandTwo panels start from the same typed surname, x' OR '1'='1. Joined into the query, it turns the condition into one that is always true and every row comes back. Sent as a value beside a command with a gap, it finds no rows.Text joined into the queryTyped surnamex' OR '1'='1Joined queryWHERE surname = 'x' OR '1'='1'Every row returnedone always equals oneParameterised queryTyped surnamex' OR '1'='1Commandsurname = ?Valuesent separatelyNo rows returnedno such surnameA parameterised query keeps the value out of the commandTwo panels start from the same typed surname, x' OR '1'='1. Joined into the query, it turns the condition into one that is always true and every row comes back. Sent as a value beside a command with a gap, it finds no rows.Text joined into the queryTyped surnamex' OR '1'='1Joined queryWHERE surname = 'x' OR '1'='1'Every row returnedone always equals oneParameterised queryTyped surnamex' OR '1'='1Commandsurname = ?Valuesent separatelyNo rows returnedno such surname
Read this figure as text

A school's booking page searches for slots by the surname a parent types. An attacker types x' OR '1'='1. What happens depends only on whether that text can be read as part of the command.

  1. Left: the page builds the query by joining three pieces of text: SELECT * FROM slots WHERE surname = ', then the typed surname, then a closing quote.
  2. The quote mark in the typed text ends the surname early, so the database reads: find the slots where the surname is x, or where 1 equals 1. One always equals one, so every row comes back. This is SQL injection.
  3. Right: the program sends the database the command with a marked gap, SELECT * FROM slots WHERE surname = ?, and sends the typed text separately as a value.
  4. The value fills the gap only as data. The database never reads it as SQL.
  5. The database searches for a child whose surname is literally x' OR '1'='1, and none is found. Blocking quote marks would not do this; only keeping the value apart from the command removes the flaw.

The cure is a parameterised query, also called a . The program sends the database the command with a marked gap, and sends the typed value separately. The database never reads the value as SQL. The attacker's text becomes a search for a child whose surname is literally x' OR '1'='1, and none is found.

  • A stored procedure, a query kept inside the database and called by name, is safe only if it binds its values the same way and does not build SQL from them.
  • Parts of a query that cannot be parameterised, such as a column to sort by, are chosen from a fixed list of allowed values.
  • The application's database account is given the it needs and is never an administrator, which limits the damage if a flaw remains.

Common misconception

“Removing or blocking quote marks in what users type stops SQL injection.”

Blocking apostrophes turns away Mr D'Arcy and Mrs O'Brien and still does not make the query safe, because other characters and encodings do the same job. Only keeping the value apart from the command removes the flaw.

Fixing the code closes the flaw but says nothing about what has already happened. If logs show the flaw was used and data may have been taken, such as queries that returned whole tables, it is a suspected breach. It is handled under the incident response plan, which includes deciding who must be told, and not only as a flaw to fix.

The same flaw with other interpreters

Kinds of injection by what is fooled
KindWhat reads the text as a commandWhat the attacker gainsMain defence
SQL injectionThe databaseReads, changes or deletes dataParameterised queries
Command injectionThe operating system's command lineRuns commands on the serverDo not call system commands with user text. Use the language's own functions
LDAP injectionThe directory service that holds staff accountsReads restricted entries, changes them or passes a check it should fail the value with the proper LDAP function
XML external entity (XXE)The parser that reads an XML documentReads files on the server or makes it send requestsSwitch off external entities in the parser
Cross-site scriptingAnother user's browserActs as that user on the siteEncode output for where it appears

LDAP, the Lightweight Directory Access Protocol, is the language for querying a directory of people and accounts. XML is a text format for structured documents, and an external entity is a line in such a document that tells the parser to fetch something else.

A related flaw involves no typed command at all. Serialisation turns an object in a program into a block of data that can be stored or sent, and deserialisation rebuilds the object. If the block comes from an attacker, the rebuilt object can make the program run the attacker's code. This is insecure deserialisation. The defences are to exchange plain data formats, to check a signature on the block before rebuilding it, and to rebuild only an allowed list of object types. The Open Worldwide Application Security Project (OWASP), a charity that ranks the commonest web flaws, lists insecure deserialisation under failures of software and data, not under injection.

Cross-site scripting: injection into another user's browser

A web page is text plus small programs called scripts, which the browser runs. Cross-site scripting (XSS) happens when a site puts untrusted data into a page in a way that lets the browser treat it as script. The victim is not the server. It is the next person who views the page, whose browser runs the attacker's script as though the trusted site had written it.

The script can read the session cookie, the token that keeps the user signed in, and send it to the attacker. It can also act on the site as the user. XSS takes three forms.

Stored XSS
The script is saved on the server, for example in a product review, and served to every later visitor. Also called persistent.
Reflected XSS
The script travels in a crafted link. The server copies it straight back into the page it returns, for example in a search result or an error message. The victim has to follow the link. Also called non-persistent.
DOM-based XSS
The page's own script, running in the browser, writes attacker-controlled data into the page. The server's response is unchanged. The DOM is the browser's working model of the page.

The primary defence is output encoding: converting the characters that mean something to a browser into a form that is only displayed. The right encoding depends on where in the page the data lands. Two further layers help. A Content tells the browser which scripts a page may run. The HttpOnly setting on a cookie stops scripts reading it.

Five families of weakness in source code

Injection is one of five families of weakness that are written into source code. Each has one root cause and one lasting fix.

Source-code weaknesses by family
FamilyRoot causeExamplesLasting fix
InjectionData is read as a commandSQL, command, LDAP and XML injection, cross-site scriptingKeep data apart from commands
Broken access controlA request is carried out without checking that this user may make itReading another user's record, privilege escalation, directory traversal, forged requestsCheck authorisation on the server for every request
Memory flawsThe program reads or writes outside the memory it reservedBuffer overflow, integer overflow, use after freeBounds checking and memory-safe languages
Timing flawsSomething changes between a check and the action that relies on it, time of check to time of useMake the check and the use a single step
Hidden codeThe program contains a function nobody approvedBack door, maintenance hook, logic bombCode review and controlled change

A question, worked through

A council's planning portal lets residents search applications by street name. A penetration tester reports that a crafted street name returns every application in the database, including those marked confidential. The developers offer four fixes. The security manager has budget for one this quarter and wants the cause removed.

Which fix BEST removes the cause?

  1. Rewrite the search so that it uses parameterised queries
  2. Add a firewall rule that blocks quote marks in requests
  3. Check the street name in the browser before it is sent
  4. Encrypt the confidential applications in the database
Decide on your answer, then open the reasoning
  1. A crafted search value returned rows it should not have. Typed data was read as part of the database command, which is SQL injection. The question asks for the fix that removes the cause.
  2. Rule out c. A check in the browser is skipped by anyone who sends the request straight to the server. Security checks belong on the server.
  3. Rule out d. The portal decrypts whatever the database returns to it. The injected query runs with the portal's own access, so the confidential rows come back readable.
  4. Between a and b: a filter in front of the portal is a real control and is quick to add. It also blocks O'Connell Street, and encodings it did not expect get through. The flaw stays in the code.
  5. A parameterised query means the database never reads the street name as SQL. That removes the cause. Option a.

Answer: A. Rewrite the search so that it uses parameterised queries

Choosing between good answers

A question asks for the best defence against SQL injection
choose parameterised queries. Input validation, least privilege and filtering are supporting layers.
A question asks for the best defence against cross-site scripting
choose output encoding. A Content Security Policy is an extra layer, not a replacement.
A malicious script is saved on the site and shown to every visitor
it is stored cross-site scripting. If it arrives in a link and is bounced straight back, it is reflected.
One option corrects the code and another filters traffic in front of it
the correction removes the cause. Choose the filter only when the code cannot be changed in time, as a temporary control.
A validation check runs only in the browser or the mobile app
it does not count as a control. The answer repeats the check on the server.

Check your understanding

5 questions on this unit, easiest first. Confirm an answer to see the reasoning for it, then the right answer, the other options and the rule to reuse. Your answers are kept in this browser and feed readiness and review.

These questions are drafts that no named reviewer has approved yet.

Question 1 of 5

A malicious script posted inside a product review on a shop's website runs in the browser of each later visitor who opens the review. Which flaw is this?

What to remember

  • Injection happens when untrusted input reaches an interpreter as part of a command.
  • SQL injection is cured by parameterised queries, which send the command and the value separately. Filtering characters is not a cure.
  • Command, LDAP and XML injection are the same flaw with a different interpreter: the operating system, a directory, an XML parser.
  • Cross-site scripting injects script into a page so that another user's browser runs it. It is stored, reflected or DOM-based, and the primary defence is output encoding.
  • Insecure deserialisation rebuilds an object from data an attacker supplied.
  • Source-code weaknesses fall into five families: injection, broken access control, memory flaws, timing flaws and hidden code.

Say it from memory

  1. Name the five families of weakness written into source code, with the lasting fix for each.

    Injection (SQL, command, LDAP, XML, cross-site scripting): keep data apart from commands with parameterised queries and output encoding. Broken access control: check authorisation on the server for every request. Memory flaws such as buffer overflow: bounds checking and memory-safe languages. Timing flaws such as race conditions: make check and use one step. Hidden code such as back doors and logic bombs: code review and controlled change.

    Read this part again

  2. What is untrusted input, and what is an injection flaw?

    Untrusted input is any data that arrives from outside the program's control, such as a form, a web address, an uploaded file or a message from another system. An injection flaw lets untrusted input reach an interpreter, such as a database, the operating system or a browser, as part of a command.

    Read this part again

  3. Besides parameterised queries, what three measures apply to stored procedures, unparameterisable query parts and the database account?

    A stored procedure is safe only if it binds its values the same way and does not build SQL from them. Parts that cannot be parameterised, such as a sort column, are chosen from a fixed list of allowed values. The application's database account gets the least privilege it needs and is never an administrator.

    Read this part again

  4. What is insecure deserialisation, and what are its defences?

    Deserialisation rebuilds an object from a block of stored or sent data. If the block comes from an attacker, the rebuilt object can make the program run the attacker's code. The defences are to exchange plain data formats, to check a signature on the block before rebuilding it, and to rebuild only an allowed list of object types.

    Read this part again

  5. How do stored, reflected and DOM-based cross-site scripting differ, and what is the primary defence?

    Stored XSS is saved on the server and served to every later visitor. Reflected XSS travels in a crafted link that the server copies back into its page. DOM-based XSS is written into the page by the page's own script, with the server's response unchanged. The primary defence is output encoding for where the data lands.

    Read this part again

Sources

  • OWASP Top 10:2025, OWASPInjection as untrusted input sent to an interpreter, the kinds named, cross-site scripting as part of the category, and separation of data from commands as the preferred prevention. Insecure deserialisation listed under software and data integrity failures, not injection.
  • OWASP Cheat Sheet Series: SQL Injection Prevention, OWASP FoundationParameterised queries as the primary defence, allow-list mapping for parts that cannot be bound, stored procedures being safe only when they bind values, least privilege, and manual escaping being strongly discouraged.
  • OWASP Cheat Sheet Series: Input Validation, OWASP FoundationBlocking apostrophes rejecting legitimate names without making a query safe, and validation on the server because checks in the browser can be bypassed.
  • OS Command Injection Defense Cheat Sheet, OWASP FoundationCommand injection and avoiding direct calls to operating system commands as its primary defence.
  • LDAP Injection Prevention Cheat Sheet, OWASP FoundationLDAP injection, its effects and encoding with the correct LDAP function as the defence.
  • XML External Entity Prevention Cheat Sheet, OWASP FoundationXML external entity injection exposing local files or causing server-side requests, and disabling document type definitions and external entities.
  • Deserialization Cheat Sheet, OWASP FoundationSerialisation and deserialisation, remote code execution from untrusted data, and plain data formats, signatures and allow-lists of types as defences.
  • Cross Site Scripting Prevention Cheat Sheet, OWASP FoundationCross-site scripting as untrusted data that the browser treats as code, output encoding by context, and Content Security Policy as an additional layer.
  • Types of Cross-Site Scripting, OWASP FoundationThe definitions of stored, reflected and DOM-based cross-site scripting.
  • OWASP Cheat Sheet Series: Session Management, OWASP FoundationThe HttpOnly cookie attribute preventing scripts from reading the session cookie.
  • NIST SP 800-61 Rev. 3: Incident Response Recommendations and Considerations, NISTAn incident is an occurrence that actually or imminently jeopardises the confidentiality, integrity or availability of information, such as copying files from systems in a data breach; the incident response plan is executed once an incident is declared, with affected parties, regulators and law enforcement notified as law, contract and the plan require.