Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- """Print the captured phishing-kit Socket.IO session as an ASCII timeline."""
- import argparse
- import json
- import shutil
- import subprocess
- import textwrap
- from collections import Counter
- from pathlib import Path
- SERVER_IP = "104.21.53.42"
- POLLING_STREAM = 22
- WEBSOCKET_STREAM = 34
- def arguments():
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("pcap", type=Path)
- parser.add_argument("--output", type=Path, help="save the terminal output")
- parser.add_argument("--width", type=int, default=0, help="table width")
- return parser.parse_args()
- def run(command):
- return subprocess.run(
- command, check=True, capture_output=True, text=True, errors="replace"
- ).stdout
- def parse_socketio(payload):
- text = payload.decode("utf-8", errors="replace")
- if text.startswith("0"):
- data = json.loads(text[1:])
- return {
- "bootstrap": (
- f"Engine.IO open: upgrades={data.get('upgrades', [])}, "
- f"pingInterval={data.get('pingInterval')}, "
- f"pingTimeout={data.get('pingTimeout')}, "
- f"maxPayload={data.get('maxPayload')}"
- )
- }
- if text == "5":
- return {"bootstrap": "Engine.IO transport upgrade complete"}
- if text.startswith("40"):
- return {"bootstrap": "Socket.IO namespace connect"}
- if text.startswith("42"):
- try:
- data = json.loads(text[2:])
- except json.JSONDecodeError:
- return {}
- if isinstance(data, list) and data and isinstance(data[0], str):
- return {
- "event": data[0],
- "data": data[1] if len(data) > 1 else None,
- }
- return {}
- def make_record(frame, epoch, source, transport, payload, part=1):
- return {
- "frame": int(frame),
- "epoch": float(epoch),
- "direction": "C <<< S" if source == SERVER_IP else "C >>> S",
- "transport": transport,
- "length": len(payload),
- "part": part,
- **parse_socketio(payload),
- }
- def extract(pcap):
- records = []
- http_filter = (
- f'tcp.stream == {POLLING_STREAM} && '
- 'http.request.uri contains "/socket.io/" && http.file_data'
- )
- fields = ["frame.number", "frame.time_epoch", "ip.src", "http.file_data"]
- command = ["tshark", "-r", str(pcap), "-Y", http_filter, "-T", "fields"]
- for field in fields:
- command += ["-e", field]
- for line in run(command).splitlines():
- frame, epoch, source, body = line.split("\t")
- for part, payload in enumerate(bytes.fromhex(body).split(b"\x1e"), 1):
- if payload:
- records.append(
- make_record(frame, epoch, source, "http-polling", payload, part)
- )
- ws_filter = f"tcp.stream == {WEBSOCKET_STREAM} && websocket"
- command = [
- "tshark", "-r", str(pcap), "-Y", ws_filter,
- "-T", "json", "-x", "-j", "frame ip websocket",
- ]
- for packet in json.loads(run(command)):
- layers = packet["_source"]["layers"]
- raw = layers["websocket"]["websocket.payload_raw"]
- raw = raw[0] if isinstance(raw, list) else raw
- records.append(
- make_record(
- layers["frame"]["frame.number"],
- layers["frame"]["frame.time_epoch"],
- layers["ip"]["ip.src"],
- "websocket",
- bytes.fromhex(raw),
- )
- )
- return sorted(records, key=lambda row: (row["epoch"], row["frame"], row["part"]))
- def shorten(value, limit=120):
- value = str(value).replace("\r", " ").replace("\n", " ")
- return value if len(value) <= limit else value[: limit - 3] + "..."
- def element_name(element):
- if not isinstance(element, dict):
- return ""
- return shorten(
- element.get("text")
- or element.get("ariaLabel")
- or element.get("id")
- or element.get("name")
- or element.get("tagName")
- or ""
- )
- def objects(value):
- if isinstance(value, dict):
- yield value
- for child in value.values():
- yield from objects(child)
- elif isinstance(value, list):
- for child in value:
- yield from objects(child)
- def dom_fields(data):
- fields = []
- for item in objects(data):
- tag = str(item.get("nodeName", "")).upper()
- attrs = item.get("attributes")
- if tag not in {"INPUT", "TEXTAREA", "BUTTON"} or not isinstance(attrs, dict):
- continue
- name = attrs.get("id") or attrs.get("name") or attrs.get("aria-label") or attrs.get("type") or tag.lower()
- label = f"{tag.lower()}:{name}"
- if label not in fields:
- fields.append(label)
- return fields[:12]
- def details(record):
- event = record["event"]
- data = record.get("data")
- if event == "domreset":
- return "clear current document before the next DOM update"
- if not isinstance(data, dict):
- return "no application object"
- if event == "inputchange":
- path = data.get("cssPath") or data.get("csspath") or ""
- value = json.dumps(data.get("value", ""), ensure_ascii=False)
- result = (
- f"field={path}; value={shorten(value)}; "
- f"selection={data.get('selectionStart', '')}:{data.get('selectionEnd', '')}"
- )
- name = element_name(data.get("element"))
- return result + (f"; metadata={name}" if name else "")
- if event in {"click", "submit"}:
- result = f"target={data.get('cssPath', '')}"
- target = element_name(data.get("element"))
- submit = element_name(data.get("submitElement"))
- return result + (f"; element={target}" if target else "") + (f"; submit={submit}" if submit else "")
- if event == "selectionchange":
- return f"field={data.get('startCssPath', '')}; offsets={data.get('startOffset', '')}:{data.get('endOffset', '')}"
- if event == "keypress":
- return f"key={data.get('name', '')}; target={data.get('cssPath', '')}"
- if event in {"updateBrowserUrl", "redir"}:
- return f"url={shorten(json.dumps(data.get('url', ''), ensure_ascii=False))}"
- if event == "authhold":
- return f"holding={data.get('holding')}; loader={data.get('loader', '')}"
- if event == "domchanges":
- main = data.get("main", {})
- areas = [name for name in ("head", "bodydiv") if name in main]
- result = f"packet={record['length']:,} bytes; areas={','.join(areas) or 'none'}"
- if isinstance(data.get("iframes"), list) and data["iframes"]:
- result += f"; iframes={len(data['iframes'])}"
- fields = dom_fields(data)
- if fields:
- result += f"; fields={', '.join(fields)}"
- if data.get("loadingFinished"):
- result += "; loadingFinished=true"
- if data.get("authHoldRelease"):
- result += "; authHoldRelease=true"
- return result
- return shorten(json.dumps(data, ensure_ascii=False, separators=(",", ":")), 180)
- def table(headers, rows, widths):
- border = "+" + "+".join("-" * (width + 2) for width in widths) + "+"
- output = [border]
- for number, row in enumerate([headers, *rows]):
- cells = [
- textwrap.wrap(str(value).replace("\n", " "), width) or [""]
- for value, width in zip(row, widths)
- ]
- for line in range(max(map(len, cells))):
- values = [cell[line] if line < len(cell) else "" for cell in cells]
- output.append("| " + " | ".join(value.ljust(width) for value, width in zip(values, widths)) + " |")
- output.append(border)
- return output
- def render(pcap, records, width):
- events = [record for record in records if "event" in record]
- title = "RECONSTRUCTED SOCKET.IO SESSION"
- lines = [
- title,
- "=" * len(title),
- f"Source : {pcap.name}",
- f"Protocol records : {len(records)}",
- f"Application events : {len(events)}",
- "Direction : C >>> S client to server | C <<< S server to client",
- "",
- "OBSERVED EVENT COUNTS",
- "---------------------",
- ]
- counts = Counter((row["direction"], row["event"], row["transport"]) for row in events)
- count_rows = []
- for direction, event in sorted({(key[0], key[1]) for key in counts}):
- polling = counts[direction, event, "http-polling"]
- websocket = counts[direction, event, "websocket"]
- count_rows.append([direction, event, polling + websocket, polling, websocket])
- lines += table(["DIR", "EVENT", "TOTAL", "POLLING", "WEBSOCKET"], count_rows, [7, 24, 7, 9, 10])
- boot = [row for row in records if "bootstrap" in row]
- boot_rows = [[row["frame"], row["direction"], row["transport"], row["bootstrap"]] for row in boot]
- lines += ["", "TRANSPORT BOOTSTRAP", "-------------------"]
- lines += table(["FRAME", "DIR", "TRANSPORT", "MESSAGE"], boot_rows, [6, 7, 12, width - 38])
- event_rows = [
- [row["frame"], row["direction"], row["transport"], row["event"], details(row)]
- for row in events
- ]
- lines += ["", "APPLICATION EVENT TIMELINE", "--------------------------"]
- lines += table(
- ["FRAME", "DIR", "TRANSPORT", "EVENT", "DECODED DETAILS"],
- event_rows,
- [6, 7, 12, 16, width - 57],
- )
- return "\n".join(lines) + "\n"
- def main():
- args = arguments()
- if not args.pcap.is_file():
- raise SystemExit(f"PCAP not found: {args.pcap}")
- width = max(112, args.width or shutil.get_terminal_size((150, 24)).columns)
- output = render(args.pcap, extract(args.pcap), width)
- if args.output:
- args.output.write_text(output, encoding="utf-8")
- else:
- print(output, end="")
- if __name__ == "__main__":
- main()
Advertisement