Skip to content

Web Security

Security questions test whether you think about attacker-controlled input, least privilege, and the difference between a control that stops an attack and one that merely detects it. Memorising the OWASP list is not enough; you need the mechanism and the fix.

Most breaches come from a few patterns: unvalidated input reaching an interpreter (injection), untrusted data reaching a browser without encoding (XSS), missing object-level authorisation (IDOR), and the server being tricked into making a request (SSRF). Defend at the boundary: parameterise queries, encode output, check ownership on every object, allow-list outbound destinations, hash secrets, pin and audit dependencies, send restrictive headers. Assume something gets through and log enough to detect it.

ID Category The failure
A01 Broken Access Control Users act outside their permissions; IDOR lives here
A02 Cryptographic Failures Plaintext or weakly hashed secrets, no TLS, bad randomness
A03 Injection Input interpreted as code: SQL, shell, LDAP, template
A04 Insecure Design No threat modelling; no rate limit on password reset
A05 Security Misconfiguration Default creds, verbose errors, open buckets, permissive CORS
A06 Vulnerable and Outdated Components Unpatched dependencies
A07 Authentication Failures Weak passwords, no lockout, broken session handling
A08 Data Integrity Failures Unsafe deserialisation, unsigned updates, CI compromise
A09 Logging and Monitoring Failures No detection, no audit trail
A10 Server-Side Request Forgery The server fetches an attacker-chosen URL

A01 is the most common in practice, and rarely exotic: a GET /invoices/123 that never checks that invoice 123 belongs to the caller.

Never build a command by concatenating data into it.

# vulnerable
User.where("email = '#{params[:email]}'")
# safe: bound parameter, or hash condition
User.where("email = ?", params[:email])
User.where(email: params[:email])
# shell injection
system("convert #{params[:file]} out.png") # vulnerable
system("convert", params[:file], "out.png") # safe, no shell

Injection appears wherever a string is parsed by another language: SQL, shell, LDAP, XPath, regex, templates, log lines. The fix is the same: a parameterised interface, or an allow-list where none exists. ORM helpers are safe only as intended — where("id = #{id}") is raw SQL with interpolation. Column and table names cannot be bound, so they need an allow-list, not escaping.

  • Stored: persisted and served to other users (a comment, a profile name).
  • Reflected: echoed from the request into the response (a search page).
  • DOM-based: client-side JavaScript writes untrusted data into the DOM.
el.innerHTML = userComment; // vulnerable
el.textContent = userComment; // safe
el.innerHTML = DOMPurify.sanitize(userComment); // only when HTML is required

Defences in layers:

  1. Context-aware output encoding. HTML body, attribute, URL, JS and CSS contexts each need different escaping. Modern frameworks escape by default; the danger is the escape hatch — dangerouslySetInnerHTML, v-html, {@html ...}.
  2. Content Security Policy as a second layer: default-src 'self' blocks inline and third-party script; nonces or hashes allow what you need. CSP limits damage, it does not fix XSS.
  3. HttpOnly cookies so a successful XSS cannot read the session.
  4. Sanitise on render, not only on input, whenever the context changes.

Do not write your own sanitiser. HTML parsing is a swamp of edge cases and mutation XSS.

The server fetches a user-supplied URL — image import, webhook tester, PDF renderer, link preview.

POST /api/preview {"url": "http://169.254.169.254/latest/meta-data/iam/security-credentials/"}

That is the cloud metadata service; in the worst case it returns temporary credentials. Defences:

  • Allow-list schemes and hosts. A deny-list of “localhost, 127.0.0.1, 169.254.169.254” is bypassable with decimal IPs, IPv6, DNS rebinding and redirects.
  • Resolve the hostname yourself, check the IP against private ranges, and connect to that IP — not the hostname — to defeat rebinding.
  • Block redirects or re-validate every hop.
  • Run the fetcher in a network namespace with no route to internal services, plus an egress firewall.
  • Require IMDSv2 on cloud instances, which blocks the trivial unauthenticated GET.

The endpoint takes an identifier and trusts it.

def show
render json: Invoice.find(params[:id]) # any user reads any invoice
end
def show
render json: current_user.invoices.find(params[:id]) # scoped, 404 otherwise
end

Scope every query through the authenticated principal’s relationship to the data. find on the global model is the bug. This is A01 and the most common finding in bug bounty reports.

  • Never commit secrets. Assume anything public is scraped within minutes; private repos are read by insiders and CI too.
  • Store them in a secret manager or, at minimum, environment variables injected at deploy — not in a .env baked into an image.
  • Rotate on a schedule and on suspected exposure; rotation must be routine, not an incident.
  • One credential per service, minimum scope, no shared admin key.
  • Enable secret scanning in CI and pre-commit hooks.
  • Configuration can live in git; secrets cannot.

Your dependency tree is code you did not write, executed with your privileges.

  • Commit lockfiles and install from them. Resolving version ranges in CI is non-reproducible.
  • Audit continuously (bundler-audit, npm audit, Dependabot, Renovate) and merge the patches. A06 is about unpatched components, not about having dependencies.
  • Watch typosquatting and dependency confusion: an internal package name missing from the public registry can be claimed by an attacker.
  • Postinstall scripts execute arbitrary code at install time; disable them where possible.
  • Generate an SBOM so “are we affected?” takes minutes, not a day.
  • Sign or checksum build artifacts; never pull binaries over plain HTTP.
Header Value Effect
Strict-Transport-Security max-age=63072000; includeSubDomains Forces HTTPS in future requests
Content-Security-Policy default-src 'self'; script-src 'self' 'nonce-...' Restricts resource origins
X-Content-Type-Options nosniff Stops MIME sniffing turning text into script
Referrer-Policy strict-origin-when-cross-origin Stops leaking full URLs cross-site
Permissions-Policy camera=(), microphone=() Disables browser features
X-Frame-Options / frame-ancestors DENY / 'none' Blocks clickjacking

HSTS has a long tail: browsers cache it, so mistakes are hard to undo. Roll out with a short max-age first; preload is effectively permanent.

Prevention fails eventually, and A09 exists because teams cannot answer “was this exploited?”.

  • Log authentication events, authorisation denials, admin actions and validation failures — with actor, resource and request id, never passwords or tokens.
  • Alert on patterns: a spike in 403s, a burst of 401s from one IP, a sudden change in data volume.
  • Keep an append-only audit trail outside the application’s write path.
  • Have a documented incident response path. Logging without a responder is theatre.
  1. How does parameterisation stop SQL injection when the query is still built from a string?
  2. Why is CSP not a substitute for output encoding?
  3. How would you let users import an image from a URL without enabling SSRF?
  4. Where do you enforce object-level authorisation so a new endpoint cannot forget it?
  5. What is dependency confusion, and how does a scoped private registry prevent it?
  • “We escape input on the way in.” Encode on output, for the specific context. Input sanitisation destroys legitimate data and misses payloads rendered elsewhere.
  • “The ORM prevents injection.” Only when you do not interpolate raw SQL into it.
  • “CORS protects the API.” It is a browser policy; attackers use curl.
  • “We are not a target.” Automated scanners do not care.
  • “HTTPS everywhere means end-to-end encryption.” It terminates somewhere; internal hops may be plaintext.
  • “Blocking localhost fixes SSRF.” Redirects, rebinding and alternate IP encodings bypass a string deny-list.