Files
Operation-Lovecraft-Fallen-…/frida_hooks/paralogue_mitm.py
T
2026-04-15 22:24:44 -07:00

1254 lines
49 KiB
Python

#!/usr/bin/env python3
"""paralogue_mitm.py - merged proxy + in-process plaintext decoder.
Single-process tool that does three things at once:
1. TCP proxy on 11001 (game server) and 18801 (HTTP dispatch).
Redirects traffic from the game to the real servers, logs raw
encrypted packets for archival.
2. Frida redirect: rewrites ws2_32!connect() destinations so port
11001 points at 127.0.0.1 (this proxy).
3. Frida plaintext decoder: hooks the game's decrypt/encrypt wrapper
at RVA 0x49A2EB0, reassembles [2B prefix][PacketHead][body] framing,
identifies each body against the 239-type catalog, and writes
structured JSONL with every decoded request/response.
Because the plaintext is captured in-process, there is no ChaCha20 key
reproduction, no keystream file, and no offset alignment race between
wire ciphertext and the in-process cipher state. The proxy and the
decoder live in one asyncio event loop.
Usage
python paralogue_mitm.py
python paralogue_mitm.py --no-proxy # decoder only
python paralogue_mitm.py --no-decoder # proxy-only forwarding
Output
captures/mitm_<ts>_decoded.jsonl decoded messages
captures/mitm_<ts>_wire.jsonl raw wire traffic (ciphertext)
captures/mitm_<ts>_chunks.jsonl raw plaintext chunks from hook
"""
from __future__ import annotations
import argparse
import asyncio
import json
import os
import sys
import time
from typing import Optional
import frida
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, SCRIPT_DIR)
from paralogue_decoder import ( # noqa: E402
Stream, drain_stream, identify_body, identify_body_strict,
msg_to_dict, short_repr, load_known_ids, save_known_ids, CATALOG,
PACKET_HEAD_CLS,
)
try:
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms
HAVE_CRYPTO = True
except ImportError:
HAVE_CRYPTO = False
import struct
class WireCipher:
"""ChaCha20 decryptor that tracks a byte-offset counter.
IDA analysis of sub_1449A2EB0 (decrypt) and sub_1449A52C0 (encrypt)
shows both directions share the key (+0x68) and nonce (+0x78) on the
same socket `this`, but maintain independent byte counters at +0x98
(encrypt/C->S) and +0xA0 (decrypt/S->C). So one captured key serves
both directions; only the counter differs.
ChaCha20 interface: 256-bit key + 128-bit nonce where the first 4B
are a little-endian block counter. offset / 64 => block, offset % 64
=> skip within the current block.
"""
def __init__(self, key: bytes, nonce12: bytes, start_offset: int = 0):
if not HAVE_CRYPTO:
raise RuntimeError("cryptography library required")
if len(key) != 32 or len(nonce12) != 12:
raise ValueError("key must be 32B, nonce must be 12B")
self.key = key
self.nonce = nonce12
self.offset = start_offset
def decrypt(self, data: bytes) -> bytes:
if not data:
return b""
block = self.offset // 64
skip = self.offset % 64
full_nonce = struct.pack("<I", block) + self.nonce
cipher = Cipher(algorithms.ChaCha20(self.key, full_nonce), mode=None)
dec = cipher.decryptor()
if skip:
dec.update(b"\x00" * skip)
out = dec.update(data)
self.offset += len(data)
return out
# ChaCha20 is symmetric: encrypt == decrypt (both XOR against the
# keystream). Distinct method for readability at call sites.
encrypt = decrypt
class WireRewriter:
"""Server->Client frame-aware rewriter.
Decrypts wire bytes received from the server, splits them into
protobuf frames ([2B prefix][head][body]), runs each frame through
an optional modify callback, re-encrypts, and returns the new wire
bytes to forward to the client.
Two independent ChaCha20 ciphers share the key/nonce but track
separate byte offsets:
* cipher_in — advances by len(server-bytes-received)
* cipher_out — advances by len(client-bytes-forwarded)
When the modify callback returns the same bytes, in and out stay in
lockstep and the emitted wire ciphertext is byte-identical to the
input (since ChaCha20 XOR is an involution). When modify changes a
frame's size the two diverge, but the client's own decrypt counter
tracks proxy-sent bytes so it stays in sync with cipher_out.
The first S->C packet is a hybrid: 2B-prefix plaintext handshake
(`VerifyLoginTokenRsp`, msg_id 1002) optionally followed by an
encrypted tail that is the first post-handshake frame. The
plaintext handshake is passed through untouched; only the tail
feeds the ciphers.
"""
def __init__(self, modify_cb=None, label: str = "S->C"):
self.label = label
self.cipher_in: Optional[WireCipher] = None
self.cipher_out: Optional[WireCipher] = None
self.pre_enc_buf = bytearray()
self.handshake_done = False
# Encrypted bytes forwarded before the key arrived. Client will
# have processed them at its own counter; once the key arrives
# we initialize our ciphers at the corresponding offset so we
# don't re-decrypt those already-sent bytes.
self.passthrough_enc_bytes = 0
self.plain_buf = bytearray() # decrypted plaintext, awaiting framing
self.modify_cb = modify_cb
self.frames_seen = 0
self.frames_modified = 0
def set_key(self, key: bytes, nonce: bytes) -> None:
if self.cipher_in is not None:
return
# Both ciphers start AFTER any bytes we forwarded unchanged before
# the key was available. Client's own decrypt counter == bytes
# received since handshake == passthrough_enc_bytes.
off = self.passthrough_enc_bytes
self.cipher_in = WireCipher(key, nonce, off)
self.cipher_out = WireCipher(key, nonce, off)
def process(self, data: bytes) -> bytes:
if not self.handshake_done:
return self._handshake_phase(data)
# Post-handshake: decrypt, buffer plaintext, drain complete frames,
# re-encrypt and return.
if self.cipher_in is None:
# Key still not captured (client hasn't processed first decrypt
# yet). Forward bytes untouched so the client can make
# progress; count them so the eventual cipher start offset
# reflects what's already on the wire.
self.passthrough_enc_bytes += len(data)
return data
plain = self.cipher_in.decrypt(data)
self.plain_buf.extend(plain)
return self._drain_and_encrypt()
# ---- internal helpers ----
def _drain_and_encrypt(self) -> bytes:
from paralogue_decoder import PACKET_HEAD_CLS
out_plain = bytearray()
while True:
if len(self.plain_buf) < 2:
break
hlen = (self.plain_buf[0] << 8) | self.plain_buf[1]
if hlen == 0 or hlen > 32:
# Invalid framing — forward rest as-is and bail. Shouldn't
# happen in a healthy stream.
out_plain.extend(self.plain_buf)
self.plain_buf = bytearray()
break
if len(self.plain_buf) < 2 + hlen:
break
try:
head = PACKET_HEAD_CLS()
head.MergeFromString(bytes(self.plain_buf[2:2 + hlen]))
body_len = int(head.body_len)
except Exception:
break
total = 2 + hlen + body_len
if len(self.plain_buf) < total:
break
frame = bytes(self.plain_buf[:total])
del self.plain_buf[:total]
self.frames_seen += 1
out_frame = self._maybe_modify(frame, head)
if out_frame is not frame:
self.frames_modified += 1
out_plain.extend(out_frame)
if self.cipher_out is None:
# Shouldn't happen (cipher_in implies cipher_out), but be safe.
return bytes(out_plain)
return self.cipher_out.encrypt(bytes(out_plain))
def _maybe_modify(self, frame: bytes, head) -> bytes:
if self.modify_cb is None:
return frame
hlen = (frame[0] << 8) | frame[1]
body = frame[2 + hlen:]
new_body = self.modify_cb(int(head.msg_id), head, body)
if new_body is None or new_body is body:
return frame
# Update head.body_len to reflect the new body size and re-emit.
head.body_len = len(new_body)
new_head = head.SerializeToString()
new_hlen = len(new_head)
return bytes([(new_hlen >> 8) & 0xFF, new_hlen & 0xFF]) + new_head + new_body
def _handshake_phase(self, data: bytes) -> bytes:
from paralogue_decoder import PACKET_HEAD_CLS
self.pre_enc_buf.extend(data)
if len(self.pre_enc_buf) < 2:
return b""
hlen = (self.pre_enc_buf[0] << 8) | self.pre_enc_buf[1]
if hlen == 0 or hlen > 32:
return b"" # keep buffering
if len(self.pre_enc_buf) < 2 + hlen:
return b""
try:
head = PACKET_HEAD_CLS()
head.MergeFromString(bytes(self.pre_enc_buf[2:2 + hlen]))
body_len = int(head.body_len)
except Exception:
return b""
frame_end = 2 + hlen + body_len
if len(self.pre_enc_buf) < frame_end:
return b""
handshake = bytes(self.pre_enc_buf[:frame_end])
tail = bytes(self.pre_enc_buf[frame_end:])
self.pre_enc_buf = bytearray()
self.handshake_done = True
out = bytearray(handshake)
if tail:
if self.cipher_in is None:
# Forward the encrypted tail untouched. Client needs it
# to finish key setup (the tail IS the first encrypted
# frame that triggers the decrypt call where Frida reads
# the key). Count it so cipher offsets start after these
# bytes once the key arrives.
self.passthrough_enc_bytes += len(tail)
out.extend(tail)
else:
plain = self.cipher_in.decrypt(tail)
self.plain_buf.extend(plain)
out.extend(self._drain_and_encrypt())
return bytes(out)
def expand_card_bag_open_rsp_modifier(msg_id: int, head, body: bytes):
"""modify_cb: when the server sends a CardBagOpenRsp (msg_id=1193)
in response to a blueprint open, expand `rets` to include every
card_id 0..1000. The client appends each returned card_id to its
local learn_cards collection, so the Experiment UI count jumps by
however many valid card_ids are in that range. Invalid ones are
silently dropped by the client's DataTable filter."""
if msg_id != 1193:
return None
import paralogue_net_full_pb2 as pb
try:
msg = pb.CardBagOpenRsp()
msg.MergeFromString(body)
except Exception:
return None
# Preserve pack_guarantee/total_guarantee from the real response;
# just replace rets with a full 0..1000 array.
del msg.rets[:]
for cid in range(0, 2001):
r = msg.rets.add()
r.card_id = cid
msg.status = 1
try:
out = msg.SerializeToString()
except Exception:
return None
print(f" [inject] CardBagOpenRsp: rets=0..2000 ({len(msg.rets)} cards) "
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
gated by feature IDs in this list, every experiment should unlock."""
if msg_id != 1006:
return None
import paralogue_net_full_pb2 as pb
try:
msg = pb.PlayerMainDataRsp()
msg.MergeFromString(body)
except Exception:
return None
for fid in range(1, 2001):
msg.unlockFunctions.append(fid)
try:
out = msg.SerializeToString()
except Exception:
return None
print(f" [inject] PlayerMainDataRsp: unlockFunctions=1..2000 "
f"(body {len(body)}B -> {len(out)}B)")
return out
def inject_role_attrs_modifier(msg_id: int, head, body: bytes):
"""modify_cb: for RoleListFullS2C (msg_id=1202), mark every role as
unlocked and saturate every attrs entry to a high value. If the
per-role attrs map is the actual 'experiments' storage, the UI
should display every experiment as complete after this rewrites
the login push."""
if msg_id != 1202:
return None
import paralogue_net_full_pb2 as pb
try:
msg = pb.RoleListFullS2C()
msg.MergeFromString(body)
except Exception:
return None
touched_roles = 0
touched_attrs = 0
for role in msg.role_list.roles:
role.is_unlock = True
for k in list(role.attrs.keys()):
role.attrs[k] = 999
touched_attrs += 1
# Saturate related dilation/favor/stamina fields too, in case
# "experiments" is gated by these rather than the attrs map.
role.favor_lv = 99
role.vaginal_dilation_lv = 99
role.anal_dilation_lv = 99
touched_roles += 1
try:
out = msg.SerializeToString()
except Exception:
return None
print(f" [inject] RoleListFullS2C: {touched_roles} roles unlocked, "
f"{touched_attrs} attrs saturated (body {len(body)}B -> {len(out)}B)")
return out
def inject_items_1_to_2000_modifier(msg_id: int, head, body: bytes):
"""modify_cb: when a BagItemFullS2C (msg_id=1036) passes through,
densely fill every observed ID range so we can see which tab each
prefix maps to. The client's ItemTable silently drops invalid IDs,
so spraying a range only reveals items the game defines.
Observed ranges in real traffic:
0xxxx (2..574) -> likely Gift
1xxxx (11001..11042) -> Pack
2xxxx (20005..28007) -> Card or Normal
3xxxx (31013..31442) -> Cloth (confirmed)
4xxxx (40001..40022) -> Normal (experiments?)
9xxxx (99981..99999) -> Money/Title
100001 -> singleton
"""
if msg_id != 1036:
return None
import paralogue_net_full_pb2 as pb
try:
msg = pb.BagItemFullS2C()
msg.MergeFromString(body)
except Exception:
return None
# Build candidate IDs: dense across each observed range.
# NOTE: blueprints (11xxx) deliberately excluded — sending a
# CardBagOpenReq with a forged id to the server would trigger
# status=13 rejections at best and may flag the account, so
# we don't want fake blueprints polluting the bag at all.
candidates = set()
candidates.update(range(1, 1000)) # 0xxxx low
candidates.update(range(20000, 29000)) # 2xxxx card/normal
candidates.update(range(31000, 32000)) # 3xxxx cloth
candidates.update(range(40000, 41000)) # 4xxxx experiments?
candidates.update(range(99900, 100100)) # 99xxx money
candidates.update(range(100000, 100100)) # singleton neighborhood
existing = {it.itemId for it in msg.items}
added = 0
for iid in sorted(candidates):
if iid in existing:
continue
it = msg.items.add()
it.itemId = iid
it.num = 1
added += 1
# Diagnostic: bump the count of a known currency item. If the UI
# reflects this, the client is honoring our rewritten packet and
# the missing injected items are being filtered by the client-side
# ItemTable (they need to exist in the data asset). If the UI
# ignores this bump too, the client is reading bag state from
# somewhere other than BagItemFullS2C.
TARGET_BUMP_ID = 99991
TARGET_BUMP_NUM = 999999
bumped = False
for it in msg.items:
if it.itemId == TARGET_BUMP_ID:
it.num = TARGET_BUMP_NUM
bumped = True
break
try:
out = msg.SerializeToString()
except Exception:
return None
print(f" [inject] BagItemFullS2C: +{added} items, "
f"bump[{TARGET_BUMP_ID}]->{TARGET_BUMP_NUM}={bumped} "
f"(body {len(body)}B -> {len(out)}B)")
return out
PROCESS_NAME = "Paralogue-Win64-Shipping.exe"
DECODER_JS = os.path.join(SCRIPT_DIR, "protocol_decoder.js")
REDIRECT_JS = os.path.join(SCRIPT_DIR, "redirect_connect.js")
DISPATCH_JS = os.path.join(SCRIPT_DIR, "dispatch_dump.js")
ITEM_DUMP_JS = os.path.join(SCRIPT_DIR, "item_table_dump.js")
OUT_DIR = os.path.join(SCRIPT_DIR, "captures")
os.makedirs(OUT_DIR, exist_ok=True)
GAME_SERVER_IP = "3.33.185.193"
DISPATCH_IP = "13.248.150.146"
GAME_PORT = 11001
HTTP_PORT = 18801
REAL_SERVER_IPS = [
"13.248.150.146", "35.71.128.233", "3.33.185.193", "76.223.57.31",
]
# ---------------------------------------------------------------------------
# session state
# ---------------------------------------------------------------------------
class Session:
STRONG_SCORE = 60
def __init__(self, ts: int):
self.decoded_path = os.path.join(OUT_DIR, f"mitm_{ts}_decoded.jsonl")
self.wire_path = os.path.join(OUT_DIR, f"mitm_{ts}_wire.jsonl")
self.chunks_path = os.path.join(OUT_DIR, f"mitm_{ts}_chunks.jsonl")
self.dispatch_path = os.path.join(OUT_DIR, f"mitm_{ts}_dispatch.jsonl")
self._decoded_fp = open(self.decoded_path, "w", encoding="utf-8")
self._wire_fp = open(self.wire_path, "w", encoding="utf-8")
self._chunks_fp = open(self.chunks_path, "w", encoding="utf-8")
self._dispatch_fp = open(self.dispatch_path, "w", encoding="utf-8")
# msg_id -> factory_rva (module-relative, stable across runs under ASLR).
self.msg_id_to_factory: dict[int, str] = {}
# factory_rva -> type_name once resolved by strict identification.
# Persisted: factories are stable across runs because the exe is
# built without /DYNAMICBASE (module_base == 0x140000000 always).
self.factory_to_type: dict[str, str] = {}
self._factory_map_path = os.path.join(SCRIPT_DIR, "factory_to_type.json")
if os.path.isfile(self._factory_map_path):
try:
with open(self._factory_map_path, "r", encoding="utf-8") as f:
self.factory_to_type = json.load(f)
except Exception:
self.factory_to_type = {}
self.streams: dict[tuple[str, int], Stream] = {}
self.msg_id_cache = load_known_ids()
self._user_ids = set(self.msg_id_cache.keys())
self.decoded_seq = 0
self.wire_seq = 0
self.chunk_seq = 0
self._send_offset = 0
# Cryptography experiment: if Frida provides the key/nonce, try
# decrypting wire ciphertext ourselves using OpenSSL's ChaCha20.
# Success proves we can do Frida-free decoding on the proxy side.
self.session_key: Optional[bytes] = None
self.session_nonce: Optional[bytes] = None
self.session_offset_at_capture: int = 0
self._captured_plaintext_at_offset: dict[int, bytes] = {}
self._verify_pending: list[tuple[int, bytes]] = []
# Per-direction wire decryption state. Initialized on first key
# capture. Wire bytes are fed through these to recover plaintext
# without needing the Frida plaintext hook.
self.wire_cipher_c2s: Optional[WireCipher] = None
self.wire_cipher_s2c: Optional[WireCipher] = None
# Proxy-observed wire bytes per direction since the connection
# started. On key capture we snapshot these to align counters.
self.wire_bytes_c2s: int = 0
self.wire_bytes_s2c: int = 0
self.wire_streams: dict[str, Stream] = {
"C->S": Stream(label="wire-C->S"),
"S->C": Stream(label="wire-S->C"),
}
# Pre-encryption state. The RSA handshake frame (msg_id 1001 C->S
# / 1002 S->C) is sent as plaintext BEFORE ChaCha20 kicks in. The
# packet that carries the S->C handshake response may also carry
# the first encrypted frame in its tail. We buffer each direction
# and parse exactly one plaintext frame; anything after it feeds
# the WireCipher at offset 0.
self._pre_enc_buf: dict[str, bytearray] = {"C->S": bytearray(),
"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.
self.s2c_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()}
def close(self) -> None:
for fp in (self._decoded_fp, self._wire_fp, self._chunks_fp,
self._dispatch_fp):
try:
fp.close()
except Exception:
pass
def record_dispatch_entry(self, msg_id: int, vtbl: str,
factory_abs: str) -> None:
# Key by vtable address (stable .rdata, unlike heap-allocated
# factory object). vtbl == class identifier across runs.
self.msg_id_to_factory[msg_id] = vtbl
self._dispatch_fp.write(json.dumps({
"msg_id": msg_id,
"vtbl": vtbl,
"factory_abs": factory_abs,
}) + "\n")
self._dispatch_fp.flush()
# ---- key capture --------------------------------------------------
def record_session_key(self, key: bytes, nonce: bytes, offset: int,
flag: int = 0, this_id: str = "",
offset_enc: int = 0, offset_dec: int = 0) -> None:
# The game pools cipher contexts across reconnects; a single
# this_id can host multiple keys over time. Key by (this_id, key).
if not hasattr(self, "keys_by_ctx"):
self.keys_by_ctx: dict[tuple[str, str], dict] = {}
ck = (this_id, key.hex())
if ck in self.keys_by_ctx:
return
self.keys_by_ctx[ck] = {
"key": key, "nonce": nonce,
"offset_at_capture": offset,
"flag": flag, "this_id": this_id,
}
if self.session_key is None:
self.session_key = key
self.session_nonce = nonce
self.session_offset_at_capture = offset
# Initialize per-direction wire decryptors. The game's counter
# at capture time reflects how many post-handshake bytes have
# already flowed; proxy aligns by assuming its observed wire
# bytes so far for that direction == game counter at capture.
if HAVE_CRYPTO and len(nonce) == 12:
try:
self.wire_cipher_c2s = WireCipher(key, nonce, offset_enc)
self.wire_cipher_s2c = WireCipher(key, nonce, offset_dec)
self._wire_c2s_snapshot = self.wire_bytes_c2s
self._wire_s2c_snapshot = self.wire_bytes_s2c
if self.s2c_rewriter is not None:
self.s2c_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"
f" key = {key.hex()}\n"
f" nonce = {nonce.hex()}\n"
f" game counters: enc(C->S)={offset_enc} dec(S->C)={offset_dec}\n"
f" proxy wire: C->S={self.wire_bytes_c2s} S->C={self.wire_bytes_s2c}\n"
f" pending bytes: C->S={len(self._wire_pending['C->S'])} "
f"S->C={len(self._wire_pending['S->C'])}\n"
f"{'='*64}\n")
for d in ("C->S", "S->C"):
pending = bytes(self._wire_pending[d])
self._wire_pending[d] = bytearray()
if pending:
self._feed_cipher(d, pending)
try:
with open(os.path.join(OUT_DIR, "current_session_key.json"), "w") as f:
json.dump({
"contexts": [
{
"this_id": v["this_id"],
"flag": v["flag"],
"offset_at_capture": v["offset_at_capture"],
"key_hex": v["key"].hex(),
"nonce_hex": v["nonce"].hex(),
} for v in self.keys_by_ctx.values()
],
"ts": time.time(),
}, f, indent=2)
except Exception:
pass
def _try_verify_library(self) -> None:
"""Sanity-check the cryptography-library ChaCha20 against a known
plaintext+ciphertext pair, IF we have any samples logged. The
current merged tool only captures plaintext, not ciphertext, so
this prints the library's keystream at offset 0 for manual
comparison against a captured wire packet.
"""
if not HAVE_CRYPTO or self.session_key is None:
return
import struct
full_nonce = struct.pack("<I", 0) + self.session_nonce
cipher = Cipher(algorithms.ChaCha20(self.session_key, full_nonce), mode=None)
ks64 = cipher.encryptor().update(b"\x00" * 64)
print(f"[verify] cryptography keystream @ game_offset=0 (first 32B):")
print(f" {ks64[:32].hex()}")
print(f"[verify] XOR this against the first 64B of encrypted payload")
print(f" on the wire (post-handshake) to check alignment.")
# ---- wire (ciphertext) ---------------------------------------------
def log_wire(self, direction: str, data: bytes, label: str = "") -> None:
self.wire_seq += 1
rec = {
"n": self.wire_seq,
"ts": time.time(),
"d": direction,
"sz": len(data),
"hex": data.hex(),
"label": label,
}
self._wire_fp.write(json.dumps(rec) + "\n")
self._wire_fp.flush()
arrow = ">>>" if direction == "C->S" else "<<<"
extra = f" {label}" if label else ""
print(f"[wire #{self.wire_seq:04d}] {arrow} {direction} {len(data):5d}B{extra}")
if direction == "C->S":
self.wire_bytes_c2s += len(data)
cipher = self.wire_cipher_c2s
else:
self.wire_bytes_s2c += len(data)
cipher = self.wire_cipher_s2c
# Phase 1: consume the plaintext handshake frame (msg_id 1001/1002).
if not self._handshake_done[direction]:
buf = self._pre_enc_buf[direction]
buf.extend(data)
# Need at least 2B for prefix length.
if len(buf) < 2:
return
prefix = int.from_bytes(buf[:2], "big")
if len(buf) < 2 + prefix:
return
# Parse head to get body_len.
try:
from paralogue_decoder import PACKET_HEAD_CLS
head = PACKET_HEAD_CLS()
head.ParseFromString(bytes(buf[2:2 + prefix]))
body_len = int(head.body_len)
except Exception:
return
frame_end = 2 + prefix + body_len
if len(buf) < frame_end:
return
handshake_body = bytes(buf[2 + prefix:frame_end])
self._emit_decoded(direction, 0, head, handshake_body, source="wire")
leftover = bytes(buf[frame_end:])
self._handshake_done[direction] = True
self._pre_enc_buf[direction] = bytearray()
data = leftover # fall through to cipher path with the tail
if not data:
return
if cipher is None:
# Key not captured yet (async). Stash and drain later.
self._wire_pending[direction].extend(data)
return
self._feed_cipher(direction, bytes(data))
def _feed_cipher(self, direction: str, data: bytes) -> None:
cipher = (self.wire_cipher_c2s if direction == "C->S"
else self.wire_cipher_s2c)
if cipher is None or not data:
return
try:
plain = cipher.decrypt(data)
except Exception as e:
print(f"[!] wire decrypt failed ({direction}): {e}")
return
stream = self.wire_streams[direction]
stream.add(stream.frontier, plain)
for head, body, _skipped in drain_stream(stream):
self._emit_decoded(direction, stream.consumed, head, body,
source="wire")
# ---- chunks (plaintext from Frida hook) ---------------------------
def log_chunk(self, meta: dict, data: bytes) -> None:
self.chunk_seq += 1
this_id = meta["this_id"]
source = meta.get("source", "recv")
# recv path = decrypt wrapper = S->C plaintext (post-decrypt)
# send path = pre-send helper = C->S plaintext (pre-encrypt)
if source == "send":
direction = "C->S"
enc = 1
off = self._send_offset
self._send_offset += len(data)
else:
direction = "S->C"
enc = 0
off = int(meta.get("off", 0))
rec = {
"n": self.chunk_seq,
"dir": direction,
"off": off,
"len": len(data),
"hex": data.hex(),
}
self._chunks_fp.write(json.dumps(rec) + "\n")
self._chunks_fp.flush()
key = (this_id, enc)
stream = self.streams.get(key)
if stream is None:
stream = Stream(label=direction)
self.streams[key] = stream
stream.add(off, data)
for head, body, _skipped in drain_stream(stream):
self._emit_decoded(direction, off, head, body)
# ---- decoded -------------------------------------------------------
def _emit_decoded(self, direction: str, off: int, head, body: bytes,
source: str = "frida") -> None:
mid = int(head.msg_id)
# Preferred order for this msg_id:
# 1. factory-pinned name (ground truth from dispatch table + one
# confident strict-parse earlier in the session)
# 2. user-provided known_msg_ids.json entry
# 3. legacy cache (heuristic-learned)
factory = self.msg_id_to_factory.get(mid)
preferred = None
if factory and factory in self.factory_to_type:
preferred = self.factory_to_type[factory]
if preferred is None:
preferred = self.msg_id_cache.get(mid)
strict = identify_body_strict(body) if body else []
strict_names = [s[0] for s in strict]
# If multiple strict candidates, apply a direction-aware
# naming preference so we can still pin confidently: inbound
# (S->C) messages are typically named *S2C, outbound (C->S)
# are *C2S/*Req. If exactly one candidate matches the expected
# suffix pattern, treat that as the unambiguous choice.
if len(strict_names) > 1:
if direction == "S->C":
suffixed = [n for n in strict_names if n.endswith("S2C")]
else:
suffixed = [n for n in strict_names
if n.endswith("C2S") or n.endswith("Req")]
if len(suffixed) == 1:
strict_names = suffixed
strict = [s for s in strict if s[0] == suffixed[0]]
# Pin factory -> type when strict identification is unambiguous.
if (factory and factory not in self.factory_to_type
and len(strict_names) == 1):
pinned = strict_names[0]
self.factory_to_type[factory] = pinned
self.msg_id_cache[mid] = pinned
# Strict ID trumps any prior heuristic cache entry.
save_known_ids(self.msg_id_cache)
try:
with open(self._factory_map_path, "w", encoding="utf-8") as f:
json.dump(self.factory_to_type, f, indent=2, sort_keys=True)
except Exception:
pass
print(f" [pinned] msg_id={mid} factory={factory} -> {pinned}")
name, parsed, score, cand, top = identify_body(body, preferred)
# If the strict set is non-empty, override the heuristic pick:
# prefer the strict candidate that matches `preferred` or the
# first strict candidate otherwise.
if strict and (preferred in strict_names or name not in strict_names):
pick = preferred if preferred in strict_names else strict_names[0]
for sn, sm, _exact in strict:
if sn == pick:
name, parsed = sn, sm
score = max(score, 200)
break
if name and not preferred and score >= self.STRONG_SCORE:
self.msg_id_cache[mid] = name
if mid not in self._user_ids:
save_known_ids(self.msg_id_cache)
if parsed is not None:
fields_obj = msg_to_dict(parsed)
parsed_ok = True
else:
fields_obj = None
parsed_ok = False
try:
head_hex = head.SerializeToString().hex()
except Exception:
head_hex = ""
self.decoded_seq += 1
record = {
"seq": self.decoded_seq,
"ts": time.time(),
"source": source,
"direction": direction,
"stream_offset": off,
"msg_id": mid,
"msg_type": name or "<unknown>",
"packet_id": int(head.packet_id),
"flag": int(head.flag),
"body_len": int(head.body_len),
"seq_id": int(head.seq_id),
"total_pack_count": int(head.total_pack_count),
"identify_score": score,
"identify_candidates": cand,
"strict_candidates": strict_names,
"factory_rva": factory,
"top_candidates": [{"type": n, "score": s} for n, s in top],
"parsed": parsed_ok,
"fields": fields_obj,
"head_hex": head_hex,
"body_hex": body.hex(),
}
self._decoded_fp.write(json.dumps(record, ensure_ascii=False) + "\n")
self._decoded_fp.flush()
tag = "W" if source == "wire" else "F"
summary = short_repr(fields_obj) if parsed_ok else f"_raw={body[:24].hex()}"
print(
f"[dec #{self.decoded_seq:04d}] [{tag}] {direction} "
f"msg_id={mid:<5d} {record['msg_type']:<28s} "
f"body={record['body_len']:>5d}B {summary}"
)
# ---------------------------------------------------------------------------
# asyncio proxy
# ---------------------------------------------------------------------------
async def pipe(reader, writer, session: Session, direction: str) -> None:
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)
await writer.drain()
else:
writer.write(data)
await writer.drain()
except (ConnectionResetError, BrokenPipeError, asyncio.CancelledError):
pass
finally:
try:
writer.close()
except Exception:
pass
async def handle_game_client(reader, writer, session: Session) -> None:
addr = writer.get_extra_info("peername")
print(f"[+] game client {addr}")
# Reset the rewriter for the new TCP connection: each game login
# begins with a fresh RSA handshake and a new ChaCha20 key, so
# handshake state + counters must start from zero.
if session.s2c_rewriter is not None:
cb = session.s2c_rewriter.modify_cb
session.s2c_rewriter = WireRewriter(modify_cb=cb, label="S->C")
print("[*] s2c_rewriter reset for new connection")
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,
)
print(f"[-] game client {addr} disconnected")
async def handle_http_client(reader, writer, session: Session) -> None:
addr = writer.get_extra_info("peername")
print(f"[+] http client {addr}")
try:
sr, sw = await asyncio.open_connection(DISPATCH_IP, HTTP_PORT)
except Exception as e:
print(f"[!] cannot reach http: {e}")
writer.close()
return
async def c2s(r, w):
try:
while True:
d = await r.read(65536)
if not d:
break
try:
first = d.split(b"\r\n", 1)[0].decode(errors="replace")
print(f" [HTTP C->S] {first}")
except Exception:
pass
w.write(d)
await w.drain()
except Exception:
pass
async def s2c(r, w):
try:
while True:
d = await r.read(65536)
if not d:
break
for ip in REAL_SERVER_IPS:
if ip.encode() in d:
pad = b" " * (len(ip) - len("127.0.0.1"))
d = d.replace(ip.encode(), b"127.0.0.1" + pad)
w.write(d)
await w.drain()
except Exception:
pass
await asyncio.gather(c2s(reader, sw), s2c(sr, writer), return_exceptions=True)
print(f"[-] http client {addr} disconnected")
# ---------------------------------------------------------------------------
# Frida bridge
# ---------------------------------------------------------------------------
class FridaBridge:
"""Attaches Frida scripts and forwards messages to the asyncio session.
Frida fires `on_message` on its own thread; we marshal into the main
asyncio loop via `loop.call_soon_threadsafe` so the Session's file I/O
stays single-threaded.
"""
def __init__(self, session: Session, loop: asyncio.AbstractEventLoop,
with_redirect: bool = True):
self.session = session
self.loop = loop
self.with_redirect = with_redirect
self.frida_session = None
self.scripts: list = []
async def start(self) -> None:
with open(DECODER_JS, "r", encoding="utf-8") as f:
decoder_src = f.read()
redirect_src = None
if self.with_redirect:
with open(REDIRECT_JS, "r", encoding="utf-8") as f:
redirect_src = f.read()
print(f"[*] waiting for {PROCESS_NAME} ...")
while self.frida_session is None:
try:
for proc in frida.get_local_device().enumerate_processes():
if proc.name == PROCESS_NAME:
print(f"[*] attaching to PID {proc.pid}")
self.frida_session = frida.attach(proc.pid)
break
except Exception as e:
print(f"[!] {e}")
if self.frida_session is None:
await asyncio.sleep(1)
if redirect_src:
r = self.frida_session.create_script(redirect_src)
r.on("message", self._redirect_msg)
r.load()
self.scripts.append(r)
print("[*] redirect hook loaded")
d = self.frida_session.create_script(decoder_src)
d.on("message", self._decoder_msg)
d.load()
self.scripts.append(d)
print("[*] decoder hook loaded")
try:
with open(DISPATCH_JS, "r", encoding="utf-8") as f:
dispatch_src = f.read()
dp = self.frida_session.create_script(dispatch_src)
dp.on("message", self._dispatch_msg)
dp.load()
self.scripts.append(dp)
print("[*] dispatch hook loaded")
except FileNotFoundError:
print("[!] dispatch_dump.js missing; skipping table walk")
try:
with open(ITEM_DUMP_JS, "r", encoding="utf-8") as f:
idsrc = f.read()
ip = self.frida_session.create_script(idsrc)
ip.on("message", self._item_dump_msg)
ip.load()
self.scripts.append(ip)
print("[*] item_table_dump hook loaded")
except FileNotFoundError:
pass
def stop(self) -> None:
for s in self.scripts:
try:
s.unload()
except Exception:
pass
if self.frida_session:
try:
self.frida_session.detach()
except Exception:
pass
def _item_dump_msg(self, message, data):
if message.get("type") == "error":
print(f"[!] item_dump js: {message.get('description','')}")
return
p = message.get("payload") or {}
t = p.get("t")
if t == "ready":
print(f"[*] {p.get('msg','')}")
elif t == "item_subsystem":
print(f"[*] item subsystem pointer: {p.get('addr')}")
self._item_ids = []
elif t == "item_block":
print(f" item block @ {p.get('ptr')} count={p.get('count')}")
elif t == "item_id":
if not hasattr(self, "_item_ids"):
self._item_ids = []
self._item_ids.append(int(p["id"]))
elif t == "item_dump_done":
ids = sorted(set(getattr(self, "_item_ids", [])))
path = os.path.join(SCRIPT_DIR, "client_item_ids.json")
with open(path, "w", encoding="utf-8") as f:
json.dump(ids, f)
print(f"[*] item dump: {len(ids)} unique ids -> {path}")
# summarize by prefix
from collections import Counter
buckets = Counter(iid // 1000 for iid in ids)
print(" prefix histogram (id//1000): " +
" ".join(f"{k}x:{v}" for k, v in sorted(buckets.items())))
def _dispatch_msg(self, message, data):
if message.get("type") == "error":
print(f"[!] dispatch js: {message.get('description','')}")
return
p = message.get("payload") or {}
t = p.get("t")
if t == "dispatch_info":
print(f"[*] dispatch table: used={p.get('used')} "
f"size={p.get('hash_size')} inline={p.get('inline')}")
print(f"[*] module_base={p.get('module_base')} "
f"module_size={hex(p.get('module_size', 0))} "
f"buckets={p.get('buckets')}")
elif t == "dispatch_entry":
# Log the first few entries fully to diagnose struct layout.
if self.session.msg_id_to_factory == {} or len(
self.session.msg_id_to_factory) < 3:
raw = data.hex() if data else ""
print(f" dispatch msg_id={p.get('msg_id')} "
f"factory={p.get('factory')} vtbl={p.get('vtbl')} "
f"first_vtbl_entry={p.get('first_vtbl_entry')} "
f"raw={raw}")
self.loop.call_soon_threadsafe(
self.session.record_dispatch_entry,
int(p["msg_id"]),
p.get("vtbl", ""),
p.get("factory", ""),
)
elif t == "dispatch_done":
print(f"[*] dispatch table walk complete: {p.get('total')} entries")
elif t == "error":
print(f"[!] dispatch: {p.get('msg','')}")
def _redirect_msg(self, message, data):
if message.get("type") == "error":
print(f"[!] redirect js: {message.get('description','')}")
return
p = message.get("payload") or {}
t = p.get("t")
if t == "ready":
print(f"[*] redirect: {p.get('msg','')}")
elif t == "redirect":
print(f"[*] redirect: {p.get('from')}:{p.get('port')} -> {p.get('to')}")
def _decoder_msg(self, message, data):
if message.get("type") == "error":
print(f"[!] decoder js: {message.get('description','')}")
return
p = message.get("payload") or {}
t = p.get("t")
if t == "ready":
print(f"[*] decoder: {p.get('msg','')}")
elif t == "chunk" and data is not None:
chunk = bytes(data)
self.loop.call_soon_threadsafe(self.session.log_chunk, p, chunk)
elif t == "session_key":
key = bytes.fromhex(p.get("key_hex", ""))
nonce = bytes.fromhex(p.get("nonce_hex", ""))
off = int(p.get("offset", 0))
off_enc = int(p.get("offset_enc", 0))
off_dec = int(p.get("offset_dec", off))
flag = int(p.get("flag", 0))
this_id = p.get("this_id", "")
self.loop.call_soon_threadsafe(
self.session.record_session_key, key, nonce, off, flag,
this_id, off_enc, off_dec,
)
elif t == "status":
print(f"[*] hook calls: {p.get('calls',0)} | "
f"decoded: {self.session.decoded_seq} | "
f"mapped: {len(self.session.msg_id_cache)}")
# ---------------------------------------------------------------------------
# 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")
print("=" * 64)
print(" Paralogue MITM (proxy + plaintext decoder)")
print(f" decoded -> {session.decoded_path}")
print(f" wire -> {session.wire_path}")
print(f" chunks -> {session.chunks_path}")
print("=" * 64)
game_server = http_server = None
if proxy_enabled:
game_server = await asyncio.start_server(
lambda r, w: handle_game_client(r, w, session),
"0.0.0.0", GAME_PORT, reuse_address=True,
)
print(f"[*] game proxy listening on 0.0.0.0:{GAME_PORT}")
http_server = await asyncio.start_server(
lambda r, w: handle_http_client(r, w, session),
"0.0.0.0", HTTP_PORT, reuse_address=True,
)
print(f"[*] http proxy listening on 0.0.0.0:{HTTP_PORT}")
bridge: Optional[FridaBridge] = None
if decoder_enabled:
loop = asyncio.get_running_loop()
bridge = FridaBridge(session, loop, with_redirect=proxy_enabled)
await bridge.start()
print("[*] Ctrl+C to stop\n")
stop_evt = asyncio.Event()
async def serve_forever():
tasks = []
if game_server:
tasks.append(asyncio.create_task(game_server.serve_forever()))
tasks.append(asyncio.create_task(http_server.serve_forever()))
tasks.append(asyncio.create_task(stop_evt.wait()))
await asyncio.gather(*tasks, return_exceptions=True)
try:
await serve_forever()
except KeyboardInterrupt:
pass
finally:
if bridge:
bridge.stop()
if game_server:
game_server.close()
if http_server:
http_server.close()
session.close()
print("\n[=] session summary")
print(f" decoded messages: {session.decoded_seq}")
print(f" wire packets: {session.wire_seq}")
print(f" chunks: {session.chunk_seq}")
print(f" msg_id mappings: {len(session.msg_id_cache)}")
def main() -> None:
ap = argparse.ArgumentParser(description="Paralogue MITM (proxy + decoder in one)")
ap.add_argument("--no-proxy", action="store_true",
help="skip the TCP proxy; only run the Frida decoder")
ap.add_argument("--no-decoder", action="store_true",
help="skip the Frida decoder; only run the TCP proxy")
ap.add_argument("--inject-items", action="store_true",
help="rewrite S->C BagItemFullS2C to append items "
"1..2000 (client-side visualization only; "
"server-side state unchanged)")
args = ap.parse_args()
proxy_enabled = not args.no_proxy
decoder_enabled = not args.no_decoder
if not (proxy_enabled or decoder_enabled):
print("nothing to do (both proxy and decoder disabled)")
sys.exit(1)
if args.inject_items and not proxy_enabled:
print("--inject-items requires the proxy (do not pass --no-proxy)")
sys.exit(1)
try:
asyncio.run(run(proxy_enabled, decoder_enabled,
inject_items=args.inject_items))
except KeyboardInterrupt:
print("\n[*] stopped")
if __name__ == "__main__":
main()