This repository has been archived by the owner on Jan 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 30
/
kanan.py
469 lines (422 loc) · 16.9 KB
/
kanan.py
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
import frida
import glob
import sys
import getopt
import time
import os
import json
import tempfile
import shutil
import subprocess
import ctypes
import toml
import psutil
import winreg
import keyring
from http import client
from hashlib import sha256, sha512
from binascii import hexlify
from base64 import b64encode
from json import loads, dumps
from subprocess import Popen
from io import StringIO
from pathlib import Path
from getpass import getpass
from sys import argv
def get_login_passport():
# Get the motherboard UUID
uuid = str(subprocess.check_output('wmic csproduct get uuid'))
uuid = uuid[uuid.find("\\n")+2 : -15]
# Get the operating system GUID
guid = winreg.QueryValueEx(winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Cryptography"), "MachineGuid")[0]
# Generate a device ID from UUID and GUID.
device_id = hexlify(sha256(bytes(uuid + guid, 'utf-8')).digest()).decode('utf-8')
# Ask the user for nexon account ID.
email = input("Nexon Account Email: ")
password = keyring.get_password('mabinogi', email)
if password:
password_found = True
else:
print("Password will be stored in Windows Credential Manager.")
password = input("Password: ")
# First HTTPS request.
password_sha512 = hexlify(sha512(bytes(password, 'utf-8')).digest()).decode('utf-8')
headers = {
'Content-Type': 'application/json'
}
body = {
'id': email,
'password': password_sha512,
'auto_login': False,
'client_id': '7853644408',
'scope': 'us.launcher.all',
'device_id': device_id
}
connection = client.HTTPSConnection('www.nexon.com', 443)
connection.request('POST', '/account-webapi/login/launcher', body=dumps(body), headers=headers)
response = loads(connection.getresponse().read().decode('utf-8'))
# Check if the response successfully returned an access token.
if not 'access_token' in response:
print("Account credentials are invalid. Exiting.")
os.system("pause")
sys.exit()
# If the password was not retrieved though keyring, we can save it now.
if not password_found:
keyring.set_password('mabinogi', email, password)
# Unset the credentials. Never leave credentials lingering in memory.
email = None
password = None
# Second HTTPS request.
access_token_b64 = b64encode(bytes(response['access_token'], 'utf-8')).decode('utf-8')
headers = {
'Cookie': 'nxtk=' + response['access_token'] + ';domain=.nexon.net;path=/;',
'Authorization': 'bearer ' + access_token_b64
}
connection = client.HTTPSConnection('api.nexon.io', 443)
connection.request('GET', '/users/me/passport', headers=headers)
response = loads(connection.getresponse().read().decode('utf-8'))
# Return the login passport.
return response['passport']
def usage():
# Prints usage information about how to use kanan.
print("""
usage: python kanan.py <options> [scripts]
If [scripts] is empty then all scripts in the ./scripts directory will be
loaded based on the current configuration.
-h --help
Displays this help text.
-d --debug
Runs each script in debug mode.
-t --test
Runs each script in testing mode where no patches should be applied.
-v --verbose
More information is output to the console by certain scripts.
-a --all
Run all scripts regardless of disabled.txt
-p<id> --process <id>
Attach kanan to a specific instance of mabi given by a process id.
-s --start
kanan will attempt to start mabi for you (useful for multi-client).
-m --morrighan
kanan will attempt to start mabi with Morrighan for you.
""")
class KananApp:
def __init__(self):
self.debug = 'false'
self.test = 'false'
self.verbose = 'false'
self.run_all = 'false'
self.pid = None
self.session = None
self.auto_start = False
self.morrighan = False
self.path = sys.path[0].replace('\\', '\\\\')
self.script_defaults = ''
self.scripts = []
self.scans = []
self.scripts_to_load = [] # From the command line args.
with open('config.toml') as conf:
config = conf.read()
config += '\n'
try:
with open('private.toml') as conf:
config += conf.read()
except FileNotFoundError:
pass
self.config = toml.loads(config)
def on_message(self, message, data):
"""Called when a script sends us a message."""
if message['type'] == 'send':
payload = message['payload']
if isinstance(payload, dict):
if 'signature' in payload:
self.scans.append(payload)
elif 'file' in payload:
with open('./output/' + payload['file'], 'w') as outfile:
print(payload['data'], file=outfile)
elif self.debug == 'true':
print(time.strftime("%I:%M:%S ") + payload)
else:
print(payload)
elif message['type'] == 'error':
print(message['stack'])
def get_option(self, filename, option):
"""Retruns a mods option or None if it doesn't exist"""
modname = os.path.splitext(os.path.basename(filename))[0]
if modname in self.config:
if option in self.config[modname]:
return self.config[modname][option]
else:
print("NOTICE: " + modname + " is missing the '" + option +
"' entry in config.toml")
else:
print("NOTICE: " + modname + " does not have a config.toml entry")
return None
def is_disabled(self, filename):
"""Determines if a filename has been disabled by the user."""
if self.run_all == 'true':
return 'Defaults.js'.casefold() in filename.casefold()
if '.disabled' in filename or 'Defaults.js' in filename:
return True
return self.get_option(filename, 'enable') is False
def is_coalesced(self, filename):
"""Determines if a filename is eligible to be coalesced according to the
user."""
if '.coalesce' in filename:
return True
return self.get_option(filename, 'coalesce')
def is_delayed(self, filename):
"""Determines if a filename is to be loaded last by the user."""
if '.delayed' in filename:
return True
return self.get_option(filename, 'delay')
def _parse_command_line(self):
# Handle command line arguments.
try:
opts, args = getopt.getopt(sys.argv[1:],
'hdp:tvasm',
['help', 'debug', 'pid=', 'test',
'verbose', 'all', 'start',
'morrighan'])
except getopt.GetoptError as err:
print(err)
usage()
sys.exit(2)
for opt, arg in opts:
if opt in ('-h', '--help'):
usage()
sys.exit()
elif opt in ('-d', '--debug'):
self.debug = 'true'
elif opt in ('-p', '--pid'):
self.pid = int(arg)
elif opt in ('-t', '--test'):
self.test = 'true'
elif opt in ('-v', '--verbose'):
self.verbose = 'true'
elif opt in ('-a', '--all'):
self.run_all = 'true'
elif opt in ('-s', '--start'):
self.auto_start = True
elif opt in ('-m', '--morrighan'):
self.morrighan = True
else:
assert False, "Unhandled option"
self.scripts_to_load = args
def _attach(self):
# Attach to Mabinogi.
while ctypes.windll.user32.FindWindowA(b'Mabinogi', None) == 0:
time.sleep(1)
try:
self.session = frida.attach('Client.exe' if self.pid is None else
self.pid)
# Force the use of v8 for modern javascript (only for newer
# versions of frida).
enable_jit = getattr(self.session, 'enable_jit', None)
if callable(enable_jit):
enable_jit()
except frida.ProcessNotFoundError:
print("Couldn't attach to Client.exe.")
print("Make sure you're running kanan as administrator!")
input()
sys.exit()
def _detach(self):
# Detach from Mabinogi.
try:
self.session.detach()
except:
pass
def _load_defaults(self):
# Load Defaults.js and set additional variables that are available to
# every loaded script. The reason we don't load defaults in the
# constructor is because we need to wait till the command line args
# have been parsed.
cfg = json.dumps(self.config)
self.script_defaults = 'var debug = {};\n'.format(self.debug)
self.script_defaults += 'var testing = {};\n'.format(self.test)
self.script_defaults += 'var verbose = {};\n'.format(self.verbose)
self.script_defaults += 'var path = "{}";\n'.format(self.path)
self.script_defaults += 'var config = {};\n'.format(cfg)
with open('./scripts/Defaults.js') as defaults:
self.script_defaults += defaults.read()
def _script_specific_defaults(self, filename):
# Returns defaults that need to be added to each script that are
# specific to that script and therefor cannot be added to
# self.script_defaults
shortname = os.path.basename(filename)
name = os.path.splitext(shortname)[0]
scriptname = 'var scriptName = "{}";\n'.format(shortname)
modname = 'var modName = "{}";\n'.format(name)
return scriptname + modname
def _run_script(self, source):
# Run a single script and add it to the list of scripts.
# Prepend the results of every scan to the source.
if self.debug == 'true':
scans = json.dumps(self.scans)
source = 'var scans = {};\n'.format(scans) + source
script_loaded = False
num_failed_load_attempts = 0
while not script_loaded and num_failed_load_attempts < 3:
try:
script = self.session.create_script(source)
script.on('message', self.on_message)
script.load()
script_loaded = True
except frida.TransportError:
print("Retrying...")
num_failed_load_attempts += 1
if script_loaded:
self.scripts.append(script)
else:
print("Failed to load script!!!")
def _run_scripts(self):
# Loads and runs all the scripts according to the settings.
self._load_defaults()
# If we have a specific list of scripts to load from the command line
# then load those and return.
if self.scripts_to_load:
for filename in self.scripts_to_load:
shortname = os.path.basename(filename)
with open(filename) as script:
source = self.script_defaults
source += self._script_specific_defaults(filename)
source += script.read()
self._run_script(source)
return
coalesced_source = self.script_defaults
for filename in glob.iglob('./scripts/**/*.js', recursive=True):
shortname = os.path.basename(filename)
if self.is_disabled(filename) or self.is_delayed(filename):
continue
with open(filename) as script:
if self.is_coalesced(filename) and self.debug == 'false':
print("Coalescing " + shortname)
specific_defs = self._script_specific_defaults(filename)
coalesced_source += specific_defs
coalesced_source += script.read()
continue
else:
print("Running " + shortname)
source = self.script_defaults
source += self._script_specific_defaults(filename)
source += script.read()
self._run_script(source)
# Execute the coalesced script.
if self.debug == 'false':
print("Running coalesced script...")
self._run_script(coalesced_source)
# Execute delayed scripts.
print("Running delayed scripts...")
for filename in glob.iglob('./scripts/**/*.js', recursive=True):
shortname = os.path.basename(filename)
if self.is_disabled(filename) or not self.is_delayed(filename):
continue
with open(filename) as script:
print("Running " + shortname)
source = self.script_defaults
source += self._script_specific_defaults(filename)
source += script.read()
self._run_script(source)
def _unload_scripts(self):
# Unloads all the loaded scripts and clears the loaded scripts list.
for script in self.scripts:
try:
script.unload()
except:
pass
self.scripts = []
def _process_alive(self, pid):
# Checks if a process with the supplied pid is active.
processes = [line.split() for line in
subprocess.check_output('tasklist').splitlines()]
# Skip the malformed entries at the beginning.
[processes.pop(i) for i in [0, 1, 2]]
pidstr = str(pid).encode('utf-8')
for process in processes:
if process[1] == pidstr:
return True
return False
def _start_mabi(self):
# Starts mabinogi if it can. Hopefully this can be improved so it
# doesn't rely on the config files in the future.
mabidir = Path(self.get_option('AutoStart', 'directory'))
args = self.get_option('AutoStart', 'args')
passport = get_login_passport()
args = args + ' /P:' + passport
if not mabidir.exists():
print("Couldn't find Client.exe in " + str(mabidir))
print("Please make sure the directory is correct in config.toml")
print("Will wait for Client.exe to begin instead.")
return None
mabipath = str(mabidir)
if self.morrighan:
print("Starting Morrighan.exe...")
clientpath = str(mabidir / "Morrighan.exe")
else:
print("Starting Client.exe...")
clientpath = str(mabidir / "Client.exe")
# Try starting mabi.
try:
subprocess.Popen(clientpath + " " + args, cwd=mabipath)
except OSError:
print("Couldn't start Client.exe.")
print("Make sure you're running kanan as administrator!")
input()
sys.exit()
# Now we need to wait until mabi has been unpacked.
# TODO: Figure out a better way please!!!
time.sleep(1)
return get_newest_client_pid()
def run(self):
"""Runs kanan."""
self._parse_command_line()
print("Kanan's Mabinogi Mod")
if self.auto_start:
self.pid = self._start_mabi()
while True:
print("Waiting for Client.exe...")
self._attach()
print("Attached to Client.exe...")
print("Running scripts...")
self._run_scripts()
print("All done!")
if self.pid:
while self._process_alive(self.pid):
time.sleep(1)
else:
while ctypes.windll.user32.FindWindowA(b'Mabinogi', None) != 0:
time.sleep(1)
print("Unloading scripts (patches may stay applied)...")
self._unload_scripts()
print("Detaching from Client.exe...")
self._detach()
if self.pid:
return
def cleanup_tmp_frida_trash():
"""Frida creates a new directory and extracts necessary files each time you
run it. They aren't necessary after the game closes/crashes so we can
delete them here."""
tempdir = Path(tempfile.gettempdir())
for folder in glob.iglob(str(tempdir / 'frida*')):
try:
shutil.rmtree(folder)
except PermissionError:
pass
def get_newest_client_pid():
"""Searches through all the Client.exe's to find the newest one.
Returns -1 if Client.exe is not found."""
time = 0
pid = -1
for proc in psutil.process_iter():
if proc.name() == 'Client.exe':
if time < proc.create_time():
time = proc.create_time()
pid = proc.pid
return pid
def main():
"""The entrypoint for kanan"""
cleanup_tmp_frida_trash()
app = KananApp()
app.run()
if __name__ == "__main__":
main()