Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 38 ยท Cryptographic Failures and Injection

Command Injection and Other Injection Types

Learn OS command injection, NoSQL operator injection, LDAP, header and template injection, and the shared defense: keep data separate from instructions with safe APIs and allow-lists.

Every injection flaw follows one pattern: a program builds a command for some interpreter by joining strings, and untrusted input changes what the command means. SQL and the browser were covered in the last two lessons. This lesson looks at other interpreters and shows that the cure is always the same: keep instructions and data separate.

OS command injection

Many programs call operating-system commands to resize images, ping hosts, convert documents or run Git. If user input is placed in a shell command line, shell metacharacters (;, &&, |, `, $(), newline) can append a second command.

Python
# VULNERABLE: the string goes through a shell
os.system("ping -c 1 " + host)

Input like example.org; cat /etc/passwd runs two commands. The attacker then runs code with the application's own privileges.

Fixes, in order of preference

  1. Do not run a command at all. Use a library or language feature (an image library instead of convert, an HTTP client instead of curl).
  2. Use an argument list with no shell. Pass the program and its arguments separately: subprocess.run(["ping", "-c", "1", host]) or execFile in Node, ProcessBuilder in Java, proc_open with an array in PHP. Without a shell, ; is just a character inside an argument.
  3. Validate against an allow-list of acceptable values (a strict host-name pattern, a fixed set of options).
  4. Prevent option injection: a value beginning with - can be read as a command-line option. Use -- to end options, or reject leading dashes.
  5. Run with least privilege, in a container or sandbox, with restricted network access.

The demo below does not run a shell. It builds the argument list that a real call would receive and shows how a shell would split the vulnerable string, using Python's shlex.

Python String command versus argument list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The safe version restricts the input to characters that are valid in a host name, and even then passes it as a single argument.

NoSQL injection

Document databases accept queries as objects. If a JSON request body is passed straight into the query, an attacker can supply an operator object instead of a string:

JSON
{ "username": "admin", "password": { "$ne": null } }

"Password not equal to null" matches any account with a password. The fix: validate types (the password must be a string), build the query yourself from validated values, and disable operator parsing from user input.

Python Operator injection in a toy document store

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

(The toy matches function mimics the idea of a query operator. It is not a real database driver.)

LDAP, XPath and similar query languages

Directory lookups (LDAP filters) and XML queries (XPath) use special characters too: *, (, ), |, & in LDAP. Escape with the library's functions designed for that language, or use parameterized APIs when offered. A wildcard * in a username filter can turn "find this user" into "find all users".

Header and log injection

If user input containing a carriage return and line feed (\r\n) is placed into an HTTP header or a log line, an attacker can start new header lines (response splitting) or forge log entries.

Python Neutralising newlines in logs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Structured logging (JSON lines, with each value as its own field) removes this whole class of problems.

Template injection (SSTI)

Template engines turn text into pages. If user input is used as the template itself (not as data given to a template), the attacker can run template expressions, which in many engines reach code execution.

Python
# VULNERABLE: the user's text becomes part of the template source
render_template_string("Hello " + name)

# SAFE: the template is fixed; the user's text is data
render_template_string("Hello {{ name }}", name=name)

Rule: templates come from developers; users supply values.

Other places to look

  • Expression and eval-style features: eval, exec, Function(), expression languages (EL, SpEL, OGNL).
  • Deserialization of untrusted objects (see the integrity chapter later).
  • XML external entities (XXE): disable DTDs and external entities in XML parsers.
  • Email header injection in contact forms: strip newlines from addresses and subjects.
  • CSV injection: a cell starting with = can run a formula when opened in a spreadsheet; prefix risky cells with a quote.
  • Regular-expression injection and ReDoS: user input used as a pattern, or patterns with catastrophic backtracking.

One rule to remember

flowchart LR
  I["Untrusted input"] --> Q{"Used as data or as instructions?"}
  Q -->|"Data"| S["Pass through a safe API (parameters, argument arrays, auto-escape)"]
  Q -->|"Instructions"| N["Do not allow. Map to an allow-list of fixed choices"]

If user input must choose behavior, let it select from options you defined; never let it write the instruction itself.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which call avoids command injection best?

    An argument list with no shell treats the value as one argument, and validation limits what it can be.
  2. 2. What does {"password": {"$ne": null}} do in a naive NoSQL login?

    The operator object changes the query's meaning. Type validation (must be a string) stops it.
  3. 3. Why remove CR and LF characters from values written to logs?

    Newlines let an attacker start a new line that looks like a genuine event.
  4. 4. What is the safe pattern for template engines?

    When the user controls template source, they control code execution. Values must stay values.

Summary

  • All injection mixes untrusted data into an interpreter's instructions; fix it by separating the two.
  • Avoid shells: use libraries or argument arrays, validate against allow-lists and block option injection.
  • Validate the types of JSON input to stop NoSQL operator injection; escape LDAP and XPath with the right library.
  • Neutralise newlines in headers, logs and email fields; prefer structured logging.
  • Never build templates from user input; users supply data, developers supply instructions.

Next: Insecure Design: Thinking Before Coding (A04)