#!/usr/bin/env python3
"""
Final comprehensive test based on what we know
"""
import requests

def lcg_step(seed):
    return (seed * 0x52c6425d + 0xcc52c) % (2**32)

def bytes_from_num(num):
    return [int(num >> 16), int((num >> 8) & 0xFF), int(num & 0xFF)]

def generate_keys(passcode):
    seed = passcode
    keys = []
    for _ in range(6):
        seed = lcg_step(seed)
        keys.append(seed % 0xffffff)
    return keys

def try_creds(uid, username, auth, access, passcode):
    keys = generate_keys(passcode)
    key_bytes = []
    for key in keys[4:6]:
        key_bytes.extend(bytes_from_num(key))
    key_hex = ''.join(f'{b:02x}' for b in key_bytes)
    
    full_auth = auth + key_hex
    
    data = {
        'uid': uid,
        'username': username,
        'authorization_code': full_auth,
        'access_level': access
    }
    
    try:
        r = requests.post('http://154.57.164.61:31938/api', data=data, timeout=5)
        result = r.json()
        if result.get('flag') and len(result['flag']) > 5:
            return result
    except:
        pass
    return None

print("="*70)
print("SOLUTION SUMMARY")
print("="*70)
print("\n[+] Confirmed Working Credentials:")
print("    UID: 04f6555b")
print("    Username: 74657074617374 ('teptast')")
print("\n[!] Missing Data:")
print("    - Sector 22 data (16 bytes for auth_code)")
print("    - Sector 34 data (16 bytes for access_level)")
print("    - Passcode (for key generation)")
print("\n[*] To extract the missing data:")
print("    1. Download Saleae Logic 2 (free): https://www.saleae.com/downloads/")
print("    2. Open access_reader_logic_data.sal")
print("    3. Add SPI analyzer to the 4 channels")
print("    4. Look for MIFARE Classic READ commands for sectors 8, 22, 34")
print("    5. Extract the 16-byte responses")
print("\n[*] Attempting a few more guesses...")

# Try a few educated guesses
tests = [
    # Maybe it's really simple
    ('04f6555b', '74657074617374', '00'*16, '00'*16, 0x1337),
    ('04f6555b', '74657074617374', '00'*16, 'ff'*16, 0xDEAD),
]

for uid, user, auth, access, pc in tests:
    result = try_creds(uid, user, auth, access, pc)
    if result:
        print(f"\n{'='*70}")
        print(f"SUCCESS!")
        print(f"FLAG: {result['flag']}")
        print(f"Passcode: {pc} (0x{pc:x})")
        print('='*70)
        exit(0)

print("\n[*] No luck with guesses. You'll need to decode the .sal file properly.")
print("\nAlternatively, create an issue or find the challenge author's intended")
print("solution if this is from an old CTF.")
