#!/usr/bin/env python3
"""
Look at ACTUAL packet data / payload, not just lengths
Maybe the flag is in the packet contents themselves
"""

import struct

def parse_pcap_with_data(filename):
    with open(filename, 'rb') as f:
        # Read global header
        f.read(24)
        
        packets = []
        pkt_num = 0
        
        while True:
            # Read packet header
            packet_header = f.read(16)
            if len(packet_header) < 16:
                break
            
            ts_sec, ts_usec, incl_len, orig_len = struct.unpack('IIII', packet_header)
            
            # Read packet data
            packet_data = f.read(incl_len)
            if len(packet_data) < incl_len:
                break
            
            pkt_num += 1
            packets.append({
                'num': pkt_num,
                'length': incl_len,
                'data': packet_data
            })
        
        return packets

packets = parse_pcap_with_data('sniffed.pcap')

print(f"Total packets: {len(packets)}\n")

# Look for ASCII strings in packet payloads
print("=" * 80)
print("SEARCHING FOR ASCII STRINGS IN PACKET PAYLOADS:")
print("=" * 80)

all_text = b""
for pkt in packets:
    # Skip ethernet (14 bytes) and look at the rest
    payload = pkt['data'][14:] if len(pkt['data']) > 14 else pkt['data']
    
    # Extract printable ASCII
    text = b''.join([bytes([b]) if 32 <= b <= 126 else b' ' for b in payload])
    all_text += text
    
    # Check for HTB
    if b'HTB' in payload or b'flag' in payload.lower():
        print(f"\nPacket {pkt['num']}: Found interesting content!")
        print(f"  Length: {pkt['length']}")
        print(f"  Data (first 200 bytes): {payload[:200]}")
        print(f"  ASCII: {text.decode('ascii', errors='ignore')[:200]}")

# Check all combined text
all_text_str = all_text.decode('ascii', errors='ignore')
if 'HTB{' in all_text_str:
    print("\n" + "=" * 80)
    print("FOUND HTB FLAG IN COMBINED PAYLOAD!")
    print("=" * 80)
    start = all_text_str.find('HTB{')
    end = all_text_str.find('}', start) + 1
    print(f"🚩 FLAG: {all_text_str[start:end]}")
else:
    print("\nNo HTB flag found in packet payloads.")
    print(f"Combined text length: {len(all_text_str)} characters")
    print(f"Sample: {all_text_str[:500]}")

# Try looking at specific byte positions in each packet
print("\n" + "=" * 80)
print("CHECKING SPECIFIC BYTE POSITIONS:")
print("=" * 80)

# Maybe a specific byte in each packet forms the message
for byte_pos in [0, 1, 14, 15, 42, -1]:  # Try various positions
    message = ""
    for pkt in packets:
        if byte_pos < len(pkt['data']):
            if byte_pos >= 0:
                b = pkt['data'][byte_pos]
            else:
                b = pkt['data'][byte_pos]
            
            if 32 <= b <= 126:
                message += chr(b)
    
    if len(message) > 5:
        print(f"Byte position {byte_pos:3d}: {message[:100]}")
        if 'HTB{' in message:
            start = message.find('HTB{')
            end = message.find('}', start) + 1
            print(f"  🚩 FLAG: {message[start:end]}")
