-
Notifications
You must be signed in to change notification settings - Fork 499
/
meshcore.js
2321 lines (2189 loc) · 125 KB
/
meshcore.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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2018-2019 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
process.on('uncaughtException', function (ex) {
require('MeshAgent').SendCommand({ "action": "msg", "type": "console", "value": "uncaughtException1: " + ex });
});
// NOTE: This seems to cause big problems, don't enable the debugger in the server's meshcore.
//attachDebugger({ webport: 9999, wait: 1 }).then(function (prt) { console.log('Point Browser for Debug to port: ' + prt); });
// Mesh Rights
var MNG_ERROR = 65;
var MESHRIGHT_EDITMESH = 1;
var MESHRIGHT_MANAGEUSERS = 2;
var MESHRIGHT_MANAGECOMPUTERS = 4;
var MESHRIGHT_REMOTECONTROL = 8;
var MESHRIGHT_AGENTCONSOLE = 16;
var MESHRIGHT_SERVERFILES = 32;
var MESHRIGHT_WAKEDEVICE = 64;
var MESHRIGHT_SETNOTES = 128;
var MESHRIGHT_REMOTEVIEW = 256;
var MESHRIGHT_NOTERMINAL = 512;
var MESHRIGHT_NOFILES = 1024;
var MESHRIGHT_NOAMT = 2048;
var MESHRIGHT_LIMITEDINPUT = 4096;
function createMeshCore(agent)
{
var obj = {};
if (process.platform == 'darwin' && !process.versions)
{
// This is an older MacOS Agent, so we'll need to check the service definition so that Auto-Update will function correctly
var child = require('child_process').execFile('/bin/sh', ['sh']);
child.stdout.str = '';
child.stdout.on('data', function (chunk) { this.str += chunk.toString(); });
child.stdin.write("cat /Library/LaunchDaemons/meshagent_osx64_LaunchDaemon.plist | tr '\n' '\.' | awk '{split($0, a, \"<key>KeepAlive</key>\"); split(a[2], b, \"<\"); split(b[2], c, \">\"); ");
child.stdin.write(" if(c[1]==\"dict\"){ split(a[2], d, \"</dict>\"); if(split(d[1], truval, \"<true/>\")>1) { split(truval[1], kn1, \"<key>\"); split(kn1[2], kn2, \"</key>\"); print kn2[1]; } }");
child.stdin.write(" else { split(c[1], ka, \"/\"); if(ka[1]==\"true\") {print \"ALWAYS\";} } }'\nexit\n");
child.waitExit();
if (child.stdout.str.trim() == 'Crashed')
{
child = require('child_process').execFile('/bin/sh', ['sh']);
child.stdout.str = '';
child.stdout.on('data', function (chunk) { this.str += chunk.toString(); });
child.stdin.write("launchctl list | grep 'meshagent' | awk '{ if($3==\"meshagent\"){print $1;}}'\nexit\n");
child.waitExit();
if (parseInt(child.stdout.str.trim()) == process.pid)
{
// The currently running MeshAgent is us, so we can continue with the update
var plist = require('fs').readFileSync('/Library/LaunchDaemons/meshagent_osx64_LaunchDaemon.plist').toString();
var tokens = plist.split('<key>KeepAlive</key>');
if (tokens[1].split('>')[0].split('<')[1] == 'dict')
{
var tmp = tokens[1].split('</dict>');
tmp.shift();
tokens[1] = '\n <true/>' + tmp.join('</dict>');
tokens = tokens.join('<key>KeepAlive</key>');
require('fs').writeFileSync('/Library/LaunchDaemons/meshagent_osx64_LaunchDaemon.plist', tokens);
var fix = '';
fix += ("function macosRepair()\n");
fix += ("{\n");
fix += (" var child = require('child_process').execFile('/bin/sh', ['sh']);\n");
fix += (" child.stdout.str = '';\n");
fix += (" child.stdout.on('data', function (chunk) { this.str += chunk.toString(); });\n");
fix += (" child.stderr.on('data', function (chunk) { });\n");
fix += (" child.stdin.write('launchctl unload /Library/LaunchDaemons/meshagent_osx64_LaunchDaemon.plist\\n');\n");
fix += (" child.stdin.write('launchctl load /Library/LaunchDaemons/meshagent_osx64_LaunchDaemon.plist\\n');\n");
fix += (" child.stdin.write('rm /Library/LaunchDaemons/meshagentRepair.plist\\n');\n");
fix += (" child.stdin.write('rm " + process.cwd() + "/macosRepair.js\\n');\n");
fix += (" child.stdin.write('launchctl stop meshagentRepair\\nexit\\n');\n");
fix += (" child.waitExit();\n");
fix += ("}\n");
fix += ("macosRepair();\n");
fix += ("process.exit();\n");
require('fs').writeFileSync(process.cwd() + '/macosRepair.js', fix);
var plist = '<?xml version="1.0" encoding="UTF-8"?>\n';
plist += '<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n';
plist += '<plist version="1.0">\n';
plist += ' <dict>\n';
plist += ' <key>Label</key>\n';
plist += (' <string>meshagentRepair</string>\n');
plist += ' <key>ProgramArguments</key>\n';
plist += ' <array>\n';
plist += (' <string>' + process.execPath + '</string>\n');
plist += ' <string>macosRepair.js</string>\n';
plist += ' </array>\n';
plist += ' <key>WorkingDirectory</key>\n';
plist += (' <string>' + process.cwd() + '</string>\n');
plist += ' <key>RunAtLoad</key>\n';
plist += ' <true/>\n';
plist += ' </dict>\n';
plist += '</plist>';
require('fs').writeFileSync('/Library/LaunchDaemons/meshagentRepair.plist', plist);
child = require('child_process').execFile('/bin/sh', ['sh']);
child.stdout.str = '';
child.stdout.on('data', function (chunk) { this.str += chunk.toString(); });
child.stdin.write("launchctl load /Library/LaunchDaemons/meshagentRepair.plist\nexit\n");
child.waitExit();
}
}
}
}
// Create Secure IPC for Diagnostic Agent Communications
obj.DAIPC = require('net').createServer();
if (process.platform != 'win32') { try { require('fs').unlinkSync(process.cwd() + '/DAIPC'); } catch (ee) { } }
obj.DAIPC.IPCPATH = process.platform == 'win32' ? ('\\\\.\\pipe\\' + require('_agentNodeId')() + '-DAIPC') : (process.cwd() + '/DAIPC');
try { obj.DAIPC.listen({ path: obj.DAIPC.IPCPATH }); } catch (e) { }
obj.DAIPC.on('connection', function (c)
{
c._send = function (j)
{
var data = JSON.stringify(j);
var packet = Buffer.alloc(data.length + 4);
packet.writeUInt32LE(data.length + 4, 0);
Buffer.from(data).copy(packet, 4);
this.end(packet);
};
this._daipc = c;
c.parent = this;
c.on('end', function () { console.log('Connection Closed'); this.parent._daipc = null; });
c.on('data', function (chunk)
{
if (chunk.length < 4) { this.unshift(chunk); return; }
var len = chunk.readUInt32LE(0);
if (len > 8192) { this.parent._daipc = null; this.end(); return; }
if (chunk.length < len) { this.unshift(chunk); return; }
var data = chunk.slice(4, len);
try
{
data = JSON.parse(data.toString());
}
catch(de)
{
this.parent._daipc = null; this.end(); return;
}
if (!data.cmd) { this.parent._daipc = null; this.end(); return; }
try
{
switch(data.cmd)
{
case 'query':
switch(data.value)
{
case 'connection':
data.result = require('MeshAgent').ConnectedServer;
this._send(data);
break;
}
break;
default:
this.parent._daipc = null;
this.end();
return;
}
}
catch(xe)
{
this.parent._daipc = null; this.end(); return;
}
});
});
function diagnosticAgent_uninstall()
{
require('service-manager').manager.uninstallService('meshagentDiagnostic');
require('task-scheduler').delete('meshagentDiagnostic/periodicStart');
};
function diagnosticAgent_installCheck(install)
{
try
{
var diag = require('service-manager').manager.getService('meshagentDiagnostic');
return (diag);
}
catch (e)
{
}
if (!install) { return (null); }
var svc = null;
try
{
require('service-manager').manager.installService(
{
name: 'meshagentDiagnostic',
displayName: 'Mesh Agent Diagnostic Service',
description: 'Mesh Agent Diagnostic Service',
servicePath: process.execPath,
parameters: ['-recovery']
//files: [{ newName: 'diagnostic.js', _buffer: Buffer.from('LyoNCkNvcHlyaWdodCAyMDE5IEludGVsIENvcnBvcmF0aW9uDQoNCkxpY2Vuc2VkIHVuZGVyIHRoZSBBcGFjaGUgTGljZW5zZSwgVmVyc2lvbiAyLjAgKHRoZSAiTGljZW5zZSIpOw0KeW91IG1heSBub3QgdXNlIHRoaXMgZmlsZSBleGNlcHQgaW4gY29tcGxpYW5jZSB3aXRoIHRoZSBMaWNlbnNlLg0KWW91IG1heSBvYnRhaW4gYSBjb3B5IG9mIHRoZSBMaWNlbnNlIGF0DQoNCiAgICBodHRwOi8vd3d3LmFwYWNoZS5vcmcvbGljZW5zZXMvTElDRU5TRS0yLjANCg0KVW5sZXNzIHJlcXVpcmVkIGJ5IGFwcGxpY2FibGUgbGF3IG9yIGFncmVlZCB0byBpbiB3cml0aW5nLCBzb2Z0d2FyZQ0KZGlzdHJpYnV0ZWQgdW5kZXIgdGhlIExpY2Vuc2UgaXMgZGlzdHJpYnV0ZWQgb24gYW4gIkFTIElTIiBCQVNJUywNCldJVEhPVVQgV0FSUkFOVElFUyBPUiBDT05ESVRJT05TIE9GIEFOWSBLSU5ELCBlaXRoZXIgZXhwcmVzcyBvciBpbXBsaWVkLg0KU2VlIHRoZSBMaWNlbnNlIGZvciB0aGUgc3BlY2lmaWMgbGFuZ3VhZ2UgZ292ZXJuaW5nIHBlcm1pc3Npb25zIGFuZA0KbGltaXRhdGlvbnMgdW5kZXIgdGhlIExpY2Vuc2UuDQoqLw0KDQp2YXIgaG9zdCA9IHJlcXVpcmUoJ3NlcnZpY2UtaG9zdCcpLmNyZWF0ZSgnbWVzaGFnZW50RGlhZ25vc3RpYycpOw0KdmFyIFJlY292ZXJ5QWdlbnQgPSByZXF1aXJlKCdNZXNoQWdlbnQnKTsNCg0KaG9zdC5vbignc2VydmljZVN0YXJ0JywgZnVuY3Rpb24gKCkNCnsNCiAgICBjb25zb2xlLnNldERlc3RpbmF0aW9uKGNvbnNvbGUuRGVzdGluYXRpb25zLkxPR0ZJTEUpOw0KICAgIGhvc3Quc3RvcCA9IGZ1bmN0aW9uKCkNCiAgICB7DQogICAgICAgIHJlcXVpcmUoJ3NlcnZpY2UtbWFuYWdlcicpLm1hbmFnZXIuZ2V0U2VydmljZSgnbWVzaGFnZW50RGlhZ25vc3RpYycpLnN0b3AoKTsNCiAgICB9DQogICAgUmVjb3ZlcnlBZ2VudC5vbignQ29ubmVjdGVkJywgZnVuY3Rpb24gKHN0YXR1cykNCiAgICB7DQogICAgICAgIGlmIChzdGF0dXMgPT0gMCkNCiAgICAgICAgew0KICAgICAgICAgICAgY29uc29sZS5sb2coJ0RpYWdub3N0aWMgQWdlbnQ6IFNlcnZlciBjb25uZWN0aW9uIGxvc3QuLi4nKTsNCiAgICAgICAgICAgIHJldHVybjsNCiAgICAgICAgfQ0KICAgICAgICBjb25zb2xlLmxvZygnRGlhZ25vc3RpYyBBZ2VudDogQ29ubmVjdGlvbiBFc3RhYmxpc2hlZCB3aXRoIFNlcnZlcicpOw0KICAgICAgICBzdGFydCgpOw0KICAgIH0pOw0KfSk7DQpob3N0Lm9uKCdub3JtYWxTdGFydCcsIGZ1bmN0aW9uICgpDQp7DQogICAgaG9zdC5zdG9wID0gZnVuY3Rpb24gKCkNCiAgICB7DQogICAgICAgIHByb2Nlc3MuZXhpdCgpOw0KICAgIH0NCiAgICBjb25zb2xlLmxvZygnTm9uIFNlcnZpY2UgTW9kZScpOw0KICAgIFJlY292ZXJ5QWdlbnQub24oJ0Nvbm5lY3RlZCcsIGZ1bmN0aW9uIChzdGF0dXMpDQogICAgew0KICAgICAgICBpZiAoc3RhdHVzID09IDApDQogICAgICAgIHsNCiAgICAgICAgICAgIGNvbnNvbGUubG9nKCdEaWFnbm9zdGljIEFnZW50OiBTZXJ2ZXIgY29ubmVjdGlvbiBsb3N0Li4uJyk7DQogICAgICAgICAgICByZXR1cm47DQogICAgICAgIH0NCiAgICAgICAgY29uc29sZS5sb2coJ0RpYWdub3N0aWMgQWdlbnQ6IENvbm5lY3Rpb24gRXN0YWJsaXNoZWQgd2l0aCBTZXJ2ZXInKTsNCiAgICAgICAgc3RhcnQoKTsNCiAgICB9KTsNCn0pOw0KaG9zdC5vbignc2VydmljZVN0b3AnLCBmdW5jdGlvbiAoKSB7IHByb2Nlc3MuZXhpdCgpOyB9KTsNCmhvc3QucnVuKCk7DQoNCg0KZnVuY3Rpb24gc3RhcnQoKQ0Kew0KDQp9Ow0K', 'base64') }]
});
svc = require('service-manager').manager.getService('meshagentDiagnostic');
}
catch (e)
{
return (null);
}
var proxyConfig = require('global-tunnel').proxyConfig;
var cert = require('MeshAgent').GenerateAgentCertificate('CN=MeshNodeDiagnosticCertificate');
var nodeid = require('tls').loadCertificate(cert.root).getKeyHash().toString('base64');
ddb = require('SimpleDataStore').Create(svc.appWorkingDirectory().replace('\\', '/') + '/meshagentDiagnostic.db');
ddb.Put('disableUpdate', '1');
ddb.Put('MeshID', Buffer.from(require('MeshAgent').ServerInfo.MeshID, 'hex'));
ddb.Put('ServerID', require('MeshAgent').ServerInfo.ServerID);
ddb.Put('MeshServer', require('MeshAgent').ServerInfo.ServerUri);
if (cert.root.pfx) { ddb.Put('SelfNodeCert', cert.root.pfx); }
if (cert.tls) { ddb.Put('SelfNodeTlsCert', cert.tls.pfx); }
if (proxyConfig)
{
ddb.Put('WebProxy', proxyConfig.host + ':' + proxyConfig.port);
}
else
{
ddb.Put('ignoreProxyFile', '1');
}
require('MeshAgent').SendCommand({ action: 'diagnostic', value: { command: 'register', value: nodeid } });
require('MeshAgent').SendCommand({ action: 'msg', type: 'console', value: 'Diagnostic Agent Registered [' + nodeid.length + '/' + nodeid + ']' });
delete ddb;
// Set a recurrent task, to run the Diagnostic Agent every 2 days
require('task-scheduler').create({name: 'meshagentDiagnostic/periodicStart', daily: 2, time: require('tls').generateRandomInteger('0', '23') + ':' + require('tls').generateRandomInteger('0', '59').padStart(2, '0'), service: 'meshagentDiagnostic'});
//require('task-scheduler').create({ name: 'meshagentDiagnostic/periodicStart', daily: '1', time: '17:16', service: 'meshagentDiagnostic' });
return (svc);
}
/*
function borderController() {
this.container = null;
this.Start = function Start(user) {
if (this.container == null) {
if (process.platform == 'win32') {
try {
this.container = require('ScriptContainer').Create({ processIsolation: 1, sessionId: user.SessionId });
} catch (ex) {
this.container = require('ScriptContainer').Create({ processIsolation: 1 });
}
} else {
this.container = require('ScriptContainer').Create({ processIsolation: 1, sessionId: user.uid });
}
this.container.parent = this;
this.container.addModule('monitor-info', getJSModule('monitor-info'));
this.container.addModule('monitor-border', getJSModule('monitor-border'));
this.container.addModule('promise', getJSModule('promise'));
this.container.once('exit', function (code) { sendConsoleText('Border Process Exited with code: ' + code); this.parent.container = this.parent._container = null; });
this.container.ExecuteString("var border = require('monitor-border'); border.Start();");
}
}
this.Stop = function Stop() {
if (this.container != null) {
this._container = this.container;
this._container.parent = this;
this.container = null;
this._container.exit();
}
}
}
obj.borderManager = new borderController();
*/
// MeshAgent JavaScript Core Module. This code is sent to and running on the mesh agent.
var meshCoreObj = { "action": "coreinfo", "value": "MeshCore v6", "caps": 14 }; // Capability bitmask: 1 = Desktop, 2 = Terminal, 4 = Files, 8 = Console, 16 = JavaScript, 32 = Temporary Agent, 64 = Recovery Agent
// Get the operating system description string
try { require('os').name().then(function (v) { meshCoreObj.osdesc = v; }); } catch (ex) { }
var meshServerConnectionState = 0;
var tunnels = {};
var lastMeInfo = null;
var lastNetworkInfo = null;
var lastPublicLocationInfo = null;
var selfInfoUpdateTimer = null;
var http = require('http');
var net = require('net');
var fs = require('fs');
var rtc = require('ILibWebRTC');
var amt = null;
var processManager = require('process-manager');
var wifiScannerLib = null;
var wifiScanner = null;
var networkMonitor = null;
var amtscanner = null;
var nextTunnelIndex = 1;
var amtPolicy = null;
// Add to the server event log
function MeshServerLog(msg, state) {
if (typeof msg == 'string') { msg = { 'action': 'log', 'msg': msg }; } else { msg.action = 'log'; }
if (state) {
if (state.userid) { msg.userid = state.userid; }
if (state.username) { msg.username = state.username; }
if (state.sessionid) { msg.sessionid = state.sessionid; }
}
mesh.SendCommand(msg);
}
// If we are running in Duktape, agent will be null
if (agent == null) {
// Running in native agent, Import libraries
db = require('SimpleDataStore').Shared();
sha = require('SHA256Stream');
mesh = require('MeshAgent');
childProcess = require('child_process');
if (mesh.hasKVM == 1) { // if the agent is compiled with KVM support
// Check if this computer supports a desktop
try { if ((process.platform == 'win32') || (process.platform == 'darwin') || (require('monitor-info').kvm_x11_support)) { meshCoreObj.caps |= 1; } } catch (ex) { }
}
} else {
// Running in nodejs
meshCoreObj.value += '-NodeJS';
meshCoreObj.caps = 8;
mesh = agent.getMeshApi();
}
mesh.DAIPC = obj.DAIPC;
/*
var AMTScanner = require("AMTScanner");
var scan = new AMTScanner();
scan.on("found", function (data) {
if (typeof data === 'string') {
console.log(data);
} else {
console.log(JSON.stringify(data, null, " "));
}
});
scan.scan("10.2.55.140", 1000);
scan.scan("10.2.55.139-10.2.55.145", 1000);
scan.scan("10.2.55.128/25", 2000);
*/
/*
// Try to load up the network monitor
try {
networkMonitor = require('NetworkMonitor');
networkMonitor.on('change', function () { sendNetworkUpdateNagle(); });
networkMonitor.on('add', function (addr) { sendNetworkUpdateNagle(); });
networkMonitor.on('remove', function (addr) { sendNetworkUpdateNagle(); });
} catch (e) { networkMonitor = null; }
*/
// Try to load up the Intel AMT scanner
try {
var AMTScannerModule = require('amt-scanner');
amtscanner = new AMTScannerModule();
//amtscanner.on('found', function (data) { if (typeof data != 'string') { data = JSON.stringify(data, null, " "); } sendConsoleText(data); });
} catch (ex) { amtscanner = null; }
// Fetch the SMBios Tables
var SMBiosTables = null;
var SMBiosTablesRaw = null;
try {
var SMBiosModule = null;
try { SMBiosModule = require('smbios'); } catch (ex) { }
if (SMBiosModule != null) {
SMBiosModule.get(function (data) {
if (data != null) {
SMBiosTablesRaw = data;
SMBiosTables = require('smbios').parse(data)
if (mesh.isControlChannelConnected) { mesh.SendCommand({ "action": "smbios", "value": SMBiosTablesRaw }); }
// If SMBios tables say that AMT is present, try to connect MEI
if (SMBiosTables.amtInfo && (SMBiosTables.amtInfo.AMT == true)) {
var amtmodule = require('amt-manage');
amt = new amtmodule(mesh, db, true);
amt.onStateChange = function (state) { if (state == 2) { sendPeriodicServerUpdate(1); } }
if (amtPolicy != null) { amt.setPolicy(amtPolicy); }
amt.start();
}
}
});
}
} catch (ex) { sendConsoleText("ex1: " + ex); }
// Try to load up the WIFI scanner
try {
var wifiScannerLib = require('wifi-scanner');
wifiScanner = new wifiScannerLib();
wifiScanner.on('accessPoint', function (data) { sendConsoleText("wifiScanner: " + data); });
} catch (ex) { wifiScannerLib = null; wifiScanner = null; }
// Get our location (lat/long) using our public IP address
var getIpLocationDataExInProgress = false;
var getIpLocationDataExCounts = [0, 0];
function getIpLocationDataEx(func) {
if (getIpLocationDataExInProgress == true) { return false; }
try {
getIpLocationDataExInProgress = true;
getIpLocationDataExCounts[0]++;
var options = http.parseUri("http://ipinfo.io/json");
options.method = 'GET';
http.request(options, function (resp) {
if (resp.statusCode == 200) {
var geoData = '';
resp.data = function (geoipdata) { geoData += geoipdata; };
resp.end = function () {
var location = null;
try {
if (typeof geoData == 'string') {
var result = JSON.parse(geoData);
if (result.ip && result.loc) { location = result; }
}
} catch (e) { }
if (func) { getIpLocationDataExCounts[1]++; func(location); }
}
} else { func(null); }
getIpLocationDataExInProgress = false;
}).end();
return true;
}
catch (e) { return false; }
}
// Remove all Gateway MAC addresses for interface list. This is useful because the gateway MAC is not always populated reliably.
function clearGatewayMac(str) {
if (str == null) return null;
var x = JSON.parse(str);
for (var i in x.netif) { if (x.netif[i].gatewaymac) { delete x.netif[i].gatewaymac } }
return JSON.stringify(x);
}
function getIpLocationData(func) {
// Get the location information for the cache if possible
var publicLocationInfo = db.Get('publicLocationInfo');
if (publicLocationInfo != null) { publicLocationInfo = JSON.parse(publicLocationInfo); }
if (publicLocationInfo == null) {
// Nothing in the cache, fetch the data
getIpLocationDataEx(function (locationData) {
if (locationData != null) {
publicLocationInfo = {};
publicLocationInfo.netInfoStr = lastNetworkInfo;
publicLocationInfo.locationData = locationData;
var x = db.Put('publicLocationInfo', JSON.stringify(publicLocationInfo)); // Save to database
if (func) func(locationData); // Report the new location
} else {
if (func) func(null); // Report no location
}
});
} else {
// Check the cache
if (clearGatewayMac(publicLocationInfo.netInfoStr) == clearGatewayMac(lastNetworkInfo)) {
// Cache match
if (func) func(publicLocationInfo.locationData);
} else {
// Cache mismatch
getIpLocationDataEx(function (locationData) {
if (locationData != null) {
publicLocationInfo = {};
publicLocationInfo.netInfoStr = lastNetworkInfo;
publicLocationInfo.locationData = locationData;
var x = db.Put('publicLocationInfo', JSON.stringify(publicLocationInfo)); // Save to database
if (func) func(locationData); // Report the new location
} else {
if (func) func(publicLocationInfo.locationData); // Can't get new location, report the old location
}
});
}
}
}
// Polyfill String.endsWith
if (!String.prototype.endsWith) {
String.prototype.endsWith = function (searchString, position) {
var subjectString = this.toString();
if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) { position = subjectString.length; }
position -= searchString.length;
var lastIndex = subjectString.lastIndexOf(searchString, position);
return lastIndex !== -1 && lastIndex === position;
};
}
// Polyfill path.join
obj.path = {
join: function () {
var x = [];
for (var i in arguments) {
var w = arguments[i];
if (w != null) {
while (w.endsWith('/') || w.endsWith('\\')) { w = w.substring(0, w.length - 1); }
if (i != 0) {
while (w.startsWith('/') || w.startsWith('\\')) { w = w.substring(1); }
}
x.push(w);
}
}
if (x.length == 0) return '/';
return x.join('/');
}
};
// Replace a string with a number if the string is an exact number
function toNumberIfNumber(x) { if ((typeof x == 'string') && (+parseInt(x) === x)) { x = parseInt(x); } return x; }
// Convert decimal to hex
function char2hex(i) { return (i + 0x100).toString(16).substr(-2).toUpperCase(); }
// Convert a raw string to a hex string
function rstr2hex(input) { var r = '', i; for (i = 0; i < input.length; i++) { r += char2hex(input.charCodeAt(i)); } return r; }
// Convert a buffer into a string
function buf2rstr(buf) { var r = ''; for (var i = 0; i < buf.length; i++) { r += String.fromCharCode(buf[i]); } return r; }
// Convert a hex string to a raw string // TODO: Do this using Buffer(), will be MUCH faster
function hex2rstr(d) {
if (typeof d != "string" || d.length == 0) return '';
var r = '', m = ('' + d).match(/../g), t;
while (t = m.shift()) r += String.fromCharCode('0x' + t);
return r
}
// Convert an object to string with all functions
function objToString(x, p, pad, ret) {
if (ret == undefined) ret = '';
if (p == undefined) p = 0;
if (x == null) { return '[null]'; }
if (p > 8) { return '[...]'; }
if (x == undefined) { return '[undefined]'; }
if (typeof x == 'string') { if (p == 0) return x; return '"' + x + '"'; }
if (typeof x == 'buffer') { return '[buffer]'; }
if (typeof x != 'object') { return x; }
var r = '{' + (ret ? '\r\n' : ' ');
for (var i in x) { if (i != '_ObjectID') { r += (addPad(p + 2, pad) + i + ': ' + objToString(x[i], p + 2, pad, ret) + (ret ? '\r\n' : ' ')); } }
return r + addPad(p, pad) + '}';
}
// Return p number of spaces
function addPad(p, ret) { var r = ''; for (var i = 0; i < p; i++) { r += ret; } return r; }
// Split a string taking into account the quoats. Used for command line parsing
function splitArgs(str) {
var myArray = [], myRegexp = /[^\s"]+|"([^"]*)"/gi;
do { var match = myRegexp.exec(str); if (match != null) { myArray.push(match[1] ? match[1] : match[0]); } } while (match != null);
return myArray;
}
// Parse arguments string array into an object
function parseArgs(argv) {
var results = { '_': [] }, current = null;
for (var i = 1, len = argv.length; i < len; i++) {
var x = argv[i];
if (x.length > 2 && x[0] == '-' && x[1] == '-') {
if (current != null) { results[current] = true; }
current = x.substring(2);
} else {
if (current != null) { results[current] = toNumberIfNumber(x); current = null; } else { results['_'].push(toNumberIfNumber(x)); }
}
}
if (current != null) { results[current] = true; }
return results;
}
// Get server target url with a custom path
function getServerTargetUrl(path) {
var x = mesh.ServerUrl;
//sendConsoleText("mesh.ServerUrl: " + mesh.ServerUrl);
if (x == null) { return null; }
if (path == null) { path = ''; }
x = http.parseUri(x);
if (x == null) return null;
return x.protocol + '//' + x.host + ':' + x.port + '/' + path;
}
// Get server url. If the url starts with "*/..." change it, it not use the url as is.
function getServerTargetUrlEx(url) {
if (url.substring(0, 2) == '*/') { return getServerTargetUrl(url.substring(2)); }
return url;
}
// Send a wake-on-lan packet
function sendWakeOnLan(hexMac) {
var count = 0;
try {
var interfaces = require('os').networkInterfaces();
var magic = 'FFFFFFFFFFFF';
for (var x = 1; x <= 16; ++x) { magic += hexMac; }
var magicbin = Buffer.from(magic, 'hex');
for (var adapter in interfaces) {
if (interfaces.hasOwnProperty(adapter)) {
for (var i = 0; i < interfaces[adapter].length; ++i) {
var addr = interfaces[adapter][i];
if ((addr.family == 'IPv4') && (addr.mac != '00:00:00:00:00:00')) {
var socket = require('dgram').createSocket({ type: "udp4" });
socket.bind({ address: addr.address });
socket.setBroadcast(true);
socket.send(magicbin, 7, "255.255.255.255");
count++;
}
}
}
}
} catch (e) { }
return count;
}
// Handle a mesh agent command
function handleServerCommand(data) {
if (typeof data == 'object') {
// If this is a console command, parse it and call the console handler
switch (data.action) {
case 'msg': {
switch (data.type) {
case 'console': { // Process a console command
if (data.value && data.sessionid) {
MeshServerLog('Processing console command: ' + data.value, data);
var args = splitArgs(data.value);
processConsoleCommand(args[0].toLowerCase(), parseArgs(args), data.rights, data.sessionid);
}
break;
}
case 'tunnel': {
if (data.value != null) { // Process a new tunnel connection request
// Create a new tunnel object
var xurl = getServerTargetUrlEx(data.value);
if (xurl != null) {
var woptions = http.parseUri(xurl);
woptions.rejectUnauthorized = 0;
//sendConsoleText(JSON.stringify(woptions));
//sendConsoleText('TUNNEL: ' + JSON.stringify(data));
var tunnel = http.request(woptions);
tunnel.upgrade = onTunnelUpgrade;
tunnel.on('error', function (e) { sendConsoleText('ERROR: ' + JSON.stringify(e)); });
tunnel.sessionid = data.sessionid;
tunnel.rights = data.rights;
tunnel.consent = data.consent;
tunnel.username = data.username;
tunnel.userid = data.userid;
tunnel.remoteaddr = data.remoteaddr;
tunnel.state = 0;
tunnel.url = xurl;
tunnel.protocol = 0;
tunnel.tcpaddr = data.tcpaddr;
tunnel.tcpport = data.tcpport;
tunnel.udpaddr = data.udpaddr;
tunnel.udpport = data.udpport;
tunnel.end();
// Put the tunnel in the tunnels list
var index = nextTunnelIndex++;
tunnel.index = index;
tunnels[index] = tunnel;
//sendConsoleText('New tunnel connection #' + index + ': ' + tunnel.url + ', rights: ' + tunnel.rights, data.sessionid);
}
}
break;
}
case 'ps': {
// Return the list of running processes
if (data.sessionid) {
processManager.getProcesses(function (plist) {
mesh.SendCommand({ "action": "msg", "type": "ps", "value": JSON.stringify(plist), "sessionid": data.sessionid });
});
}
break;
}
case 'pskill': {
// Kill a process
if (data.value) {
MeshServerLog('Killing process ' + data.value, data);
try { process.kill(data.value); } catch (e) { sendConsoleText("pskill: " + JSON.stringify(e)); }
}
break;
}
case 'services': {
// Return the list of installed services
var services = null;
try { services = require('service-manager').manager.enumerateService(); } catch (e) { }
if (services != null) { mesh.SendCommand({ "action": "msg", "type": "services", "value": JSON.stringify(services), "sessionid": data.sessionid }); }
break;
}
case 'serviceStop': {
// Stop a service
try {
var service = require('service-manager').manager.getService(data.serviceName);
if (service != null) { service.stop(); }
} catch (e) { }
break;
}
case 'serviceStart': {
// Start a service
try {
var service = require('service-manager').manager.getService(data.serviceName);
if (service != null) { service.start(); }
} catch (e) { }
break;
}
/*
case 'serviceRestart': {
// Start a service
try {
var service = require('service-manager').manager.getService(data.serviceName);
if (service != null) { service.stop(); service.start(); }
} catch (e) { }
break;
}
*/
case 'openUrl': {
// Open a local web browser and return success/fail
MeshServerLog('Opening: ' + data.url, data);
sendConsoleText('OpenURL: ' + data.url);
if (data.url) { mesh.SendCommand({ "action": "msg", "type":"openUrl", "url": data.url, "sessionid": data.sessionid, "success": (openUserDesktopUrl(data.url) != null) }); }
break;
}
case 'getclip': {
// Send the load clipboard back to the user
//sendConsoleText('getClip: ' + JSON.stringify(data));
if (require('MeshAgent').isService) {
require('clipboard').dispatchRead().then(function (str) {
if (str) {
MeshServerLog('Getting clipboard content, ' + str.length + ' byte(s)', data);
mesh.SendCommand({ "action": "msg", "type": "getclip", "sessionid": data.sessionid, "data": str });
}
});
} else {
require("clipboard").read().then(function (str) {
if (str) {
MeshServerLog('Getting clipboard content, ' + str.length + ' byte(s)', data);
mesh.SendCommand({ "action": "msg", "type": "getclip", "sessionid": data.sessionid, "data": str });
}
});
}
break;
}
case 'setclip': {
// Set the load clipboard to a user value
//sendConsoleText('setClip: ' + JSON.stringify(data));
if (typeof data.data == 'string') {
MeshServerLog('Setting clipboard content, ' + data.data.length + ' byte(s)', data);
if (typeof data.data == 'string') {
if (require('MeshAgent').isService) { require('clipboard').dispatchWrite(data.data); } else { require("clipboard")(data.data); } // Set the clipboard
mesh.SendCommand({ "action": "msg", "type": "setclip", "sessionid": data.sessionid, "success": true });
}
}
break;
}
default:
// Unknown action, ignore it.
break;
}
break;
}
case 'acmactivate': {
if (amt != null) {
MeshServerLog('Attempting Intel AMT ACM mode activation', data);
amt.setAcmResponse(data);
}
break;
}
case 'wakeonlan': {
// Send wake-on-lan on all interfaces for all MAC addresses in data.macs array. The array is a list of HEX MAC addresses.
sendConsoleText('Server requesting wake-on-lan for: ' + data.macs.join(', '));
for (var i in data.macs) { sendWakeOnLan(data.macs[i]); }
break;
}
case 'poweraction': {
// Server telling us to execute a power action
if ((mesh.ExecPowerState != undefined) && (data.actiontype)) {
var forced = 0;
if (data.forced == 1) { forced = 1; }
data.actiontype = parseInt(data.actiontype);
MeshServerLog('Performing power action=' + data.actiontype + ', forced=' + forced, data);
sendConsoleText('Performing power action=' + data.actiontype + ', forced=' + forced + '.');
var r = mesh.ExecPowerState(data.actiontype, forced);
sendConsoleText('ExecPowerState returned code: ' + r);
}
break;
}
case 'iplocation': {
// Update the IP location information of this node. Only do this when requested by the server since we have a limited amount of time we can call this per day
getIpLocationData(function (location) { mesh.SendCommand({ "action": "iplocation", "type": "publicip", "value": location }); });
break;
}
case 'toast': {
// Display a toast message
if (data.title && data.msg) {
MeshServerLog('Displaying toast message, title=' + data.title + ', message=' + data.msg, data);
try { require('toaster').Toast(data.title, data.msg); } catch (ex) { }
}
break;
}
case 'openUrl': {
// Open a local web browser and return success/fail
//sendConsoleText('OpenURL: ' + data.url);
MeshServerLog('Opening: ' + data.url, data);
if (data.url) { mesh.SendCommand({ "action": "openUrl", "url": data.url, "sessionid": data.sessionid, "success": (openUserDesktopUrl(data.url) != null) }); }
break;
}
case 'amtPolicy': {
// Store the latest Intel AMT policy
amtPolicy = data.amtPolicy;
if (data.amtPolicy != null) { db.Put('amtPolicy', JSON.stringify(data.amtPolicy)); } else { db.Put('amtPolicy', null); }
if (amt != null) { amt.setPolicy(amtPolicy, true); }
break;
}
case 'getScript': {
// Received a configuration script from the server
sendConsoleText('getScript: ' + JSON.stringify(data));
break;
}
case 'ping': { mesh.SendCommand('{"action":"pong"}'); break; }
case 'pong': { break; }
default:
// Unknown action, ignore it.
break;
}
}
}
// Called when a file changed in the file system
/*
function onFileWatcher(a, b) {
console.log('onFileWatcher', a, b, this.path);
var response = getDirectoryInfo(this.path);
if ((response != undefined) && (response != null)) { this.tunnel.s.write(JSON.stringify(response)); }
}
*/
// Get a formated response for a given directory path
function getDirectoryInfo(reqpath) {
var response = { path: reqpath, dir: [] };
if (((reqpath == undefined) || (reqpath == '')) && (process.platform == 'win32')) {
// List all the drives in the root, or the root itself
var results = null;
try { results = fs.readDrivesSync(); } catch (e) { } // TODO: Anyway to get drive total size and free space? Could draw a progress bar.
if (results != null) {
for (var i = 0; i < results.length; ++i) {
var drive = { n: results[i].name, t: 1 };
if (results[i].type == 'REMOVABLE') { drive.dt = 'removable'; } // TODO: See if this is USB/CDROM or something else, we can draw icons.
response.dir.push(drive);
}
}
} else {
// List all the files and folders in this path
if (reqpath == '') { reqpath = '/'; }
var results = null, xpath = obj.path.join(reqpath, '*');
//if (process.platform == "win32") { xpath = xpath.split('/').join('\\'); }
try { results = fs.readdirSync(xpath); } catch (e) { }
if (results != null) {
for (var i = 0; i < results.length; ++i) {
if ((results[i] != '.') && (results[i] != '..')) {
var stat = null, p = obj.path.join(reqpath, results[i]);
//if (process.platform == "win32") { p = p.split('/').join('\\'); }
try { stat = fs.statSync(p); } catch (e) { } // TODO: Get file size/date
if ((stat != null) && (stat != undefined)) {
if (stat.isDirectory() == true) {
response.dir.push({ n: results[i], t: 2, d: stat.mtime });
} else {
response.dir.push({ n: results[i], t: 3, s: stat.size, d: stat.mtime });
}
}
}
}
}
}
return response;
}
// Tunnel callback operations
function onTunnelUpgrade(response, s, head) {
this.s = s;
s.httprequest = this;
s.end = onTunnelClosed;
s.tunnel = this;
//sendConsoleText('onTunnelUpgrade - ' + this.tcpport + ' - ' + this.udpport);
if (this.tcpport != null) {
// This is a TCP relay connection, pause now and try to connect to the target.
s.pause();
s.data = onTcpRelayServerTunnelData;
var connectionOptions = { port: parseInt(this.tcpport) };
if (this.tcpaddr != null) { connectionOptions.host = this.tcpaddr; } else { connectionOptions.host = '127.0.0.1'; }
s.tcprelay = net.createConnection(connectionOptions, onTcpRelayTargetTunnelConnect);
s.tcprelay.peerindex = this.index;
} if (this.udpport != null) {
// This is a UDP relay connection, get the UDP socket setup. // TODO: ***************
s.data = onUdpRelayServerTunnelData;
s.udprelay = require('dgram').createSocket({ type: 'udp4' });
s.udprelay.bind({ port: 0 });
s.udprelay.peerindex = this.index;
s.udprelay.on('message', onUdpRelayTargetTunnelConnect);
s.udprelay.udpport = this.udpport;
s.udprelay.udpaddr = this.udpaddr;
s.udprelay.first = true;
} else {
// This is a normal connect for KVM/Terminal/Files
s.data = onTunnelData;
}
}
// Called when UDP relay data is received // TODO****
function onUdpRelayTargetTunnelConnect(data) {
var peerTunnel = tunnels[this.peerindex];
peerTunnel.s.write(data);
}
// Called when we get data from the server for a TCP relay (We have to skip the first received 'c' and pipe the rest)
function onUdpRelayServerTunnelData(data) {
if (this.udprelay.first === true) {
delete this.udprelay.first; // Skip the first 'c' that is received.
} else {
this.udprelay.send(data, parseInt(this.udprelay.udpport), this.udprelay.udpaddr ? this.udprelay.udpaddr : '127.0.0.1');
}
}
// Called when the TCP relay target is connected
function onTcpRelayTargetTunnelConnect() {
var peerTunnel = tunnels[this.peerindex];
this.pipe(peerTunnel.s); // Pipe Target --> Server
peerTunnel.s.first = true;
peerTunnel.s.resume();
}
// Called when we get data from the server for a TCP relay (We have to skip the first received 'c' and pipe the rest)
function onTcpRelayServerTunnelData(data) {
if (this.first == true) { this.first = false; this.pipe(this.tcprelay); } // Pipe Server --> Target
}
function onTunnelClosed() {
if (tunnels[this.httprequest.index] == null) return; // Stop duplicate calls.
//sendConsoleText("Tunnel #" + this.httprequest.index + " closed.", this.httprequest.sessionid);
delete tunnels[this.httprequest.index];
/*
// Close the watcher if required
if (this.httprequest.watcher != undefined) {
//console.log('Closing watcher: ' + this.httprequest.watcher.path);
//this.httprequest.watcher.close(); // TODO: This line causes the agent to crash!!!!
delete this.httprequest.watcher;
}
*/
// If there is a upload or download active on this connection, close the file
if (this.httprequest.uploadFile) { fs.closeSync(this.httprequest.uploadFile); this.httprequest.uploadFile = undefined; }
if (this.httprequest.downloadFile) { fs.closeSync(this.httprequest.downloadFile); this.httprequest.downloadFile = undefined; }
// Clean up WebRTC
if (this.webrtc != null) {
if (this.webrtc.rtcchannel) { try { this.webrtc.rtcchannel.close(); } catch (e) { } this.webrtc.rtcchannel.removeAllListeners('data'); this.webrtc.rtcchannel.removeAllListeners('end'); delete this.webrtc.rtcchannel; }
if (this.webrtc.websocket) { delete this.webrtc.websocket; }
try { this.webrtc.close(); } catch (e) { }
this.webrtc.removeAllListeners('connected');
this.webrtc.removeAllListeners('disconnected');
this.webrtc.removeAllListeners('dataChannel');
delete this.webrtc;
}
// Clean up WebSocket
this.removeAllListeners('data');
}
function onTunnelSendOk() { /*sendConsoleText("Tunnel #" + this.index + " SendOK.", this.sessionid);*/ }
function onTunnelData(data) {
//console.log("OnTunnelData");
//sendConsoleText('OnTunnelData, ' + data.length + ', ' + typeof data + ', ' + data);
// If this is upload data, save it to file
if (this.httprequest.uploadFile) {
try { fs.writeSync(this.httprequest.uploadFile, data); } catch (e) { this.write(new Buffer(JSON.stringify({ action: 'uploaderror' }))); return; } // Write to the file, if there is a problem, error out.
this.write(new Buffer(JSON.stringify({ action: 'uploadack', reqid: this.httprequest.uploadFileid }))); // Ask for more data
return;
}
/*
// If this is a download, send more of the file
if (this.httprequest.downloadFile) {
var buf = new Buffer(4096);
var len = fs.readSync(this.httprequest.downloadFile, buf, 0, 4096, null);
this.httprequest.downloadFilePtr += len;
if (len > 0) { this.write(buf.slice(0, len)); } else { fs.closeSync(this.httprequest.downloadFile); this.httprequest.downloadFile = undefined; this.end(); }
return;
}
*/
if (this.httprequest.state == 0) {
// Check if this is a relay connection
if (data == 'c') { this.httprequest.state = 1; /*sendConsoleText("Tunnel #" + this.httprequest.index + " now active", this.httprequest.sessionid);*/ }