-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnm_codec.py
More file actions
261 lines (206 loc) · 8.97 KB
/
nm_codec.py
File metadata and controls
261 lines (206 loc) · 8.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
#!/usr/bin/env python3
"""
NMRunParamDLL.dll codec — pure Python clone.
Reverse-engineered from NMRunParamDLL.dll v1.x (NetMarble, used by ChaguChagu/Goley).
Implements the launcher → game IPC envelope:
* CMDLINE = "<RegionAuth> <KEY24>" (24-byte ASCII key)
* ENV VARS = NMRunEnv_ENUM + chunk vars (pipe-delim names) (concatenated hex)
Pipeline:
plaintext "K1=V1;<<grp=>>;K2=V2;" --PAD--> N*8 bytes --3DES-EDE3 CBC--> ciphertext --HEX--> hex blob
Cipher: 3DES-EDE3 (EDE pattern, 3 independent 8-byte sub-keys), CBC mode.
Key: 24-byte ASCII string, NUL-terminated, SPACE-padded if shorter than 24.
IV: first 8 bytes of the 24-byte key (= sub-key #1).
Pad: count-byte (PKCS5-like) padding to next 8-byte boundary.
NB: if plaintext is *already* multiple of 8, NO padding is added.
Usage:
python nm_codec.py spawn --path "C:\\Joygame\\Goley\\BinaryTr\\Goley_.exe"
"""
from __future__ import annotations
import argparse
import os
import subprocess
import sys
from pathlib import Path
try:
from pyDes import des, ECB, CBC, PAD_NORMAL # type: ignore
except ImportError:
print("WARNING: Installing pyDes dynamically...", file=sys.stderr)
subprocess.run([sys.executable, "-m", "pip", "install", "pyDes"], check=True)
from pyDes import des, ECB, CBC, PAD_NORMAL # type: ignore
# ---------- key handling ---------- #
def normalize_key(s: str | bytes) -> bytes:
"""Map any user key string to the canonical 24-byte form the DLL would use.
Matches sub_1000DA50 in NMRunParamDLL.dll:
* Copy first 24 bytes verbatim (stopping at NUL).
* Space-pad the remainder up to 24 bytes.
"""
if isinstance(s, str):
s = s.encode("latin1", errors="replace")
s = s.split(b"\0", 1)[0][:24]
return s + b" " * (24 - len(s))
# ---------- 3DES-EDE3 CBC ---------- #
def _des_ks(k8: bytes, encrypt: bool) -> des:
"""Single DES key (ECB, no padding — caller handles CBC + padding)."""
return des(k8, ECB, padmode=PAD_NORMAL)
def _block_encrypt(key24: bytes, block8: bytes) -> bytes:
"""3DES-EDE3 encrypt one 8-byte block (no chaining)."""
k1, k2, k3 = key24[0:8], key24[8:16], key24[16:24]
out = _des_ks(k1, True).encrypt(block8, padmode=PAD_NORMAL)
out = _des_ks(k2, False).decrypt(out, padmode=PAD_NORMAL)
out = _des_ks(k3, True).encrypt(out, padmode=PAD_NORMAL)
return out
def _block_decrypt(key24: bytes, block8: bytes) -> bytes:
"""3DES-EDE3 decrypt one 8-byte block (no chaining)."""
k1, k2, k3 = key24[0:8], key24[8:16], key24[16:24]
out = _des_ks(k3, False).decrypt(block8, padmode=PAD_NORMAL)
out = _des_ks(k2, True).encrypt(out, padmode=PAD_NORMAL)
out = _des_ks(k1, False).decrypt(out, padmode=PAD_NORMAL)
return out
def cbc_encrypt(key24: bytes, plaintext: bytes, iv: bytes | None = None) -> bytes:
iv = iv if iv is not None else key24[:8]
pt = _apply_padding(plaintext)
ct = bytearray()
prev = iv
for i in range(0, len(pt), 8):
block = bytes(a ^ b for a, b in zip(pt[i:i + 8], prev))
enc = _block_encrypt(key24, block)
ct.extend(enc)
prev = enc
return bytes(ct)
def cbc_decrypt(key24: bytes, ciphertext: bytes, iv: bytes | None = None) -> bytes:
iv = iv if iv is not None else key24[:8]
assert len(ciphertext) % 8 == 0, "ciphertext must be multiple of 8 bytes"
pt = bytearray()
prev = iv
for i in range(0, len(ciphertext), 8):
cblock = ciphertext[i:i + 8]
dec = _block_decrypt(key24, cblock)
pt.extend(a ^ b for a, b in zip(dec, prev))
prev = cblock
return _strip_padding(bytes(pt))
# ---------- padding ---------- #
def _apply_padding(data: bytes) -> bytes:
rem = len(data) % 8
if rem == 0:
return data
pad_n = 8 - rem
return data + bytes([pad_n] * pad_n)
def _strip_padding(data: bytes) -> bytes:
if not data:
return data
last = data[-1]
if 0 < last < 8 and data[-last:] == bytes([last] * last):
return data[:-last]
return data
# ---------- KV envelope ---------- #
def kv_serialize(params: dict[str, str], groups: dict[str, dict[str, str]] | None = None) -> bytes:
parts = [f"{k}={v}" for k, v in params.items()]
for grp, kv in (groups or {}).items():
parts.append(f"<<{grp}=>>")
parts.extend(f"{k}={v}" for k, v in kv.items())
return (";".join(parts) + ";").encode("latin1", errors="replace")
def kv_parse(blob: bytes) -> tuple[dict[str, str], dict[str, dict[str, str]]]:
text = blob.decode("latin1", errors="replace")
root: dict[str, str] = {}
groups: dict[str, dict[str, str]] = {}
current = root
for entry in text.split(";"):
entry = entry.lstrip(" ")
if not entry:
continue
if entry.startswith("<<") and entry.endswith("=>>"):
name = entry[2:-3]
current = groups.setdefault(name, {})
continue
if "=" not in entry:
continue
k, v = entry.split("=", 1)
current[k] = v
return root, groups
# ---------- high-level ---------- #
def encode(plaintext: bytes, key: str | bytes) -> str:
key24 = normalize_key(key)
ct = cbc_encrypt(key24, plaintext)
return ct.hex().upper()
def decode(hex_blob: str, key: str | bytes) -> bytes:
key24 = normalize_key(key)
ct = bytes.fromhex(hex_blob)
return cbc_decrypt(key24, ct)
# ---------- CLI ---------- #
def _params_from_args(items: list[str]) -> dict[str, str]:
out: dict[str, str] = {}
for it in items:
if "=" not in it:
raise SystemExit(f"bad -p arg (need KEY=VAL): {it!r}")
k, v = it.split("=", 1)
out[k] = v
return out
def _spawn(exe_path: str, region: str, key: str, params: dict[str, str],
chunk_var: str = "NMRP_DATA", no_launch: bool = False) -> None:
plain = kv_serialize(params)
hex_blob = encode(plain, key)
env = os.environ.copy()
env["NMRunEnv_ENUM"] = chunk_var
env[chunk_var] = hex_blob
key24 = normalize_key(key).decode("latin1")
cmdline = f'"{exe_path}" {region}Auth {key24}'
cwd = str(Path(exe_path).parent)
print(f"[i] target exe: {exe_path}")
print(f"[i] working dir: {cwd}")
print(f"[i] cmdline: {cmdline!r}")
print(f"[i] env NMRunEnv_ENUM = {chunk_var!r}")
print(f"[i] env {chunk_var} = {hex_blob[:60]}... ({len(hex_blob)} chars)")
print(f"[i] plaintext: {plain!r}")
if no_launch:
return
subprocess.Popen(cmdline, env=env, cwd=cwd, shell=False)
print(f"[+] launched successfully")
def main(argv):
p = argparse.ArgumentParser(description="NMRunParamDLL.dll codec & launcher")
sub = p.add_subparsers(dest="cmd", required=True)
pe = sub.add_parser("encode", help="plaintext params → hex blob")
pe.add_argument("--key", required=True, help="24-byte ASCII key (space-padded if shorter)")
pe.add_argument("-p", "--param", action="append", default=[], help="KEY=VAL (repeatable)")
pd = sub.add_parser("decode", help="hex blob → plaintext params")
pd.add_argument("--key", required=True)
pd.add_argument("blob")
ps = sub.add_parser("spawn", help="set env vars + launch Goley_.exe")
ps.add_argument("--path", default=r"C:\Joygame\Goley\BinaryTr\Goley_.exe", help="Path to Goley_.exe")
ps.add_argument("--key", default="GoleyTest1234567890ABCD")
ps.add_argument("--region", default="TR", choices=["NM", "KR", "TR", "ID", "VN", "GL"])
ps.add_argument("-p", "--param", action="append", default=[
"SERVER_IP=127.0.0.1", "SERVICE=goley", "OVERRIDE_LANGUAGE=TK"
])
ps.add_argument("--no-launch", action="store_true",
help="print env+cmdline only; don't actually start the game")
pt = sub.add_parser("test", help="self-test: encode then decode and check equality")
pt.add_argument("--key", default="TestKey1")
args = p.parse_args(argv)
if args.cmd == "encode":
params = _params_from_args(args.param)
plain = kv_serialize(params)
blob = encode(plain, args.key)
print(blob)
elif args.cmd == "decode":
plain = decode(args.blob, args.key)
root, groups = kv_parse(plain)
print(f"raw plaintext: {plain!r}")
print(f"root: {root}")
if groups:
print(f"groups: {groups}")
elif args.cmd == "spawn":
params = _params_from_args(args.param)
_spawn(args.path, args.region, args.key, params, no_launch=args.no_launch)
elif args.cmd == "test":
params = {"SERVER_IP": "127.0.0.1", "SERVICE": "goley", "OVERRIDE_LANGUAGE": "TK"}
plain = kv_serialize(params)
blob = encode(plain, args.key)
print(f"plaintext: {plain!r}")
print(f"key24: {normalize_key(args.key)!r}")
print(f"hex blob: {blob}")
roundtrip = decode(blob, args.key)
print(f"roundtrip: {roundtrip!r}")
assert roundtrip == plain, "ROUNDTRIP FAILED"
print("OK — roundtrip verified")
if __name__ == "__main__":
main(sys.argv[1:])