import struct

def parse_pcap(filename):
    """Parse PCAP file and return packet data"""
    with open(filename, 'rb') as f:
        f.read(24)  # Skip global header
        
        packets = []
        packet_num = 1
        
        while True:
            packet_header = f.read(16)
            if len(packet_header) < 16:
                break
            
            ts_sec, ts_usec, incl_len, orig_len = struct.unpack('IIII', packet_header)
            packet_data = f.read(incl_len)
            if len(packet_data) < incl_len:
                break
            
            packets.append({'num': packet_num, 'data': packet_data, 'length': incl_len})
            packet_num += 1
        
        return packets

def search_for_htb(packets):
    """Search for HTB{ pattern in packets"""
    print("=" * 70)
    print("SEARCHING FOR 'HTB{' PATTERN IN PACKETS")
    print("=" * 70)
    
    for pkt in packets:
        data = pkt['data']
        # Search for HTB{ in packet
        if b'HTB{' in data:
            idx = data.index(b'HTB{')
            # Extract surrounding context
            start = max(0, idx - 10)
            end = min(len(data), idx + 50)
            context = data[start:end]
            print(f"\n✓ Found 'HTB{{' in packet {pkt['num']} at byte offset {idx}")
            print(f"  Context (hex): {context.hex()}")
            print(f"  Context (ascii): {context}")
            
            # Try to extract full flag
            try:
                end_idx = data.index(b'}', idx) + 1
                flag = data[idx:end_idx]
                print(f"  🚩 POSSIBLE FLAG: {flag.decode('ascii', errors='ignore')}")
            except:
                pass

def analyze_all_positions(packets):
    """Try extracting from different byte positions"""
    print("\n" + "=" * 70)
    print("TRYING DIFFERENT BYTE POSITIONS")
    print("=" * 70)
    
    positions = [0, 1, 2, -1, -2, -3]  # First few and last few bytes
    
    for pos in positions:
        chars = []
        for pkt in packets:
            if len(pkt['data']) > abs(pos):
                try:
                    byte_val = pkt['data'][pos]
                    if 32 <= byte_val <= 126:
                        chars.append(chr(byte_val))
                except:
                    pass
        
        message = ''.join(chars)
        if 'HTB{' in message:
            print(f"\n✓ Position {pos}: FOUND FLAG!")
            start = message.index('HTB{')
            end = message.index('}', start) + 1
            print(f"  🚩 FLAG: {message[start:end]}")
        else:
            # Show a preview
            preview = message[:50] if len(message) > 50 else message
            print(f"\n  Position {pos}: {preview}... (no HTB{{ found)")

def analyze_payload_only(packets):
    """Extract data after network headers (usually Ethernet + IP + TCP/UDP)"""
    print("\n" + "=" * 70)
    print("ANALYZING PACKET PAYLOADS (AFTER HEADERS)")
    print("=" * 70)
    
    # Common header sizes
    eth_size = 14
    ip_min = 20
    tcp_min = 20
    
    for offset in [eth_size, eth_size + ip_min, eth_size + ip_min + tcp_min]:
        print(f"\nTrying offset {offset} bytes (skipping headers):")
        chars = []
        for pkt in packets:
            if len(pkt['data']) > offset:
                byte_val = pkt['data'][offset]
                if 32 <= byte_val <= 126:
                    chars.append(chr(byte_val))
        
        message = ''.join(chars)
        if 'HTB{' in message:
            print(f"  ✓ FOUND FLAG!")
            start = message.index('HTB{')
            end = message.index('}', start) + 1
            print(f"  🚩 FLAG: {message[start:end]}")
        else:
            preview = message[:40] if len(message) > 40 else message
            print(f"  Preview: {preview}...")

if __name__ == "__main__":
    pcap_file = "sniffed.pcap"
    
    print(f"Analyzing {pcap_file}...\n")
    packets = parse_pcap(pcap_file)
    print(f"Total packets: {len(packets)}\n")
    
    # Search for HTB{ string in raw packet data
    search_for_htb(packets)
    
    # Try different byte positions
    analyze_all_positions(packets)
    
    # Try skipping common headers
    analyze_payload_only(packets)
