--- name: sh-kb-path-traversal description: "Knowledge base for finding path/directory traversal and local/remote file inclusion - user-controlled paths reaching filesystem or include operations, enabling arbitrary file read/write or code inclusion. Use when hunting traversal/LFI/RFI, zip-slip, or unsafe path joins. CWE-22/23/98, OWASP A01:2021-Broken Access Control." --- # Path Traversal & File Inclusion - Hunter Knowledge Base User-controlled path components reach a filesystem operation without being confined to an intended base directory, letting an attacker read/write files outside it (`../../etc/passwd`) or include/execute files. ## Sources Filenames/paths in request params/body/headers, upload filenames, `Content-Disposition`, archive entry names (zip-slip), template/view/theme/locale names, download/attachment ids that map to paths, catch-all route segments (`/files/*`, Next `[...slug]`), values stored earlier (second-order: a stored filename or path later read by a job, export or backup/restore), and paths received from other services or queues. ## Sinks (grep targets) - **Read/write**: `open(`, `readFile`/`readFileSync`, `fs.createReadStream`, `fs.writeFile`, `sendFile`/ `send_file`, `res.download`, `File(`/`FileInputStream`, `Files.newInputStream`, `new File(base, user)`, `Paths.get(..).resolve(user)`, `os.path.join(base, user)`, `Path(base) / user`, `path.join`/`path.resolve`, Go `filepath.Join`/`os.Open`/`http.ServeFile`, .NET `Path.Combine`/`File.ReadAllText`/`PhysicalFile`, Ruby `File.join`/`send_file`, PHP `file_get_contents`/`fopen`/`readfile`/`move_uploaded_file`/`unlink`. Writes and deletes (upload dest, `unlink`, `rm`, rename) matter as much as reads. - **Include/execute (LFI/RFI)**: PHP `include`/`require`/`include_once` with user input, `virtual()`; template engines resolving user-supplied view names (Rails `render file:`/`render params[:x]`, Spring/ Thymeleaf view names from input, Jinja `get_template(user)`); dynamic `import`/`require(userPath)`; Laravel `view($request->v)`; PHP stream wrappers reachable via filesystem functions (`php://`, `phar://`). - **Archive extraction (zip-slip)**: entry names used without normalizing: Python `tarfile.extractall` (3.12+ `filter='data'` mitigates), Java `ZipEntry.getName()`/`TarArchiveEntry` + `new File(dest, name)`, Go `archive/zip`/`archive/tar` `f.Name` joined to dest, Node `adm-zip`/`unzipper`/custom `tar` handling, .NET `ZipArchiveEntry.FullName`, shell `unzip`/`tar`. Symlink entries followed by a later file entry also escape. - **Path-join traps that discard the base**: `os.path.join("/base", "/etc/x")`, `Path("/base") / "/etc/x"`, `path.resolve(base, "/etc/x")`, `Path.Combine(base, "/etc/x")` and Java `Path.resolve(absolute)` all return the absolute second argument. `filepath.Join(base, "../x")` and `path.join` clean `..` and escape. ## Detection recipe 1. `graft grep "open\(|readFile|writeFile|sendFile|send_file|path.join|path.resolve|os.path.join|Path.Combine|filepath.Join|new File\(|include\(|require\(|render file|extractall|extractTo|getName\(\)" --json`. 2. Trace the path argument to an untrusted source (including stored and cross-service sources). 3. Check for confinement: canonicalize (`realpath`) then verify the result starts with the intended base **plus a path separator**; reject `..`, absolute paths, and encoded variants. Absence of this after user input -> flag. Check the order: the check must run on the final string that is opened. 4. For uploads, check the destination name: is the client filename used verbatim, or is a server-generated name used (and the extension fixed)? For archives, check each entry's resolved path before writing. ## Payloads / PoC - `../../../../etc/passwd`, `..\..\..\..\windows\win.ini` (Windows), `....//....//` (filter bypass), URL-encoded `%2e%2e%2f`, double-encoded `%252e%252e%252f`, absolute `/etc/passwd`. `..%5c` and `..;/` (servlet path parameter) when a proxy and the app normalize differently. Null byte `%00` is rejected by most modern runtimes; do not rely on it. - Windows extras: drive letters (`C:\`), UNC paths, trailing dots/spaces, alternate data streams (`file::$DATA`). - LFI to RCE: include a log/upload/`/proc/self/environ` file containing attacker code; PHP wrappers `php://filter/convert.base64-encode/resource=index.php` (source disclosure), `data://`, `expect://`. - Zip-slip: an archive entry named `../../app/config.py` overwriting a real file. - PoC: request a file outside the base and confirm its contents return. ## Variant hunting - Grep every use of the same helper (`safe_join`, `getFile`, `resolvePath`) and every caller; check each caller applies the helper, since one raw `open()` beside it is the usual miss. - Sibling endpoints: download vs preview vs thumbnail vs export vs delete vs rename, v1 vs v2, admin tools, log viewers, i18n/theme loaders, backup/restore, plugin/template upload. - Same path-join idiom elsewhere in the repo; copy-pasted upload handlers; both read and write halves of one feature. - Every archive format handler (zip, tar, jar, apk, docx import) in the repo, not just the first one found. ## False-positive filters - Path is canonicalized and confined: `realpath`/`Path.resolve` then a base-prefix check with a trailing separator (or `relative_to`/`commonpath`), or the framework's safe static-file handler (`send_from_directory`, `express.static`, `res.sendFile(name, {root})`, Spring resource handlers with default traversal checks). - Only a **basename** is used (`os.path.basename(user)`) against a fixed directory, with no `..` reachable. On Windows check that the language's basename also splits on backslash. - The identifier is an opaque id mapped through a DB/allowlist to a server-chosen path (user never supplies path). - Python `zipfile.extract`/`extractall` strip `..` and absolute components; the risk is `tarfile`, symlinks and other languages. Extension-only filters do not stop traversal but may limit impact. - Evidence for a real finding: the tainted segment reaches the open/write call, no canonical-prefix check, and the process can read or write the target. Weak guards that are still bypassable: `startswith(base)` with no separator (`/data/uploads` matches `/data/uploads_x`), `replace("../", "")` (nested `....//`), checking before URL-decoding or before symlink resolution, extension checks on the unsanitized name. ## CWE / OWASP / severity CWE-22 (traversal), CWE-23, CWE-98 (RFI), CWE-73 (external control of filename). OWASP A01:2021. Arbitrary file read of secrets/config -> **high/critical**; write or LFI->RCE -> **critical**. ## Chaining hints File read -> `secrets` (config/keys/`.env`) -> DB/cloud access; LFI + log poisoning -> RCE; zip-slip write -> overwrite code/config -> RCE; feeds `access-control` (read other tenants' files). ## Detection signals (for defenders) - **Web/proxy/WAF logs** (raw URI before normalization, query, status, bytes out): `..`, `%2e%2e`, `%252e`, `..%5c`, `..;/` in path or parameter values; sensitive targets in values (`/etc/passwd`, `win.ini`, `/proc/self/environ`, `web.config`, `.env`, `php://`). Success looks like a 200 with a body size and content type unlike the endpoint's normal output, or one client iterating `../` depth. - **Application/file audit logs** (auditd, Sysmon file events, EDR file telemetry; need process, path, operation): the web/app worker process opening files outside its content directories (`/etc/shadow`, `~/.ssh`, `/proc/*/environ`, cloud credential files), or creating files outside the upload directory, especially script types (`.php`, `.jsp`, `.aspx`) under a web root or cron/systemd/startup paths. - **Behavior-based ideas**: (1) alert when a web server process reads a file from a sensitive-path set it never read in a baseline window; (2) alert when an upload request is followed by a new executable-type file in a served directory within seconds. - ATT&CK: T1190 Exploit Public-Facing Application; T1083 File and Directory Discovery; T1005 Data from Local System; T1552.001 Credentials In Files (config/key theft); T1505.003 Web Shell (write or LFI to webshell). ## Mitigation Don't build filesystem paths from user input. Map opaque ids to server-controlled paths; if a name is needed, take only the basename (or generate the name), canonicalize, and enforce a base-directory prefix check including the separator; reject `..`, absolute paths, and encoded traversal; validate archive entry names and refuse symlink entries before extraction; never `include` user-controlled paths; run with a least-privilege filesystem account and a read-only code tree.