#!/usr/bin/env python3
"""
Extract the actual MIFARE sector reads from filtered MISO
"""
import csv

print("[*] Parsing export.csv for MIFARE READ responses...")

with open('export.csv', 'r') as f:
    reader = list(csv.DictReader(f))

# MIFARE Classic READ command returns 18 bytes:
# 16 bytes of data + 2 bytes CRC

# Look for sequences where we have 18-byte responses
# Filter out common status bytes
status = {0x00, 0x02, 0x04, 0x08, 0x0a, 0x0c, 0x0e, 0x10, 0x12, 0x14, 0x16, 0x1a,
          0x80, 0x82, 0x88, 0x8a, 0x8c, 0x90, 0x92, 0x93, 0x94, 0x98, 0x9a,
          0xc2, 0xc4, 0x20, 0x03, 0x30, 0x24, 0x34}

all_miso = []
for row in reader:
    if row['type'] == 'result' and row['miso'] and row['miso'].startswith('0x'):
        m = int(row['miso'], 16)
        if m not in status:
            all_miso.append(m)

print(f"[+] Filtered MISO: {len(all_miso)} bytes")

# Display in 16-byte chunks
print("\n[*] Looking for 16-byte sector data:")
for i in range(0, min(len(all_miso), 256), 16):
    block = all_miso[i:i+16]
    hex_str = ''.join(f'{b:02x}' for b in block)
    ascii_str = ''.join(chr(b) if 32 <= b < 127 else '.' for b in block)
    unique = len(set(block))
    ascii_count = sum(1 for b in block if 32 <= b < 127)
    
    if unique >= 4 and len(block) == 16:  # At least 4 different bytes
        print(f"\nBlock {i//16} (offset {i:04x}):")
        print(f"  {hex_str}")
        print(f"  '{ascii_str}' ({ascii_count} ASCII, {unique} unique)")
        
        # Check for username patterns
        if b'axel' in bytes(block) or b'tept' in bytes(block) or b'outrun' in bytes(block):
            print(f"  >>> POSSIBLE SECTOR 8 (Username) <<<")
            
            # Show next two blocks
            if i + 32 <= len(all_miso):
                b2 = all_miso[i+16:i+32]
                h2 = ''.join(f'{b:02x}' for b in b2)
                a2 = ''.join(chr(b) if 32 <= b < 127 else '.' for b in b2)
                print(f"\n  Next: {h2}")
                print(f"        '{a2}'")
                print(f"  >>> POSSIBLE SECTOR 22 <<<")
                
                b3 = all_miso[i+32:i+48]
                h3 = ''.join(f'{b:02x}' for b in b3)
                a3 = ''.join(chr(b) if 32 <= b < 127 else '.' for b in b3)
                print(f"\n  Next: {h3}")
                print(f"        '{a3}'")
                print(f"  >>> POSSIBLE SECTOR 34 <<<")
                break

# Also try finding specific patterns
print("\n[*] Searching for '6460' pattern (looks common in data)...")
for i in range(len(all_miso) - 17):
    if all_miso[i] == 0x64 and all_miso[i+1] == 0x60:
        block = all_miso[i:i+16]
        hex_str = ''.join(f'{b:02x}' for b in block)
        ascii_str = ''.join(chr(b) if 32 <= b < 127 else '.' for b in block)
        print(f"\nOffset {i:04x}: {hex_str}")
        print(f"           '{ascii_str}'")
        
        # Show context
        if i + 48 <= len(all_miso):
            for j in range(1, 3):
                bn = all_miso[i+(j*16):i+((j+1)*16)]
                hn = ''.join(f'{b:02x}' for b in bn)
                an = ''.join(chr(b) if 32 <= b < 127 else '.' for b in bn)
                print(f"     +{j}:  {hn}")
                print(f"           '{an}'")
        break  # Just show first match
