#!/usr/bin/env python3
"""
Look at MOSI/MISO pairs to find READ operations
"""
import csv

print("[*] Analyzing MOSI/MISO pairs for MIFARE READ operations...")

with open('export.csv', 'r') as f:
    reader = list(csv.DictReader(f))

# MIFARE Classic READ command is 0x30 followed by block number
# We're looking for MOSI=0x30 (READ) followed by MISO containing data

read_responses = []

for i in range(len(reader) - 20):
    row = reader[i]
    
    # Look for READ command (0x30) in MOSI
    if row['type'] == 'result' and row['mosi'] and row['mosi'] == '0x30':
        print(f"\n[+] Found READ command at line {i}")
        
        # Get the next 20 MISO bytes (should contain the 16-byte response + CRC)
        miso_data = []
        for j in range(i, min(i+25, len(reader))):
            r = reader[j]
            if r['type'] == 'result' and r['miso'] and r['miso'].startswith('0x'):
                m = int(r['miso'], 16)
                if m not in [0x00]:  # Skip nulls
                    miso_data.append(m)
        
        if len(miso_data) >= 16:
            block = miso_data[: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"  Response: {hex_str}")
            print(f"  ASCII:    '{ascii_str}'")
            
            read_responses.append(block)
            
            if len(read_responses) >= 3:  # Get first 3 reads (sectors 8, 22, 34)
                break

if len(read_responses) >= 3:
    print(f"\n{'='*70}")
    print("EXTRACTED SECTORS:")
    print(f"{'='*70}")
    
    for idx, sector in enumerate(read_responses):
        hex_str = ''.join(f'{b:02x}' for b in sector)
        ascii_str = ''.join(chr(b) if 32 <= b < 127 else '.' for b in sector)
        
        print(f"\nSector {idx} (likely {[8,22,34][idx] if idx < 3 else '?'}):")
        print(f"  {hex_str}")
        print(f"  '{ascii_str}'")
        
        if idx == 0:
            # Try as username
            username_hex = hex_str.strip('0')
            print(f"  Username: {username_hex}")
        elif idx == 1:
            print(f"  Auth Code: {hex_str}")
        elif idx == 2:
            print(f"  Access Level: {hex_str}")
else:
    print(f"\n[-] Only found {len(read_responses)} READ responses")
    print("[*] Trying different approach - looking for sector numbers in MOSI...")
    
    # Sectors 8, 22, 34 in hex: 0x08, 0x16, 0x22
    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}")
                # Show next few MISO bytes
                miso = []
                for j in range(i, min(i+20, len(reader))):
                    r = reader[j]
                    if r['type'] == 'result' and r['miso'] and r['miso'].startswith('0x'):
                        m = int(r['miso'], 16)
                        if m not in [0x00]:
                            miso.append(m)
                
                if miso:
                    print(f"  MISO: {' '.join(f'{b:02x}' for b in miso[:20])}")
                break
