From 9ea86831f3f48f9cc7ce33d100c5abb6c3481415 Mon Sep 17 00:00:00 2001 From: creinky Date: Sun, 22 Nov 2026 22:16:40 -0700 Subject: [PATCH] Initial commit: PCAP decode tool with credential extraction and stream reassembly --- README.md | 57 +++++ pcap_decode.py | 648 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 705 insertions(+) create mode 100644 README.md create mode 100755 pcap_decode.py diff --git a/README.md b/README.md new file mode 100644 index 0000000..d0ab692 --- /dev/null +++ b/README.md @@ -0,0 +1,57 @@ +# PCAP Decode + +A comprehensive network packet analysis tool that reassembles TCP streams, extracts credentials, and decodes traffic from pcap captures in a single command. + +## Features + +- **TCP Stream Reassembly** - Reconstructs complete conversations from fragmented packets +- **Credential Extraction** - Automatically finds plaintext passwords and auth tokens in HTTP Basic Auth headers, login forms, FTP, and Telnet sessions +- **DNS Lookup Decoding** - Shows all domain name resolutions +- **TLS SNI Detection** - Identifies destination hostnames from HTTPS handshakes (even though the session itself is encrypted) +- **File Extraction** - Pulls images to `extracted_files/images/` and other transferred files to `extracted_files/files/` +- **Conversation Summary** - Provides a high-level flow summary of network activity + +## Limitations + +TLS encrypts payload data, so only the SNI hostname is recoverable from HTTPS sessions — never request/response contents, credentials, or files within encrypted traffic. + +## Installation + +```bash +python -m pip install scapy +``` + +## Usage + +Run everything in one command: + +```bash +python pcap_decode.py capture.pcap +``` + +Customize the output directory: + +```bash +python pcap_decode.py capture.pcap --extract-dir out +``` + +Get a raw per-packet dump instead of the full analysis: + +```bash +python pcap_decode.py capture.pcap --raw +``` + +Filter and limit raw output: + +```bash +python pcap_decode.py capture.pcap --raw --filter http --limit 50 +``` + +## Example Output + +The tool produces a structured report with sections for: +- Credentials found (prioritized at the top) +- DNS lookups +- TLS SNI hostnames +- TCP stream conversations +- Extracted files listing diff --git a/pcap_decode.py b/pcap_decode.py new file mode 100755 index 0000000..2a70e39 --- /dev/null +++ b/pcap_decode.py @@ -0,0 +1,648 @@ +#!/usr/bin/env python3 +""" +One command does everything: reassembles TCP streams, decodes DNS lookups, +pulls plaintext HTTP passwords/credentials (Basic Auth headers, login form +fields) to the top of the report, extracts images to extracted_files/images/ +and any other transferred files to extracted_files/files/, and lists TLS SNI +(destination hostnames seen in HTTPS handshakes — readable even though the +session itself is encrypted) plus a conversation/flow summary. + +Note: none of this works against HTTPS bodies — TLS encrypts the payload, so +only the SNI hostname is recoverable from encrypted sessions, never the +request/response contents, credentials, or files. + +Usage: + python pcap_decode.py capture.pcap # everything, one command + python pcap_decode.py capture.pcap --extract-dir out # change where files are saved + python pcap_decode.py capture.pcap --raw # per-packet line dump instead + python pcap_decode.py capture.pcap --raw --filter http --limit 50 + +Requires: scapy (python -m pip install scapy) +""" +import argparse +import base64 +import os +import re +import struct +import sys +from collections import defaultdict +from urllib.parse import parse_qsl + +try: + from scapy.all import rdpcap, TCP, UDP, ICMP, IP, IPv6, Raw, DNS, DNSQR + from scapy.layers.http import HTTPRequest, HTTPResponse +except ImportError: + sys.exit("Missing dependency. Install with: python -m pip install scapy") + +CRED_KEY_PATTERN = re.compile(r"pass|pwd|passwd|secret|token|auth", re.IGNORECASE) +SESSION_KEY_PATTERN = re.compile(r"sess|sid|token|auth", re.IGNORECASE) +IMAGE_EXTS = { + "image/jpeg": "jpg", "image/jpg": "jpg", "image/png": "png", + "image/gif": "gif", "image/bmp": "bmp", "image/webp": "webp", +} +FTP_PORT = 21 +TELNET_PORT = 23 + + +# ---------- TLS SNI extraction (no decryption needed — SNI is sent in cleartext) ---------- + +def extract_sni(payload: bytes): + try: + if len(payload) < 5 or payload[0] != 0x16: # TLS handshake record + return None + pos = 5 + if payload[pos] != 0x01: # ClientHello + return None + pos += 4 # handshake type + length + pos += 2 + 32 # client version + random + session_id_len = payload[pos] + pos += 1 + session_id_len + cipher_suites_len = struct.unpack("!H", payload[pos:pos + 2])[0] + pos += 2 + cipher_suites_len + compression_len = payload[pos] + pos += 1 + compression_len + if pos + 2 > len(payload): + return None + ext_total_len = struct.unpack("!H", payload[pos:pos + 2])[0] + pos += 2 + end = pos + ext_total_len + while pos + 4 <= end: + ext_type = struct.unpack("!H", payload[pos:pos + 2])[0] + ext_len = struct.unpack("!H", payload[pos + 2:pos + 4])[0] + pos += 4 + if ext_type == 0x00: # server_name + sni_pos = pos + 2 # skip server_name_list length + name_len = struct.unpack("!H", payload[sni_pos + 1:sni_pos + 3])[0] + name = payload[sni_pos + 3:sni_pos + 3 + name_len] + return name.decode(errors="replace") + pos += ext_len + except (IndexError, struct.error): + return None + return None + + +# ---------- TCP stream reassembly (so HTTP bodies spanning multiple packets are readable) ---------- + +def build_tcp_streams(packets): + """Group TCP packets into per-direction byte streams. + Returns dict: (client_ip, client_port, server_ip, server_port) -> {"client": bytes, "server": bytes} + """ + segments = defaultdict(list) # (src,sport,dst,dport) -> [(seq, payload), ...] + syn_senders = {} # frozenset({(ip,port),(ip,port)}) -> (ip,port) that sent the initial SYN + + for pkt in packets: + if not (pkt.haslayer(TCP) and IP in pkt): + continue + ip, tcp = pkt[IP], pkt[TCP] + src, dst, sport, dport = ip.src, ip.dst, tcp.sport, tcp.dport + + if tcp.flags & 0x02 and not tcp.flags & 0x10: # SYN without ACK == connection initiator + flow_key = frozenset([(src, sport), (dst, dport)]) + syn_senders.setdefault(flow_key, (src, sport)) + + if pkt.haslayer(Raw): + payload = bytes(pkt[Raw].load) + if payload: + segments[(src, sport, dst, dport)].append((tcp.seq, payload)) + + def assemble(key): + segs = sorted(set(segments.get(key, [])), key=lambda x: x[0]) + return b"".join(p for _, p in segs) + + flows = {} + handled = set() + for (src, sport, dst, dport) in list(segments.keys()): + pair = frozenset([(src, sport, dst, dport), (dst, dport, src, sport)]) + if pair in handled: + continue + handled.add(pair) + + flow_key = frozenset([(src, sport), (dst, dport)]) + client_addr = syn_senders.get(flow_key, (src, sport)) # fallback: first sender seen + + if client_addr == (src, sport): + cli_ip, cli_port, srv_ip, srv_port = src, sport, dst, dport + else: + cli_ip, cli_port, srv_ip, srv_port = dst, dport, src, sport + + flows[(cli_ip, cli_port, srv_ip, srv_port)] = { + "client": assemble((cli_ip, cli_port, srv_ip, srv_port)), + "server": assemble((srv_ip, srv_port, cli_ip, cli_port)), + } + return flows + + +def parse_http_messages(stream: bytes): + """Yield (start_line, headers_dict, body_bytes) parsed from a raw HTTP byte stream.""" + pos, n, count = 0, len(stream), 0 + while pos < n and count < 500: + header_end = stream.find(b"\r\n\r\n", pos) + if header_end == -1: + break + lines = stream[pos:header_end].split(b"\r\n") + if not lines or not lines[0]: + break + start_line = lines[0].decode(errors="replace") + headers = {} + for line in lines[1:]: + if b":" in line: + k, _, v = line.partition(b":") + key = k.decode(errors="replace").strip().lower() + val = v.decode(errors="replace").strip() + headers[key] = headers[key] + "\n" + val if key in headers else val + + body_start = header_end + 4 + content_length = headers.get("content-length") + transfer_encoding = headers.get("transfer-encoding", "").lower() + + if "chunked" in transfer_encoding: + body = bytearray() + cpos = body_start + while True: + line_end = stream.find(b"\r\n", cpos) + if line_end == -1: + break + try: + chunk_size = int(stream[cpos:line_end].split(b";")[0].strip(), 16) + except ValueError: + break + if chunk_size == 0: + trailer_end = stream.find(b"\r\n\r\n", line_end + 2) + cpos = trailer_end + 4 if trailer_end != -1 else line_end + 2 + break + chunk_start = line_end + 2 + body.extend(stream[chunk_start:chunk_start + chunk_size]) + cpos = chunk_start + chunk_size + 2 + next_pos, body = cpos, bytes(body) + elif content_length is not None: + try: + clen = int(content_length) + except ValueError: + clen = 0 + body = stream[body_start:body_start + clen] + next_pos = body_start + clen + else: + body, next_pos = b"", body_start + + if next_pos <= pos: + break + yield start_line, headers, body + pos = next_pos + count += 1 + + +def strip_telnet_iac(data: bytes) -> bytes: + """Remove Telnet IAC option-negotiation sequences, leaving the readable session bytes.""" + out = bytearray() + i, n = 0, len(data) + while i < n: + if data[i] != 0xFF: + out.append(data[i]) + i += 1 + continue + if i + 1 >= n: + break + cmd = data[i + 1] + if cmd == 0xFF: # escaped literal 0xFF + out.append(0xFF) + i += 2 + elif cmd in (0xFB, 0xFC, 0xFD, 0xFE): # WILL/WONT/DO/DONT + option byte + i += 3 + elif cmd == 0xFA: # subnegotiation, runs until IAC SE + end = data.find(b"\xff\xf0", i + 2) + i = end + 2 if end != -1 else n + else: # other 2-byte commands (NOP, GA, etc.) + i += 2 + return bytes(out) + + +def save_bytes(extract_dir, filename, data, saved_files): + os.makedirs(extract_dir, exist_ok=True) + filename = re.sub(r'[^\w.\-]', '_', filename) + out_path = os.path.join(extract_dir, filename) + with open(out_path, "wb") as f: + f.write(data) + saved_files.append((out_path, len(data))) + + +def extract_multipart_files(body, headers, extract_dir, label, saved_images, saved_files): + m = re.search(r'boundary=("?)([^";]+)\1', headers.get("content-type", "")) + if not m: + return + boundary = ("--" + m.group(2)).encode() + for part in body.split(boundary): + part = part.strip(b"\r\n") + if not part or part == b"--": + continue + header_end = part.find(b"\r\n\r\n") + if header_end == -1: + continue + part_headers, part_body = part[:header_end], part[header_end + 4:] + disp = re.search(rb'filename="([^"]*)"', part_headers) + if disp and part_body: + filename = disp.group(1).decode(errors="replace") or "upload.bin" + ext = filename.rsplit(".", 1)[-1].lower() if "." in filename else "" + if ext in {"jpg", "jpeg", "png", "gif", "bmp", "webp"}: + save_bytes(os.path.join(extract_dir, "images"), f"{label}_{filename}", part_body, saved_images) + else: + save_bytes(os.path.join(extract_dir, "files"), f"{label}_{filename}", part_body, saved_files) + + +# ---------- summary report (default) ---------- + +def print_report(packets, extract_dir): + proto_counts = defaultdict(int) + dns_queries = [] # (src, dst, qname) + dns_answers = [] # (qname, rdata) + tls_sni = {} # (src, dst) -> hostname + flows = defaultdict(lambda: [0, 0]) # (src,sport,dst,dport,proto) -> [packets, bytes] + + for pkt in packets: + if IP in pkt: + src, dst = pkt[IP].src, pkt[IP].dst + elif IPv6 in pkt: + src, dst = pkt[IPv6].src, pkt[IPv6].dst + else: + src = dst = None + + if pkt.haslayer(TCP): + proto_counts["TCP"] += 1 + sport, dport = pkt[TCP].sport, pkt[TCP].dport + elif pkt.haslayer(UDP): + proto_counts["UDP"] += 1 + sport, dport = pkt[UDP].sport, pkt[UDP].dport + elif pkt.haslayer(ICMP): + proto_counts["ICMP"] += 1 + sport = dport = None + else: + proto_counts["other"] += 1 + sport = dport = None + + if src and sport is not None: + proto_name = "TCP" if pkt.haslayer(TCP) else "UDP" + key = (src, sport, dst, dport, proto_name) + flows[key][0] += 1 + flows[key][1] += len(pkt) + + if pkt.haslayer(DNS): + dns = pkt[DNS] + if dns.qr == 0 and dns.qdcount > 0: + try: + dns_queries.append((src, dst, dns[DNSQR].qname.decode(errors="replace").rstrip("."))) + except Exception: + pass + elif dns.qr == 1: + try: + qname = dns[DNSQR].qname.decode(errors="replace").rstrip(".") if dns.qdcount else "?" + except Exception: + qname = "?" + for i in range(dns.ancount): + try: + rdata = dns.an[i].rdata + if isinstance(rdata, bytes): + rdata = rdata.decode(errors="replace") + dns_answers.append((qname, str(rdata))) + except Exception: + pass + + if pkt.haslayer(Raw) and dst: + sni = extract_sni(bytes(pkt[Raw].load)) + if sni: + tls_sni[(src, dst)] = sni + + # HTTP: reassemble TCP streams so multi-packet bodies (forms, images) are readable + http_requests, http_responses = [], [] + form_fields, credentials, cookies = [], [], [] + telnet_sessions = [] + saved_images, saved_files = [], [] + file_counter = 0 + + for (cli_ip, cli_port, srv_ip, srv_port), sides in build_tcp_streams(packets).items(): + if cli_port == FTP_PORT or srv_port == FTP_PORT: + for line in sides["client"].decode(errors="replace").split("\r\n"): + line = line.strip() + if re.match(r"^(USER|PASS)\s", line, re.IGNORECASE): + credentials.append(f" [FTP] {cli_ip}:{cli_port} -> {srv_ip}:{srv_port} {line}") + + if cli_port == TELNET_PORT or srv_port == TELNET_PORT: + for direction, raw in (("client", sides["client"]), ("server", sides["server"])): + cleaned = strip_telnet_iac(raw).decode("latin-1", errors="replace") + text = "".join(c if c.isprintable() or c in "\r\n" else "." for c in cleaned).strip() + if text: + telnet_sessions.append((cli_ip, cli_port, srv_ip, srv_port, direction, text[:1000])) + + for start_line, headers, body in parse_http_messages(sides["client"]): + if not re.match(r"^(GET|POST|PUT|DELETE|HEAD|OPTIONS|PATCH) .+ HTTP/", start_line): + continue + http_requests.append((cli_ip, cli_port, srv_ip, srv_port, start_line)) + + auth = headers.get("authorization", "") + if auth.lower().startswith("basic "): + try: + decoded = base64.b64decode(auth.split(" ", 1)[1]).decode(errors="replace") + credentials.append(f" [HTTP Basic Auth] {cli_ip}:{cli_port} -> {srv_ip}:{srv_port} " + f"{start_line} credentials: {decoded}") + except Exception: + pass + + cookie_header = headers.get("cookie") + if cookie_header: + cookies.append((cli_ip, cli_port, srv_ip, srv_port, "sent", cookie_header.replace("\n", "; "))) + + content_type = headers.get("content-type", "") + if not body: + continue + if "multipart/form-data" in content_type: + file_counter += 1 + extract_multipart_files(body, headers, extract_dir, f"upload{file_counter}_{cli_ip}", + saved_images, saved_files) + elif "urlencoded" in content_type: + for k, v in parse_qsl(body.decode(errors="replace")): + flagged = bool(CRED_KEY_PATTERN.search(k)) + form_fields.append((cli_ip, cli_port, srv_ip, srv_port, k, v, flagged)) + if flagged: + credentials.append(f" [form field] {cli_ip}:{cli_port} -> {srv_ip}:{srv_port} {k}={v}") + elif content_type.startswith("image/"): + file_counter += 1 + ext = IMAGE_EXTS.get(content_type.split(";")[0].strip().lower(), "img") + save_bytes(os.path.join(extract_dir, "images"), f"upload{file_counter}_{cli_ip}.{ext}", + body, saved_images) + + for start_line, headers, body in parse_http_messages(sides["server"]): + if not start_line.upper().startswith("HTTP/"): + continue + http_responses.append((cli_ip, cli_port, srv_ip, srv_port, start_line)) + + set_cookie = headers.get("set-cookie") + if set_cookie: + for part in set_cookie.split("\n"): + cookies.append((cli_ip, cli_port, srv_ip, srv_port, "set", part.strip())) + + content_type = headers.get("content-type", "") + if not body: + continue + if content_type.startswith("image/"): + file_counter += 1 + ext = IMAGE_EXTS.get(content_type.split(";")[0].strip().lower(), "img") + save_bytes(os.path.join(extract_dir, "images"), f"resp{file_counter}_{srv_ip}.{ext}", + body, saved_images) + elif "multipart" in content_type: + file_counter += 1 + extract_multipart_files(body, headers, extract_dir, f"resp{file_counter}_{srv_ip}", + saved_images, saved_files) + + total = len(packets) + print("=" * 70) + print(f"SUMMARY ({total} packets)") + print("=" * 70) + for proto, count in sorted(proto_counts.items(), key=lambda x: -x[1]): + print(f" {proto:<8} {count}") + + print("\n" + "=" * 70) + print(f"PLAINTEXT PASSWORDS / CREDENTIALS ({len(credentials)})") + print("=" * 70) + if credentials: + for line in credentials: + print(line) + else: + print(" none found (either no plaintext logins were captured, or traffic was HTTPS-encrypted)") + + print("\n" + "=" * 70) + print(f"HTTP COOKIES / SESSION TOKENS ({len(cookies)}, plaintext HTTP only)") + print("=" * 70) + if cookies: + print(" (a stolen session cookie can hijack an already-logged-in session — no password needed)") + for cli_ip, cli_port, srv_ip, srv_port, direction, cookie_str in cookies: + marker = " <-- possible session token" if SESSION_KEY_PATTERN.search(cookie_str) else "" + arrow = f"{cli_ip}:{cli_port} -> {srv_ip}:{srv_port}" if direction == "sent" \ + else f"{srv_ip}:{srv_port} -> {cli_ip}:{cli_port}" + tag = "Cookie" if direction == "sent" else "Set-Cookie" + print(f" {arrow} {tag}: {cookie_str}{marker}") + else: + print(" none found") + + print("\n" + "=" * 70) + print(f"IMAGES EXTRACTED ({len(saved_images)}) -> {os.path.abspath(os.path.join(extract_dir, 'images'))}") + print("=" * 70) + if saved_images: + for path, size in saved_images: + print(f" {path} ({size} bytes)") + else: + print(" none found") + + print("\n" + "=" * 70) + print(f"OTHER FILES EXTRACTED ({len(saved_files)}) -> {os.path.abspath(os.path.join(extract_dir, 'files'))}") + print("=" * 70) + if saved_files: + for path, size in saved_files: + print(f" {path} ({size} bytes)") + else: + print(" none found") + + if form_fields: + print("\n" + "=" * 70) + print(f"HTTP FORM DATA ({len(form_fields)} fields, plaintext HTTP only)") + print("=" * 70) + for cli_ip, cli_port, srv_ip, srv_port, k, v, flagged in form_fields: + marker = " <-- possible credential" if flagged else "" + print(f" {cli_ip}:{cli_port} -> {srv_ip}:{srv_port} {k}={v}{marker}") + + if telnet_sessions: + print("\n" + "=" * 70) + print(f"TELNET SESSIONS ({len(telnet_sessions)} stream(s))") + print("=" * 70) + for cli_ip, cli_port, srv_ip, srv_port, direction, text in telnet_sessions: + who = f"{cli_ip}:{cli_port}" if direction == "client" else f"{srv_ip}:{srv_port}" + print(f" [{who} ({direction})]") + for line in text.splitlines(): + if line.strip(): + print(f" {line}") + + if dns_queries: + print("\n" + "=" * 70) + print(f"DNS QUERIES ({len(dns_queries)})") + print("=" * 70) + seen = set() + for src, dst, qname in dns_queries: + if (src, qname) in seen: + continue + seen.add((src, qname)) + print(f" {src:<16} -> {dst:<16} {qname}") + + if dns_answers: + print("\n" + "=" * 70) + print(f"DNS ANSWERS ({len(dns_answers)})") + print("=" * 70) + seen = set() + for qname, rdata in dns_answers: + if (qname, rdata) in seen: + continue + seen.add((qname, rdata)) + print(f" {qname:<40} -> {rdata}") + + if http_requests: + print("\n" + "=" * 70) + print(f"HTTP REQUESTS ({len(http_requests)})") + print("=" * 70) + for cli_ip, cli_port, srv_ip, srv_port, start_line in http_requests: + print(f" {cli_ip}:{cli_port} -> {srv_ip}:{srv_port} {start_line}") + + if http_responses: + print("\n" + "=" * 70) + print(f"HTTP RESPONSES ({len(http_responses)})") + print("=" * 70) + for cli_ip, cli_port, srv_ip, srv_port, start_line in http_responses: + print(f" {srv_ip}:{srv_port} -> {cli_ip}:{cli_port} {start_line}") + + if tls_sni: + print("\n" + "=" * 70) + print(f"TLS SNI / HTTPS DESTINATIONS ({len(tls_sni)})") + print("=" * 70) + print(" (hostname requested in the ClientHello — visible even though the") + print(" session itself is encrypted; bodies/credentials are NOT recoverable)") + for (src, dst), hostname in tls_sni.items(): + print(f" {src:<16} -> {dst:<16} {hostname}") + + if flows: + print("\n" + "=" * 70) + print(f"TOP CONVERSATIONS (by bytes, top 20 of {len(flows)})") + print("=" * 70) + ranked = sorted(flows.items(), key=lambda kv: -kv[1][1])[:20] + for (src, sport, dst, dport, proto), (pkt_count, byte_count) in ranked: + print(f" {src}:{sport:<6} -> {dst}:{dport:<6} {proto:<4} " + f"{pkt_count:>6} pkts {byte_count:>10} bytes") + + print() + + +# ---------- per-packet raw line (kept behind --raw) ---------- + +def describe_packet(pkt, index): + ts = getattr(pkt, "time", None) + ts_str = f"{float(ts):.6f}" if ts is not None else "?" + + if IP in pkt: + src, dst = pkt[IP].src, pkt[IP].dst + proto_layer = "IP" + elif IPv6 in pkt: + src, dst = pkt[IPv6].src, pkt[IPv6].dst + proto_layer = "IPv6" + else: + src, dst = "?", "?" + proto_layer = pkt.name + + sport = dport = None + proto = proto_layer + extra = "" + + if pkt.haslayer(TCP): + proto = "TCP" + sport, dport = pkt[TCP].sport, pkt[TCP].dport + flags = pkt.sprintf("%TCP.flags%") + extra = f"flags={flags} seq={pkt[TCP].seq} ack={pkt[TCP].ack}" + elif pkt.haslayer(UDP): + proto = "UDP" + sport, dport = pkt[UDP].sport, pkt[UDP].dport + elif pkt.haslayer(ICMP): + proto = "ICMP" + extra = f"type={pkt[ICMP].type} code={pkt[ICMP].code}" + + if pkt.haslayer(DNS): + dns = pkt[DNS] + if dns.qr == 0 and dns.qdcount > 0: + qname = dns[DNSQR].qname.decode(errors="replace") + extra += f" DNS query: {qname}" + elif dns.qr == 1: + answers = [] + for i in range(dns.ancount): + try: + rdata = dns.an[i].rdata + if isinstance(rdata, bytes): + rdata = rdata.decode(errors="replace") + answers.append(str(rdata)) + except Exception: + pass + if answers: + extra += f" DNS answer: {', '.join(answers)}" + + if pkt.haslayer(HTTPRequest): + req = pkt[HTTPRequest] + method = req.Method.decode(errors="replace") if req.Method else "?" + host = req.Host.decode(errors="replace") if req.Host else "" + path = req.Path.decode(errors="replace") if req.Path else "" + extra += f" HTTP {method} {host}{path}" + if pkt.haslayer(HTTPResponse): + resp = pkt[HTTPResponse] + code = resp.Status_Code.decode(errors="replace") if resp.Status_Code else "?" + extra += f" HTTP response {code}" + + if pkt.haslayer(Raw): + sni = extract_sni(bytes(pkt[Raw].load)) + if sni: + extra += f" TLS SNI: {sni}" + + endpoint = f"{src}:{sport} -> {dst}:{dport}" if sport else f"{src} -> {dst}" + length = len(pkt) + + line = f"[{index:>5}] t={ts_str} {proto:<5} {endpoint:<45} len={length}" + if extra: + line += f" {extra.strip()}" + + if pkt.haslayer(Raw) and proto in ("TCP", "UDP") and not extra.strip(): + payload = bytes(pkt[Raw].load) + printable = payload[:64].decode("latin-1", errors="replace") + printable = "".join(c if c.isprintable() else "." for c in printable) + line += f" payload[:64]={printable!r}" + + return line + + +def matches_filter(pkt, filt): + if filt is None: + return True + filt = filt.lower() + if filt == "tcp": + return pkt.haslayer(TCP) + if filt == "udp": + return pkt.haslayer(UDP) + if filt == "icmp": + return pkt.haslayer(ICMP) + if filt == "dns": + return pkt.haslayer(DNS) + if filt == "http": + return pkt.haslayer(HTTPRequest) or pkt.haslayer(HTTPResponse) + return True + + +def print_raw(packets, args): + shown = 0 + for i, pkt in enumerate(packets, 1): + if not matches_filter(pkt, args.filter): + continue + print(describe_packet(pkt, i)) + shown += 1 + if args.limit and shown >= args.limit: + break + print(f"\nShown: {shown} / {len(packets)} packets") + + +def main(): + ap = argparse.ArgumentParser(description="Analyze a pcap into a legible security-research report") + ap.add_argument("pcap_file") + ap.add_argument("--extract-dir", default="extracted_files", help="where to save carved files/images") + ap.add_argument("--raw", action="store_true", help="print per-packet lines instead of the summary report") + ap.add_argument("--limit", type=int, default=None, help="(--raw mode) max packets to print") + ap.add_argument("--filter", default=None, help="(--raw mode) tcp|udp|icmp|dns|http") + args = ap.parse_args() + + packets = rdpcap(args.pcap_file) + print(f"Loaded {len(packets)} packets from {args.pcap_file}\n") + + if args.raw: + print_raw(packets, args) + else: + print_report(packets, args.extract_dir) + + +if __name__ == "__main__": + main()