1041 lines
41 KiB
Python
1041 lines
41 KiB
Python
#!/usr/bin/env python3
|
|
"""paralogue_gui.py — ImGui-based GUI for the Paralogue MITM proxy.
|
|
|
|
Renders a real-time packet inspector, modifier configuration panel,
|
|
session dashboard, wire traffic hex viewer, and dispatch table — all
|
|
driven by the same proxy + Frida backend as paralogue_mitm.py.
|
|
|
|
Usage:
|
|
python paralogue_gui.py
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import collections
|
|
import json
|
|
import os
|
|
import sys
|
|
import threading
|
|
import time
|
|
from typing import Any, Optional
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# imgui_bundle imports
|
|
# ---------------------------------------------------------------------------
|
|
|
|
from imgui_bundle import imgui, immapp, hello_imgui, imgui_md
|
|
from imgui_bundle import imgui_color_text_edit as te
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Project imports — paralogue_mitm must be importable (no auto-run).
|
|
# ---------------------------------------------------------------------------
|
|
|
|
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
|
|
sys.path.insert(0, SCRIPT_DIR)
|
|
|
|
import subprocess
|
|
|
|
from paralogue_mitm import ( # noqa: E402
|
|
Session, WireRewriter, WireCipher, FridaBridge,
|
|
run_with_session, build_frame,
|
|
expand_card_bag_open_rsp_modifier,
|
|
inject_unlock_functions_modifier,
|
|
inject_role_attrs_modifier,
|
|
inject_items_1_to_2000_modifier,
|
|
inject_blueprints_modifier,
|
|
GAME_PORT, HTTP_PORT, PROCESS_NAME,
|
|
)
|
|
from paralogue_decoder import ( # noqa: E402
|
|
msg_to_dict, short_repr, load_known_ids, PACKET_HEAD_CLS, CATALOG,
|
|
)
|
|
import paralogue_net_full_pb2 as pb_mod # noqa: E402
|
|
|
|
STEAM_LAUNCH_URL = "steam://rungameid/2701680"
|
|
GUI_CONFIG_PATH = os.path.join(SCRIPT_DIR, "gui_config.json")
|
|
DISPATCH_TYPES_PATH = os.path.join(SCRIPT_DIR, "dispatch_type_names.json")
|
|
|
|
# Pre-loaded msg_id → type name map from Frida extraction (191 entries).
|
|
_DISPATCH_TYPES: dict[str, str] = {}
|
|
if os.path.isfile(DISPATCH_TYPES_PATH):
|
|
try:
|
|
with open(DISPATCH_TYPES_PATH, "r", encoding="utf-8") as _f:
|
|
_DISPATCH_TYPES = json.load(_f)
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Config persistence.
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def _load_gui_config() -> dict:
|
|
if os.path.isfile(GUI_CONFIG_PATH):
|
|
try:
|
|
with open(GUI_CONFIG_PATH, "r", encoding="utf-8") as f:
|
|
return json.load(f)
|
|
except Exception:
|
|
pass
|
|
return {}
|
|
|
|
|
|
def _save_gui_config(flags: dict[str, bool], params: dict[str, Any]) -> None:
|
|
try:
|
|
with open(GUI_CONFIG_PATH, "w", encoding="utf-8") as f:
|
|
json.dump({"modifier_flags": flags, "modifier_params": params},
|
|
f, indent=2)
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Shared state between asyncio proxy thread and imgui render thread.
|
|
# ---------------------------------------------------------------------------
|
|
|
|
_DEFAULT_FLAGS: dict[str, bool] = {
|
|
"card_bag_expand": False,
|
|
"inject_blueprints": False,
|
|
"unlock_functions": False,
|
|
"role_attrs": False,
|
|
"inject_items": False,
|
|
}
|
|
|
|
_DEFAULT_PARAMS: dict[str, Any] = {
|
|
"card_range_max": 2000,
|
|
"role_attr_value": 999,
|
|
}
|
|
|
|
|
|
class SharedState:
|
|
def __init__(self) -> None:
|
|
self.lock = threading.Lock()
|
|
|
|
# --- written by proxy thread, read by GUI ---
|
|
self.packets: collections.deque[dict] = collections.deque(maxlen=10_000)
|
|
self.wire_log: collections.deque[dict] = collections.deque(maxlen=2_000)
|
|
self.log_lines: collections.deque[str] = collections.deque(maxlen=500)
|
|
self.session_key_hex: str = ""
|
|
self.session_nonce_hex: str = ""
|
|
self.game_pid: int = 0
|
|
self.frida_status: str = "waiting"
|
|
self.dispatch_entries: list[dict] = []
|
|
self.factory_to_type: dict[str, str] = {}
|
|
self.rewriter_frames_seen: int = 0
|
|
self.rewriter_frames_modified: int = 0
|
|
self.decoded_count: int = 0
|
|
self.wire_count: int = 0
|
|
self.chunk_count: int = 0
|
|
|
|
# --- written by GUI thread, read by proxy ---
|
|
self.restart_frida_requested: bool = False
|
|
# Packet injection queue: GUI pushes, proxy thread consumes.
|
|
self.inject_queue: collections.deque[dict] = collections.deque()
|
|
|
|
# Load saved config or use defaults.
|
|
saved = _load_gui_config()
|
|
self.modifier_flags: dict[str, bool] = {
|
|
**_DEFAULT_FLAGS,
|
|
**saved.get("modifier_flags", {}),
|
|
}
|
|
self.modifier_params: dict[str, Any] = {
|
|
**_DEFAULT_PARAMS,
|
|
**saved.get("modifier_params", {}),
|
|
}
|
|
# Snapshot for dirty-check (auto-save on change).
|
|
self._last_saved_flags = dict(self.modifier_flags)
|
|
self._last_saved_params = dict(self.modifier_params)
|
|
|
|
def save_if_dirty(self) -> None:
|
|
"""Called from GUI thread each frame; writes config to disk only
|
|
when something actually changed."""
|
|
if (self.modifier_flags != self._last_saved_flags
|
|
or self.modifier_params != self._last_saved_params):
|
|
_save_gui_config(self.modifier_flags, self.modifier_params)
|
|
self._last_saved_flags = dict(self.modifier_flags)
|
|
self._last_saved_params = dict(self.modifier_params)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# GUISession — Session subclass that mirrors data into SharedState.
|
|
# ---------------------------------------------------------------------------
|
|
|
|
class GUISession(Session):
|
|
def __init__(self, shared: SharedState, ts: int):
|
|
super().__init__(ts)
|
|
self._shared = shared
|
|
|
|
def _emit_decoded(self, direction, off, head, body, source="frida"):
|
|
super()._emit_decoded(direction, off, head, body, source)
|
|
mid = int(head.msg_id)
|
|
rec = {
|
|
"seq": self.decoded_seq,
|
|
"ts": time.time(),
|
|
"direction": direction,
|
|
"source": source,
|
|
"msg_id": mid,
|
|
"msg_type": "<unknown>",
|
|
"body_len": int(head.body_len),
|
|
"body_hex": body.hex(),
|
|
"fields": None,
|
|
"json_str": "",
|
|
"score": 0,
|
|
}
|
|
# Use dispatch_type_names for definitive type lookup first.
|
|
type_name = _DISPATCH_TYPES.get(str(mid))
|
|
if not type_name:
|
|
factory = self.msg_id_to_factory.get(mid)
|
|
if factory and factory in self.factory_to_type:
|
|
type_name = self.factory_to_type[factory]
|
|
if not type_name:
|
|
type_name = self.msg_id_cache.get(mid)
|
|
|
|
if type_name:
|
|
rec["msg_type"] = type_name
|
|
# Try parsing body as the known type directly.
|
|
import paralogue_net_full_pb2 as pb
|
|
cls = getattr(pb, type_name, None)
|
|
if cls and body:
|
|
try:
|
|
m = cls()
|
|
m.MergeFromString(body)
|
|
rec["fields"] = msg_to_dict(m)
|
|
from google.protobuf import json_format
|
|
rec["json_str"] = json_format.MessageToJson(
|
|
m, preserving_proto_field_name=True, indent=2)
|
|
rec["score"] = 200
|
|
except Exception:
|
|
pass
|
|
|
|
# Fallback to heuristic if direct parse failed.
|
|
if rec["fields"] is None and body:
|
|
try:
|
|
from paralogue_decoder import identify_body
|
|
name, parsed, score, cand, top = identify_body(body, type_name)
|
|
if parsed is not None:
|
|
rec["fields"] = msg_to_dict(parsed)
|
|
if name:
|
|
rec["msg_type"] = name
|
|
from google.protobuf import json_format
|
|
rec["json_str"] = json_format.MessageToJson(
|
|
parsed, preserving_proto_field_name=True, indent=2)
|
|
rec["score"] = score
|
|
except Exception:
|
|
pass
|
|
|
|
self._shared.packets.append(rec)
|
|
self._shared.decoded_count = self.decoded_seq
|
|
|
|
def log_wire(self, direction, data, label=""):
|
|
super().log_wire(direction, data, label)
|
|
self._shared.wire_log.append({
|
|
"ts": time.time(),
|
|
"dir": direction,
|
|
"sz": len(data),
|
|
"hex": data[:128].hex(),
|
|
})
|
|
self._shared.wire_count = self.wire_seq
|
|
|
|
def log_chunk(self, meta, data):
|
|
super().log_chunk(meta, data)
|
|
self._shared.chunk_count = self.chunk_seq
|
|
|
|
def record_session_key(self, key, nonce, offset, flag=0, this_id="",
|
|
offset_enc=0, offset_dec=0):
|
|
super().record_session_key(key, nonce, offset, flag, this_id,
|
|
offset_enc, offset_dec)
|
|
self._shared.session_key_hex = key.hex()
|
|
self._shared.session_nonce_hex = nonce.hex()
|
|
|
|
def record_dispatch_entry(self, msg_id, vtbl, factory_abs):
|
|
super().record_dispatch_entry(msg_id, vtbl, factory_abs)
|
|
pinned_name = self.factory_to_type.get(vtbl, "")
|
|
with self._shared.lock:
|
|
self._shared.dispatch_entries.append({
|
|
"msg_id": msg_id,
|
|
"vtbl": vtbl,
|
|
"type_name": pinned_name,
|
|
"pinned": bool(pinned_name),
|
|
})
|
|
self._shared.factory_to_type = dict(self.factory_to_type)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Modifier callback that reads live GUI toggles.
|
|
# ---------------------------------------------------------------------------
|
|
|
|
MODIFIER_MAP: dict[str, Any] = {
|
|
"card_bag_expand": expand_card_bag_open_rsp_modifier,
|
|
"inject_blueprints": inject_blueprints_modifier,
|
|
"unlock_functions": inject_unlock_functions_modifier,
|
|
"role_attrs": inject_role_attrs_modifier,
|
|
"inject_items": inject_items_1_to_2000_modifier,
|
|
}
|
|
|
|
|
|
def gui_combined_modify_cb(shared: SharedState, msg_id, head, body):
|
|
"""Chain all enabled modifiers: each one's output becomes the next
|
|
one's input. This way multiple modifiers targeting the same msg_id
|
|
(e.g. inject_blueprints + inject_items both hit BagItemFullS2C)
|
|
all get a chance to run."""
|
|
flags = shared.modifier_flags
|
|
current = body
|
|
modified = False
|
|
for key, fn in MODIFIER_MAP.items():
|
|
if flags.get(key, False):
|
|
r = fn(msg_id, head, current)
|
|
if r is not None:
|
|
current = r
|
|
modified = True
|
|
return current if modified else None
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Proxy background thread.
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def _run_proxy(shared: SharedState) -> None:
|
|
import frida as _frida
|
|
|
|
loop = asyncio.new_event_loop()
|
|
asyncio.set_event_loop(loop)
|
|
|
|
ts = int(time.time())
|
|
session = GUISession(shared, ts)
|
|
session.s2c_rewriter = WireRewriter(
|
|
modify_cb=lambda m, h, b: gui_combined_modify_cb(shared, m, h, b),
|
|
label="S->C",
|
|
)
|
|
# C->S rewriter: identity transform (no modify_cb) but enables
|
|
# packet injection by giving us cipher_out control.
|
|
session.c2s_rewriter = WireRewriter(modify_cb=None, label="C->S")
|
|
|
|
# Background coroutine: poll Frida status + handle restart requests.
|
|
async def _frida_status_poller():
|
|
while True:
|
|
await asyncio.sleep(1)
|
|
bridge = getattr(session, "bridge", None)
|
|
if bridge and bridge.frida_session:
|
|
try:
|
|
pid = bridge.frida_session._impl.pid
|
|
except Exception:
|
|
pid = 0
|
|
shared.game_pid = pid
|
|
shared.frida_status = "attached"
|
|
elif bridge:
|
|
shared.frida_status = "waiting for game"
|
|
else:
|
|
shared.frida_status = "no bridge"
|
|
|
|
# Update rewriter stats.
|
|
rw = session.s2c_rewriter
|
|
if rw:
|
|
shared.rewriter_frames_seen = rw.frames_seen
|
|
shared.rewriter_frames_modified = rw.frames_modified
|
|
|
|
# Handle restart request from GUI.
|
|
if shared.restart_frida_requested:
|
|
shared.restart_frida_requested = False
|
|
shared.frida_status = "restarting..."
|
|
shared.log_lines.append("[*] Frida restart requested")
|
|
if bridge:
|
|
bridge.stop()
|
|
bridge.frida_session = None
|
|
bridge.scripts.clear()
|
|
shared.dispatch_entries.clear()
|
|
try:
|
|
await bridge.start()
|
|
shared.frida_status = "attached"
|
|
shared.log_lines.append("[*] Frida reattached")
|
|
except Exception as e:
|
|
shared.frida_status = f"error: {e}"
|
|
shared.log_lines.append(f"[!] Frida restart failed: {e}")
|
|
|
|
async def _injection_consumer():
|
|
"""Poll inject_queue and send frames via the appropriate cipher.
|
|
Acquires the per-direction write lock to prevent interleaving
|
|
with pipe()'s normal forwarding."""
|
|
while True:
|
|
await asyncio.sleep(0.1)
|
|
while shared.inject_queue:
|
|
pkt = shared.inject_queue.popleft()
|
|
d = pkt.get("direction", "S->C")
|
|
mid = pkt.get("msg_id", 0)
|
|
body = pkt.get("body", b"")
|
|
pid = pkt.get("packet_id", -1)
|
|
if pid == -1:
|
|
if d == "S->C":
|
|
# S->C pushes use packet_id=0; only responses
|
|
# to a specific request use a non-zero id.
|
|
pid = 0
|
|
else:
|
|
# C->S requests use incrementing packet_id.
|
|
session._inject_packet_id += 1
|
|
pid = session._inject_packet_id
|
|
frame = build_frame(mid, body, packet_id=pid)
|
|
lock = (session.s2c_write_lock if d == "S->C"
|
|
else session.c2s_write_lock)
|
|
try:
|
|
async with lock:
|
|
if d == "S->C":
|
|
w = session.client_writer
|
|
rw = session.s2c_rewriter
|
|
if w is None:
|
|
shared.log_lines.append(
|
|
"[!] inject S->C: no client connection")
|
|
continue
|
|
if rw and rw.cipher_out:
|
|
ct = rw.cipher_out.encrypt(frame)
|
|
else:
|
|
ct = frame
|
|
w.write(ct)
|
|
await w.drain()
|
|
else:
|
|
w = session.server_writer
|
|
rw_c2s = session.c2s_rewriter
|
|
if w is None:
|
|
shared.log_lines.append(
|
|
"[!] inject C->S: no server connection")
|
|
continue
|
|
if rw_c2s and rw_c2s.cipher_out:
|
|
ct = rw_c2s.cipher_out.encrypt(frame)
|
|
else:
|
|
ct = frame
|
|
w.write(ct)
|
|
await w.drain()
|
|
shared.log_lines.append(
|
|
f"[inject] {d} msg_id={mid} body={len(body)}B")
|
|
except Exception as e:
|
|
shared.log_lines.append(f"[!] inject error: {e}")
|
|
|
|
async def _main():
|
|
asyncio.create_task(_frida_status_poller())
|
|
asyncio.create_task(_injection_consumer())
|
|
await run_with_session(session, proxy_enabled=True,
|
|
decoder_enabled=True)
|
|
|
|
try:
|
|
loop.run_until_complete(_main())
|
|
except Exception as e:
|
|
shared.log_lines.append(f"[!] proxy thread error: {e}")
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# GUI rendering helpers.
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def _render_tree(key: str, val: Any) -> None:
|
|
"""Recursively render a dict/list/scalar as an imgui tree."""
|
|
if isinstance(val, dict):
|
|
if imgui.tree_node(f"{key} {{{len(val)}}}"):
|
|
for k, v in val.items():
|
|
_render_tree(str(k), v)
|
|
imgui.tree_pop()
|
|
elif isinstance(val, list):
|
|
if imgui.tree_node(f"{key} [{len(val)}]"):
|
|
for i, v in enumerate(val):
|
|
_render_tree(f"[{i}]", v)
|
|
imgui.tree_pop()
|
|
else:
|
|
s = str(val)
|
|
if len(s) > 120:
|
|
s = s[:117] + "..."
|
|
imgui.text(f"{key}: {s}")
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# GUI state (persists across frames, lives in main thread only).
|
|
# ---------------------------------------------------------------------------
|
|
|
|
class GuiState:
|
|
def __init__(self) -> None:
|
|
self.selected_seq: int = -1
|
|
self._editor_seq: int = -1 # seq currently loaded into editor
|
|
# Packet Inspector filters
|
|
self.filter_type: str = ""
|
|
self.filter_msg_id: int = 0
|
|
self.show_c2s: bool = True
|
|
self.show_s2c: bool = True
|
|
self.show_frida: bool = True
|
|
self.show_wire: bool = True
|
|
self.auto_scroll: bool = True
|
|
# JSON editor for detail pane
|
|
self.json_editor: te.TextEditor = te.TextEditor()
|
|
self.json_editor.set_language_definition(
|
|
te.TextEditor.LanguageDefinitionId.json)
|
|
self.json_editor.set_read_only_enabled(True)
|
|
self.json_editor.set_show_whitespaces_enabled(False)
|
|
# Replay state
|
|
self.replay_dir: int = 0 # 0 = same as original, 1 = C->S, 2 = S->C
|
|
# Wire tab
|
|
self.selected_wire: int = -1
|
|
# Dispatch tab
|
|
self.dispatch_filter: str = ""
|
|
# Composer tab
|
|
self.composer_editor: te.TextEditor = te.TextEditor()
|
|
self.composer_editor.set_language_definition(
|
|
te.TextEditor.LanguageDefinitionId.json)
|
|
self.composer_type_idx: int = 0
|
|
self.composer_dir: int = 0 # 0 = C->S, 1 = S->C
|
|
self._composer_loaded_idx: int = -1
|
|
|
|
|
|
_gs = GuiState()
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Tab renderers.
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def _tab_packet_inspector(shared: SharedState) -> None:
|
|
gs = _gs
|
|
# --- filter bar ---
|
|
imgui.text("Filters:")
|
|
imgui.same_line()
|
|
_, gs.show_c2s = imgui.checkbox("C->S", gs.show_c2s)
|
|
imgui.same_line()
|
|
_, gs.show_s2c = imgui.checkbox("S->C", gs.show_s2c)
|
|
imgui.same_line()
|
|
_, gs.show_frida = imgui.checkbox("Frida", gs.show_frida)
|
|
imgui.same_line()
|
|
_, gs.show_wire = imgui.checkbox("Wire", gs.show_wire)
|
|
imgui.same_line()
|
|
imgui.set_next_item_width(80)
|
|
_, gs.filter_msg_id = imgui.input_int("msg_id", gs.filter_msg_id, 0, 0)
|
|
imgui.same_line()
|
|
imgui.set_next_item_width(150)
|
|
_, gs.filter_type = imgui.input_text("type", gs.filter_type)
|
|
imgui.same_line()
|
|
_, gs.auto_scroll = imgui.checkbox("Auto-scroll", gs.auto_scroll)
|
|
|
|
# --- packet table ---
|
|
flags = (imgui.TableFlags_.scroll_y | imgui.TableFlags_.row_bg
|
|
| imgui.TableFlags_.resizable | imgui.TableFlags_.borders_inner_h)
|
|
avail = imgui.get_content_region_avail()
|
|
table_h = avail.y * 0.55 if gs.selected_seq >= 0 else avail.y - 4
|
|
if imgui.begin_table("packets", 7, flags, imgui.ImVec2(0, table_h)):
|
|
imgui.table_setup_column("Seq", imgui.TableColumnFlags_.width_fixed, 50)
|
|
imgui.table_setup_column("Dir", imgui.TableColumnFlags_.width_fixed, 40)
|
|
imgui.table_setup_column("Src", imgui.TableColumnFlags_.width_fixed, 40)
|
|
imgui.table_setup_column("MsgID", imgui.TableColumnFlags_.width_fixed, 55)
|
|
imgui.table_setup_column("Type", imgui.TableColumnFlags_.width_stretch)
|
|
imgui.table_setup_column("Size", imgui.TableColumnFlags_.width_fixed, 60)
|
|
imgui.table_setup_column("Score", imgui.TableColumnFlags_.width_fixed, 45)
|
|
imgui.table_headers_row()
|
|
|
|
snapshot = list(shared.packets)
|
|
for rec in snapshot:
|
|
d = rec.get("direction", "")
|
|
src = rec.get("source", "")
|
|
if d == "C->S" and not gs.show_c2s:
|
|
continue
|
|
if d == "S->C" and not gs.show_s2c:
|
|
continue
|
|
if src == "frida" and not gs.show_frida:
|
|
continue
|
|
if src == "wire" and not gs.show_wire:
|
|
continue
|
|
if gs.filter_msg_id and rec.get("msg_id") != gs.filter_msg_id:
|
|
continue
|
|
if gs.filter_type and gs.filter_type.lower() not in rec.get("msg_type", "").lower():
|
|
continue
|
|
|
|
imgui.table_next_row()
|
|
is_sel = rec["seq"] == gs.selected_seq
|
|
imgui.table_next_column()
|
|
clicked, _ = imgui.selectable(
|
|
str(rec["seq"]), is_sel,
|
|
imgui.SelectableFlags_.span_all_columns)
|
|
if clicked:
|
|
gs.selected_seq = rec["seq"] if not is_sel else -1
|
|
imgui.table_next_column()
|
|
arrow = ">>" if d == "C->S" else "<<"
|
|
col = imgui.ImVec4(0.4, 0.8, 1, 1) if d == "C->S" else imgui.ImVec4(1, 0.7, 0.3, 1)
|
|
imgui.text_colored(col, arrow)
|
|
imgui.table_next_column()
|
|
imgui.text("F" if src == "frida" else "W")
|
|
imgui.table_next_column()
|
|
imgui.text(str(rec.get("msg_id", "")))
|
|
imgui.table_next_column()
|
|
imgui.text(rec.get("msg_type", ""))
|
|
imgui.table_next_column()
|
|
imgui.text(str(rec.get("body_len", "")))
|
|
imgui.table_next_column()
|
|
imgui.text(str(rec.get("score", "")))
|
|
|
|
if gs.auto_scroll:
|
|
imgui.set_scroll_here_y(1.0)
|
|
imgui.end_table()
|
|
|
|
# --- detail pane ---
|
|
if gs.selected_seq >= 0:
|
|
imgui.separator()
|
|
sel = None
|
|
for rec in shared.packets:
|
|
if rec["seq"] == gs.selected_seq:
|
|
sel = rec
|
|
break
|
|
if sel:
|
|
# Header line with colored direction.
|
|
d = sel.get("direction", "")
|
|
dcol = imgui.ImVec4(0.4, 0.8, 1, 1) if d == "C->S" else imgui.ImVec4(1, 0.7, 0.3, 1)
|
|
imgui.text(f"Packet #{sel['seq']} ")
|
|
imgui.same_line()
|
|
imgui.text_colored(dcol, d)
|
|
imgui.same_line()
|
|
imgui.text(f" [{sel.get('source','')}] "
|
|
f"msg_id={sel.get('msg_id')} "
|
|
f"type={sel.get('msg_type')} "
|
|
f"body={sel.get('body_len')}B")
|
|
|
|
# Tabs for tree view vs raw JSON vs hex.
|
|
if imgui.begin_tab_bar("detail_tabs"):
|
|
fields = sel.get("fields")
|
|
if imgui.begin_tab_item("Tree")[0]:
|
|
imgui.begin_child("fields_tree", imgui.ImVec2(0, 0),
|
|
child_flags=imgui.ChildFlags_.borders)
|
|
if fields and isinstance(fields, dict):
|
|
for k, v in fields.items():
|
|
_render_tree(k, v)
|
|
else:
|
|
imgui.text_colored(imgui.ImVec4(0.6, 0.6, 0.6, 1),
|
|
"(no parsed fields)")
|
|
imgui.end_child()
|
|
imgui.end_tab_item()
|
|
if imgui.begin_tab_item("JSON")[0]:
|
|
# Update editor text only when selection changes.
|
|
if gs._editor_seq != gs.selected_seq:
|
|
gs._editor_seq = gs.selected_seq
|
|
jtext = sel.get("json_str", "")
|
|
if not jtext and fields:
|
|
try:
|
|
jtext = json.dumps(fields, indent=2,
|
|
ensure_ascii=False,
|
|
default=str)
|
|
except Exception:
|
|
jtext = str(fields)
|
|
if not jtext:
|
|
jtext = "{}"
|
|
# Cap at 64KB to avoid native crash in TextEditor
|
|
# with very large protobuf messages.
|
|
if len(jtext) > 65536:
|
|
jtext = jtext[:65536] + "\n\n... (truncated)"
|
|
gs.json_editor.set_text(jtext)
|
|
code_font = imgui_md.get_code_font()
|
|
if code_font:
|
|
imgui.push_font(code_font.font, code_font.size)
|
|
gs.json_editor.render("json_detail")
|
|
if code_font:
|
|
imgui.pop_font()
|
|
imgui.end_tab_item()
|
|
if imgui.begin_tab_item("Hex")[0]:
|
|
imgui.begin_child("fields_hex", imgui.ImVec2(0, 0),
|
|
child_flags=imgui.ChildFlags_.borders)
|
|
hex_str = sel.get("body_hex", "")
|
|
# Format as hex dump: 16 bytes per line.
|
|
lines = []
|
|
raw = bytes.fromhex(hex_str) if hex_str else b""
|
|
for off in range(0, len(raw), 16):
|
|
chunk = raw[off:off + 16]
|
|
hx = " ".join(f"{b:02x}" for b in chunk)
|
|
asc = "".join(chr(b) if 32 <= b < 127 else "."
|
|
for b in chunk)
|
|
lines.append(f"{off:06x} {hx:<48s} {asc}")
|
|
imgui.text("\n".join(lines) if lines else "(empty body)")
|
|
imgui.end_child()
|
|
imgui.end_tab_item()
|
|
if imgui.begin_tab_item("Send")[0]:
|
|
orig_dir = sel.get("direction", "S->C")
|
|
imgui.text("Direction:")
|
|
imgui.same_line()
|
|
_, gs.replay_dir = imgui.radio_button("Original##rdir",
|
|
gs.replay_dir, 0)
|
|
imgui.same_line()
|
|
_, gs.replay_dir = imgui.radio_button("C->S##rdir",
|
|
gs.replay_dir, 1)
|
|
imgui.same_line()
|
|
_, gs.replay_dir = imgui.radio_button("S->C##rdir",
|
|
gs.replay_dir, 2)
|
|
send_dir = (orig_dir if gs.replay_dir == 0
|
|
else "C->S" if gs.replay_dir == 1
|
|
else "S->C")
|
|
imgui.same_line()
|
|
imgui.text_colored(imgui.ImVec4(0.7, 0.7, 0.7, 1),
|
|
f" -> {send_dir}")
|
|
|
|
if imgui.button("Replay Original"):
|
|
body = bytes.fromhex(sel.get("body_hex", ""))
|
|
shared.inject_queue.append({
|
|
"direction": send_dir,
|
|
"msg_id": sel.get("msg_id", 0),
|
|
"body": body,
|
|
})
|
|
shared.log_lines.append(
|
|
f"[GUI] replay {send_dir} msg_id={sel.get('msg_id')}")
|
|
imgui.same_line()
|
|
|
|
if imgui.button("Open in Composer"):
|
|
_open_in_composer(gs, sel, send_dir)
|
|
imgui.end_tab_item()
|
|
imgui.end_tab_bar()
|
|
|
|
|
|
def _open_in_composer(gs, sel: dict, direction: str) -> None:
|
|
"""Copy a captured packet's JSON into the Composer tab for editing."""
|
|
type_name = sel.get("msg_type", "")
|
|
# Find the type in the composer dropdown list.
|
|
try:
|
|
idx = _COMPOSER_TYPES.index(type_name)
|
|
except ValueError:
|
|
idx = gs.composer_type_idx # keep current if not found
|
|
gs.composer_type_idx = idx
|
|
gs._composer_loaded_idx = -1 # force reload on next frame
|
|
# Set direction.
|
|
gs.composer_dir = 0 if direction == "C->S" else 1
|
|
# Load the packet's JSON into composer editor.
|
|
jtext = sel.get("json_str", "")
|
|
if not jtext:
|
|
fields = sel.get("fields")
|
|
if fields:
|
|
try:
|
|
jtext = json.dumps(fields, indent=2, ensure_ascii=False,
|
|
default=str)
|
|
except Exception:
|
|
jtext = "{}"
|
|
if jtext:
|
|
gs.composer_editor.set_text(jtext)
|
|
gs._composer_loaded_idx = idx # prevent overwrite on next frame
|
|
|
|
|
|
def _tab_configuration(shared: SharedState) -> None:
|
|
imgui.text("Modifier Toggles")
|
|
imgui.separator()
|
|
|
|
labels = {
|
|
"card_bag_expand": "Card Bag Expand (CardBagOpenRsp -> rets 0..N, unlocks experiments)",
|
|
"inject_blueprints": "Inject Blueprints (BagItemFullS2C 11xxx, adds lootboxes to bag)",
|
|
"unlock_functions": "Unlock Functions (PlayerMainDataRsp)",
|
|
"role_attrs": "Role Attrs Saturate (RoleListFullS2C, boosts affection)",
|
|
"inject_items": "Inject Bag Items (BagItemFullS2C, dense fill other ranges)",
|
|
}
|
|
|
|
for key, label in labels.items():
|
|
cur = shared.modifier_flags.get(key, False)
|
|
_, new = imgui.checkbox(label, cur)
|
|
if new != cur:
|
|
shared.modifier_flags[key] = new
|
|
|
|
imgui.spacing()
|
|
imgui.separator()
|
|
imgui.text("Parameters")
|
|
|
|
v = shared.modifier_params.get("card_range_max", 2000)
|
|
_, v = imgui.slider_int("Card range max", v, 100, 10000)
|
|
shared.modifier_params["card_range_max"] = v
|
|
|
|
v2 = shared.modifier_params.get("role_attr_value", 999)
|
|
_, v2 = imgui.slider_int("Role attr value", v2, 1, 9999)
|
|
shared.modifier_params["role_attr_value"] = v2
|
|
|
|
imgui.spacing()
|
|
imgui.separator()
|
|
imgui.text(f"Rewriter: {shared.rewriter_frames_seen} frames seen, "
|
|
f"{shared.rewriter_frames_modified} modified")
|
|
active = any(shared.modifier_flags.values())
|
|
col = imgui.ImVec4(0, 1, 0, 1) if active else imgui.ImVec4(0.6, 0.6, 0.6, 1)
|
|
imgui.text_colored(col, f"Rewriter {'ACTIVE' if active else 'inactive'}")
|
|
|
|
|
|
def _tab_session_info(shared: SharedState) -> None:
|
|
imgui.text("Session Key")
|
|
imgui.same_line()
|
|
imgui.set_next_item_width(-1)
|
|
imgui.input_text("##key", shared.session_key_hex or "(not captured)",
|
|
imgui.InputTextFlags_.read_only)
|
|
|
|
imgui.text("Nonce ")
|
|
imgui.same_line()
|
|
imgui.set_next_item_width(-1)
|
|
imgui.input_text("##nonce", shared.session_nonce_hex or "(not captured)",
|
|
imgui.InputTextFlags_.read_only)
|
|
|
|
imgui.spacing()
|
|
imgui.separator()
|
|
|
|
# --- Frida status with color ---
|
|
status = shared.frida_status
|
|
if "attached" in status:
|
|
col = imgui.ImVec4(0, 1, 0, 1)
|
|
elif "waiting" in status or "restarting" in status:
|
|
col = imgui.ImVec4(1, 1, 0, 1)
|
|
else:
|
|
col = imgui.ImVec4(1, 0.3, 0.3, 1)
|
|
imgui.text(f"Game PID: {shared.game_pid or 'N/A'}")
|
|
imgui.text("Frida Status: ")
|
|
imgui.same_line()
|
|
imgui.text_colored(col, status)
|
|
imgui.text(f"Proxy Ports: game={GAME_PORT} http={HTTP_PORT}")
|
|
|
|
imgui.spacing()
|
|
|
|
# --- Action buttons ---
|
|
if imgui.button("Restart Frida"):
|
|
shared.restart_frida_requested = True
|
|
shared.log_lines.append("[GUI] Frida restart requested")
|
|
imgui.same_line()
|
|
if imgui.button("Launch Game (Steam)"):
|
|
try:
|
|
os.startfile(STEAM_LAUNCH_URL)
|
|
shared.log_lines.append(f"[GUI] Launching game via {STEAM_LAUNCH_URL}")
|
|
except Exception as e:
|
|
shared.log_lines.append(f"[!] Failed to launch game: {e}")
|
|
imgui.same_line()
|
|
imgui.text_colored(imgui.ImVec4(0.5, 0.5, 0.5, 1),
|
|
"(restart Frida after game relaunches)")
|
|
|
|
imgui.spacing()
|
|
imgui.separator()
|
|
n_pinned = sum(1 for e in shared.dispatch_entries if e.get("pinned"))
|
|
imgui.text(f"Dispatch Table: {len(shared.dispatch_entries)} entries, "
|
|
f"{n_pinned} pinned")
|
|
imgui.text(f"Decoded Msgs: {shared.decoded_count}")
|
|
imgui.text(f"Wire Packets: {shared.wire_count}")
|
|
imgui.text(f"Frida Chunks: {shared.chunk_count}")
|
|
|
|
imgui.spacing()
|
|
imgui.separator()
|
|
imgui.text("Console Log (recent)")
|
|
imgui.begin_child("console", imgui.ImVec2(0, 0), child_flags=imgui.ChildFlags_.borders)
|
|
for line in shared.log_lines:
|
|
imgui.text_wrapped(line)
|
|
imgui.set_scroll_here_y(1.0)
|
|
imgui.end_child()
|
|
|
|
|
|
def _tab_wire_traffic(shared: SharedState) -> None:
|
|
gs = _gs
|
|
flags = (imgui.TableFlags_.scroll_y | imgui.TableFlags_.row_bg
|
|
| imgui.TableFlags_.resizable | imgui.TableFlags_.borders_inner_h)
|
|
avail = imgui.get_content_region_avail()
|
|
table_h = avail.y * 0.6 if gs.selected_wire >= 0 else avail.y - 4
|
|
if imgui.begin_table("wire", 4, flags, imgui.ImVec2(0, table_h)):
|
|
imgui.table_setup_column("Time", imgui.TableColumnFlags_.width_fixed, 80)
|
|
imgui.table_setup_column("Dir", imgui.TableColumnFlags_.width_fixed, 40)
|
|
imgui.table_setup_column("Size", imgui.TableColumnFlags_.width_fixed, 60)
|
|
imgui.table_setup_column("Hex (first 64B)", imgui.TableColumnFlags_.width_stretch)
|
|
imgui.table_headers_row()
|
|
|
|
snapshot = list(shared.wire_log)
|
|
for i, rec in enumerate(snapshot):
|
|
imgui.table_next_row()
|
|
is_sel = i == gs.selected_wire
|
|
imgui.table_next_column()
|
|
t = rec.get("ts", 0)
|
|
ts_str = time.strftime("%H:%M:%S", time.localtime(t))
|
|
clicked, _ = imgui.selectable(ts_str, is_sel,
|
|
imgui.SelectableFlags_.span_all_columns)
|
|
if clicked:
|
|
gs.selected_wire = i if not is_sel else -1
|
|
imgui.table_next_column()
|
|
d = rec.get("dir", "")
|
|
arrow = ">>" if d == "C->S" else "<<"
|
|
col = imgui.ImVec4(0.4, 0.8, 1, 1) if d == "C->S" else imgui.ImVec4(1, 0.7, 0.3, 1)
|
|
imgui.text_colored(col, arrow)
|
|
imgui.table_next_column()
|
|
imgui.text(str(rec.get("sz", "")))
|
|
imgui.table_next_column()
|
|
h = rec.get("hex", "")
|
|
imgui.text(h[:128] + ("..." if len(h) > 128 else ""))
|
|
|
|
imgui.set_scroll_here_y(1.0)
|
|
imgui.end_table()
|
|
|
|
if gs.selected_wire >= 0:
|
|
snapshot = list(shared.wire_log)
|
|
if 0 <= gs.selected_wire < len(snapshot):
|
|
imgui.separator()
|
|
rec = snapshot[gs.selected_wire]
|
|
imgui.text(f"Full hex ({rec.get('sz', 0)} bytes):")
|
|
imgui.begin_child("hex_full", imgui.ImVec2(0, 0), child_flags=imgui.ChildFlags_.borders)
|
|
imgui.text_wrapped(rec.get("hex", ""))
|
|
imgui.end_child()
|
|
|
|
|
|
def _tab_dispatch_table(shared: SharedState) -> None:
|
|
gs = _gs
|
|
_, gs.dispatch_filter = imgui.input_text("Filter type", gs.dispatch_filter)
|
|
|
|
flags = (imgui.TableFlags_.scroll_y | imgui.TableFlags_.row_bg
|
|
| imgui.TableFlags_.resizable | imgui.TableFlags_.borders_inner_h
|
|
| imgui.TableFlags_.sortable)
|
|
if imgui.begin_table("dispatch", 4, flags):
|
|
imgui.table_setup_column("MsgID", imgui.TableColumnFlags_.width_fixed, 60)
|
|
imgui.table_setup_column("VTable", imgui.TableColumnFlags_.width_fixed, 130)
|
|
imgui.table_setup_column("Type Name", imgui.TableColumnFlags_.width_stretch)
|
|
imgui.table_setup_column("Pinned", imgui.TableColumnFlags_.width_fixed, 50)
|
|
imgui.table_headers_row()
|
|
|
|
with shared.lock:
|
|
entries = list(shared.dispatch_entries)
|
|
|
|
for e in entries:
|
|
tn = e.get("type_name", "")
|
|
if gs.dispatch_filter and gs.dispatch_filter.lower() not in tn.lower():
|
|
continue
|
|
imgui.table_next_row()
|
|
if e.get("pinned"):
|
|
imgui.table_set_bg_color(imgui.TableBgTarget_.row_bg0,
|
|
imgui.get_color_u32(imgui.ImVec4(0.1, 0.3, 0.1, 1)))
|
|
elif not tn:
|
|
imgui.table_set_bg_color(imgui.TableBgTarget_.row_bg0,
|
|
imgui.get_color_u32(imgui.ImVec4(0.3, 0.1, 0.1, 1)))
|
|
imgui.table_next_column()
|
|
imgui.text(str(e.get("msg_id", "")))
|
|
imgui.table_next_column()
|
|
imgui.text(e.get("vtbl", ""))
|
|
imgui.table_next_column()
|
|
imgui.text(tn or "<unknown>")
|
|
imgui.table_next_column()
|
|
imgui.text("Yes" if e.get("pinned") else "")
|
|
|
|
imgui.end_table()
|
|
|
|
|
|
# Build sorted list of all dispatch type names for the composer dropdown.
|
|
_COMPOSER_TYPES: list[str] = sorted(_DISPATCH_TYPES.values()) if _DISPATCH_TYPES else []
|
|
if not _COMPOSER_TYPES:
|
|
_COMPOSER_TYPES = sorted(pb_mod.DESCRIPTOR.message_types_by_name.keys())
|
|
|
|
|
|
def _tab_composer(shared: SharedState) -> None:
|
|
gs = _gs
|
|
imgui.text("Compose and send a custom protobuf packet")
|
|
imgui.separator()
|
|
|
|
# Type selector.
|
|
imgui.text("Type:")
|
|
imgui.same_line()
|
|
imgui.set_next_item_width(300)
|
|
changed, gs.composer_type_idx = imgui.combo(
|
|
"##composer_type", gs.composer_type_idx, _COMPOSER_TYPES)
|
|
|
|
# Direction.
|
|
imgui.same_line()
|
|
imgui.text(" Dir:")
|
|
imgui.same_line()
|
|
_, gs.composer_dir = imgui.radio_button("C->S##cdir", gs.composer_dir, 0)
|
|
imgui.same_line()
|
|
_, gs.composer_dir = imgui.radio_button("S->C##cdir", gs.composer_dir, 1)
|
|
|
|
# On type change (or first load), populate editor with empty message JSON.
|
|
if changed or gs._composer_loaded_idx != gs.composer_type_idx:
|
|
gs._composer_loaded_idx = gs.composer_type_idx
|
|
type_name = _COMPOSER_TYPES[gs.composer_type_idx]
|
|
cls = getattr(pb_mod, type_name, None)
|
|
if cls:
|
|
try:
|
|
from google.protobuf import json_format
|
|
m = cls()
|
|
jtext = json_format.MessageToJson(
|
|
m, preserving_proto_field_name=True,
|
|
including_default_value_fields=True, indent=2)
|
|
except Exception:
|
|
jtext = "{}"
|
|
else:
|
|
jtext = "{}"
|
|
gs.composer_editor.set_text(jtext)
|
|
|
|
# Editor.
|
|
code_font = imgui_md.get_code_font()
|
|
if code_font:
|
|
imgui.push_font(code_font.font, code_font.size)
|
|
gs.composer_editor.render("composer_editor")
|
|
if code_font:
|
|
imgui.pop_font()
|
|
|
|
# Send button.
|
|
send_dir = "C->S" if gs.composer_dir == 0 else "S->C"
|
|
type_name = _COMPOSER_TYPES[gs.composer_type_idx]
|
|
|
|
if imgui.button(f"Send as {send_dir}"):
|
|
jtext = gs.composer_editor.get_text()
|
|
cls = getattr(pb_mod, type_name, None)
|
|
if cls is None:
|
|
shared.log_lines.append(f"[!] composer: unknown type {type_name}")
|
|
else:
|
|
try:
|
|
from google.protobuf import json_format
|
|
m = cls()
|
|
json_format.Parse(jtext, m)
|
|
body = m.SerializeToString()
|
|
# Find msg_id from dispatch_type_names (reverse lookup).
|
|
mid = 0
|
|
for k, v in _DISPATCH_TYPES.items():
|
|
if v == type_name:
|
|
mid = int(k)
|
|
break
|
|
shared.inject_queue.append({
|
|
"direction": send_dir,
|
|
"msg_id": mid,
|
|
"body": body,
|
|
})
|
|
shared.log_lines.append(
|
|
f"[GUI] composed {send_dir} msg_id={mid} "
|
|
f"type={type_name} body={len(body)}B")
|
|
except Exception as e:
|
|
shared.log_lines.append(f"[!] composer error: {e}")
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Top-level render callback.
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def render_gui(shared: SharedState) -> None:
|
|
shared.save_if_dirty()
|
|
if imgui.begin_tab_bar("main_tabs"):
|
|
if imgui.begin_tab_item("Packets")[0]:
|
|
_tab_packet_inspector(shared)
|
|
imgui.end_tab_item()
|
|
if imgui.begin_tab_item("Config")[0]:
|
|
_tab_configuration(shared)
|
|
imgui.end_tab_item()
|
|
if imgui.begin_tab_item("Session")[0]:
|
|
_tab_session_info(shared)
|
|
imgui.end_tab_item()
|
|
if imgui.begin_tab_item("Wire")[0]:
|
|
_tab_wire_traffic(shared)
|
|
imgui.end_tab_item()
|
|
if imgui.begin_tab_item("Dispatch")[0]:
|
|
_tab_dispatch_table(shared)
|
|
imgui.end_tab_item()
|
|
if imgui.begin_tab_item("Composer")[0]:
|
|
_tab_composer(shared)
|
|
imgui.end_tab_item()
|
|
imgui.end_tab_bar()
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Entry point.
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def main() -> None:
|
|
shared = SharedState()
|
|
|
|
proxy_thread = threading.Thread(target=_run_proxy, args=(shared,),
|
|
daemon=True, name="proxy")
|
|
proxy_thread.start()
|
|
|
|
runner_params = hello_imgui.RunnerParams()
|
|
runner_params.app_window_params.window_title = "Paralogue MITM"
|
|
runner_params.app_window_params.window_geometry.size = (1400, 900)
|
|
runner_params.callbacks.show_gui = lambda: render_gui(shared)
|
|
runner_params.fps_idling.fps_idle = 30.0
|
|
|
|
add_on_params = immapp.AddOnsParams()
|
|
add_on_params.with_markdown = True
|
|
|
|
immapp.run(runner_params, add_on_params)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|