#Why this matters
Injection flaws appear whenever data crosses into a place where it can be read as instructions: a browser page, a database query, an operating-system command or a template. The root cause is always the same: the application mixed untrusted data with code and relied on luck to keep them apart. Two disciplines remove most of that risk. Validation decides what the application is willing to accept. Encoding makes sure that whatever it accepted is treated purely as data when it is written to its destination.
#Three different tools
| Technique | Question it answers | Where it is applied |
|---|---|---|
| Validation | Is this input acceptable for this field? | When input arrives, on the server |
| Sanitization | Can I remove the dangerous parts of rich content that I must keep? | Only when users may submit formatted content |
| Output encoding | How do I show this value safely here? | At the moment of output, per context |
Validation reduces the attack surface but is not a complete defence: a name such as O'Brien is valid and must still be handled safely in a query and in a page. Encoding and parameterized queries are what make valid-but-unusual data harmless.
#Allowlist validation on the server
Client-side checks improve usability but an attacker can send requests without your page, so every rule must be repeated on the server. Define each field by what is allowed.
- Type and range: an integer between 1 and 100, a date in ISO format, a value from a fixed list.
- Length: a minimum and a maximum, to limit abuse and storage problems.
- Format: a strict pattern anchored at both ends, for example a username of 3 to 32 letters, digits or underscores.
- Canonical form: decode and normalise once, then validate the result, and reject input that is still encoded after decoding.
- Reject, do not repair: silently "cleaning" input hides mistakes and often creates new dangerous strings.
import re
USERNAME = re.compile(r"[A-Za-z0-9_]{3,32}")
def parse_username(raw: str) -> str:
value = raw.strip()
if not USERNAME.fullmatch(value):
raise ValueError("invalid username")
return value
def parse_page_size(raw: str) -> int:
size = int(raw) # raises ValueError for non numbers
if size not in range(1, 101):
raise ValueError("page size out of range")
return size#Context-aware output encoding
The same text needs different treatment depending on where it lands. The characters that matter in an HTML body are not the same as those that matter in a URL or inside a script.
| Context | Dangerous characters | Safe approach |
|---|---|---|
| HTML text | less-than, ampersand | HTML entity encoding, for example < |
| HTML attribute | quotes, spaces | Always quote attributes and encode quotes as entities |
| URL parameter | reserved characters | Percent-encoding of the value |
| JavaScript data | quotes, line breaks, closing tags | Pass data as JSON in a data attribute instead of building script text |
| CSS | many | Avoid putting untrusted data in styles |
Use the framework features that do this by default. Template engines such as Jinja2, Twig and Blade escape variables automatically; the risky moments are the explicit opt-outs, such as |safe or the unescaped output syntax, and DOM APIs such as innerHTML.
// Unsafe: the value is parsed as markup
element.innerHTML = userComment;
// Safe: the value is treated as plain text
element.textContent = userComment;When users really must submit formatted text, sanitize it with a maintained library such as DOMPurify and an allowlist of tags, then still serve it with a Content Security Policy.
#Content Security Policy as a safety net
A strict policy limits where scripts may load from and blocks inline script, so an injection that slips through is much harder to use.
$ curl -sI https://lab.example.test/ | grep -i content-security-policy
content-security-policy: default-src 'self'; script-src 'self'; object-src 'none'; base-uri 'self'CSP complements encoding and never replaces it: keep both layers.
#Defending / Common mistakes
- Building a blacklist of bad words or tags; attackers find the variant you missed.
- Validating only in the browser.
- Encoding once on input and storing the result, which double-encodes later or fails in other contexts. Encode when writing output.
- Using the right escaping for the wrong context, for example HTML escaping inside a script block.
- Turning off auto-escaping for convenience and forgetting to turn it on again.
- Treating validation as a replacement for parameterized queries.
#Summary
Define valid input explicitly and enforce it on the server by type, length, range and strict format. Encode at output for the exact context and prefer framework defaults and safe DOM APIs. Sanitize rich content with a maintained library, add a Content Security Policy as a second layer, and never mix untrusted data into code.