--- name: sh-kb-file-upload description: "Knowledge base for finding unrestricted/insecure file upload - uploads that allow dangerous file types, execution in the upload dir, path control over the stored name, or missing content validation, leading to RCE, XSS, or overwrite. Use when hunting file-upload issues. CWE-434/436/616, OWASP A04/A05:2021." --- # Unrestricted File Upload - Hunter Knowledge Base Uploads become dangerous when the app trusts the client-provided type/name, stores files where they can be executed or served, or skips content validation. Worst case: upload a web shell and get RCE. ## What to hunt - **Executable upload + reachable path** (CWE-434): uploading `.php`/`.jsp`/`.aspx`/`.py` (or a bypass variant) into a directory the web server executes -> RCE. - **Type/extension trust**: validating only the client `Content-Type` or extension (spoofable); no server-side content/magic-byte check. - **Path control over stored name**: attacker sets the filename/path (traversal `../`, overwrite of an existing file, null byte, double extension `shell.php.jpg`, trailing dot/space, case tricks, NTFS Alternate Data Stream `shell.asp:.jpg`, or a name like `shell.p.phphp` that becomes `shell.php` after a single-pass, non-recursive strip of a blacklisted extension). - **Upload-then-validate race window**: the app writes the file to a web-reachable path first and deletes it afterward if validation fails - an attacker who requests the file fast enough (or repeatedly re-uploads to widen the window) can get it executed before it's removed. - **Content-driven XSS / SVG / HTML / polyglot**: uploading `.svg`/`.html` served inline on the app origin -> stored XSS; image polyglots; `.xml`-backed formats -> XXE. - **Missing limits**: no size/rate limit -> DoS; zip-bomb; decompression bombs. - **Metadata/EXIF or antivirus gaps**; server-side image processing (ImageMagick "ImageTragick") RCE. - **Archive handling**: zip/tar extraction that joins entry names to a target dir without resolving and checking the result stays inside it (zip-slip); symlink entries that point outside and are written through later; unbounded expansion size or entry count. - **Document/format parsers**: office/PDF/XML-backed uploads parsed server-side (XXE, SSRF through external references, formula injection in CSV/XLSX that is later opened by staff), image libs fetching remote URLs from SVG/MVG/PDF content, video/thumbnail tools invoked on the file. - **Import-by-URL and presigned flows**: server fetches a user-supplied URL and stores it (SSRF plus type bypass); presigned S3/GCS upload URLs that let the client choose key, content-type or size (path/prefix not pinned, overwrites other users' objects, `text/html` served from the app bucket domain). - **Serving side**: `Content-Type` derived from the extension or from the user's declared type; no `nosniff`; inline disposition for user content; download-by-name routes that accept `../` (traversal read); upload dir shared across tenants with guessable names (access-control gap). - **Missing-check bugs**: upload endpoint with no authentication or no ownership check on the target record; avatar/attachment replacement of another user's file by id; "chunked" or resumable upload APIs that apply validation to the first chunk only or trust a client-sent final filename on completion. ## Sinks / patterns (grep targets) Upload handlers and where they write: `request.files`, `MultipartFile`, `multer`, `formidable`, `move_uploaded_file`, `save(`/`saveAs(`, `fs.writeFile(uploadPath)`, `os.path.join(upload_dir, filename)`, `secure_filename` (Flask - check it's actually used), `Content-Type` checks, extension allowlist/denylist. Also how the file is later **served** (static route over the upload dir) or **processed** (image libs). Per stack, check what actually enforces the name/type: - **Python**: Flask `secure_filename` strips path parts but a result of `""` or an extension-only name still needs handling; Django `FileField` + `upload_to` (user name still used unless renamed), `FileExtensionValidator` checks the name only, `ImageField` only runs Pillow `verify()`; FastAPI `UploadFile.filename` is client-controlled. - **JS/TS**: `multer` `diskStorage` `filename` callback returning `file.originalname`; `fileFilter` checking `mimetype` (client-supplied); `formidable` `keepExtensions` with a user-controlled path; `express-fileupload` `useTempFiles` and `mv(path)` with the raw name; Next.js route handlers writing `formData` file names to disk. - **Java/Spring**: `MultipartFile.getOriginalFilename()` joined to a path (can contain separators on some stacks), `transferTo`, `Files.copy(in, root.resolve(name))`; Tomcat serving the upload dir with JSP handling enabled. - **PHP/Laravel**: `$_FILES['f']['name']`/`['type']` (client-supplied), `move_uploaded_file` into the webroot; Laravel `$request->file()->getClientOriginalName()`/`getClientOriginalExtension()` vs `hashName()`/`extension()` (server-guessed), `storeAs` with a user name; `mimes:` rule guesses from content, not a guarantee of safety. - **Ruby/Rails**: Active Storage `content_type` from the client and inline serving of `text/html`/`svg`; CarrierWave with no `extension_allowlist`; Paperclip-style content-type spoofing. - **Go**: `header.Filename` into `filepath.Join(dir, name)`; `http.DetectContentType` only sniffs 512 bytes. - **C#/ASP.NET**: `IFormFile.FileName` joined with `Path.Combine` (an absolute second argument discards the first), `ContentType` checks, files saved under `wwwroot`. ## Detection recipe 1. `graft grep "request.files|MultipartFile|multer|move_uploaded_file|save(|writeFile|upload" --json`. 2. For each upload: How is the type validated (extension? content-type? magic bytes?). Is the stored name attacker-controlled? Where is it stored, and is that path executable or served inline on the app origin? 3. Trace the stored filename for traversal/overwrite; check size/count limits. 4. Trace the file past the write: later reads, thumbnails, previews, virus-scan or conversion jobs, ZIP/CSV/XML import, email attachment forwarding, and admin or support views (second-order: stored file triggers a bug when a privileged user or worker opens it). 5. Check the response headers where it is served (`Content-Type`, `Content-Disposition`, `X-Content-Type-Options`, CSP) and the origin it is served from. 6. Check the web server/handler config for the upload dir (handler mappings, `AddHandler`, `.htaccess` allowed, `web.config`, nginx `location ~ \.php$` reaching the upload path, `try_files` quirks). ## Variant hunting Once one weak upload is found: grep every other upload entry point (same grep as above) and compare their validators; find the shared validator or storage helper and every caller; check sibling features (avatar, attachment, import, logo, theme, plugin/package upload, backup restore, bulk CSV) and API-version or mobile twins; check admin-only uploads that a lower role can reach; check copy-pasted extension lists for missing interpreter extensions or for case-sensitivity bugs in the comparison. ## Payloads / PoC - Web shell: `shell.php` with `` if PHP execution reachable; `.jsp`/`.aspx` equiv. - Bypasses: double extension `shell.php.jpg`, null byte `shell.php%00.jpg`, case `shell.PhP`, trailing dot/space `shell.php.`, spoofed `Content-Type: image/png` with PHP body, magic-byte prefix + code, alternative interpreter extensions often missing from blacklists (`.phtml`, `.php5`, `.pht`, `.shtml`, `.asp;.aspx`), URL-encoded extension `exploit%2Ephp`, polyglot image+payload files (e.g. built with ExifTool) that pass magic-byte/dimension checks. - Stored XSS: upload `poc.svg` containing `` or `poc.html`, served inline. - Traversal/overwrite: filename `../../app/config.py` (zip-slip for archives). - PoC: upload the file, then request its served URL and observe execution/script/overwrite. ## False-positive filters - Server-side **content** validation (magic bytes / re-encode image) **and** an extension **allowlist** (not denylist), with a server-generated random stored name (client name discarded). - Uploads stored outside the webroot / on object storage with `Content-Disposition: attachment` and a non-executing content-type, served from a separate origin/domain. - Size/count/rate limits enforced; archives validated before extraction. - The upload dir is on a host/path where nothing is executed and the web server only serves static types; a bypassed extension then yields stored content only, so rate it by what that content can do (XSS if served inline on the app origin, overwrite, DoS), not as RCE. - Real evidence of a finding: attacker controls the stored name or type, the validation can be shown to be absent or bypassable, and the file is reachable by an executor (web server, parser, worker, privileged viewer). State which executor. A denylist alone, or client-side checks alone, is a finding only when that reach exists. - Validation happens **before** the file is written to any web-reachable path (no upload-then-delete-on-fail race window). - Per-directory config overrides disabled (Apache `AllowOverride None`, IIS handler mappings locked) so a smuggled `.htaccess`/`web.config` in the upload dir can't grant execution; on Windows, 8.3 short-filename generation disabled (`fsutil behavior set disable8dot3 1`) so a blocked long name can't be reached via its short alias. ## Detection signals (for defenders) - **Logs needed**: web/proxy/WAF logs with method, path, `Content-Type` of the request and response, multipart filename (if logged), request size, status; application upload audit log (user, original and stored name, size, detected type); web server access logs for the upload dir; EDR process and file-write events on the host. - **Attempts**: one source uploading many files with varied or double extensions, interpreter extensions, or names containing `../`, `%00`, `;`, or alternate-stream markers; mismatch between declared `Content-Type` and detected content; repeated rapid upload then request of the same path (race attempts); upload followed immediately by 404/403 then retries. - **Success**: a file in an upload or static directory later requested with query parameters and a 200 where other files in that directory are only fetched plainly; web server or app runtime process spawning a shell or interpreter (`sh`, `cmd.exe`, `powershell.exe`, `whoami`, `curl`); new script-type files written under the webroot by the web server user; server-side image/convert tools (e.g. `convert`, `gs`, `ffmpeg`) spawning children; outbound connections from the web tier to new hosts after an upload. - **Behaviour detection ideas**: (1) file-create events for executable/script extensions under web-served directories by the web server account, joined to an inbound upload request; (2) web server parent process starting a shell or system-recon command, regardless of the file name used. - **ATT&CK**: T1190 (Exploit Public-Facing Application), T1505.003 (Server Software Component: Web Shell), T1059 (Command and Scripting Interpreter) for execution afterwards. ## CWE / OWASP / severity CWE-434 (unrestricted upload), CWE-436 (interpretation conflict), CWE-616. OWASP A04/A05:2021. Upload->RCE -> **critical**; stored XSS via upload -> high; overwrite/DoS -> per impact. ## Chaining hints Upload web shell -> RCE -> `secrets`/lateral (chain terminus); SVG/HTML upload -> stored `xss` -> admin takeover; filename control -> `path-traversal` overwrite; XML-backed upload -> `xxe`; feeds `injection` (processing the file with a shell). ## Mitigation Allowlist expected extensions **and** validate content (magic bytes / re-encode images) *before* the file touches any web-reachable path; discard the client filename and generate a random server-side name; store outside the webroot or on object storage served from a separate origin with `Content-Disposition: attachment` and a safe content-type; disable per-directory config overrides and short-filename generation; enforce size/count/rate limits; scan for malware; keep image-processing libraries patched.