#!/usr/bin/env python3
"""
Extract clean hex values from the region data
"""
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 extract_region.py output:
raw_bytes = [
    0x00, 0x02, 0x92, 0x64, 0x00, 0x04, 0x64, 0x02, 0x00, 0x0a, 0x82, 0x00, 0x00, 0x08, 0x60, 0x08,  # Offset 0x40
    0x16, 0x08, 0xcd, 0x08, 0x33, 0x08, 0x5e, 0x08, 0x31, 0x08, 0x4d, 0x08, 0x4f, 0x08, 0x86, 0x08,  # Offset 0x50
    0x34, 0x08, 0xcd, 0x08, 0x1f, 0x00, 0x0e, 0x04, 0x00, 0x04, 0x00, 0x04, 0x00, 0x04, 0x00, 0x04,  # Offset 0x60
]

# Username: axel_outrun  
username_hex = '6178656c5f6f757472756e'  # "axel_outrun" without nulls

# Filter out 0x00 bytes from raw data
filtered = [b for b in raw_bytes if b != 0x00]

print(f"[+] Filtered bytes: {len(filtered)}")
print(f"    {' '.join(f'{b:02x}' for b in filtered)}")

# Try first 16 as sector 22, next 16 as sector 34
if len(filtered) >= 32:
    sector_22 = ''.join(f'{b:02x}' for b in filtered[:16])
    sector_34 = ''.join(f'{b:02x}' for b in filtered[16:32])
    
    print(f"\n[*] Sector 22: {sector_22}")
    print(f"[*] Sector 34: {sector_34}")
    print(f"[*] Username: axel_outrun ({username_hex})")
    print(f"[*] UID: 04f6555b")
    
    # Try passcodes
    for pc in [0, 1, 1234, 0x1337, 0xDEAD]:
        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 + key_hex
        
        data = {
            'uid': '04f6555b',
            'username': username_hex,
            'authorization_code': auth_code,
            'access_level': sector_34
        }
        
        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 with passcode {pc} (0x{pc:x})!")
                print(f"FLAG: {result['flag']}")
                print(f"{'='*70}")
                exit(0)
            else:
                print(f"  PC {pc:06x}: {result}")
        except Exception as e:
            print(f"  PC {pc:06x}: Error")
    
    print("\n[-] None of the common passcodes worked")
    print("[!] May need to extract passcode from the capture or brute force")
