#!/bin/bash
# Extract last byte of each packet from tcpdump output

tcpdump -r sniffed.pcap -xx 2>/dev/null | python3 -c "
import sys
import re

packets = []
current_packet_hex_lines = []
packet_num = 0

for line in sys.stdin:
    line = line.rstrip()
    # Check if this is a timestamp line (new packet)
    if re.match(r'^\d\d:\d\d:', line):
        packet_num += 1
        if current_packet_hex_lines:
            # Get last hex line of previous packet
            last_line = current_packet_hex_lines[-1]
            # Extract hex values (skip the address part like '0x00a0:')
            hex_values = last_line.split()[1:]  # Skip address
            if hex_values:
                # Last value is something like 'c068' - we want the last 2 chars
                last_hex_pair = hex_values[-1]
                # Get last byte (last 2 characters)
                last_byte = last_hex_pair[-2:]
                dec = int(last_byte, 16)
                if 32 <= dec <= 126:
                    packets.append((packet_num, chr(dec)))
        current_packet_hex_lines = []
    elif line.strip().startswith('0x'):
        current_packet_hex_lines.append(line)

# Handle last packet
packet_num += 1
if current_packet_hex_lines:
    last_line = current_packet_hex_lines[-1]
    hex_values = last_line.split()[1:]
    if hex_values:
        last_hex_pair = hex_values[-1]
        last_byte = last_hex_pair[-2:]
        dec = int(last_byte, 16)
        if 32 <= dec <= 126:
            packets.append((packet_num, chr(dec)))

# Show all printable packets
print('Printable last bytes:')
for num, char in packets:
    print(f'  Packet {num}: {repr(char)}')

# Extract full message
full_message = ''.join([char for _, char in packets])
print(f'\nFull message: {full_message}')

# Extract packets 9-41 for flag
flag_chars = [char for num, char in packets if 9 <= num <= 41]
flag = ''.join(flag_chars)
print(f'\nPackets 9-41: {flag}')
print(f'\n🚩 FLAG: HTB{{{flag}}}')
"

