Guest User

render socketio pcap

a guest
Aug 5th, 2026
452
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.86 KB | Cybersecurity | 0 0
  1. #!/usr/bin/env python3
  2. """Print the captured phishing-kit Socket.IO session as an ASCII timeline."""
  3.  
  4. import argparse
  5. import json
  6. import shutil
  7. import subprocess
  8. import textwrap
  9. from collections import Counter
  10. from pathlib import Path
  11.  
  12.  
  13. SERVER_IP = "104.21.53.42"
  14. POLLING_STREAM = 22
  15. WEBSOCKET_STREAM = 34
  16.  
  17.  
  18. def arguments():
  19.     parser = argparse.ArgumentParser(description=__doc__)
  20.     parser.add_argument("pcap", type=Path)
  21.     parser.add_argument("--output", type=Path, help="save the terminal output")
  22.     parser.add_argument("--width", type=int, default=0, help="table width")
  23.     return parser.parse_args()
  24.  
  25.  
  26. def run(command):
  27.     return subprocess.run(
  28.         command, check=True, capture_output=True, text=True, errors="replace"
  29.     ).stdout
  30.  
  31.  
  32. def parse_socketio(payload):
  33.     text = payload.decode("utf-8", errors="replace")
  34.  
  35.     if text.startswith("0"):
  36.         data = json.loads(text[1:])
  37.         return {
  38.             "bootstrap": (
  39.                 f"Engine.IO open: upgrades={data.get('upgrades', [])}, "
  40.                 f"pingInterval={data.get('pingInterval')}, "
  41.                 f"pingTimeout={data.get('pingTimeout')}, "
  42.                 f"maxPayload={data.get('maxPayload')}"
  43.             )
  44.         }
  45.     if text == "5":
  46.         return {"bootstrap": "Engine.IO transport upgrade complete"}
  47.     if text.startswith("40"):
  48.         return {"bootstrap": "Socket.IO namespace connect"}
  49.     if text.startswith("42"):
  50.         try:
  51.             data = json.loads(text[2:])
  52.         except json.JSONDecodeError:
  53.             return {}
  54.         if isinstance(data, list) and data and isinstance(data[0], str):
  55.             return {
  56.                 "event": data[0],
  57.                 "data": data[1] if len(data) > 1 else None,
  58.             }
  59.     return {}
  60.  
  61.  
  62. def make_record(frame, epoch, source, transport, payload, part=1):
  63.     return {
  64.         "frame": int(frame),
  65.         "epoch": float(epoch),
  66.         "direction": "C <<< S" if source == SERVER_IP else "C >>> S",
  67.         "transport": transport,
  68.         "length": len(payload),
  69.         "part": part,
  70.         **parse_socketio(payload),
  71.     }
  72.  
  73.  
  74. def extract(pcap):
  75.     records = []
  76.     http_filter = (
  77.         f'tcp.stream == {POLLING_STREAM} && '
  78.         'http.request.uri contains "/socket.io/" && http.file_data'
  79.     )
  80.     fields = ["frame.number", "frame.time_epoch", "ip.src", "http.file_data"]
  81.     command = ["tshark", "-r", str(pcap), "-Y", http_filter, "-T", "fields"]
  82.     for field in fields:
  83.         command += ["-e", field]
  84.  
  85.     for line in run(command).splitlines():
  86.         frame, epoch, source, body = line.split("\t")
  87.         for part, payload in enumerate(bytes.fromhex(body).split(b"\x1e"), 1):
  88.             if payload:
  89.                 records.append(
  90.                     make_record(frame, epoch, source, "http-polling", payload, part)
  91.                 )
  92.  
  93.     ws_filter = f"tcp.stream == {WEBSOCKET_STREAM} && websocket"
  94.     command = [
  95.         "tshark", "-r", str(pcap), "-Y", ws_filter,
  96.         "-T", "json", "-x", "-j", "frame ip websocket",
  97.     ]
  98.     for packet in json.loads(run(command)):
  99.         layers = packet["_source"]["layers"]
  100.         raw = layers["websocket"]["websocket.payload_raw"]
  101.         raw = raw[0] if isinstance(raw, list) else raw
  102.         records.append(
  103.             make_record(
  104.                 layers["frame"]["frame.number"],
  105.                 layers["frame"]["frame.time_epoch"],
  106.                 layers["ip"]["ip.src"],
  107.                 "websocket",
  108.                 bytes.fromhex(raw),
  109.             )
  110.         )
  111.  
  112.     return sorted(records, key=lambda row: (row["epoch"], row["frame"], row["part"]))
  113.  
  114.  
  115. def shorten(value, limit=120):
  116.     value = str(value).replace("\r", " ").replace("\n", " ")
  117.     return value if len(value) <= limit else value[: limit - 3] + "..."
  118.  
  119.  
  120. def element_name(element):
  121.     if not isinstance(element, dict):
  122.         return ""
  123.     return shorten(
  124.         element.get("text")
  125.         or element.get("ariaLabel")
  126.         or element.get("id")
  127.         or element.get("name")
  128.         or element.get("tagName")
  129.         or ""
  130.     )
  131.  
  132.  
  133. def objects(value):
  134.     if isinstance(value, dict):
  135.         yield value
  136.         for child in value.values():
  137.             yield from objects(child)
  138.     elif isinstance(value, list):
  139.         for child in value:
  140.             yield from objects(child)
  141.  
  142.  
  143. def dom_fields(data):
  144.     fields = []
  145.     for item in objects(data):
  146.         tag = str(item.get("nodeName", "")).upper()
  147.         attrs = item.get("attributes")
  148.         if tag not in {"INPUT", "TEXTAREA", "BUTTON"} or not isinstance(attrs, dict):
  149.             continue
  150.         name = attrs.get("id") or attrs.get("name") or attrs.get("aria-label") or attrs.get("type") or tag.lower()
  151.         label = f"{tag.lower()}:{name}"
  152.         if label not in fields:
  153.             fields.append(label)
  154.     return fields[:12]
  155.  
  156.  
  157. def details(record):
  158.     event = record["event"]
  159.     data = record.get("data")
  160.     if event == "domreset":
  161.         return "clear current document before the next DOM update"
  162.     if not isinstance(data, dict):
  163.         return "no application object"
  164.  
  165.     if event == "inputchange":
  166.         path = data.get("cssPath") or data.get("csspath") or ""
  167.         value = json.dumps(data.get("value", ""), ensure_ascii=False)
  168.         result = (
  169.             f"field={path}; value={shorten(value)}; "
  170.             f"selection={data.get('selectionStart', '')}:{data.get('selectionEnd', '')}"
  171.         )
  172.         name = element_name(data.get("element"))
  173.         return result + (f"; metadata={name}" if name else "")
  174.  
  175.     if event in {"click", "submit"}:
  176.         result = f"target={data.get('cssPath', '')}"
  177.         target = element_name(data.get("element"))
  178.         submit = element_name(data.get("submitElement"))
  179.         return result + (f"; element={target}" if target else "") + (f"; submit={submit}" if submit else "")
  180.  
  181.     if event == "selectionchange":
  182.         return f"field={data.get('startCssPath', '')}; offsets={data.get('startOffset', '')}:{data.get('endOffset', '')}"
  183.     if event == "keypress":
  184.         return f"key={data.get('name', '')}; target={data.get('cssPath', '')}"
  185.     if event in {"updateBrowserUrl", "redir"}:
  186.         return f"url={shorten(json.dumps(data.get('url', ''), ensure_ascii=False))}"
  187.     if event == "authhold":
  188.         return f"holding={data.get('holding')}; loader={data.get('loader', '')}"
  189.  
  190.     if event == "domchanges":
  191.         main = data.get("main", {})
  192.         areas = [name for name in ("head", "bodydiv") if name in main]
  193.         result = f"packet={record['length']:,} bytes; areas={','.join(areas) or 'none'}"
  194.         if isinstance(data.get("iframes"), list) and data["iframes"]:
  195.             result += f"; iframes={len(data['iframes'])}"
  196.         fields = dom_fields(data)
  197.         if fields:
  198.             result += f"; fields={', '.join(fields)}"
  199.         if data.get("loadingFinished"):
  200.             result += "; loadingFinished=true"
  201.         if data.get("authHoldRelease"):
  202.             result += "; authHoldRelease=true"
  203.         return result
  204.  
  205.     return shorten(json.dumps(data, ensure_ascii=False, separators=(",", ":")), 180)
  206.  
  207.  
  208. def table(headers, rows, widths):
  209.     border = "+" + "+".join("-" * (width + 2) for width in widths) + "+"
  210.     output = [border]
  211.  
  212.     for number, row in enumerate([headers, *rows]):
  213.         cells = [
  214.             textwrap.wrap(str(value).replace("\n", " "), width) or [""]
  215.             for value, width in zip(row, widths)
  216.         ]
  217.         for line in range(max(map(len, cells))):
  218.             values = [cell[line] if line < len(cell) else "" for cell in cells]
  219.             output.append("| " + " | ".join(value.ljust(width) for value, width in zip(values, widths)) + " |")
  220.         output.append(border)
  221.     return output
  222.  
  223.  
  224. def render(pcap, records, width):
  225.     events = [record for record in records if "event" in record]
  226.     title = "RECONSTRUCTED SOCKET.IO SESSION"
  227.     lines = [
  228.         title,
  229.         "=" * len(title),
  230.         f"Source             : {pcap.name}",
  231.         f"Protocol records   : {len(records)}",
  232.         f"Application events : {len(events)}",
  233.         "Direction          : C >>> S  client to server | C <<< S  server to client",
  234.         "",
  235.         "OBSERVED EVENT COUNTS",
  236.         "---------------------",
  237.     ]
  238.  
  239.     counts = Counter((row["direction"], row["event"], row["transport"]) for row in events)
  240.     count_rows = []
  241.     for direction, event in sorted({(key[0], key[1]) for key in counts}):
  242.         polling = counts[direction, event, "http-polling"]
  243.         websocket = counts[direction, event, "websocket"]
  244.         count_rows.append([direction, event, polling + websocket, polling, websocket])
  245.     lines += table(["DIR", "EVENT", "TOTAL", "POLLING", "WEBSOCKET"], count_rows, [7, 24, 7, 9, 10])
  246.  
  247.     boot = [row for row in records if "bootstrap" in row]
  248.     boot_rows = [[row["frame"], row["direction"], row["transport"], row["bootstrap"]] for row in boot]
  249.     lines += ["", "TRANSPORT BOOTSTRAP", "-------------------"]
  250.     lines += table(["FRAME", "DIR", "TRANSPORT", "MESSAGE"], boot_rows, [6, 7, 12, width - 38])
  251.  
  252.     event_rows = [
  253.         [row["frame"], row["direction"], row["transport"], row["event"], details(row)]
  254.         for row in events
  255.     ]
  256.     lines += ["", "APPLICATION EVENT TIMELINE", "--------------------------"]
  257.     lines += table(
  258.         ["FRAME", "DIR", "TRANSPORT", "EVENT", "DECODED DETAILS"],
  259.         event_rows,
  260.         [6, 7, 12, 16, width - 57],
  261.     )
  262.     return "\n".join(lines) + "\n"
  263.  
  264.  
  265. def main():
  266.     args = arguments()
  267.     if not args.pcap.is_file():
  268.         raise SystemExit(f"PCAP not found: {args.pcap}")
  269.     width = max(112, args.width or shutil.get_terminal_size((150, 24)).columns)
  270.     output = render(args.pcap, extract(args.pcap), width)
  271.     if args.output:
  272.         args.output.write_text(output, encoding="utf-8")
  273.     else:
  274.         print(output, end="")
  275.  
  276.  
  277. if __name__ == "__main__":
  278.     main()
  279.  
Advertisement
Comments
  • User was banned
Add Comment
Please, Sign In to add comment