Injection & XSS defences
Explain why injection and XSS happen and fix them with parameterisation and output encoding.
By Invicly Tech, , in Cyber Security Fundamentals. About 11 minutes to read.
In short
Injection and cross-site scripting both happen when untrusted input is treated as code. SQL injection fixes with parameterised queries; XSS fixes with context-aware output encoding and a Content Security Policy. The defender's job is to keep data and code apart.
Explained simply
Many programs build commands out of text: a database query, a shell command, an HTML page. Injection happens when text from a user is glued into that command, and the user's text changes what the command does. The program meant to send data, but the interpreter read it as code.
SQL injection is the classic case. If a login query is built by joining strings, a user can type characters like a quote that end the data part early and add their own SQL. That can let them read other tables or skip the password check.
Cross-site scripting (XSS) is injection into a web page. If a site shows a comment without encoding it, and the comment contains script, every visitor's browser runs that script as if it came from the site. It can steal data from the page or act as the user.
The fix for both is the same idea: keep data and code apart. For databases, send the query and the data separately. For web pages, encode data for the exact place it appears so the browser treats it as text. Filtering bad words alone is never enough.
Press Play on a diagram to walk through it one step at a time.
- Step 1Untrusted input
From a user or request.
- Step 2Mixed with code
Concatenated into a query or page.
- Step 3Interpreter runs it
As SQL or script.
- Step 4Fix: separate
Parameterise and encode output.
- 1Safe APIs
Parameterised queries, subprocess lists, auto-escaping templates
- 2Input validation
Type, length and format checks; allow-lists
- 3Output encoding
Matched to HTML, attribute, JS or URL context
- 4CSP and cookie flags
Block injected scripts; HttpOnly cookies
- 5Least privilege
Limited DB account and OS user
- 6Detection
WAF alerts, CSP reports, DB error spikes
In depth
How parameterised queries really work
With a parameterised query (also called a prepared statement), the application sends the SQL text with placeholders, such as WHERE email = ? or WHERE email = %s, and sends the values separately. The database parses the SQL first and fixes its structure. Values are then only ever treated as data, so a quote inside them is just a character. This is why it works for every input, unlike escaping by hand.
Placeholders can only stand for values, not for table names, column names or keywords like ASC and DESC. For a sortable column, map the user's choice through an allow-list in code (for example "name" maps to users.name) and reject anything else.
ORMs use parameters by default, but most also offer raw SQL helpers where string building is still possible. Stored procedures are only safe if they do not build dynamic SQL inside. As a second layer, give the app's database account only the rights it needs, so an injection cannot drop tables or read other schemas.
- Values: always placeholders
- Identifiers and sort order: allow-list mapping
- Database user: least privilege, no admin rights
Other interpreters: OS commands, LDAP, templates
Any interpreter can be injected. OS command injection happens when input reaches a shell, for example running ping with a user-supplied host through a shell string. A semicolon or && in the input starts a second command. The fix is to avoid the shell: in Python, call subprocess.run with a list of arguments and the default shell=False, so input is passed as one argument and never parsed by a shell. Better still, use a library function instead of an external program.
The same pattern appears elsewhere. LDAP queries built from strings can be changed with characters like * and parentheses. Server-side template injection happens when user input becomes part of the template itself rather than a value passed into it. NoSQL databases can be injected through operators hidden in JSON input.
The defence is always the same shape: use an API that separates structure from data, validate input against what you expect (type, length, format), and run with least privilege.
The three kinds of XSS and context-aware encoding
Reflected XSS bounces input straight back in the response, often through a link the victim is tricked into clicking. Stored XSS saves the payload, for example in a comment, so it runs for every visitor. DOM-based XSS happens entirely in the browser when JavaScript takes data from the URL or another source and writes it into the page with an unsafe method such as innerHTML.
Output encoding must match the context where data lands. In HTML text, encode characters like the less-than sign and ampersand as entities. Inside an HTML attribute, also encode quotes and always quote the attribute. Inside JavaScript, encode as a JavaScript string, or better, pass data through a data attribute or JSON. In a URL, use URL encoding and allow only http and https schemes, so a javascript: link cannot run.
Modern frameworks encode by default: React escapes values in JSX and Jinja2 autoescapes in HTML templates. The danger is the escape hatches, such as dangerouslySetInnerHTML in React or the safe filter in Jinja2. If you must allow user HTML, clean it with a sanitizer like DOMPurify.
- Input echoed in response
- Needs victim to open a link
- Fix: encode output
- Seen in server logs
- Payload saved in DB
- Hits every viewer
- Fix: encode on output
- Most damaging
- Happens in browser JS
- Source: URL, hash, storage
- Fix: textContent, not innerHTML
- Often not in server logs
Content Security Policy as a safety net
A Content Security Policy (CSP) is a response header that tells the browser which scripts and other resources the page may load and run. Even if an attacker injects a script tag, the browser refuses to run it when it does not match the policy.
The most robust approach is a strict CSP based on nonces. The server creates a new random nonce for every response, puts it in the header (script-src 'nonce-abc123' 'strict-dynamic') and adds the same nonce attribute to each legitimate script tag. Injected scripts do not know the nonce, so they are blocked. Add object-src 'none' and base-uri 'none' to close common bypasses. Avoid 'unsafe-inline', which allows any inline script and defeats the purpose.
Roll out in stages. Start with Content-Security-Policy-Report-Only, which reports violations without blocking, and collect reports using the report-to or report-uri directive. Fix legitimate violations, then switch to enforcing mode. Violation reports from production are also a useful XSS detection signal.
- 1Add nonces
New random nonce per response
- 2Report-Only header
Nothing blocked yet
- 3Collect reports
Find legitimate violations
- 4Fix the app
Remove inline handlers, add nonces
- 5Enforce
Switch to Content-Security-Policy
- 6Monitor
New violations may mean XSS attempts
Learn it in 4 short steps
About 45m each. Track them with a timer in your plan.
- 1Explain untrusted input reaching interpreters~45m
- 2Fix queries with parameterised statements~45m
- 3Apply context-aware output encoding~45m
- 4Add a Content Security Policy~45m
Key points
- Injection and XSS both stem from mixing data with code.
- Parameterised queries stop SQL injection.
- Context-aware output encoding stops most XSS.
- A Content Security Policy limits the damage of XSS.
Key terms
Tap a card to flip it. 0/4 known
Examples
Seeing SQL injection and its fix side by side
This lab example uses an in-memory SQLite database. Step 1: create a users table with two users. Step 2: build a query by joining strings with a user-supplied name. The input ends the string early and adds OR '1'='1', which is always true, so every row comes back. Step 3: run the same input through a parameterised query. The database treats the whole input as one name, finds no such user and returns nothing. The only change is how the value reaches the database.
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE users (name TEXT, role TEXT)")
db.executemany("INSERT INTO users VALUES (?, ?)", [("alice", "admin"), ("bob", "user")])
name = "nobody' OR '1'='1"
unsafe = f"SELECT * FROM users WHERE name = '{name}'"
print(db.execute(unsafe).fetchall()) # [('alice', 'admin'), ('bob', 'user')]
safe = "SELECT * FROM users WHERE name = ?"
print(db.execute(safe, (name,)).fetchall()) # []Encoding output and avoiding the shell
Step 1: a comment containing an image tag with an onerror handler is shown on a page. Printed raw, the browser would treat it as HTML and run the handler. Step 2: html.escape turns the special characters into entities, so the browser shows the text instead. Step 3: a network tool takes a host name from a form. Instead of building a shell string, pass a list to subprocess.run: the whole input becomes a single argument to ping, so extra characters like a semicolon cannot start a new command. Validating the host format first adds another layer.
import html, re, subprocess
comment = '<img src=x onerror=alert(1)>'
print("<p>" + html.escape(comment) + "</p>")
# <p><img src=x onerror=alert(1)></p> shown as text, not run
host = "example.com; rm -rf /tmp/x" # hostile input
if not re.fullmatch(r"[A-Za-z0-9.-]{1,253}", host):
print("rejected")
else:
subprocess.run(["ping", "-c", "1", host]) # no shell involvedQuick reference
- Root cause: untrusted data reaches an interpreter as code
- SQL: always use placeholders; allow-list table names, columns and sort order
- Python OS commands: subprocess.run([...]) with a list, never shell=True with input
- Encode for the context: HTML text, attribute, JavaScript or URL
- Danger zones: innerHTML, dangerouslySetInnerHTML, Jinja2 |safe, eval
- Strict CSP: script-src 'nonce-...' 'strict-dynamic'; object-src 'none'; base-uri 'none'
- Test CSP with Content-Security-Policy-Report-Only before enforcing
- Use DOMPurify when you truly must accept user HTML
Common mistakes
- Trying to block injection with input filtering alone.
- Encoding for HTML but forgetting attribute or JavaScript contexts.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Rewrite this query safely in Python: cur.execute("SELECT * FROM orders WHERE id = " + order_id).
- Exercise 2medium
Add a Report-Only Content Security Policy to a test site served by nginx, load the site, and read the violations in the browser console.
- Exercise 3hard
In a small Flask app, render a user comment safely in three places: as page text, inside an HTML attribute, and as data for JavaScript.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Is input validation enough to stop SQL injection?
- No. Validation helps and catches many bad inputs, but some valid inputs contain quotes (like O'Brien). Parameterised queries are the real fix; validation is an extra layer.
- Does React protect me from XSS?
- Mostly, because JSX escapes values automatically. You are still exposed through dangerouslySetInnerHTML, javascript: URLs in href, and third-party code that writes to the DOM.
- Does a WAF stop SQL injection?
- It blocks many common payloads, but attackers can often bypass rules with encoding tricks. Treat it as a temporary shield while you fix the code.
- What is the difference between XSS and CSRF?
- XSS runs the attacker's script inside your site's pages. CSRF makes a victim's browser send an unwanted request to your site from another site, without running code on your pages.