Add ImGui GUI, full type extraction, bidirectional packet injection

Major additions:
- ImGui GUI (paralogue_gui.py) with 6 tabs: Packets, Config, Session,
  Wire, Dispatch, Composer. Real-time packet inspector with JSON syntax
  highlighting via imgui_color_text_edit. Modifier toggles with auto-save.
- Full msg_id -> type extraction via Frida GetTypeName() on all 191
  dispatch entries (extract_type_names.js, run_extract_types.py).
  Zero unknowns remaining.
- Bidirectional WireRewriter: C->S rewriter enables packet injection
  without breaking server decrypt counter. Write locks prevent
  interleaved frame corruption.
- Packet injection: replay captured packets or compose custom ones
  from the GUI Composer tab. S->C uses packet_id=0 (push semantics),
  C->S auto-increments.
- Direction enforcement in _emit_decoded: rejects type names whose
  suffix contradicts wire direction, purges stale cache entries.
- Blueprint injection modifier (11xxx range) as separate toggle.
- build_frame() helper for constructing wire frames from msg_id + body.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
MRLokopandClaude Opus 4.6 committed 2026-04-16 02:36:33 -07:00
1 parent 9c3189cac2
commit d7799f51a7
11 files changed
+2304 -73

No files matched your search

+172 -32
View File
@@ -295,6 +295,38 @@ def expand_card_bag_open_rsp_modifier(msg_id: int, head, body: bytes):
return out
def inject_blueprints_modifier(msg_id: int, head, body: bytes):
"""modify_cb: when BagItemFullS2C (msg_id=1036) passes through,
inject blueprint items in the 11000..11999 range. Blueprints are
lootbox-style Pack items that can be opened via CardBagOpenReq to
grant experiment cards. Client filters against its local ItemTable
so only valid blueprint IDs actually display."""
if msg_id != 1036:
return None
import paralogue_net_full_pb2 as pb
try:
msg = pb.BagItemFullS2C()
msg.MergeFromString(body)
except Exception:
return None
existing = {it.itemId for it in msg.items}
added = 0
for iid in range(11000, 12000):
if iid in existing:
continue
it = msg.items.add()
it.itemId = iid
it.num = 1
added += 1
try:
out = msg.SerializeToString()
except Exception:
return None
print(f" [inject] BagItemFullS2C: +{added} blueprints (11xxx) "
f"(body {len(body)}B -> {len(out)}B)")
return out
def inject_unlock_functions_modifier(msg_id: int, head, body: bytes):
"""modify_cb: for PlayerMainDataRsp (msg_id=1006), populate
unlockFunctions with every uint32 from 1..2000. If experiments are
@@ -438,6 +470,18 @@ REAL_SERVER_IPS = [
]
def _name_direction_mismatch(name: str, direction: str) -> bool:
"""True if a protobuf type name's suffix contradicts the wire direction.
E.g. 'KickPlayerS2C' on a C->S packet, or 'PlayerPingReq' on S->C."""
if direction == "C->S":
if name.endswith("S2C") or name.endswith("Rsp"):
return True
elif direction == "S->C":
if name.endswith("C2S") or name.endswith("Req"):
return True
return False
# ---------------------------------------------------------------------------
# session state
# ---------------------------------------------------------------------------
@@ -510,16 +554,40 @@ class Session:
"S->C": bytearray()}
self._handshake_done: dict[str, bool] = {"C->S": False, "S->C": False}
# S->C rewriter: enabled only when --inject-items is passed. It
# sits on the proxy's forwarding path and can rewrite frames
# before they reach the client.
# S->C rewriter: sits on the proxy's forwarding path and can
# rewrite frames before they reach the client.
self.s2c_rewriter: Optional[WireRewriter] = None
# C->S rewriter: same but for client->server direction. Needed
# for C->S packet injection (without it, injecting breaks the
# server's decrypt counter). In identity mode (no modify_cb),
# output == input due to ChaCha20 XOR involution.
self.c2s_rewriter: Optional[WireRewriter] = None
# Bytes seen post-handshake but before the Frida key capture
# arrived (async timing). Flushed through the cipher in
# record_session_key.
self._wire_pending: dict[str, bytearray] = {"C->S": bytearray(),
"S->C": bytearray()}
# Writer refs for packet injection. Set per TCP connection in
# handle_game_client(), cleared on disconnect.
self.client_writer: Optional[asyncio.StreamWriter] = None
self.server_writer: Optional[asyncio.StreamWriter] = None
# C->S injection cipher — separate from the wire-decryption
# cipher. Tracks the server's expected decrypt counter so
# injected C->S frames are decryptable. Initialized alongside
# other ciphers in record_session_key().
self.c2s_inject_cipher: Optional[WireCipher] = None
self.c2s_bytes_sent: int = 0 # total encrypted C->S bytes forwarded
# Auto-incrementing packet_id for injected frames.
self._inject_packet_id: int = 60000
# Write locks to prevent interleaved writes from pipe() and
# the injection consumer. One per direction.
self.s2c_write_lock: asyncio.Lock = asyncio.Lock()
self.c2s_write_lock: asyncio.Lock = asyncio.Lock()
def close(self) -> None:
for fp in (self._decoded_fp, self._wire_fp, self._chunks_fp,
self._dispatch_fp):
@@ -573,6 +641,8 @@ class Session:
self._wire_s2c_snapshot = self.wire_bytes_s2c
if self.s2c_rewriter is not None:
self.s2c_rewriter.set_key(key, nonce)
if self.c2s_rewriter is not None:
self.c2s_rewriter.set_key(key, nonce)
except Exception as e:
print(f"[!] wire cipher init failed: {e}")
print(f"\n{'='*64}\n SESSION KEY captured (ctx={this_id} flag={flag})\n"
@@ -756,6 +826,10 @@ class Session:
preferred = self.factory_to_type[factory]
if preferred is None:
preferred = self.msg_id_cache.get(mid)
# Don't feed a wrong-direction name as a hint — it biases
# identify_body into picking a type that contradicts the wire.
if preferred and _name_direction_mismatch(preferred, direction):
preferred = None
strict = identify_body_strict(body) if body else []
strict_names = [s[0] for s in strict]
@@ -803,6 +877,28 @@ class Session:
score = max(score, 200)
break
# Final direction sanity: reject names whose suffix contradicts
# the actual wire direction (e.g. *S2C on a C->S packet).
if name and _name_direction_mismatch(name, direction):
# Purge the stale entry from in-memory cache so it never
# gets re-saved to known_msg_ids.json via a different path.
if mid in self.msg_id_cache and self.msg_id_cache[mid] == name:
del self.msg_id_cache[mid]
save_known_ids(self.msg_id_cache)
# Try to find a direction-compatible alternative from strict.
replacement = None
for sn, sm, _ in strict:
if not _name_direction_mismatch(sn, direction):
replacement = (sn, sm)
break
if replacement:
name, parsed = replacement
score = max(score, 200)
else:
name = None
parsed = None
score = 0
if name and not preferred and score >= self.STRONG_SCORE:
self.msg_id_cache[mid] = name
if mid not in self._user_ids:
@@ -860,21 +956,43 @@ class Session:
# asyncio proxy
# ---------------------------------------------------------------------------
def build_frame(msg_id: int, body: bytes, packet_id: int = 0,
seq_id: int = 0, flag: int = 0) -> bytes:
"""Build a wire frame: [2B prefix][PacketHead][body]."""
head = PACKET_HEAD_CLS()
head.msg_id = msg_id
head.body_len = len(body)
head.packet_id = packet_id
head.seq_id = seq_id
head.flag = flag
head_bytes = head.SerializeToString()
prefix = len(head_bytes).to_bytes(2, "big")
return prefix + head_bytes + body
async def pipe(reader, writer, session: Session, direction: str) -> None:
lock = (session.s2c_write_lock if direction == "S->C"
else session.c2s_write_lock)
try:
while True:
data = await reader.read(65536)
if not data:
break
session.log_wire(direction, data)
if direction == "S->C" and session.s2c_rewriter is not None:
out = session.s2c_rewriter.process(data)
if out:
writer.write(out)
async with lock:
if direction == "S->C" and session.s2c_rewriter is not None:
out = session.s2c_rewriter.process(data)
if out:
writer.write(out)
await writer.drain()
elif direction == "C->S" and session.c2s_rewriter is not None:
out = session.c2s_rewriter.process(data)
if out:
writer.write(out)
await writer.drain()
else:
writer.write(data)
await writer.drain()
else:
writer.write(data)
await writer.drain()
except (ConnectionResetError, BrokenPipeError, asyncio.CancelledError):
pass
finally:
@@ -894,17 +1012,29 @@ async def handle_game_client(reader, writer, session: Session) -> None:
cb = session.s2c_rewriter.modify_cb
session.s2c_rewriter = WireRewriter(modify_cb=cb, label="S->C")
print("[*] s2c_rewriter reset for new connection")
if session.c2s_rewriter is not None:
cb = session.c2s_rewriter.modify_cb
session.c2s_rewriter = WireRewriter(modify_cb=cb, label="C->S")
print("[*] c2s_rewriter reset for new connection")
session.c2s_bytes_sent = 0
try:
sr, sw = await asyncio.open_connection(GAME_SERVER_IP, GAME_PORT)
except Exception as e:
print(f"[!] cannot reach real server: {e}")
writer.close()
return
await asyncio.gather(
pipe(reader, sw, session, "C->S"),
pipe(sr, writer, session, "S->C"),
return_exceptions=True,
)
# Store writer refs for packet injection.
session.client_writer = writer
session.server_writer = sw
try:
await asyncio.gather(
pipe(reader, sw, session, "C->S"),
pipe(sr, writer, session, "S->C"),
return_exceptions=True,
)
finally:
session.client_writer = None
session.server_writer = None
print(f"[-] game client {addr} disconnected")
@@ -1146,23 +1276,12 @@ class FridaBridge:
# main
# ---------------------------------------------------------------------------
async def run(proxy_enabled: bool, decoder_enabled: bool,
inject_items: bool = False) -> None:
ts = int(time.time())
session = Session(ts)
if inject_items:
def combined(msg_id, head, body):
for fn in (expand_card_bag_open_rsp_modifier,
inject_unlock_functions_modifier,
inject_role_attrs_modifier,
inject_items_1_to_2000_modifier):
r = fn(msg_id, head, body)
if r is not None:
return r
return None
session.s2c_rewriter = WireRewriter(modify_cb=combined, label="S->C")
print("[*] S->C rewriter enabled: inject BagItem items "
"+ saturate RoleListFullS2C attrs")
async def run_with_session(session: Session,
proxy_enabled: bool = True,
decoder_enabled: bool = True) -> None:
"""Core event loop: starts proxy servers, attaches Frida, serves
until cancelled. Accepts a pre-built Session so callers (e.g. the
GUI) can subclass Session to intercept data."""
print("=" * 64)
print(" Paralogue MITM (proxy + plaintext decoder)")
@@ -1189,6 +1308,7 @@ async def run(proxy_enabled: bool, decoder_enabled: bool,
loop = asyncio.get_running_loop()
bridge = FridaBridge(session, loop, with_redirect=proxy_enabled)
await bridge.start()
session.bridge = bridge # expose for GUI / callers
print("[*] Ctrl+C to stop\n")
@@ -1221,6 +1341,26 @@ async def run(proxy_enabled: bool, decoder_enabled: bool,
print(f" msg_id mappings: {len(session.msg_id_cache)}")
async def run(proxy_enabled: bool, decoder_enabled: bool,
inject_items: bool = False) -> None:
ts = int(time.time())
session = Session(ts)
if inject_items:
def combined(msg_id, head, body):
for fn in (expand_card_bag_open_rsp_modifier,
inject_unlock_functions_modifier,
inject_role_attrs_modifier,
inject_items_1_to_2000_modifier):
r = fn(msg_id, head, body)
if r is not None:
return r
return None
session.s2c_rewriter = WireRewriter(modify_cb=combined, label="S->C")
print("[*] S->C rewriter enabled: inject BagItem items "
"+ saturate RoleListFullS2C attrs")
await run_with_session(session, proxy_enabled, decoder_enabled)
def main() -> None:
ap = argparse.ArgumentParser(description="Paralogue MITM (proxy + decoder in one)")
ap.add_argument("--no-proxy", action="store_true",