forked from reswitched/pegaswitch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
repl.js
executable file
·505 lines (464 loc) · 12 KB
/
repl.js
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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
#!/usr/bin/env node
/* eslint no-mixed-operators: "off" */
require('colors');
const brokenConsole = require('console');
const repl = require('repl');
const events = require('events');
const fs = require('fs');
const path = require('path');
const WebSocket = require('ws');
const History = require('repl.history');
const stringArgv = require('string-argv');
const Table = require('easy-table');
const utils = require('./exploit/utils');
const ee = new events.EventEmitter();
const wss = new WebSocket.Server({ port: 8100 });
const historyPath = path.resolve(__dirname, '.shell_history');
//This is needed to update the output to the console so the writing in start.js shows
console.log('');
let connection = null;
let connections = {};
let nameToAddr = {};
function sendMsg (cmd, args = []) {
connection.send(JSON.stringify({
cmd,
args
}));
}
ee.on('error', function (message) {
brokenConsole.error('ERROR:', message.slice(0, 2));
});
function loadConfig() {
try {
fs.statSync("config.json"); // test existence
return JSON.parse(fs.readFileSync("config.json", "utf-8"));
} catch(e) {
var config = { // default config
};
fs.writeFileSync("config.json", JSON.stringify(config), "utf-8");
return config;
}
}
const fns = {
sp: {
response: 'gotsp',
helptxt: 'Return SP'
},
reboot: {
response: 'rebooting',
helptxt: 'Reboot console'
},
gc: {
response: 'gcran',
helptxt: 'Forcefully run GC'
},
malloc: {
response: 'mallocd',
args: 1,
help: 'malloc <bytes>',
helptxt: 'Allocates space at returned address'
},
free: {
response: 'freed',
wait: false,
args: 1,
help: 'free <address>',
helptxt: 'Frees memory at address allocated by malloc'
},
write4: {
response: 'wrote4',
wait: false,
minArgs: 2,
maxArgs: 3,
help: 'write4 <addr> <data> <offset=0>',
helptxt: 'Writes 4 bytes of data to address'
},
write8: {
response: 'wrote8',
wait: false,
minArgs: 2,
maxArgs: 3,
help: 'write8 <addr> <data> <offset=0>',
helptxt: 'Writes 8 bytes of data to address'
},
read4: {
response: 'rread',
minArgs: 1,
maxArgs: 2,
help: 'read4 <addr> <offset=0>',
helptxt: 'Reads 4 bytes of data from address'
},
read8: {
response: 'rread',
minArgs: 1,
maxArgs: 2,
help: 'read8 <addr> <offset=0>',
helptxt: 'Reads 8 bytes of data from address'
},
readstring: {
response: 'rreadstring',
minArgs: 1,
maxArgs: 2,
help: 'readstring <addr> <bytes=4>',
helptxt: 'Reads data at address and prints as string'
},
eval: {
response: 'evald',
help: 'eval <...code>',
helptxt: 'Evals code on remote console and returns response if applicable. If no arguments are passed it will switch to js shell instead'
},
evalfile: {
response: 'evald',
help: 'evalfile <filename>',
helptxt: 'Evals code read from file',
complete: function (line) {
var args = line.split(' ');
var dirPath = './';
var path = '';
var match = args[1].match(/^.*[/\\]/);
if (match !== null) {
dirPath = path = match[0];
}
var matchPiece = args[1].substr(path.length);
try {
var files = fs.readdirSync(dirPath);
var completions = files.filter((c) => (path + c).startsWith(args[1])).map((c) => fs.lstatSync(dirPath + c).isDirectory() ? c + '/' : c).filter((c) => c.endsWith('/') || c.endsWith('.js'));
return [completions, matchPiece];
} catch (e) {
return [[], line];
}
},
setup: function (args, callback) {
try {
var filepath = path.resolve(__dirname, args[0]);
fs.statSync(filepath);
return [fs.readFileSync(filepath).toString()];
} catch (e) {
return callback(null, 'invalid file ' + e.message);
}
}
},
runnro: {
response: 'rannro',
help: 'runnro <filename>',
helptext: 'Executes the given NRO',
complete: function (line) {
var args = line.split(' ');
var dirPath = './';
var path = '';
var match = args[1].match(/^.*[/\\]/);
if (match !== null) {
dirPath = path = match[0];
}
var matchPiece = args[1].substr(path.length);
try {
var files = fs.readdirSync(dirPath);
var completions = files.filter((c) => (path + c).startsWith(args[1])).map((c) => fs.lstatSync(dirPath + c).isDirectory() ? c + '/' : c).filter((c) => c.endsWith('/') || c.endsWith('.nro'));
return [completions, matchPiece];
} catch (e) {
throw e;
}
},
setup: function (args, callback) {
try {
var filepath = path.resolve(__dirname, args[0]);
fs.statSync(filepath);
return [Array.from(new Uint8Array(fs.readFileSync(filepath).buffer))].concat(args.slice(1));
} catch (e) {
return callback(null, 'invalid file ' + e.message);
}
}
},
nspwn: {
response: 'redirected',
help: 'nspwn <path>',
helptext: 'Redirects Album applet\'s exefs to the given path',
minArgs: 1,
maxArgs: 1
},
enable: {
help: 'enable <property>',
helptxt: 'Set the config property to `true`',
noSend: true,
setup: function (args, callback) {
var config = loadConfig();
config[args[0]] = true;
fs.writeFileSync("config.json", JSON.stringify(config), "utf-8");
console.log("enabled " + args[0] + " (won't take effect until you reconnect switch)");
return callback();
},
complete: function (line) {
var args = line.split(" ");
var completions = Object.keys(loadConfig()).map((c) => args[0] + " " + c);
return [args[1].length ? completions.filter((k) => k.startsWith(line) && k.length > 0) : completions, line];
}
},
disable: {
help: 'disable <property>',
helptxt: 'Set the config property to `false`',
noSend: true,
setup: function (args, callback) {
var config = loadConfig();
config[args[0]] = false;
fs.writeFileSync("config.json", JSON.stringify(config), "utf-8");
console.log("disabled " + args[0] + " (won't take effect until you reconnect switch)");
return callback();
},
complete: function (line) {
var args = line.split(" ");
var completions = Object.keys(loadConfig()).map((c) => args[0] + " " + c);
return [args[1].length ? completions.filter((k) => k.startsWith(line) && k.length > 0) : completions, line];
}
},
select: {
help: 'select <serial>|<name>|none',
helptxt: 'Select a different Switch to send commands to',
noSend: true,
setup(args, callback) {
if(args[0] == "none") {
selectConsole(null);
} else {
var ws = lookupConnection(args[0]);
if(ws) {
selectConsole(ws.serial);
} else {
utils.log(("No such console '" + args[0] + "'. Try `consoles` to get a list of connected consoles").bold);
}
}
return callback();
},
complete(line) {
var args = line.split(" ");
var names = Object.keys(connections).filter((k) => connections[k]).concat(Object.keys(nameToAddr)).filter(lookupConnection);
var completions = names;
completions.push("none");
return [args[1].length ? completions.filter((k) => k.startsWith(args[1]) && k.length > 0) : completions, args[1]];
}
},
consoles: {
help: 'consoles',
helptxt: 'List connected consoles',
noSend: true,
setup(args, callback) {
var t = new Table();
Object.values(connections).forEach((ws) => {
if(ws != null) {
t.cell("Serial Number", ws.serial);
t.cell("Version", ws.fwVersion);
t.cell("Name", ws.name || "<unnamed>");
t.newRow();
}
});
console.log(t.toString());
return callback();
}
},
exit: {
help: 'exit',
helptxt: 'Close REPL and shut off server',
noSend: true,
setup(args, callback) {
process.exit();
}
},
quit: {
help: 'quit',
helptxt: 'Close REPL and shut off server',
noSend: true,
setup(args, callback) {
process.exit();
}
}
};
function showHelp (callback) {
for (let k in fns) {
let out = `${k.bold}: ${fns[k].helptxt}`;
if (fns[k].help) {
out += ` (${fns[k].help})`.dim;
}
console.log(out);
}
console.log();
return callback();
}
let _; // last value reg
let isJavascript = false;
function defaultHandler (saveVal, callback) {
return function (response) {
if (saveVal) {
_ = response;
}
return callback(null, response);
};
}
function handle (input, context, filename, callback) {
let tmp = input.replace(/\n$/, '');
if (isJavascript){
if(tmp.trim()==''){
isJavascript = false;
setPrompt();
return callback();
}
tmp = "eval "+tmp;
}
//for an eval with no arguments, just do js shell
if(tmp.trim()=="eval"){
isJavascript = true;
setPrompt();
console.log("Entered javascript interpreter. Hit [Enter] to exit");
return callback();
}
if (!tmp) {
return callback();
}
let saveVal = false;
let args = tmp.trimLeft().split(' ');
let cmd = args.shift();
if (cmd === '_') {
return callback(null, _);
} else if (cmd === 'help') {
return showHelp(callback);
} else if (cmd === '$') {
// if prefixed with $ we
// save the response to _
saveVal = true;
cmd = args.shift();
}
for (let i = 0; i < args.length; i++) {
if (args[i] === '_') {
if (_ === undefined) {
return callback(null, '_ has no value');
}
args[i] = _;
}
}
let fn = fns[cmd];
if (!fn) {
return callback(null, 'unknown cmd');
}
if (
fn.args !== undefined && fn.args !== args.length ||
fn.minArgs !== undefined && fn.minArgs > args.length ||
fn.maxArgs !== undefined && args.length > fn.maxArgs
) {
return callback(null, fn.help);
}
if (!connection && !fn.noSend) {
if(Object.values(connections).some((c) => c !== null)) {
console.log("No console selected (use the `select` command).".bold);
r.prompt();
} else {
console.log("No consoles connected.".bold);
r.prompt();
}
return;
}
if (fn.setup) {
args = fn.setup(args, callback);
if (!args) {
return;
}
}
if (!fn.noSend) {
var handle = fn.handler ? fn.handler(args, callback) : defaultHandler(saveVal, callback);
ee.once(fn.response, handle);
sendMsg(cmd, args);
if (fn.wait === false) {
ee.removeListener(fn.response, handle);
return callback();
}
}
}
function complete (line) {
var args = line.split(' ');
var cmd = args.shift();
if (args.length === 0) {
return [cmd.length ? Object.keys(fns).map((name) => name + ' ').filter((fn) => fn.startsWith(cmd)) : Object.keys(fns), line];
} else {
if (fns[cmd] && fns[cmd].complete) {
return fns[cmd].complete(line);
} else {
return [[], line];
}
}
}
const r = repl.start({
prompt: '',
eval: handle,
completer: complete
});
History(r, historyPath);
function consoleName(serial) {
return serial;
}
function setPrompt() {
var jsPart = isJavascript ? "/js" : "";
if(connection) {
r.setPrompt(("switch '" + consoleName(connection.serial) + "' (" + connection.fwVersion + ")" + jsPart).cyan + "> ");
} else {
r.setPrompt(("switch" + jsPart).cyan + "> ");
}
}
function lookupConnection(name) {
if(connections[name]) { // serial number
return connections[name];
}
if(nameToAddr[name]) { // name
return connections[nameToAddr[name]];
}
return null;
}
function selectConsole(serial) {
if(serial == null) {
connection = null;
setPrompt();
r.prompt(true);
} else {
connection = connections[serial];
setPrompt();
r.prompt(true);
}
}
wss.on('connection', function (ws) {
ws.on('close', function () {
if(ws.serial && connections[ws.serial] == ws) {
connections[ws.serial] = null;
console.log();
console.log("Switch '" + consoleName(ws.serial) + "' (" + ws.fwVersion + ") disconnected.");
if(connection === ws) {
selectConsole(null);
} else {
r.prompt(true);
}
}
});
ws.on('message', function(data) {
data = JSON.parse(data);
const type = data.type;
const response = data.response;
if(type == "identification") {
var u8 = new Uint8Array(0x18);
var u32 = new Uint32Array(u8.buffer);
for(var i = 0; i < data.serial.length; i++) {
u32[i] = data.serial[i];
}
var serial = String.fromCharCode.apply(null, u8);
ws.serial = serial;
ws.fwVersion = data.version;
connections[serial] = ws;
console.log();
console.log("Switch '" + consoleName(serial) + "' (" + data.version + ") connected.");
if(connection === null || connection.serial == serial) {
selectConsole(serial);
} else {
r.prompt(true);
}
} else {
ee.emit(type, response, ws.serial);
}
});
});
r.on('exit', () => {
process.exit();
});
selectConsole(null);