Access control, path traversal and file uploads

Broken object-level authorisation (IDOR), function-level checks and mass assignment; path traversal and zip slip; and file uploads that become web shells or stored XSS. How each is found and the engineering fixes that remove the class.

FREEBy ·Lesson·12 min read·Intermediate → Advanced
IDORbroken object level authorizationmass assignmentpath traversalzip slipfile upload security

01Broken access control and IDOR

✓What you will learn
  • Explain IDOR / BOLA, function-level authorisation failures and mass assignment
  • Find access-control bugs with two-account testing and authorisation tests
  • Prevent path traversal by canonicalising and checking paths, or by not using user paths at all
  • Make file uploads safe: storage, naming, type checks, serving headers and processing sandboxes

Broken access control has been first in the OWASP Top 10 since 2021, and broken object level authorisation (BOLA) is first in the OWASP API Security Top 10. The most common form is the insecure direct object reference (IDOR): the application checks that you are logged in, then fetches whatever object ID you ask for without checking that it is yours.

IDOR in one requesthttp
GET /api/invoices/18342 HTTP/1.1
Authorization: Bearer <token for alice>

HTTP/1.1 200 OK
{"id":18342,"customer":"alice","total":"£120.00"}

# Alice changes one digit:
GET /api/invoices/18343 HTTP/1.1
Authorization: Bearer <token for alice>

HTTP/1.1 200 OK
{"id":18343,"customer":"bob","total":"£9,400.00"}     <- authenticated, but not authorised
FailureExampleCheck that was missing
Object level (IDOR / BOLA)Read or edit another user's invoice by IDDoes this subject own or have a grant on this object?
Function level (BFLA)Ordinary user calls POST /api/admin/usersDoes this role allow this operation at all?
Mass assignmentPATCH /api/me with {"name":"A","role":"admin"}Which fields may this caller set?
Tenant isolationQuery filters by id but not by tenant_idIs this object in the caller's tenant?
!Unguessable IDs are not authorisation

Switching to UUIDs makes enumeration harder, but IDs leak through URLs, logs, shared links, emails and other API responses. The server must still check ownership on every request.

02Finding and fixing access-control bugs

Scanners are poor at finding access-control bugs because they do not know who should see what. The reliable technique is two-account testing: perform every action as user A, replay each request with user B's session (and with no session), and compare. Burp Suite extensions such as Autorize automate the replay. In code review, look for handlers that load an object by ID from the request and never mention the current user or tenant.

Scope the query, not just the routets
// VULNERABLE: authenticated, but any invoice ID works
app.get("/api/invoices/:id", requireAuth, async (req, res) => {
  const inv = await db.query("SELECT * FROM invoices WHERE id = $1", [req.params.id]);
  res.json(inv.rows[0]);
});

// FIXED: the ownership check is part of the query, so it cannot be forgotten later in the handler
app.get("/api/invoices/:id", requireAuth, async (req, res) => {
  const inv = await db.query(
    "SELECT id, total_pence, status FROM invoices WHERE id = $1 AND tenant_id = $2 AND customer_id = $3",
    [req.params.id, req.user.tenantId, req.user.customerId],
  );
  if (inv.rowCount === 0) return res.status(404).end();  // 404, not 403: do not confirm the ID exists
  res.json(inv.rows[0]);
});
  • Deny by default and enforce in one layer: a data-access layer that always scopes by tenant and owner, or a policy engine (OPA, Cedar, a ReBAC service) consulted on every object access.
  • Explicit field allow-lists for writes. Map request bodies onto DTOs with only the permitted fields, so role or tenant_id in a request body is ignored.
  • Authorisation tests in CI: a matrix of roles by endpoint by expected result, run on every change. New endpoints without an entry fail the build.
  • Database row-level security (PostgreSQL RLS keyed on a session tenant variable) is a strong backstop for multi-tenant isolation.

03Path traversal and zip slip

Path traversal happens when user input becomes part of a file path. The textbook payload is ../../../../etc/passwd: each .. climbs a directory, escaping the intended folder. Variants include URL-encoded forms (%2e%2e%2f), double encoding, backslashes on Windows, absolute paths that make path.join irrelevant in some APIs, and symbolic links inside the allowed directory that point outside it.

Zip slip is the archive version: a zip or tar entry named ../../app/config.js is written outside the extraction directory when the extractor trusts entry names. Many libraries in many languages had this flaw when it was widely reported in 2018.

Canonicalise, then check, then follow links and check againts
import path from "node:path";
import { realpath } from "node:fs/promises";

const BASE = path.resolve("/srv/app/exports");

export async function resolveInside(userPath: string): Promise<string> {
  const candidate = path.resolve(BASE, userPath);              // canonicalise: collapses ../ and handles absolute input
  if (candidate !== BASE && !candidate.startsWith(BASE + path.sep)) throw new Error("path escapes base directory");
  const real = await realpath(candidate);                       // follow symlinks, then check again
  if (real !== BASE && !real.startsWith(BASE + path.sep)) throw new Error("symlink escapes base directory");
  return real;
}
// Better still: look files up by ID in a table and never build paths from user input at all.
iWhy the trailing separator matters

A check of startsWith("/srv/app/exports") also accepts /srv/app/exports-old/secret. Compare against the base plus the path separator. Decode input fully before canonicalising, and do the check on the final path the file system call will use.

04File uploads

An upload feature lets strangers write files to your systems. What goes wrong depends on where the file lands and what later reads it.

RiskHow it happensFix
Web shellA .php or .jsp file saved under the web root and requested by URL, so the server executes itStore outside the web root, ideally in object storage; never execute from upload locations
Stored XSSAn HTML or SVG file served from your main origin with a renderable content typeServe from a separate sandbox domain with Content-Disposition: attachment and X-Content-Type-Options: nosniff
Overwrite and traversalThe client-supplied filename is used as the storage pathGenerate random storage keys; keep the original name only as metadata
Parser exploitsImage and document libraries parse hostile input: ImageTragick (CVE-2016-3714), XXE in DOCX or SVGProcess in a sandboxed worker with no network; re-encode images; disable external entities
Resource exhaustionHuge files, decompression bombs, millions of tiny filesSize limits at the proxy, decompressed size limits, quotas
Malware distributionYour domain hosts malicious files for othersMalware scanning, abuse reporting, signed short-lived download URLs
  • Check type by content, not by name or header: the Content-Type header and the file extension are attacker-supplied. Inspect magic bytes, allow-list a small set of types, and re-encode images so only pixel data survives.
  • Set the response type yourself when serving: an allow-listed Content-Type, plus nosniff, so the browser does not guess HTML from content.

05Explaining it well

▭On the whiteboard · Access, paths and uploads4 points
01
objects
every query scoped by tenant and owner | deny by default | 404 for others' IDs
02
writes
field allow-lists, no mass assignment | role checks per function
03
paths
IDs not paths | canonicalise then check with separator | realpath for symlinks | safe archive extraction
04
uploads
object storage, random keys | content-based type allow-list | sandbox domain, attachment, nosniff | sandboxed processing
◎Interview radar

Access control questions test whether you think in terms of objects rather than routes. "Logged in" is not "allowed". Good answers move the check into the data-access layer, mention two-account testing and an authorisation test matrix in CI, and note that UUIDs do not fix IDOR. For uploads, saying "separate sandbox domain plus attachment plus nosniff" shows real-world experience.

“How to say it in the room

"Authentication tells me who you are; authorisation has to be checked on every object. I scope every query by tenant and owner in the data-access layer, return 404 for objects you do not own, and allow-list writable fields so mass assignment cannot set roles. We test it with a role-by-endpoint matrix in CI and two-account replay. For files I avoid user paths entirely, and uploads go to object storage under random keys, are type-checked by content, processed in a sandbox and served from a separate domain as attachments with nosniff."

Test yourself

An API uses random UUIDs for documents and checks that the caller is logged in. A pentester reads another tenant's document using a UUID found in a shared link. What is the root cause?

Q1Why return 404 rather than 403 for another user's object?+

A 403 confirms that the ID exists, which helps enumeration and can leak information. A 404 treats objects you may not see as non-existent.

Q2Why serve user uploads from a separate domain?+

If an uploaded HTML or SVG file is ever rendered, script runs in the sandbox domain's origin, which has no access to your main site's cookies, storage or APIs.

Q3Is checking the file extension enough for uploads?+

No. Extensions and content types are attacker-supplied, and polyglot files can be valid as two types at once. Check content, allow-list types, re-encode where possible and control the serving headers.

Finished this one?
Tick it and it shows as done on the roadmap and the course.