These are the notes for Cybersecurity Fundamentals (defensive), episode 39. Episode 38 showed SQL injection and its fix, parameterised queries. Today we find the same mistake, data crossing into an interpreter as code, in six more places: the operating system shell, NoSQL databases, LDAP directories, template engines and expression languages, HTTP headers, and log files and email headers. We finish with the one idea that covers them all: interpreter boundaries. Every term is explained the first time it appears, and the Glossary at the end defines them all again.
Neha, Ravi, Asha and every value are made up. Every demo is a small local toy program that creates its own files and data; nothing is sent over the network. Never try these inputs against systems you do not own or are not explicitly authorised to test. Every code sample runs with Python 3.13 (Jinja2 3.1 for one demo) on Linux, and every output below is copied from a real run.
The problems you'll solve
| Problem | Idea it teaches |
|---|---|
| A semicolon in a file name runs a second command | OS command injection, shell metacharacters |
| How to run a program safely | Avoiding the shell, argument arrays, -- |
| A PIN that is an object, not a string | NoSQL (operator) injection, type and schema checks |
A * that finds every employee |
LDAP injection, RFC 4515 filter escaping |
| Users write the greeting template | Server-side template injection (SSTI) |
A calculator built on eval() |
Expression language injection, allowlist parsers |
| A line break adds an HTTP header | CRLF injection, HTTP header injection |
| A forged line in the security log; a hidden Bcc | Log injection, email header injection |
| What do all of these have in common? | Interpreter boundaries |
Problem 1: OS command injection
A small admin tool counts the lines in a file by asking the operating system's shell to run wc -l <name>. The shell is the program that reads commands and runs them, like the terminal (bash, sh, cmd.exe, PowerShell). wc -l is a standard Unix program that counts lines.
Demo 1: a file name glued into a shell command
subprocess.run(cmd, shell=True) means "give this whole string to the shell to interpret".
# A toy "count the lines in a file" tool. It hands the user's text to the SHELL.
import subprocess
open("notes.txt", "w").write("buy chai\ncall Ravi\n")
def count_lines(filename):
cmd = "wc -l " + filename # glued into a shell command
print("shell runs:", cmd)
out = subprocess.run(cmd, shell=True, capture_output=True, text=True)
print(" ", (out.stdout + out.stderr).strip().replace("\n", "\n "))
count_lines("notes.txt")
count_lines("notes.txt; echo INJECTED: this ran as a second command")
count_lines("notes.txt && whoami")
Output:
shell runs: wc -l notes.txt
2 notes.txt
shell runs: wc -l notes.txt; echo INJECTED: this ran as a second command
2 notes.txt
INJECTED: this ran as a second command
shell runs: wc -l notes.txt && whoami
2 notes.txt
root
With ;, the shell ran wc, then ran echo as a second command. With &&, it ran whoami (which prints the account the program runs as). OS command injection is user input becoming operating-system commands. On a real server those commands run with the server's permissions.
Shell metacharacters
A metacharacter is a character with a special meaning to the shell.
| Characters | Meaning to the shell |
|---|---|
; and a newline |
End this command, start another |
&& / \|\| |
Run the next command if the previous one succeeded / failed |
\| (pipe) |
Feed one command's output into another |
& |
Run in the background |
$( ) and backticks |
Run a command and insert its output |
> < |
Redirect output to / input from a file |
* ? |
Wildcards that expand to file names |
Blocking a few of these never works reliably: there are many, they differ between shells, and a block list always misses one. The fix is not filtering: it is not calling a shell.
Real-life example: ordering at a chai stall
| At a chai stall | In the code |
|---|---|
| Shouting a whole sentence: "one chai; and give me the cash box" | shell=True: one string, interpreted |
| A token with fixed fields: item = chai, qty = 1 | An argument array: ["wc", "-l", name] |
| Making the chai yourself | Doing the job in your own language, e.g. open() the file |
Demo 2: avoid the shell, or use an argument array
An argument array (argument list) is a list where the program name and each argument are separate items. Python's subprocess.run([...]) (without shell=True) passes them straight to the program; no shell interprets them. -- tells most Unix programs "options end here", so a name starting with - can't be read as an option (that would be argument injection).
# Fix 1: avoid the shell. Fix 2: if you must run a program, pass an ARGUMENT ARRAY.
import subprocess
open("notes.txt", "w").write("buy chai\ncall Ravi\n")
def count_lines_python(filename): # best: no shell, no program
try:
with open(filename) as f: return f"{sum(1 for _ in f)} lines"
except OSError as e: return f"{type(e).__name__}: {e.strerror}"
def count_lines_args(filename): # list = one argument, no shell
out = subprocess.run(["wc", "-l", "--", filename], capture_output=True, text=True)
return (out.stdout + out.stderr).strip()
for name in ["notes.txt", "notes.txt; echo INJECTED"]:
print(f"{name!r:28} python: {count_lines_python(name)}")
print(f"{'':28} args : {count_lines_args(name)}")
Output:
'notes.txt' python: 2 lines
args : 2 notes.txt
'notes.txt; echo INJECTED' python: FileNotFoundError: No such file or directory
args : wc: 'notes.txt; echo INJECTED': No such file or directory
The dangerous name is now just a strange file name that doesn't exist. Order of preference:
- Avoid the program entirely: use the language's own library (open the file, use
zipfile,shutil, an HTTP client...). - If you must run a program, use an argument array, no shell, and
--before user-supplied names. - Allowlist what users may choose (e.g. only files in one folder, see Practice 1) and run the tool with least privilege.
Problem 2: NoSQL injection
A NoSQL database is one that doesn't use SQL tables; many store documents, records written like JSON (MongoDB is a popular example). Queries are objects too, e.g. {"user": "asha", "pin": "4821"}, and operators live inside them, e.g. {"$ne": x} meaning "not equal to x". If a user can send an object where we expected a string, they can send an operator.
Demo 3: a PIN that is an operator
This is a toy matcher that understands one MongoDB-style operator, $ne.
# A toy document database with MongoDB-style operators, like {"$ne": x} = "not equal to x"
import json
USERS = [{"user": "asha", "pin": "4821", "role": "admin"},
{"user": "neha", "pin": "1357", "role": "customer"}]
def matches(doc, query):
for field, want in query.items():
if isinstance(want, dict) and "$ne" in want: # operator: not equal
if doc.get(field) == want["$ne"]: return False
elif doc.get(field) != want: return False
return True
def login(body): # body = the JSON the browser sent
data = json.loads(body)
q = {"user": data["user"], "pin": data["pin"]} # passed straight in
hit = [d["user"] for d in USERS if matches(d, q)]
return f"welcome {hit[0]}" if hit else "wrong pin"
def login_fixed(body):
data = json.loads(body)
if not all(isinstance(data.get(k), str) for k in ("user", "pin")):
return "400 user and pin must be strings"
return login(body)
for body in ['{"user": "asha", "pin": "0000"}', '{"user": "asha", "pin": {"$ne": ""}}']:
print(f"{body:37} -> {login(body)}")
print(f"{'':37} fixed: {login_fixed(body)}")
Output:
{"user": "asha", "pin": "0000"} -> wrong pin
fixed: wrong pin
{"user": "asha", "pin": {"$ne": ""}} -> welcome asha
fixed: 400 user and pin must be strings
Asha's PIN is certainly "not equal to empty", so the object version logged in as the admin. This is NoSQL injection, here operator injection. Fixes:
- Check the type and shape of input: a PIN must be a string of 4 digits. Use a schema, a written description of what each field must be (Practice 2).
- Never pass raw user JSON into a query; build the query yourself from validated values.
- Many NoSQL drivers and libraries have options to reject or sanitise
$operators in user input; use them.
Problem 3: LDAP injection
Companies keep employee accounts in a directory. LDAP (Lightweight Directory Access Protocol) is how applications query it. LDAP filters look like (uid=neha) or (&(uid=neha)(dept=sales)) (& means AND). In a filter value, * means "anything".
Demo 4: a star finds everyone
The toy server understands * and the escaped form \XX (two hex digits) for a literal character. RFC 4515 (the LDAP filter standard) says \, *, (, ) and the NUL character must be written as \5c, \2a, \28, \29 and \00 in a value.
# LDAP filters look like (uid=neha). In a filter value, * means "anything".
import re
DIRECTORY = ["asha", "neha", "ravi"] # uid of every employee
def server_search(flt): # a toy directory server for filters like (uid=...)
value, rx, i = flt[5:-1], "", 0
while i < len(value):
if value[i] == "*": rx += ".*"; i += 1 # wildcard
elif value[i] == "\\": rx += re.escape(chr(int(value[i+1:i+3], 16))); i += 3
else: rx += re.escape(value[i]); i += 1 # literal
return [u for u in DIRECTORY if re.fullmatch(rx, u)]
def ldap_escape(value): # RFC 4515: \ * ( ) NUL become \5c \2a \28 \29 \00
out = value.replace("\\", "\\5c")
for ch, code in [("*", "\\2a"), ("(", "\\28"), (")", "\\29"), ("\0", "\\00")]:
out = out.replace(ch, code)
return out
for uid in ["neha", "*", "n*"]:
glued, safe = "(uid=" + uid + ")", "(uid=" + ldap_escape(uid) + ")"
print(f"{uid!r:7} glued {glued:12} -> {server_search(glued)}")
print(f"{'':7} escaped {safe:12} -> {server_search(safe)}")
Output:
'neha' glued (uid=neha) -> ['neha']
escaped (uid=neha) -> ['neha']
'*' glued (uid=*) -> ['asha', 'neha', 'ravi']
escaped (uid=\2a) -> []
'n*' glued (uid=n*) -> ['neha']
escaped (uid=n\2a) -> []
Glued, * returned every employee and n* everyone starting with n. Escaped, the star is just a character. In real directories the same trick can widen a search or a login check, and brackets can add whole new conditions (Practice 3). Use your LDAP library's filter-escaping function or filter builder; never glue strings.
Problem 4: template injection and expression language injection
A template is text with placeholders, like a wedding card design: "Dear {name}, you are invited". A template engine fills in the placeholders. Users should provide values, never the template itself. When users control the template, that's server-side template injection (SSTI).
Demo 5: the user writes the template
Python's str.format is a tiny template engine, and it can walk through object attributes.
# Server-side template injection: the USER controls the template, not just the values
class App:
secret_key = "sk_live_9f2c...e1" # signs everyone's session cookies
class User:
def __init__(self, name): self.name, self.app = name, App()
def greeting_unsafe(template, user): # "customise your greeting!"
return template.format(user=user)
def greeting_safe(text, user): # fixed template, user text is a VALUE
return "Hello {name}! {msg}".format(name=user.name, msg=text)
neha = User("Neha")
for t in ["Hi {user.name}, happy shopping!", "Leak: {user.app.secret_key}"]:
print("unsafe:", greeting_unsafe(t, neha))
print("safe :", greeting_safe(t, neha))
Output:
unsafe: Hi Neha, happy shopping!
safe : Hello Neha! Hi {user.name}, happy shopping!
unsafe: Leak: sk_live_9f2c...e1
safe : Hello Neha! Leak: {user.app.secret_key}
{user.app.secret_key} walked from the user object to the app and printed the key that signs everyone's session cookies; with it, someone could forge sessions. Full template engines (Jinja2, Twig, FreeMarker, Velocity...) are far more powerful, so SSTI can be much worse.
Demo 6: Jinja2 and eval()
Jinja2 is a popular Python template engine. eval() runs a string as Python code. An expression language is a small language for evaluating formulas or expressions inside another system (examples: Java EL, OGNL, Spring SpEL; here, Python itself acts as one). Expression language injection is user input being evaluated as an expression.
# Two more interpreters: a template engine (Jinja2) and Python's own eval()
import ast, operator
from jinja2 import Template
print("jinja, user text AS template :", Template("Hi {{ 7*7 }}").render())
print("jinja, user text as a VALUE :", Template("Hi {{ msg }}").render(msg="{{ 7*7 }}"))
DB_PASSWORD = "chai@123" # something the calculator must never see
def calc_unsafe(expr): return eval(expr) # an "expression language" = Python itself
OPS = {ast.Add: operator.add, ast.Sub: operator.sub,
ast.Mult: operator.mul, ast.Div: operator.truediv}
def calc_safe(expr): # allow ONLY numbers and + - * /
def ev(n):
if isinstance(n, ast.Constant) and type(n.value) in (int, float): return n.value
if isinstance(n, ast.BinOp) and type(n.op) in OPS:
return OPS[type(n.op)](ev(n.left), ev(n.right))
raise ValueError(f"not allowed: {type(n).__name__}")
return ev(ast.parse(expr, mode="eval").body)
for e in ["2 + 3 * 4", "DB_PASSWORD"]:
try: safe = calc_safe(e)
except ValueError as err: safe = f"ValueError: {err}"
print(f"{e:12} unsafe: {calc_unsafe(e)!s:10} safe: {safe}")
Output:
jinja, user text AS template : Hi 49
jinja, user text as a VALUE : Hi {{ 7*7 }}
2 + 3 * 4 unsafe: 14 safe: 14
DB_PASSWORD unsafe: chai@123 safe: ValueError: not allowed: Name
- As a template,
{{ 7*7 }}became49: the engine executed it. As a value, it was printed as text. eval("DB_PASSWORD")handed over a secret. The safe calculator parses the text into a syntax tree (ast) and allows only numbers and+ - * /, soDB_PASSWORDis refused:ValueError: not allowed: Name.
Fixes: never let users write templates (fixed templates, user text only as values); never eval() / exec() user input; use a tiny parser that allows only what you need. If users truly must write templates, use a sandboxed engine (e.g. Jinja2's sandbox) and treat it as high risk.
Problem 5: CRLF and HTTP header injection
Text hides two invisible characters: CR (carriage return, \r) and LF (line feed, \n). Together, CR LF ends a line. In HTTP (episode 21), each header line ends with CR LF and a blank line ends the headers. If an app copies user text into a header and the text contains CR LF, the user can start a new header line. That's CRLF injection, also called HTTP header injection (or response splitting when it breaks the response into parts).
Demo 7: a glued redirect, and a library that refuses
Nothing is sent: putrequest/putheader only build a request in memory.
# CRLF injection: in HTTP, "\r\n" (carriage return + line feed) ends a header line
def redirect_unsafe(target): # builds a raw HTTP response by gluing
return "HTTP/1.1 302 Found\r\nLocation: " + target + "\r\n\r\n"
for target in ["/orders", "/home\r\nSet-Cookie: role=admin"]:
print(redirect_unsafe(target).replace("\r\n", "\\r\\n\n"))
from http.client import HTTPConnection # a real library refuses CR/LF in headers
c = HTTPConnection("example.invalid") # nothing is sent; we only build a request
c.putrequest("GET", "/")
try:
c.putheader("Location", "/home\r\nSet-Cookie: role=admin")
except ValueError as e:
print("http.client ->", type(e).__name__ + ":", e)
Output:
HTTP/1.1 302 Found\r\n
Location: /orders\r\n
\r\n
HTTP/1.1 302 Found\r\n
Location: /home\r\n
Set-Cookie: role=admin\r\n
\r\n
http.client -> ValueError: Invalid header value b'/home\r\nSet-Cookie: role=admin'
The glued response gained a user-written Set-Cookie: role=admin header. Python's real http.client refused the same value with ValueError: Invalid header value. Let your framework build headers (modern ones refuse CR/LF) and reject line breaks in any value that goes into a header.
Problem 6: log injection and email header injection
Demo 8: the same line break in logs and email
repr() gives Python's representation of a value, showing a newline as \n.
# The same line-break trick in LOG files and EMAIL headers
def log_unsafe(user): return f"2026-11-09 10:01 login FAILED user={user}"
def log_safe(user): return f"2026-11-09 10:01 login FAILED user={user!r}" # repr shows \n
forged = "ravi\n2026-11-09 10:02 login OK user=asha"
print("--- unsafe log ---"); print(log_unsafe(forged))
print("--- safe log ---"); print(log_safe(forged))
from email.message import EmailMessage
m = EmailMessage()
try:
m["Subject"] = "Order 1042\r\nBcc: everyone@example.com" # from a "subject" form field
except ValueError as e:
print("--- email ---\n" + type(e).__name__ + ":", e)
Output:
--- unsafe log ---
2026-11-09 10:01 login FAILED user=ravi
2026-11-09 10:02 login OK user=asha
--- safe log ---
2026-11-09 10:01 login FAILED user='ravi\n2026-11-09 10:02 login OK user=asha'
--- email ---
ValueError: Header values may not contain linefeed or carriage return characters
- Log injection: the unsafe log now shows a second line,
login OK user=asha, that never happened. Logs are evidence during an investigation, and forged lines mislead people and tools. Fix: encode or reject line breaks, and prefer structured logs (e.g. JSON, one field per value). - Email header injection: a subject with CR LF could add hidden recipients through Bcc (blind carbon copy). Python's
emaillibrary refuses:Header values may not contain linefeed or carriage return characters. Always build emails with a real email library.
The one idea: interpreter boundaries
An interpreter boundary is any place a string crosses from your program into something that interprets it: a shell, a database, a directory, a template engine, an HTTP message, a log reader, a mail system, a browser. At every border, data must stay declared as data.
| Boundary | Best (data kept separate) | Next best | Weakest |
|---|---|---|---|
| SQL | Parameters | Escaping | Block lists |
| Shell | Library call / argument array | Allowlist values | Removing ; |
| NoSQL | Typed, schema-validated values | Driver operator sanitising | Block lists |
| LDAP | Filter builder / escaping function | RFC 4515 escaping by hand | Block lists |
| Templates / expressions | Fixed templates, values only; no eval |
Sandboxed engine | Block lists |
| HTTP headers, email, logs | Framework / library builders; JSON logs | Reject or encode CR LF | Ignoring it |
How common is it?
- OWASP Top 10:2025, A05 Injection (fetched 9 Nov 2026) lists OS command injection (CWE-78), command injection (CWE-77), LDAP injection (CWE-90), NoSQL, ORM, Expression Language (EL) and OGNL injection among common injection types, and recommends keeping data separate from commands, using a safe API that avoids the interpreter entirely, or a parameterised interface.
- MITRE 2025 CWE Top 25 (updated 15 Dec 2025): CWE-78 OS Command Injection is #9, CWE-94 Code Injection is #10, CWE-77 Command Injection is #23.
The whole chain
- A semicolon ran a second command → avoid the shell, argument arrays,
--. - A PIN became an operator → check type and shape (schemas).
- A star found everyone → LDAP filter escaping.
- Users wrote the template;
evalran their text → fixed templates, noeval, allowlist parsers. - A line break added a header → reject CR LF; use framework header builders.
- A fake log line, a hidden Bcc → encode line breaks, structured logs, real email libraries.
- Every interpreter boundary: data stays data.
Common mistakes (and what they print)
| Mistake | Real message / result | Why | Fix |
|---|---|---|---|
shell=True with user input |
INJECTED: this ran as a second command |
; starts a new command |
Python itself, or ["wc", "-l", "--", name] |
| Raw JSON into a query | {"pin": {"$ne": ""}} -> welcome asha |
An object can be an operator | Require strings; schema check |
| Glued LDAP filter | (uid=*) -> ['asha', 'neha', 'ravi'] |
* is a wildcard |
RFC 4515 escaping / filter builder |
eval() on user text |
DB_PASSWORD unsafe: chai@123 |
eval runs any Python |
Allowlist parser (ast) |
| User-controlled template | unsafe: Leak: sk_live_9f2c...e1 |
Templates can walk objects | Fixed template; text as a value |
| Header from user text | ValueError: Invalid header value b'/home\r\nSet-Cookie: role=admin' |
\r\n starts a new header |
Reject CR/LF; framework headers |
| Plain-text log of user input | A forged login OK user=asha line |
\n starts a new log line |
repr()/encode; JSON logs |
Mini project: a support-ticket handler that crosses three boundaries safely
# Mini project: a support-ticket handler that crosses 3 interpreter boundaries safely
import json, subprocess, os
from email.message import EmailMessage
def handle_ticket(user, subject, attachment):
problems = []
# 1) log: structured JSON, one field per value, so line breaks can't forge lines
log_line = json.dumps({"event": "ticket", "user": user, "subject": subject})
# 2) email: a real library builds headers and refuses CR/LF
msg = EmailMessage()
try:
msg["Subject"] = "Ticket: " + subject
except ValueError as e:
problems.append(f"subject refused ({e})")
# 3) program: an argument list, no shell, and -- before the file name
open("upload.bin", "wb").write(b"x" * 1234)
if attachment != "upload.bin": # allowlist: only files we stored
return log_line, problems + ["unknown attachment"], "size: skipped"
size = subprocess.run(["wc", "-c", "--", attachment], capture_output=True, text=True)
return log_line, problems or ["ok"], "size: " + size.stdout.strip()
for args in [("neha", "Late delivery", "upload.bin"),
("ravi\n{\"event\":\"admin login\"}", "Hi\r\nBcc: all@example.com", "upload.bin; echo X")]:
for part in handle_ticket(*args):
print(" ", part)
print()
os.remove("upload.bin")
Output:
{"event": "ticket", "user": "neha", "subject": "Late delivery"}
['ok']
size: 1234 upload.bin
{"event": "ticket", "user": "ravi\n{\"event\":\"admin login\"}", "subject": "Hi\r\nBcc: all@example.com"}
['subject refused (Header values may not contain linefeed or carriage return characters)', 'unknown attachment']
size: skipped
The second ticket tries a forged log line, a hidden Bcc and a shell trick in one go: the JSON log keeps the line break inside a field, the email library refuses the subject, and the allowlist refuses the attachment name before any program runs.
Practice
- Make the file tool accept only files inside a
reportsfolder, with no shell at all. - Add a schema check to the NoSQL login: exactly
userandpin, both strings, the PIN 4 digits. - Show what brackets do to an LDAP filter, glued vs escaped.
- Name one interpreter boundary in an app you use or build, and the safe tool for it.
Practice 1 solution
Path.resolve() turns a path into an absolute one (following ..), and is_relative_to checks it is still inside the folder; this also blocks path traversal (../secret.txt), which gets its own episode later.
# Practice 1 solution: the file tool only counts files inside one folder (no shell at all)
from pathlib import Path
BASE = Path("reports").resolve()
BASE.mkdir(exist_ok=True); (BASE / "q3.txt").write_text("a\nb\nc\n")
Path("secret.txt").write_text("top secret\n")
def count_lines(name):
target = (BASE / name).resolve()
if not target.is_relative_to(BASE): # blocks ../ path tricks
return "403 outside the reports folder"
if not target.is_file():
return "404 no such report"
return f"{len(target.read_text().splitlines())} lines"
for name in ["q3.txt", "q3.txt; echo INJECTED", "../secret.txt", "/etc/passwd"]:
print(f"{name!r:24} -> {count_lines(name)}")
Output:
'q3.txt' -> 3 lines
'q3.txt; echo INJECTED' -> 404 no such report
'../secret.txt' -> 403 outside the reports folder
'/etc/passwd' -> 403 outside the reports folder
Practice 2 solution
# Practice 2 solution: a tiny schema check before the NoSQL-style login
import json, re
SCHEMA = {"user": re.compile(r"[a-z]{3,20}"), "pin": re.compile(r"\d{4}")}
def validate(body):
data = json.loads(body)
if set(data) != set(SCHEMA):
return None, "400 expected exactly: user, pin"
for field, rx in SCHEMA.items():
if not isinstance(data[field], str) or not rx.fullmatch(data[field]):
return None, f"400 bad {field}"
return data, "ok"
for body in ['{"user": "asha", "pin": "4821"}', '{"user": "asha", "pin": {"$ne": ""}}',
'{"user": "asha", "pin": "4821", "role": "admin"}', '{"user": "ASHA*", "pin": "1"}']:
print(f"{body:48} -> {validate(body)[1]}")
Output:
{"user": "asha", "pin": "4821"} -> ok
{"user": "asha", "pin": {"$ne": ""}} -> 400 bad pin
{"user": "asha", "pin": "4821", "role": "admin"} -> 400 expected exactly: user, pin
{"user": "ASHA*", "pin": "1"} -> 400 bad user
Practice 3 solution
# Practice 3 solution: brackets in an LDAP filter value, glued vs escaped
def ldap_escape(value): # RFC 4515
out = value.replace("\\", "\\5c")
for ch, code in [("*", "\\2a"), ("(", "\\28"), (")", "\\29"), ("\0", "\\00")]:
out = out.replace(ch, code)
return out
uid = "neha)(dept=*"
print("glued :", "(&(uid=" + uid + ")(active=yes))")
print("escaped:", "(&(uid=" + ldap_escape(uid) + ")(active=yes))")
Output:
glued : (&(uid=neha)(dept=*)(active=yes))
escaped: (&(uid=neha\29\28dept=\2a)(active=yes))
Glued, neha)(dept=* closed the uid condition and added a new (dept=*) condition. Escaped, the brackets and star are just characters inside the uid value.
Practice 4 example answer
"Our app generates PDF invoices by calling a command-line converter with the customer's company name in the file name": use the converter's library API, or an argument array with --, and a file name we generate ourselves (e.g. invoice-1042.pdf), never the customer's text.
Quick quiz
# name comes from the user
import subprocess, os
# A
os.system("gzip " + name)
# B
subprocess.run(f"gzip {name}", shell=True)
# C
subprocess.run("gzip " + name.replace(";", ""), shell=True)
# D
subprocess.run(["gzip", "--", name])
Which call is safe?
Answer
D. Only D skips the shell: the name is one argument in a list, and -- ends the options. A (os.system always uses the shell) and B hand a glued string to the shell. C removes ;, but &&, |, $( ) and newlines still work.
Interview questions
- What is OS command injection? User input becoming operating-system commands, usually because it was glued into a string run by a shell.
- How do you run an external program safely? Prefer a library; otherwise an argument array without a shell,
--before user values, an allowlist of values, least privilege. - Why is
shell=True(oros.system) risky? The whole string is interpreted by the shell, so metacharacters in user input run extra commands. - What is NoSQL injection? Input changing a NoSQL query, often by sending an object containing an operator (e.g.
$ne) where a string was expected. - How do you prevent LDAP injection? Escape filter values per RFC 4515 (or use a filter builder) and validate input.
- What is SSTI? Server-side template injection: the user controls a template, which the engine evaluates, exposing objects or running code.
- Why never
eval()user input? It executes arbitrary code with the program's rights; use a restricted parser instead. - What is CRLF injection? Inserting
\r\ninto a value that goes into a line-based protocol (HTTP headers, email headers, logs) to start new lines. - Why do log injection bugs matter? Logs are evidence; forged lines mislead investigations and monitoring tools.
- What single principle covers all injection? At every interpreter boundary, keep data separate from code: parameters, argument arrays, builders, encoding.
Glossary
| Term | Meaning | Example |
|---|---|---|
| Interpreter | A program that reads text and acts on it | bash, SQLite, Jinja2, a browser |
| Interpreter boundary | Where a string crosses into an interpreter | Calling a shell from Python |
| Shell | The program that reads and runs OS commands | bash, sh, cmd.exe, PowerShell |
| OS command injection | User input becoming operating-system commands | notes.txt; echo INJECTED |
| Command injection | Input changing a command an app builds | CWE-77 |
| Metacharacter | A character with special meaning to the shell | ; \| && $( ) |
| Pipe | \|, feeding one command's output into another |
ls \| wc -l |
subprocess.run |
Python's function for running programs | subprocess.run(["wc", "-l", f]) |
shell=True |
Ask Python to run the string through a shell | Dangerous with user input |
| Argument array | Program name and arguments as separate list items | ["wc", "-l", "--", name] |
-- |
"End of options" marker for most Unix programs | wc -l -- -file.txt |
| Argument injection | A value starting with - read as an option |
--help as a "file name" |
| NoSQL database | A non-SQL database, often storing JSON-like documents | MongoDB |
| Document | A JSON-like record in a document database | {"user": "asha"} |
| Operator (NoSQL) | A special key that changes a query's meaning | {"$ne": ""} |
| NoSQL / operator injection | Input that inserts operators into a query | PIN sent as an object |
| Schema | A written description of what each field must be | PIN: 4-digit string |
| Directory (LDAP) | A database of accounts and groups | Company employee directory |
| LDAP | Lightweight Directory Access Protocol | (uid=neha) |
| LDAP filter | A query expression in brackets | (&(uid=neha)(dept=sales)) |
| LDAP injection | Input changing an LDAP filter | * matching everyone |
| RFC 4515 | The standard for LDAP filter strings and escaping | * → \2a |
| Template | Text with placeholders filled by an engine | "Dear {name}" |
| Template engine | Software that fills templates | Jinja2, str.format |
| SSTI | Server-side template injection: users control the template | {user.app.secret_key} |
| Sandbox | A restricted environment limiting what code may do | Jinja2's sandboxed environment |
eval() |
Runs a string as Python code | eval("2 + 3") |
| Expression language | A small language for evaluating expressions in a system | Java EL, OGNL, SpEL |
| Expression language injection | Input evaluated as an expression | eval("DB_PASSWORD") |
| Code injection | Input interpreted as code by the app | CWE-94 |
ast |
Python's module for parsing code into a syntax tree | Allowlist calculator |
| CR / LF | Carriage return \r / line feed \n |
\r\n ends an HTTP header line |
| CRLF injection | Inserting line breaks into line-based data | Extra Set-Cookie header |
| HTTP header injection | User text creating new HTTP headers | Same as above |
| Log injection | User text forging or corrupting log lines | Fake login OK line |
| Structured logs | Logs as fields (e.g. JSON) instead of free text | {"user": "..."} |
| Email header injection | User text adding email headers | Hidden Bcc: |
| Bcc | Blind carbon copy: hidden recipients | Bcc: everyone@example.com |
repr() |
Python's representation of a value, showing escapes | 'ravi\n...' |
| Allowlist | A fixed list of allowed values | Only files in reports/ |
| Least privilege | Give each part only the rights it needs | Tool runs as a limited user |
Summary
- Injection is not just SQL: shells, NoSQL, LDAP, templates, expression languages, HTTP headers, logs and email are all interpreters.
- Avoid the shell; if you must run a program, use an argument array and
--. - Validate type and shape of JSON input; escape LDAP filters per RFC 4515.
- Never let users write templates, and never
eval()their input. - Reject or encode CR LF in headers and logs; use framework and library builders and structured logs.
- At every interpreter boundary, data stays data. Next episode: cross-site scripting and output encoding.