#!/usr/bin/env python3
"""
Try ALL possible 6-byte sequences from extracted data as potential keys
"""

def lcg_step(seed):
    return (seed * 0x52c6425d + 0xcc52c) % (2**32)

def lcg_inverse(x):
    a = 0x52c6425d
    c = 0xcc52c
    a_inv = pow(a, -1, 2**32)
    return ((x - c) * a_inv) % (2**32)

def crack_from_two_outputs(out4, out5):
    """Try to find passcode from two consecutive 3-byte outputs"""
    # out4 and out5 are (state % 0xffffff)
    # Brute force the upper byte of the full 32-bit state
    
    for upper in range(256):
        state4_full = (upper << 24) | out4
        state5_full = lcg_step(state4_full)
        
        if (state5_full % 0xffffff) == out5:
            # Valid! Walk back 4 steps to get seed
            state = state4_full
            for _ in range(4):
                state = lcg_inverse(state)
            return state
    
    return None

# Extracted data (MOSI bytes from final script):
data_hex = '0292640464020a820860081608cd0833085e0831084d084f0886083408cd081f'
data_bytes = bytes.fromhex(data_hex)

print(f"[*] Testing all 6-byte sequences from {len(data_bytes)} bytes...")
print()

found_passcodes = []

for i in range(len(data_bytes) - 5):
    seq = data_bytes[i:i+6]
    
    # Split into two 3-byte values
    key4 = (seq[0] << 16) | (seq[1] << 8) | seq[2]
    key5 = (seq[3] << 16) | (seq[4] << 8) | seq[5]
    
    # Skip if values are suspicious (all same, all zeros/FFs)
    if key4 == 0 or key5 == 0:
        continue
    if key4 == 0xffffff or key5 == 0xffffff:
        continue
    if key4 == key5:
        continue
    
    # Try to crack passcode
    passcode = crack_from_two_outputs(key4, key5)
    
    if passcode is not None:
        print(f"Offset {i}: {seq.hex()}")
        print(f"  Key4={key4:06x}, Key5={key5:06x}")
        print(f"  PASSCODE: {passcode}")
        
        # Verify
        def verify(pc):
            seed = pc
            keys = []
            for _ in range(6):
                seed = lcg_step(seed)
                keys.append(seed % 0xffffff)
            return keys
        
        keys = verify(passcode)
        print(f"  Generated keys: {', '.join(f'{k:06x}' for k in keys)}")
        print(f"  Keys[4-5]: {keys[4]:06x} {keys[5]:06x}")
        print()
        
        found_passcodes.append((passcode, i, seq.hex()))

if found_passcodes:
    print(f"\n{'='*70}")
    print(f"FOUND {len(found_passcodes)} POSSIBLE PASSCODE(S)!")
    print(f"{'='*70}")
    
    for pc, offset, seq in found_passcodes:
        print(f"\nPasscode: {pc}")
        print(f"  From offset {offset}: {seq}")
        
        # Try with API
        import requests
        
        keys = []
        seed = pc
        for _ in range(6):
            seed = lcg_step(seed)
            keys.append(seed % 0xffffff)
        
        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)
        
        sector_22 = '0292640464020a820860'
        auth_code = sector_22 + key_hex
        
        data = {
            'uid': '04f6555b',
            'username': '6178656c5f6f757472756e',
            'authorization_code': auth_code,
            'access_level': '085e0831084d084f0886083408cd081f'
        }
        
        try:
            r = requests.post('http://154.57.164.76:32127/api', data=data, timeout=3)
            result = r.json()
            
            if result.get('flag') and len(result.get('flag', '')) > 5:
                print(f"\n{'='*70}")
                print(f"FLAG FOUND!")
                print(f"Passcode: {pc}")
                print(f"FLAG: {result['flag']}")
                print(f"{'='*70}")
                exit(0)
            else:
                print(f"  API response: {result}")
        except Exception as e:
            print(f"  API error: {e}")
else:
    print("\n[-] No valid passcodes found from consecutive 6-byte sequences")
    print("[!] The keys might not be consecutive in the data")
    print("[!] Or they might be interleaved with status bytes")
