#!/usr/bin/env python3
import struct

def parse_pcap(filename):
    with open(filename, 'rb') as f:
        f.read(24)
        packets = []
        while True:
            ph = f.read(16)
            if len(ph) < 16:
                break
            _, _, incl_len, _ = struct.unpack('IIII', ph)
            pd = f.read(incl_len)
            if len(pd) < incl_len:
                break
            packets.append(pd)
        return packets

packets = parse_pcap('sniffed.pcap')

print("Looking for '{' (0x7b) and other special characters in ALL bytes:")
print("=" * 80)

# Check all last bytes
message_bytes = []
for i, pkt in enumerate(packets):
    b = pkt[-1]
    message_bytes.append(b)
    if b == 0x7b:  # '{'
        print(f"✓ Packet {i+1}: Found '{{' (0x7b)!")
    elif b == 0x7d:  # '}'
        print(f"✓ Packet {i+1}: Found '}}' (0x7d)!")
    elif b in [0x48, 0x54, 0x42]:  # H, T, B
        print(f"  Packet {i+1}: Found '{chr(b)}' (0x{b:02x})")

# Build complete message with ALL bytes as hex
print("\n" + "=" * 80)
print("COMPLETE BYTE SEQUENCE:")
print("=" * 80)
hex_str = ' '.join([f'{b:02x}' for b in message_bytes])
print(hex_str)

# Try to decode the FULL sequence cleverly
print("\n" + "=" * 80)
print("DECODING STRATEGIES:")
print("=" * 80)

# Strategy 1: Just printable ASCII
printable = ''.join([chr(b) if 32 <= b <= 126 else '' for b in message_bytes])
print(f"1. Printable only: {printable}")

# Strategy 2: Replace non-printable with placeholder
with_placeholders = ''.join([chr(b) if 32 <= b <= 126 else '.' for b in message_bytes])
print(f"2. With dots: {with_placeholders}")

# Strategy 3: Look for HTB pattern in hex
# HTB in hex is: 48 54 42
print(f"\n3. Looking for HTB pattern in hex...")
for i in range(len(message_bytes) - 2):
    if message_bytes[i] == 0x48 and message_bytes[i+1] == 0x54 and message_bytes[i+2] == 0x42:
        print(f"   Found HTB at packets {i+1}, {i+2}, {i+3}!")

# Strategy 4: Maybe the flag is just the printable characters we found
print(f"\n4. Flag construction:")
print(f"   Printable sequence: {printable}")
if '}' in printable:
    close_idx = printable.find('}')
    print(f"   Position of '}}': {close_idx}")
    before_close = printable[:close_idx+1]
    print(f"   Before close brace: {before_close}")
    
    # The flag might just be: HTB{<printable_sequence_before_}>}
    possible_flag = f"HTB{{{before_close[:-1]}}}"  # Remove the } and add HTB{
    print(f"\n🚩 POSSIBLE FLAG: {possible_flag}")
