#!/usr/bin/env python3
"""
Extract sectors by removing interleaved status bytes
"""
import csv
import requests

def lcg_step(seed):
    return (seed * 0x52c6425d + 0xcc52c) % (2**32)

def generate_keys(passcode):
    seed = passcode
    keys = []
    for _ in range(6):
        seed = lcg_step(seed)
        keys.append(seed % 0xffffff)
    return keys

print("[*] Extracting sectors with proper byte filtering...")

with open('export.csv', 'r') as f:
    reader = list(csv.DictReader(f))

sectors = {}

# Search for each sector
for sector_num, sector_hex in [(8, '0x08'), (22, '0x16'), (34, '0x22')]:
    print(f"\n[*] Searching for sector {sector_num} (MOSI={sector_hex})...")
    
    for i in range(len(reader)):
        row = reader[i]
        if row['type'] == 'result' and row['mosi'] == sector_hex:
            print(f"  Found at line {i}")
            
            # Get next MISO bytes (should be 32+ bytes: 16 data with 16 status bytes interleaved)
            miso = []
            for j in range(i, min(i+40, len(reader))):
                r = reader[j]
                if r['type'] == 'result' and r['miso'] and r['miso'].startswith('0x'):
                    m = int(r['miso'], 16)
                    miso.append(m)
            
            # Remove 0x00 and extract pattern (every other byte after status)
            # Pattern appears to be: status, data, status, data, ...
            # Where status is often 0x12, 0x92, etc.
            
            # Try filtering: remove 0x00, 0x12, 0x92, 0x94, 0x98, etc.
            filtered = []
            skip = {0x00, 0x12, 0x92, 0x94, 0x98, 0x9a, 0x8c, 0x8a, 0x88, 0x80, 0x02, 0x90, 0x1a, 0x14, 0x10}
            for b in miso:
                if b not in skip:
                    filtered.append(b)
            
            if len(filtered) >= 16:
                sector_data = filtered[:16]
                sectors[sector_num] = sector_data
                
                hex_str = ''.join(f'{b:02x}' for b in sector_data)
                ascii_str = ''.join(chr(b) if 32 <= b < 127 else '.' for b in sector_data)
                
                print(f"  Data: {hex_str}")
                print(f"  ASCII: '{ascii_str}'")
            break

if len(sectors) == 3:
    print(f"\n{'='*70}")
    print("SUCCESS! Extracted all 3 sectors:")
    print(f"{'='*70}")
    
    sector_8_hex = ''.join(f'{b:02x}' for b in sectors[8])
    sector_22_hex = ''.join(f'{b:02x}' for b in sectors[22])
    sector_34_hex = ''.join(f'{b:02x}' for b in sectors[34])
    
    # Try to decode sector 8 as username
    username_hex = sector_8_hex.replace('00', '').strip()
    if not username_hex:
        username_hex = sector_8_hex
    
    print(f"\nSector 8 (Username):  {sector_8_hex}")
    print(f"Sector 22 (Auth):     {sector_22_hex}")
    print(f"Sector 34 (Access):   {sector_34_hex}")
    print(f"\nUID: 04f6555b")
    print(f"Username: {username_hex}")
    
    # Test with a few passcodes
    print(f"\n[*] Testing with common passcodes...")
    for pc in [0, 1, 1234, 0x1337, 0x4242, 42069]:
        keys = generate_keys(pc)
        key_bytes = []
        for key in keys[4:6]:
            key_bytes.extend([key >> 16, (key >> 8) & 0xFF, key & 0xFF])
        key_hex = ''.join(f'{b:02x}' for b in key_bytes)
        
        auth_code = sector_22_hex + key_hex
        
        data = {
            'uid': '04f6555b',
            'username': username_hex,
            'authorization_code': auth_code,
            'access_level': sector_34_hex
        }
        
        try:
            r = requests.post('http://154.57.164.61:31938/api', data=data, timeout=3)
            result = r.json()
            
            if result.get('flag') and len(result.get('flag', '')) > 5:
                print(f"\n{'='*70}")
                print(f"FLAG FOUND with passcode {pc}!")
                print(f"FLAG: {result['flag']}")
                print(f"{'='*70}")
                break
            else:
                print(f"  PC {pc:06x}: {result}")
        except Exception as e:
            print(f"  PC {pc:06x}: Error - {e}")
else:
    print(f"\n[-] Only found {len(sectors)}/3 sectors")
