Injection, XSS, and Session Flaws
Follow untrusted data into interpreters, understand SQL injection and cross-site scripting, and close session and CSRF gaps.
By the end, you’ll be able to…
- Explain why injection happens when data reaches an interpreter as code.
- Fix SQL injection with parameterised queries and safe query construction.
- Distinguish stored, reflected, and DOM-based XSS and apply output encoding.
- Harden sessions against CSRF, fixation, and unsafe cookie settings.
01Injection Is a Data-to-Code Problem
Injection happens when untrusted data is interpreted as instructions. SQL injection occurs when user input becomes part of a SQL statement. Command injection occurs when input becomes part of a shell command. Template injection, NoSQL injection, LDAP injection, and log injection follow the same pattern. The specific syntax changes; the root cause does not.
The classic example is a query built by string concatenation: SELECT * FROM users WHERE email = ' + input + '. If input contains a quote and additional SQL, the database executes the attacker's logic. Escaping quotes is fragile because different contexts and database engines have different rules. Parameterised queries keep the query structure separate from the data, so the database treats input as a value even when it contains SQL syntax.
The same principle applies to operating-system commands. Avoid passing user input to a shell. Use an API that accepts an argument list and validates allowed values. If a shell is unavoidable, use strict allowlists, quote arguments correctly, drop privileges, and run with the smallest possible environment. 'Sanitising' with a blocklist of characters is usually a bypass waiting to happen.
02Cross-Site Scripting and Output Context
XSS occurs when attacker-controlled content is rendered as executable script in a victim's browser. Stored XSS saves the payload on the server, for example in a comment, and serves it to every viewer. Reflected XSS bounces a payload from the request into the response, often through a search page or error message. DOM-based XSS happens when client-side JavaScript writes untrusted data into a dangerous sink such as innerHTML.
The primary defence is context-aware output encoding. HTML text, HTML attributes, JavaScript strings, URLs, CSS, and JSON each have different escaping rules. Use a templating engine that escapes by default and never concatenate untrusted strings into HTML. For rich text, sanitise with a maintained library that allows a strict subset of markup, then encode on output. Do not rely on input filtering alone.
Content Security Policy (CSP) is a powerful second layer. A strict policy can block inline scripts and restrict script sources, making many XSS payloads fail even if an encoding bug exists. CSP is not a substitute for correct encoding, and a weak policy with 'unsafe-inline' or broad wildcards provides little protection. Start with a report-only policy, measure breakage, then enforce.
03Sessions, CSRF, and Fixation
A session cookie is a bearer token. If an attacker obtains it, they can often use the account without knowing the password. Set Secure and HttpOnly, choose an appropriate SameSite value, rotate the session ID after login, expire idle sessions, and invalidate sessions on logout and password change. Do not put sensitive data in a cookie that the client can read or modify without integrity protection.
Cross-site request forgery tricks a logged-in user's browser into sending an unwanted state-changing request. SameSite cookies reduce the risk, but they are not a complete defence for every flow. Use anti-CSRF tokens tied to the session, require re-authentication for high-risk actions, and avoid state changes on GET requests. Check the Origin and Referer headers as defence in depth, not as the only control.
Session fixation occurs when an attacker can force a victim to use a known session ID and then reuse it after login. Always issue a new session identifier when privilege changes, and reject session IDs supplied in URLs. Store sessions server-side or use signed, encrypted tokens with appropriate expiry. Logout must invalidate the server-side session, not only clear the browser cookie.
04SSRF, Uploads, and Unsafe Deserialisation
Server-side request forgery (SSRF) happens when an application fetches a URL supplied by a user. An attacker can target internal services, cloud metadata endpoints, or localhost-only admin interfaces. Allowlist destinations by scheme, host, and port; resolve DNS and block private and link-local addresses; disable redirects or revalidate each hop; and use a dedicated egress proxy with logging. Never let a user choose an arbitrary URL and fetch it with the application's full network identity.
File uploads are another trust boundary. Validate content type by inspecting the bytes, not only the extension. Limit size and count. Store uploads outside the web root with randomised names. Serve them with a safe Content-Type and Content-Disposition. Scan for malware where appropriate. Never execute uploaded files, and never trust a filename as a path.
Unsafe deserialisation turns attacker-controlled bytes into objects or code. Prefer simple data formats such as JSON with a schema, avoid native object deserialisation of untrusted input, and verify integrity where a serialized object crosses a trust boundary. If a library offers a safe mode, use it. The rule is the same as injection: do not let untrusted data become instructions.
The ideas worth keeping.
- Injection is a data-to-code problem; parameterisation and safe APIs are the structural fix.
- XSS is an output-context problem; encode at the sink and use CSP as a second layer.
- Sessions are bearer credentials: secure, rotate, expire, and revoke them.
- SSRF and unsafe uploads abuse the server's trust and network position.
Make it yours.
Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.
Exercise 1: Fix the query
Rewrite this vulnerable code using a parameterised query: query = "SELECT id, email FROM users WHERE email = '" + email + "'"; cursor.execute(query). Explain why escaping quotes is not enough.
Explore a worked solution
query = "SELECT id, email FROM users WHERE email = %s"
cursor.execute(query, (email,))
Escaping quotes is not enough because SQL syntax varies across databases and contexts, and a missed or incorrect escape can still allow injection. Parameter binding keeps the query structure fixed and sends the value separately, so the database never parses the input as SQL.The safe pattern is structural separation, not character filtering. The database driver handles the value correctly for its engine.
Exercise 2: Classify and fix XSS
A search page reads the q parameter and writes it into the page with innerHTML. A user crafts a link that executes script when opened. What type of XSS is this, and what are two fixes?
Explore a worked solution
This is reflected DOM-based XSS: the payload is reflected from the URL into the DOM through an unsafe sink. Fixes: use textContent or a framework's escaped interpolation instead of innerHTML, and add a strict Content-Security-Policy that blocks inline and untrusted scripts. Encoding must match the output context; input validation alone is not sufficient.The source is the URL and the sink is innerHTML. Fix the sink and add CSP as defence in depth.
What stayed with you?
Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.
Keep exploring.
The official references behind this lesson, when you want a second angle or the full details.
One lesson closer.
Reading is a start. Trying it yourself makes the connection.