#!/usr/bin/env python3
"""
Use correct username from MISO and test
"""
import requests

def lcg_step(seed):
    return (seed * 0x52c6425d + 0xcc52c) % (2**32)

def generate_keys(passcode):
    seed = passcode
    keys = []
    for _ in range(6):
        seed = lcg_step(seed)
        keys.append(seed % 0xffffff)
    return keys

# From MISO extraction:
username_hex = "6178656c5f6f757472756e"  # "axel_outrun"
sector_22_hex = "cd335e314d4f8634cd1f0e0000000000"
sector_34_hex = "5e4ce0a703078634cd1f0e0000000000"
uid = "04f6555b"

print("[*] Testing with correct username...")
print(f"Username: {username_hex} ('axel_outrun')")
print(f"Sector 22: {sector_22_hex}")
print(f"Sector 34: {sector_34_hex}")
print(f"UID: {uid}\n")

# Test with common passcodes
for pc in [0, 1, 42, 1234, 0x1337, 0x4242, 13337, 31337, 65535]:
    keys = generate_keys(pc)
    key_bytes = []
    for key in keys[4:6]:
        key_bytes.extend([key >> 16, (key >> 8) & 0xFF, key & 0xFF])
    key_hex = ''.join(f'{b:02x}' for b in key_bytes)
    
    auth_code = sector_22_hex + key_hex
    
    data = {
        'uid': uid,
        'username': username_hex,
        'authorization_code': auth_code,
        'access_level': sector_34_hex
    }
    
    try:
        r = requests.post('http://154.57.164.61:31938/api', data=data, timeout=3)
        result = r.json()
        
        if result.get('flag') and len(result.get('flag', '')) > 5:
            print(f"\n{'='*70}")
            print(f"SUCCESS! Passcode: {pc}")
            print(f"FLAG: {result['flag']}")
            print(f"{'='*70}")
            exit(0)
        else:
            print(f"  {pc:06}: {result.get('door_status', 'Locked')}")
    except Exception as e:
        print(f"  {pc:06}: Error - {e}")

print("\n[!] Need wider brute force. Starting 0-1000000...")

# Brute force with progress
for pc in range(100000):
    if pc % 10000 == 0:
        print(f"\r[*] Testing {pc:06}...", end='', flush=True)
    
    keys = generate_keys(pc)
    key_bytes = []
    for key in keys[4:6]:
        key_bytes.extend([key >> 16, (key >> 8) & 0xFF, key & 0xFF])
    key_hex = ''.join(f'{b:02x}' for b in key_bytes)
    
    auth_code = sector_22_hex + key_hex
    
    data = {
        'uid': uid,
        'username': username_hex,
        'authorization_code': auth_code,
        'access_level': sector_34_hex
    }
    
    try:
        r = requests.post('http://154.57.164.61:31938/api', data=data, timeout=1)
        result = r.json()
        
        if result.get('flag') and len(result.get('flag', '')) > 5:
            print(f"\n\n{'='*70}")
            print(f"SUCCESS! Passcode: {pc}")
            print(f"FLAG: {result['flag']}")
            print(f"{'='*70}")
            exit(0)
    except:
        pass

print("\n[-] Not found in first 100000")
