Last updated: May 1, 2026
File upload features are everywhere — profile pictures, document uploads, attachments, imports. They’re also one of the most frequently-exploited vulnerability classes, capable of escalating from “user” to “RCE” in one click. This module covers the attack patterns and the layered defences.
The attack surface
- Attacker uploads a file (malicious)
- Server saves file to disk
- Server (or another process) later interacts with the file — serves it to users, renders it, executes it, parses it
Each interaction is a potential exploit vector. The upload itself rarely causes the damage; it’s what happens afterwards.
Classic RCE via upload
App accepts profile pictures. Doesn’t validate content. Saves to /uploads/. Webserver executes PHP in /uploads/. Attacker uploads shell.php. Navigates to /uploads/shell.php?cmd=whoami. Shell executed as web-server user.
Attack variations
Double extension bypass
Filter rejects .php. Attacker uploads shell.php.jpg. Apache with certain configurations still executes PHP. Or shell.jpg.php — some filters only check first extension.
Null-byte injection
shell.php%00.jpg — older libraries truncate at null byte, saving as shell.php.
Content-type bypass
Server checks Content-Type header only. Attacker sends PHP payload with Content-Type: image/jpeg. File contents are PHP; header says image.
Magic-byte bypass
Server checks first bytes for image magic (JPEG: FFD8FFE0). Attacker prepends magic bytes to PHP payload. File passes magic-byte check, still executes as PHP.
SVG with embedded script
SVG is XML. <svg onload="alert(1)">. If served as image/svg+xml and displayed inline, XSS in browser context. Plus XXE if server-parsed.
Path traversal
Filename ../../../var/www/html/shell.php — overwrites files outside upload directory.
Archive upload with Zip Slip
ZIP file containing entry named ../../etc/cron.d/backdoor. When server extracts, files escape intended directory.
ImageMagick / PDF RCE
Upload specially-crafted image/PDF. Server uses ImageMagick to resize or extract thumbnail. Historical CVEs (ImageTragick CVE-2016-3714) let image content trigger RCE via delegates.
Defences
1. Validate filename
- Reject path traversal characters (
..,/,\, null bytes) - Generate random filenames — don’t preserve user-supplied name
- Reject multiple extensions; whitelist allowed extensions
2. Validate content
- Check magic bytes (file type sniffing) AND content-type AND extension together
- For images: use a library to actually parse + re-encode (strips metadata, normalises format)
- Virus scan via ClamAV / similar for binary uploads
3. Storage architecture
- Serve from different domain — upload.example.com, no cookies, no PHP interpreter. XSS in uploaded content can’t reach main app’s session.
- No script execution in upload directory — Apache: AddType + disable .htaccess; Nginx: don’t route .php to FPM for upload paths
- S3 or similar object storage — uploads go to bucket; served via CDN with strict Content-Disposition + Content-Type
4. Access control
- Uploaded files require auth to access (or only accessible by uploader)
- Don’t expose internal filenames; generate random URLs or UUIDs
5. Limits
- Max file size
- Max uploads per user per time window
- Total disk quota
6. For images specifically
- Re-encode via Pillow / Sharp / ImageMagick — strips metadata, normalises format
- Set strong Content-Security-Policy for image pages (prevents script-in-SVG)
- Serve as
Content-Disposition: attachmentwhere inline display not required
Common mistakes
- Checking extension only
- Checking Content-Type only (client-controlled)
- Trusting filename
- Saving files in web-accessible directory with execute permission
- Using user-supplied filename in file system path
- No virus scanning on document uploads
- Extracting archives without Zip-Slip defence
Quick reference summary
- File upload is ONE of the highest-impact vuln classes; RCE often one click away
- Attacks: double extension, null byte, content-type spoof, magic-byte spoof, SVG XSS, path traversal, zip slip, image parser RCE
- Defence layers: filename validation, content validation, storage separation, no script exec in upload dir, strict access control, rate limits
- Best architecture: random filenames, separate domain, CDN-served, re-encoded images
- Documents (DOCX/PDF) — additional sandboxing required for parsing
Module Quiz · 20 questions
Pass with 80%+ to mark this module complete. Unlimited retries. Each question shows an explanation.
Practical depth on what to tune, what to harden, and how this maps to Indian regulatory expectations.
File upload defences — the layered checklist that survives audits
0x89 50 4E 47).Performance + detection + India context
Performanceupload bandwidth scales linearly with file size; for large uploads use multipart with resume support; consider direct-to-S3 with pre-signed URLs to offload from app servers.
Detectionalert on uploads of unexpected mime types, abnormal sizes, or to endpoints by users without upload privilege. Log every upload event with user, mime, size, hash.
India contextgovernment portals (income tax, GST, bank account verification) accept document uploads with PII; under DPDP, retention must be limited and access logged. RBI inspection findings have included “upload retention beyond purpose” as a control deficiency. For Indian fintech KYC: documents must be encrypted at rest, accessible only to authorised reviewers, deleted after the retention period.
Polyglot files and the bypass catalogue
A polyglot file is valid in two formats simultaneously. Common attacks:
Cloud-native upload patterns — direct-to-bucket and the security trade-offs
Direct-to-S3 (or GCS / Azure Blob) uploads via pre-signed URLs offload bandwidth from app servers. The pattern: app generates pre-signed POST policy with size + content-type constraints; client uploads directly to bucket; app validates and processes asynchronously. Security considerations:
File-storage retention and DPDP-aligned deletion
Uploaded files often contain PII (KYC documents, identity proofs, signed contracts). DPDP Act 2023 mandates purpose limitation and storage limitation: data retained only as long as necessary for the stated purpose. Practical implementation:
Performance discipline that strengthens security
A practical performance discipline that applies regardless of the specific vulnerability class is to instrument every endpoint with three SLOs: latency at the 50th, 95th, and 99th percentiles. The 50th percentile reflects typical user experience, the 95th catches tail behaviour visible to a meaningful fraction of users, and the 99th captures the long-tail outliers that often hide bugs (timeouts on a stale dependency, locking contention under load, garbage-collection pauses on a hot endpoint). Every release should compare these percentiles against the previous baseline; regressions of more than ten percent on the 95th percentile are typically worth investigating before shipping. Modern observability stacks make this routine — Datadog APM, New Relic, Honeycomb, Grafana Tempo with OpenTelemetry instrumentation, and on the open-source side Jaeger plus Prometheus plus Grafana — but the discipline matters more than the tool. Indian product teams that have adopted this percentile-driven culture report fewer surprise outages and a smaller incident-response load over time, which compounds into a stronger security posture: the same instrumentation that catches a slow endpoint also catches an exploitation attempt that forces unusual code paths.
Observability that catches attacks alongside outages
Observability for security overlaps with observability for reliability but adds a few specific signals worth instrumenting. First, application-layer authentication and authorisation events should produce structured logs with the user identifier, the action attempted, the source IP, the User-Agent fingerprint, and the outcome. Second, every state-changing API call should log its idempotency key, the request body shape, and the resulting object identifier. Third, every external dependency call should log the destination, the response code, and the latency. Together these three categories produce a clean event stream that a SIEM can correlate to detect both functional regressions and active attacks. The cost is moderate — log storage in Elasticsearch or Splunk runs perhaps thirty to sixty rupees per gigabyte per year at typical Indian-tier prices — and the payoff is dramatic: incidents that previously took days to investigate are typically resolved in hours when the relevant evidence has been pre-indexed. Indian regulators increasingly expect this level of operational logging, particularly RBI under the Cyber Security Framework Annex 1 and SEBI under the CSCRF master circular.
DPDP and sectoral obligations a practitioner cannot ignore
Under India’s Digital Personal Data Protection Act 2023, the operational obligations on any web application that handles personal data extend beyond simple consent collection. Section 8 requires that data fiduciaries implement reasonable security safeguards — interpreted in practice as reflecting a documented information security programme, regular vulnerability assessment, and demonstrable controls aligned to a recognised standard such as ISO 27001 or NIST CSF. Section 9 imposes data principal rights including access, correction, and erasure, which means the application must be architected so that these requests can be fulfilled within the prescribed timeframes (currently expected to be on the order of thirty days). Section 8(6) imposes breach notification: when a personal-data breach occurs, the data fiduciary must notify the Data Protection Board and affected data principals within prescribed timeframes (the draft Rules suggest seventy-two hours for material breaches). For the practitioner this translates into specific engineering tasks: data inventory and lineage tracking, retention controls and automated deletion at end-of-purpose, audit-grade logging of every access to personal data, breach-detection telemetry, and a formal incident-response playbook with regulatory-notification templates. The 2024-2025 inspections by RBI and SEBI of regulated entities have already cited DPDP-overlay obligations, so the alignment is not theoretical; it shapes what auditors expect to see in the next inspection cycle.
A small threat-modelling routine before every release
A short threat-modelling exercise specific to this vulnerability class is worth running before each release. The classic STRIDE framework — Spoofing, Tampering, Repudiation, Information disclosure, Denial of service, Elevation of privilege — provides a useful checklist when applied to the specific data flow at hand. Begin by drawing the data flow for the feature being changed: external actors at the edge, the trust boundaries they cross, the back-end services involved, the data stores read or written, and the third-party integrations called. For each trust boundary crossing, ask which STRIDE categories apply and what controls mitigate them. The output is a small set of testable assertions: this endpoint must not allow tenant A to read tenant B’s records, this mutation must require step-up authentication, this third-party call must validate the response signature, and so on. Convert each assertion into an automated test or a manual verification step in the release checklist. The discipline pays off in two ways: first, it catches design-level bugs before they reach code review; second, it produces an auditable record of security thinking that regulators value. Indian product teams that have institutionalised this practice report fewer security incidents and shorter mean-time-to-remediate when issues are found, which compounds into better customer trust and lower regulatory friction over time.
Further reading
Additional FAQs
Is checking only the file extension safe?
No. Magic bytes can lie; extensions can lie. Combine extension allow-list, magic-byte check, and re-encoding for images. For executables — do not allow at all unless absolutely necessary.
Should uploads go directly to S3 or through my server?
Direct-to-S3 with pre-signed POST is faster and cheaper. Server-side: validate content-type and size in the pre-signed policy; scan after upload via Lambda/EventBridge before exposing the file.
Custom team training + practitioner advisory
Beyond the free academy — we run private workshops, vCISO advisory, and red-team exercises tailored to your stack. For Indian SMBs scaling past their first hire.