#!/usr/bin/env python3
"""
Systematic approach - try common RFID/CTF patterns
"""
import requests
import json

def lcg_step(seed):
    """LCG from the code"""
    return (seed * 0x52c6425d + 0xcc52c) % (2**32)

def bytes_from_num(num):
    """Convert number to 3-byte array"""
    return [int(num >> 16), int((num >> 8) & 0xFF), int(num & 0xFF)]

def generate_auth_keys(passcode):
    """Generate the 6 keys for all 3 sectors"""
    seed = passcode
    keys = []
    for _ in range(6):
        seed = lcg_step(seed)
        keys.append(seed % 0xffffff)
    return keys

def try_unlock(uid, username_hex, auth_code_hex, access_level_hex, passcode):
    """Attempt to unlock with given credentials"""
    
    # Generate the keys
    keys = generate_auth_keys(passcode)
    
    # The auth_code sent is: auth_code_from_sector_22 + keys_for_sector_34
    # Keys for sector 34 are the last 2 keys (indices 4, 5)
    sector3_keys = keys[4:6]
    
    # Convert to bytes
    key_bytes = []
    for key in sector3_keys:
        key_bytes.extend(bytes_from_num(key))
        
    key_hex = ''.join(f'{b:02x}' for b in key_bytes)
    
    full_auth = auth_code_hex + key_hex
    
    data = {
        'uid': uid,
        'username': username_hex,
        'authorization_code': full_auth,
        'access_level': access_level_hex
    }
    
    try:
        response = requests.post('http://154.57.164.61:31938/api', data=data, timeout=5)
        result = response.json()
        
        if 'HTB{' in result.get('flag', ''):
            print(f"\n{'='*70}")
            print(f"SUCCESS!")
            print(f"{'='*70}")
            print(f"UID: {uid}")
            print(f"Username: {username_hex}")
            print(f"Passcode: {passcode}")
            print(f"Flag: {result['flag']}")
            print(f"{'='*70}")
            return True
            
    except Exception as e:
        pass
    
    return False

# Try systematic patterns
print("[*] Starting systematic brute force...")
print("[*] This may take a while...\n")

# Common UIDs (MIFARE Classic often starts with 04)
uids = [
    '04f6555b', '04000000', '04ffffff',  # Test UIDs
]

# Common usernames in hex
usernames =['admin', 'user', 'root', 'test', 'teptast', 'asteptet']
usernames_hex = [''.join(f'{ord(c):02x}' for c in name) for name in usernames]

# All zeros for auth_code and access_level as starting point
auth_codes = ['00' * 16]
access_levels = [' 00' * 16, 'ff' * 16]

# Try a range of passcodes
passcodes = list(range(0, 10000)) + [0xDEAD, 0xBEEF, 0xCAFE, 0xBABE, 0xDEADBEEF]

count = 0
for uid in uids:
    for username in usernames_hex:
        for auth in auth_codes:
            for access in access_levels:
                for passcode in passcodes:
                    count += 1
                    if count % 1000 == 0:
                        print(f"[*] Tried {count} combinations...")
                    
                    if try_unlock(uid, username, auth, access, passcode):
                        exit(0)

print(f"\n[*] Tried {count} combinations, no solution found.")
print("[*] May need to extract actual RFID data from logic capture.")
