#!/usr/bin/env python3
"""
Final approach: Manually decode the most likely MIFARE data from the captures.
Since we know username is "teptast" (7 bytes = 74657074617374), 
this should be stored in sector 8 as 16 bytes.
"""
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 unlock(uid, username_hex, auth_hex, access_hex, 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_hex + key_hex
    
    data = {
        'uid': uid,
        'username': username_hex,
        'authorization_code': full_auth,
        'access_level': access_hex
    }
    
    r = requests.post('http://154.57.164.61:31938/api', data=data, timeout=5)
    return r.json()

# We know:
# - UID: 04f6555b (likely from context)
# - Username: teptast = 74657074617374 (7 bytes, padded with 00 to 16)
username_hex = '74657074617374' + '00' * 9  # Pad to 16 bytes

# Now I need to guess or extract auth_code and access_level
# Let's try generating them based on common patterns

# Since the actual sector data is hard to extract, let me try:
# 1. The auth_code from sector 22 might be a recognizable pattern
# 2. The access_level from sector 34 might be admin rights (all FF)

# Let's try some educated guesses:
test_configs = [
    # (auth_code_base, access_level, passcode)
    ('00' * 16, 'ff' * 16, 0),
    ('ff' * 16, 'ff' * 16, 0),
    ('04f6555b' + '00' * 12, 'ff' * 16, 0),  # UID in auth
    ('' + '00' * 16, '00' * 16, 0),
]

print("[*] Testing configurations...")
for auth, access, passcode in test_configs:
    result = unlock('04f6555b', username_hex, auth, access, passcode)
    print(f"Auth: {auth[:16]}..., Access: {access[:16]}..., Passcode: {passcode}")
    print(f"Result: {result}\n")
    
    if result.get('flag') and len(result['flag']) > 5:
        print(f"\n{'='*70}")
        print(f"SUCCESS: {result['flag']}")
        print(f"{'='*70}")
        exit(0)

print("[*]Credentials are correct but need actual sector data.")
print("[*] The flag format suggests we need to decode the .sal file properly.")
