-
Notifications
You must be signed in to change notification settings - Fork 586
/
meshcentral.js
4344 lines (3961 loc) · 314 KB
/
meshcentral.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
/**
* @description MeshCentral main module
* @author Ylian Saint-Hilaire
* @copyright Intel Corporation 2018-2022
* @license Apache-2.0
* @version v0.0.1
*/
/*xjslint node: true */
/*xjslint plusplus: true */
/*xjslint maxlen: 256 */
/*jshint node: true */
/*jshint strict: false */
/*jshint esversion: 6 */
"use strict";
const common = require('./common.js');
// If app metrics is available
if (process.argv[2] == '--launch') { try { require('appmetrics-dash').monitor({ url: '/', title: 'MeshCentral', port: 88, host: '127.0.0.1' }); } catch (ex) { } }
function CreateMeshCentralServer(config, args) {
const obj = {};
obj.db = null;
obj.webserver = null; // HTTPS main web server, typically on port 443
obj.redirserver = null; // HTTP relay web server, typically on port 80
obj.mpsserver = null; // Intel AMT CIRA server, typically on port 4433
obj.mqttbroker = null; // MQTT server, not is not often used
obj.swarmserver = null; // Swarm server, this is used only to update older MeshCentral v1 agents
obj.smsserver = null; // SMS server, used to send user SMS messages
obj.msgserver = null; // Messaging server, used to sent used messages
obj.amtEventHandler = null;
obj.pluginHandler = null;
obj.amtScanner = null;
obj.amtManager = null; // Intel AMT manager, used to oversee all Intel AMT devices, activate them and sync policies
obj.meshScanner = null;
obj.taskManager = null;
obj.letsencrypt = null; // Let's encrypt server, used to get and renew TLS certificates
obj.eventsDispatch = {};
obj.fs = require('fs');
obj.path = require('path');
obj.crypto = require('crypto');
obj.exeHandler = require('./exeHandler.js');
obj.platform = require('os').platform();
obj.args = args;
obj.common = common;
obj.configurationFiles = null;
obj.certificates = null;
obj.connectivityByNode = {}; // This object keeps a list of all connected CIRA and agents, by nodeid->value (value: 1 = Agent, 2 = CIRA, 4 = AmtDirect)
obj.peerConnectivityByNode = {}; // This object keeps a list of all connected CIRA and agents of peers, by serverid->nodeid->value (value: 1 = Agent, 2 = CIRA, 4 = AmtDirect)
obj.debugSources = [];
obj.debugRemoteSources = null;
obj.config = config; // Configuration file
obj.dbconfig = {}; // Persistance values, loaded from database
obj.certificateOperations = null;
obj.defaultMeshCmd = null;
obj.defaultMeshCores = {};
obj.defaultMeshCoresDeflate = {};
obj.defaultMeshCoresHash = {};
obj.meshToolsBinaries = {}; // Mesh Tools Binaries, ToolName --> { hash:(sha384 hash), size:(binary size), path:(binary path) }
obj.meshAgentBinaries = {}; // Mesh Agent Binaries, Architecture type --> { hash:(sha384 hash), size:(binary size), path:(binary path) }
obj.meshAgentInstallScripts = {}; // Mesh Install Scripts, Script ID -- { hash:(sha384 hash), size:(binary size), path:(binary path) }
obj.multiServer = null;
obj.ipKvmManager = null;
obj.maintenanceTimer = null;
obj.serverId = null;
obj.serverKey = Buffer.from(obj.crypto.randomBytes(48), 'binary');
obj.loginCookieEncryptionKey = null;
obj.invitationLinkEncryptionKey = null;
obj.serverSelfWriteAllowed = true;
obj.serverStatsCounter = Math.floor(Math.random() * 1000);
obj.taskLimiter = obj.common.createTaskLimiterQueue(50, 20, 60); // (maxTasks, maxTaskTime, cleaningInterval) This is a task limiter queue to smooth out server work.
obj.agentUpdateBlockSize = 65531; // MeshAgent update block size
obj.serverWarnings = []; // List of warnings that should be shown to administrators
obj.cookieUseOnceTable = {}; // List of cookies that are already expired
obj.cookieUseOnceTableCleanCounter = 0; // Clean the cookieUseOnceTable each 20 additions
obj.firstStats = true; // True until this server saves it's not stats to the database
// Server version
obj.currentVer = null;
function getCurrentVersion() { try { obj.currentVer = JSON.parse(obj.fs.readFileSync(obj.path.join(__dirname, 'package.json'), 'utf8')).version; } catch (ex) { } return obj.currentVer; } // Fetch server version
getCurrentVersion();
// Setup the default configuration and files paths
if ((__dirname.endsWith('/node_modules/meshcentral')) || (__dirname.endsWith('\\node_modules\\meshcentral')) || (__dirname.endsWith('/node_modules/meshcentral/')) || (__dirname.endsWith('\\node_modules\\meshcentral\\'))) {
obj.parentpath = obj.path.join(__dirname, '../..');
obj.datapath = obj.path.join(__dirname, '../../meshcentral-data');
obj.filespath = obj.path.join(__dirname, '../../meshcentral-files');
obj.backuppath = obj.path.join(__dirname, '../../meshcentral-backups');
obj.recordpath = obj.path.join(__dirname, '../../meshcentral-recordings');
obj.webViewsPath = obj.path.join(__dirname, 'views');
obj.webPublicPath = obj.path.join(__dirname, 'public');
obj.webEmailsPath = obj.path.join(__dirname, 'emails');
if (obj.fs.existsSync(obj.path.join(__dirname, '../../meshcentral-web/views'))) { obj.webViewsOverridePath = obj.path.join(__dirname, '../../meshcentral-web/views'); }
if (obj.fs.existsSync(obj.path.join(__dirname, '../../meshcentral-web/public'))) { obj.webPublicOverridePath = obj.path.join(__dirname, '../../meshcentral-web/public'); }
if (obj.fs.existsSync(obj.path.join(__dirname, '../../meshcentral-web/emails'))) { obj.webEmailsOverridePath = obj.path.join(__dirname, '../../meshcentral-web/emails'); }
} else {
obj.parentpath = __dirname;
obj.datapath = obj.path.join(__dirname, '../meshcentral-data');
obj.filespath = obj.path.join(__dirname, '../meshcentral-files');
obj.backuppath = obj.path.join(__dirname, '../meshcentral-backups');
obj.recordpath = obj.path.join(__dirname, '../meshcentral-recordings');
obj.webViewsPath = obj.path.join(__dirname, 'views');
obj.webPublicPath = obj.path.join(__dirname, 'public');
obj.webEmailsPath = obj.path.join(__dirname, 'emails');
if (obj.fs.existsSync(obj.path.join(__dirname, '../meshcentral-web/views'))) { obj.webViewsOverridePath = obj.path.join(__dirname, '../meshcentral-web/views'); }
if (obj.fs.existsSync(obj.path.join(__dirname, '../meshcentral-web/public'))) { obj.webPublicOverridePath = obj.path.join(__dirname, '../meshcentral-web/public'); }
if (obj.fs.existsSync(obj.path.join(__dirname, '../meshcentral-web/emails'))) { obj.webEmailsOverridePath = obj.path.join(__dirname, '../meshcentral-web/emails'); }
}
// Clean up any temporary files
const removeTime = new Date(Date.now()).getTime() - (30 * 60 * 1000); // 30 minutes
const dir = obj.fs.readdir(obj.path.join(obj.filespath, 'tmp'), function (err, files) {
if (err != null) return;
for (var i in files) { try { const filepath = obj.path.join(obj.filespath, 'tmp', files[i]); if (obj.fs.statSync(filepath).mtime.getTime() < removeTime) { obj.fs.unlink(filepath, function () { }); } } catch (ex) { } }
});
// Look to see if data and/or file path is specified
if (obj.config.settings && (typeof obj.config.settings.datapath == 'string')) { obj.datapath = obj.config.settings.datapath; }
if (obj.config.settings && (typeof obj.config.settings.filespath == 'string')) { obj.filespath = obj.config.settings.filespath; }
// Create data and files folders if needed
try { obj.fs.mkdirSync(obj.datapath); } catch (ex) { }
try { obj.fs.mkdirSync(obj.filespath); } catch (ex) { }
// Windows Specific Code, setup service and event log
obj.service = null;
obj.servicelog = null;
if (obj.platform == 'win32') {
const nodewindows = require('node-windows');
obj.service = nodewindows.Service;
const eventlogger = nodewindows.EventLogger;
obj.servicelog = new eventlogger('MeshCentral');
}
// Start the Meshcentral server
obj.Start = function () {
var i;
try { require('./pass').hash('test', function () { }, 0); } catch (ex) { console.log('Old version of node, must upgrade.'); return; } // TODO: Not sure if this test works or not.
// Check for invalid arguments
const validArguments = ['_', 'user', 'port', 'aliasport', 'mpsport', 'mpsaliasport', 'redirport', 'rediraliasport', 'cert', 'mpscert', 'deletedomain', 'deletedefaultdomain', 'showall', 'showusers', 'showitem', 'listuserids', 'showusergroups', 'shownodes', 'showallmeshes', 'showmeshes', 'showevents', 'showsmbios', 'showpower', 'clearpower', 'showiplocations', 'help', 'exactports', 'xinstall', 'xuninstall', 'install', 'uninstall', 'start', 'stop', 'restart', 'debug', 'filespath', 'datapath', 'noagentupdate', 'launch', 'noserverbackup', 'mongodb', 'mongodbcol', 'wanonly', 'lanonly', 'nousers', 'mpspass', 'ciralocalfqdn', 'dbexport', 'dbexportmin', 'dbimport', 'dbmerge', 'dbfix', 'dbencryptkey', 'selfupdate', 'tlsoffload', 'usenodedefaulttlsciphers', 'tlsciphers', 'userallowedip', 'userblockedip', 'swarmallowedip', 'agentallowedip', 'agentblockedip', 'fastcert', 'swarmport', 'logintoken', 'logintokenkey', 'logintokengen', 'mailtokengen', 'admin', 'unadmin', 'sessionkey', 'sessiontime', 'minify', 'minifycore', 'dblistconfigfiles', 'dbshowconfigfile', 'dbpushconfigfiles', 'oldencrypt', 'dbpullconfigfiles', 'dbdeleteconfigfiles', 'vaultpushconfigfiles', 'vaultpullconfigfiles', 'vaultdeleteconfigfiles', 'configkey', 'loadconfigfromdb', 'npmpath', 'serverid', 'recordencryptionrecode', 'vault', 'token', 'unsealkey', 'name', 'log', 'dbstats', 'translate', 'createaccount', 'setuptelegram', 'resetaccount', 'pass', 'removesubdomain', 'adminaccount', 'domain', 'email', 'configfile', 'maintenancemode', 'nedbtodb', 'removetestagents', 'agentupdatetest', 'hashpassword', 'hashpass', 'indexmcrec', 'mpsdebug', 'dumpcores', 'dev', 'mysql', 'mariadb', 'trustedproxy'];
for (var arg in obj.args) { obj.args[arg.toLocaleLowerCase()] = obj.args[arg]; if (validArguments.indexOf(arg.toLocaleLowerCase()) == -1) { console.log('Invalid argument "' + arg + '", use --help.'); return; } }
const ENVVAR_PREFIX = "meshcentral_"
let envArgs = []
for (let [envvar, envval] of Object.entries(process.env)) {
if (envvar.toLocaleLowerCase().startsWith(ENVVAR_PREFIX)) {
let argname = envvar.slice(ENVVAR_PREFIX.length).toLocaleLowerCase()
if (!!argname && !(validArguments.indexOf(argname) == -1)) {
envArgs = envArgs.concat([`--${argname}`, envval])
}
}
}
envArgs = require('minimist')(envArgs)
obj.args = Object.assign(envArgs, obj.args)
if (obj.args.mongodb == true) { console.log('Must specify: --mongodb [connectionstring] \r\nSee https://docs.mongodb.com/manual/reference/connection-string/ for MongoDB connection string.'); return; }
if (obj.args.mysql == true) { console.log('Must specify: --mysql [connectionstring] \r\nExample mysql://user:[email protected]:3306/database'); return; }
if (obj.args.mariadb == true) { console.log('Must specify: --mariadb [connectionstring] \r\nExample mariadb://user:[email protected]:3306/database'); return; }
for (i in obj.config.settings) { obj.args[i] = obj.config.settings[i]; } // Place all settings into arguments, arguments have already been placed into settings so arguments take precedence.
if ((obj.args.help == true) || (obj.args['?'] == true)) {
console.log('MeshCentral v' + getCurrentVersion() + ', remote computer management web portal.');
console.log('This software is open source under Apache 2.0 license.');
console.log('Details at: https://www.meshcentral.com\r\n');
if ((obj.platform == 'win32') || (obj.platform == 'linux')) {
console.log('Run as a background service');
console.log(' --install/uninstall Install MeshCentral as a background service.');
console.log(' --start/stop/restart Control MeshCentral background service.');
console.log('');
console.log('Run standalone, console application');
}
console.log(' --user [username] Always login as [username] if account exists.');
console.log(' --port [number] Web server port number.');
console.log(' --redirport [number] Creates an additional HTTP server to redirect users to the HTTPS server.');
console.log(' --exactports Server must run with correct ports or exit.');
console.log(' --noagentupdate Server will not update mesh agent native binaries.');
console.log(' --nedbtodb Transfer all NeDB records into current database.');
console.log(' --listuserids Show a list of a user identifiers in the database.');
console.log(' --cert [name], (country), (org) Create a web server certificate with [name] server name.');
console.log(' country and organization can optionally be set.');
console.log('');
console.log('Server recovery commands, use only when MeshCentral is offline.');
console.log(' --createaccount [userid] Create a new user account.');
console.log(' --resetaccount [userid] Unlock an account, disable 2FA and set a new account password.');
console.log(' --adminaccount [userid] Promote account to site administrator.');
return;
}
// Fix a NeDB database
if (obj.args.dbfix) {
var lines = null, badJsonCount = 0, fieldNames = [], fixedDb = [];
try { lines = obj.fs.readFileSync(obj.getConfigFilePath(obj.args.dbfix), { encoding: 'utf8' }).split('\n'); } catch (ex) { console.log('Invalid file: ' + obj.args.dbfix + ': ' + ex); process.exit(); }
for (var i = 0; i < lines.length; i++) {
var x = null;
try { x = JSON.parse(lines[i]); } catch (ex) { badJsonCount++; }
if (x != null) { fixedDb.push(lines[i]); for (var j in x) { if (fieldNames.indexOf(j) == -1) { fieldNames.push(j); } } }
}
console.log('Lines: ' + lines.length + ', badJSON: ' + badJsonCount + ', Feilds: ' + fieldNames);
obj.fs.writeFileSync(obj.getConfigFilePath(obj.args.dbfix) + '-fixed', fixedDb.join('\n'), { encoding: 'utf8' });
return;
}
// Check for invalid cert name
if ((obj.args.cert != null) && ((typeof obj.args.cert != "string") || (obj.args.cert.indexOf('@') >= 0) || (obj.args.cert.indexOf('/') >= 0) || (obj.args.cert.indexOf(':') >= 0))) { console.log("Invalid certificate name"); process.exit(); return; }
// Perform a password hash
if (obj.args.hashpassword) { require('./pass').hash(obj.args.hashpassword, function (err, salt, hash, tag) { console.log(salt + ',' + hash); process.exit(); }); return; }
// Dump to mesh cores
if (obj.args.dumpcores) { obj.updateMeshCore(function () { console.log('Done.'); }, true); return; }
// Setup Telegram
if (obj.args.setuptelegram) { require('./meshmessaging.js').SetupTelegram(obj); return; }
// Perform web site translations into different languages
if (obj.args.translate) {
// Check NodeJS version
const NodeJSVer = Number(process.version.match(/^v(\d+\.\d+)/)[1]);
if (NodeJSVer < 8) { console.log("Translation feature requires Node v8 or above, current version is " + process.version + "."); process.exit(); return; }
// Check if translate.json is in the "meshcentral-data" folder, if so use that and translate default pages.
var translationFile = null, customTranslation = false;
if (require('fs').existsSync(obj.path.join(obj.datapath, 'translate.json'))) { translationFile = obj.path.join(obj.datapath, 'translate.json'); console.log("Using translate.json in meshcentral-data."); customTranslation = true; }
if (translationFile == null) { if (require('fs').existsSync(obj.path.join(__dirname, 'translate', 'translate.json'))) { translationFile = obj.path.join(__dirname, 'translate', 'translate.json'); console.log("Using default translate.json."); } }
if (translationFile == null) { console.log("Unable to find translate.json."); process.exit(); return; }
// Perform translation operations
var didSomething = false;
process.chdir(obj.path.join(__dirname, 'translate'));
const translateEngine = require('./translate/translate.js')
if (customTranslation == true) {
// Translate all of the default files using custom translation file
translateEngine.startEx(['', '', 'minifyall']);
translateEngine.startEx(['', '', 'translateall', translationFile]);
translateEngine.startEx(['', '', 'extractall', translationFile]);
didSomething = true;
} else {
// Translate all of the default files
translateEngine.startEx(['', '', 'minifyall']);
translateEngine.startEx(['', '', 'translateall']);
translateEngine.startEx(['', '', 'extractall']);
didSomething = true;
}
// Check if "meshcentral-web" exists, if so, translate all pages in that folder.
if (obj.webViewsOverridePath != null) {
didSomething = true;
var files = obj.fs.readdirSync(obj.webViewsOverridePath);
for (var i in files) {
var file = obj.path.join(obj.webViewsOverridePath, files[i]);
if (file.endsWith('.handlebars') && !file.endsWith('-min.handlebars')) {
translateEngine.startEx(['', '', 'minify', file]);
}
}
files = obj.fs.readdirSync(obj.webViewsOverridePath);
for (var i in files) {
var file = obj.path.join(obj.webViewsOverridePath, files[i]);
if (file.endsWith('.handlebars') && !file.endsWith('-min.handlebars')) {
translateEngine.startEx(['', '', 'translate', '*', translationFile, file, '--subdir:translations']);
}
}
}
// Check domains and see if "meshcentral-web-DOMAIN" exists, if so, translate all pages in that folder
for (i in obj.config.domains) {
if (i == "") continue;
var path = obj.path.join(obj.datapath, '..', 'meshcentral-web-' + i, 'views');
if (require('fs').existsSync(path)) {
didSomething = true;
var files = obj.fs.readdirSync(path);
for (var a in files) {
var file = obj.path.join(path, files[a]);
if (file.endsWith('.handlebars') && !file.endsWith('-min.handlebars')) {
translateEngine.startEx(['', '', 'minify', file]);
}
}
files = obj.fs.readdirSync(path);
for (var a in files) {
var file = obj.path.join(path, files[a]);
if (file.endsWith('.handlebars') && !file.endsWith('-min.handlebars')) {
translateEngine.startEx(['', '', 'translate', '*', translationFile, file, '--subdir:translations']);
}
}
}
}
/*
if (obj.webPublicOverridePath != null) {
didSomething = true;
var files = obj.fs.readdirSync(obj.webPublicOverridePath);
for (var i in files) {
var file = obj.path.join(obj.webPublicOverridePath, files[i]);
if (file.endsWith('.htm') && !file.endsWith('-min.htm')) {
translateEngine.startEx(['', '', 'translate', '*', translationFile, file, '--subdir:translations']);
}
}
}
*/
if (didSomething == false) { console.log("Nothing to do."); }
console.log('Finished Translating.')
process.exit();
return;
}
// Setup the Node+NPM path if possible, this makes it possible to update the server even if NodeJS and NPM are not in default paths.
if (obj.args.npmpath == null) {
try {
var nodepath = process.argv[0];
var npmpath = obj.path.join(obj.path.dirname(process.argv[0]), 'npm');
if (obj.fs.existsSync(nodepath) && obj.fs.existsSync(npmpath)) {
if (nodepath.indexOf(' ') >= 0) { nodepath = '"' + nodepath + '"'; }
if (npmpath.indexOf(' ') >= 0) { npmpath = '"' + npmpath + '"'; }
if (obj.platform == 'win32') { obj.args.npmpath = npmpath; } else { obj.args.npmpath = (nodepath + ' ' + npmpath); }
}
} catch (ex) { }
}
// Linux background service systemd handling
if (obj.platform == 'linux') {
if (obj.args.install == true) {
// Install MeshCentral in Systemd
console.log('Installing MeshCentral as background Service...');
var systemdConf = null;
const userinfo = require('os').userInfo();
if (require('fs').existsSync('/etc/systemd/system')) { systemdConf = '/etc/systemd/system/meshcentral.service'; }
else if (require('fs').existsSync('/lib/systemd/system')) { systemdConf = '/lib/systemd/system/meshcentral.service'; }
else if (require('fs').existsSync('/usr/lib/systemd/system')) { systemdConf = '/usr/lib/systemd/system/meshcentral.service'; }
else { console.log('Unable to find systemd configuration folder.'); process.exit(); return; }
console.log('Writing config file...');
require('child_process').exec('which node', {}, function (error, stdout, stderr) {
if ((error != null) || (stdout.indexOf('\n') == -1)) { console.log('ERROR: Unable to get node location: ' + error); process.exit(); return; }
const nodePath = stdout.substring(0, stdout.indexOf('\n'));
const config = '[Unit]\nDescription=MeshCentral Server\nWants=network-online.target\nAfter=network-online.target\n\n[Service]\nType=simple\nLimitNOFILE=1000000\nExecStart=' + nodePath + ' ' + __dirname + '/meshcentral\nWorkingDirectory=' + userinfo.homedir + '\nEnvironment=NODE_ENV=production\nUser=' + userinfo.username + '\nGroup=' + userinfo.username + '\nRestart=always\n# Restart service after 10 seconds if node service crashes\nRestartSec=10\n# Set port permissions capability\nAmbientCapabilities=cap_net_bind_service\n\n[Install]\nWantedBy=multi-user.target\n';
require('child_process').exec('echo \"' + config + '\" | sudo tee ' + systemdConf, {}, function (error, stdout, stderr) {
if ((error != null) && (error != '')) { console.log('ERROR: Unable to write config file: ' + error); process.exit(); return; }
console.log('Enabling service...');
require('child_process').exec('sudo systemctl enable meshcentral.service', {}, function (error, stdout, stderr) {
if ((error != null) && (error != '')) { console.log('ERROR: Unable to enable MeshCentral as a service: ' + error); process.exit(); return; }
if (stdout.length > 0) { console.log(stdout); }
console.log('Starting service...');
require('child_process').exec('sudo systemctl start meshcentral.service', {}, function (error, stdout, stderr) {
if ((error != null) && (error != '')) { console.log('ERROR: Unable to start MeshCentral as a service: ' + error); process.exit(); return; }
if (stdout.length > 0) { console.log(stdout); }
console.log('Done.');
});
});
});
});
return;
} else if (obj.args.uninstall == true) {
// Uninstall MeshCentral in Systemd
console.log('Uninstalling MeshCentral background service...');
var systemdConf = null;
if (require('fs').existsSync('/etc/systemd/system')) { systemdConf = '/etc/systemd/system/meshcentral.service'; }
else if (require('fs').existsSync('/lib/systemd/system')) { systemdConf = '/lib/systemd/system/meshcentral.service'; }
else if (require('fs').existsSync('/usr/lib/systemd/system')) { systemdConf = '/usr/lib/systemd/system/meshcentral.service'; }
else { console.log('Unable to find systemd configuration folder.'); process.exit(); return; }
console.log('Stopping service...');
require('child_process').exec('sudo systemctl stop meshcentral.service', {}, function (err, stdout, stderr) {
if ((err != null) && (err != '')) { console.log('ERROR: Unable to stop MeshCentral as a service: ' + err); }
if (stdout.length > 0) { console.log(stdout); }
console.log('Disabling service...');
require('child_process').exec('sudo systemctl disable meshcentral.service', {}, function (err, stdout, stderr) {
if ((err != null) && (err != '')) { console.log('ERROR: Unable to disable MeshCentral as a service: ' + err); }
if (stdout.length > 0) { console.log(stdout); }
console.log('Removing config file...');
require('child_process').exec('sudo rm ' + systemdConf, {}, function (err, stdout, stderr) {
if ((err != null) && (err != '')) { console.log('ERROR: Unable to delete MeshCentral config file: ' + err); }
console.log('Done.');
});
});
});
return;
} else if (obj.args.start == true) {
// Start MeshCentral in Systemd
require('child_process').exec('sudo systemctl start meshcentral.service', {}, function (err, stdout, stderr) {
if ((err != null) && (err != '')) { console.log('ERROR: Unable to start MeshCentral: ' + err); process.exit(); return; }
console.log('Done.');
});
return;
} else if (obj.args.stop == true) {
// Stop MeshCentral in Systemd
require('child_process').exec('sudo systemctl stop meshcentral.service', {}, function (err, stdout, stderr) {
if ((err != null) && (err != '')) { console.log('ERROR: Unable to stop MeshCentral: ' + err); process.exit(); return; }
console.log('Done.');
});
return;
} else if (obj.args.restart == true) {
// Restart MeshCentral in Systemd
require('child_process').exec('sudo systemctl restart meshcentral.service', {}, function (err, stdout, stderr) {
if ((err != null) && (err != '')) { console.log('ERROR: Unable to restart MeshCentral: ' + err); process.exit(); return; }
console.log('Done.');
});
return;
}
}
// FreeBSD background service handling, MUST USE SPAWN FOR SERVICE COMMANDS!
if (obj.platform == 'freebsd') {
if (obj.args.install == true) {
// Install MeshCentral in rc.d
console.log('Installing MeshCentral as background Service...');
var systemdConf = "/usr/local/etc/rc.d/meshcentral";
const userinfo = require('os').userInfo();
console.log('Writing config file...');
require('child_process').exec('which node', {}, function (error, stdout, stderr) {
if ((error != null) || (stdout.indexOf('\n') == -1)) { console.log('ERROR: Unable to get node location: ' + error); process.exit(); return; }
const nodePath = stdout.substring(0, stdout.indexOf('\n'));
const config = '#!/bin/sh\n# MeshCentral FreeBSD Service Script\n# PROVIDE: meshcentral\n# REQUIRE: NETWORKING\n# KEYWORD: shutdown\n. /etc/rc.subr\nname=meshcentral\nuser=' + userinfo.username + '\nrcvar=meshcentral_enable\n: \\${meshcentral_enable:=\\"NO\\"}\n: \\${meshcentral_args:=\\"\\"}\npidfile=/var/run/meshcentral/meshcentral.pid\ncommand=\\"/usr/sbin/daemon\\"\nmeshcentral_chdir=\\"' + obj.parentpath + '\\"\ncommand_args=\\"-r -u \\${user} -P \\${pidfile} -S -T meshcentral -m 3 ' + nodePath + ' ' + __dirname + ' \\${meshcentral_args}\\"\nload_rc_config \\$name\nrun_rc_command \\"\\$1\\"\n';
require('child_process').exec('echo \"' + config + '\" | tee ' + systemdConf + ' && chmod +x ' + systemdConf, {}, function (error, stdout, stderr) {
if ((error != null) && (error != '')) { console.log('ERROR: Unable to write config file: ' + error); process.exit(); return; }
console.log('Enabling service...');
require('child_process').exec('sysrc meshcentral_enable="YES"', {}, function (error, stdout, stderr) {
if ((error != null) && (error != '')) { console.log('ERROR: Unable to enable MeshCentral as a service: ' + error); process.exit(); return; }
if (stdout.length > 0) { console.log(stdout); }
console.log('Starting service...');
const service = require('child_process').spawn('service', ['meshcentral', 'start']);
service.stdout.on('data', function (data) { console.log(data.toString()); });
service.stderr.on('data', function (data) { console.log(data.toString()); });
service.on('exit', function (code) {
console.log((code === 0) ? 'Done.' : 'ERROR: Unable to start MeshCentral as a service');
process.exit(); // Must exit otherwise we just hang
});
});
});
});
return;
} else if (obj.args.uninstall == true) {
// Uninstall MeshCentral in rc.d
console.log('Uninstalling MeshCentral background service...');
var systemdConf = "/usr/local/etc/rc.d/meshcentral";
console.log('Stopping service...');
const service = require('child_process').spawn('service', ['meshcentral', 'stop']);
service.stdout.on('data', function (data) { console.log(data.toString()); });
service.stderr.on('data', function (data) { console.log(data.toString()); });
service.on('exit', function (code) {
if (code !== 0) { console.log('ERROR: Unable to stop MeshCentral as a service'); }
console.log('Disabling service...');
require('child_process').exec('sysrc -x meshcentral_enable', {}, function (err, stdout, stderr) {
if ((err != null) && (err != '')) { console.log('ERROR: Unable to disable MeshCentral as a service: ' + err); }
if (stdout.length > 0) { console.log(stdout); }
console.log('Removing config file...');
require('child_process').exec('rm ' + systemdConf, {}, function (err, stdout, stderr) {
if ((err != null) && (err != '')) { console.log('ERROR: Unable to delete MeshCentral config file: ' + err); }
console.log('Done.');
process.exit(); // Must exit otherwise we just hang
});
});
});
return;
} else if (obj.args.start == true) {
// Start MeshCentral in rc.d
const service = require('child_process').spawn('service', ['meshcentral', 'start']);
service.stdout.on('data', function (data) { console.log(data.toString()); });
service.stderr.on('data', function (data) { console.log(data.toString()); });
service.on('exit', function (code) {
console.log((code === 0) ? 'Done.' : 'ERROR: Unable to start MeshCentral as a service: ' + error);
process.exit(); // Must exit otherwise we just hang
});
return;
} else if (obj.args.stop == true) {
// Stop MeshCentral in rc.d
const service = require('child_process').spawn('service', ['meshcentral', 'stop']);
service.stdout.on('data', function (data) { console.log(data.toString()); });
service.stderr.on('data', function (data) { console.log(data.toString()); });
service.on('exit', function (code) {
console.log((code === 0) ? 'Done.' : 'ERROR: Unable to stop MeshCentral as a service: ' + error);
process.exit(); // Must exit otherwise we just hang
});
return;
} else if (obj.args.restart == true) {
// Restart MeshCentral in rc.d
const service = require('child_process').spawn('service', ['meshcentral', 'restart']);
service.stdout.on('data', function (data) { console.log(data.toString()); });
service.stderr.on('data', function (data) { console.log(data.toString()); });
service.on('exit', function (code) {
console.log((code === 0) ? 'Done.' : 'ERROR: Unable to restart MeshCentral as a service: ' + error);
process.exit(); // Must exit otherwise we just hang
});
return;
}
}
// Index a recorded file
if (obj.args.indexmcrec != null) {
if (typeof obj.args.indexmcrec != 'string') {
console.log('Usage: --indexmrec [filename.mcrec]');
} else if (obj.fs.existsSync(obj.args.indexmcrec)) {
console.log('Indexing file: ' + obj.args.indexmcrec);
require(require('path').join(__dirname, 'mcrec.js')).indexFile(obj.args.indexmcrec);
} else {
console.log('Unable to find file: ' + obj.args.indexmcrec);
}
return;
}
// Windows background service handling
if ((obj.platform == 'win32') && (obj.service != null)) {
// Build MeshCentral parent path and Windows Service path
var mcpath = __dirname;
if (mcpath.endsWith('\\node_modules\\meshcentral') || mcpath.endsWith('/node_modules/meshcentral')) { mcpath = require('path').join(mcpath, '..', '..'); }
const servicepath = obj.path.join(mcpath, 'WinService');
// Check if we need to install, start, stop, remove ourself as a background service
if (((obj.args.xinstall == true) || (obj.args.xuninstall == true) || (obj.args.start == true) || (obj.args.stop == true) || (obj.args.restart == true))) {
var env = [], xenv = ['user', 'port', 'aliasport', 'mpsport', 'mpsaliasport', 'redirport', 'exactport', 'rediraliasport', 'debug'];
for (i in xenv) { if (obj.args[xenv[i]] != null) { env.push({ name: 'mesh' + xenv[i], value: obj.args[xenv[i]] }); } } // Set some args as service environment variables.
var serviceFilePath = null;
if (obj.fs.existsSync(obj.path.join(servicepath, 'winservice.js'))) { serviceFilePath = obj.path.join(servicepath, 'winservice.js'); }
else if (obj.fs.existsSync(obj.path.join(__dirname, '../WinService/winservice.js'))) { serviceFilePath = obj.path.join(__dirname, '../WinService/winservice.js'); }
else if (obj.fs.existsSync(obj.path.join(__dirname, 'winservice.js'))) { serviceFilePath = obj.path.join(__dirname, 'winservice.js'); }
if (serviceFilePath == null) { console.log('Unable to find winservice.js'); return; }
const svc = new obj.service({ name: 'MeshCentral', description: 'MeshCentral Remote Management Server', script: servicepath, env: env, wait: 2, grow: 0.5 });
svc.on('install', function () { console.log('MeshCentral service installed.'); svc.start(); });
svc.on('uninstall', function () { console.log('MeshCentral service uninstalled.'); process.exit(); });
svc.on('start', function () { console.log('MeshCentral service started.'); process.exit(); });
svc.on('stop', function () { console.log('MeshCentral service stopped.'); if (obj.args.stop) { process.exit(); } if (obj.args.restart) { console.log('Holding 5 seconds...'); setTimeout(function () { svc.start(); }, 5000); } });
svc.on('alreadyinstalled', function () { console.log('MeshCentral service already installed.'); process.exit(); });
svc.on('invalidinstallation', function () { console.log('Invalid MeshCentral service installation.'); process.exit(); });
if (obj.args.xinstall == true) { try { svc.install(); } catch (ex) { logException(ex); } }
if (obj.args.stop == true || obj.args.restart == true) { try { svc.stop(); } catch (ex) { logException(ex); } }
if (obj.args.start == true) { try { svc.start(); } catch (ex) { logException(ex); } }
if (obj.args.xuninstall == true) { try { svc.uninstall(); } catch (ex) { logException(ex); } }
return;
}
// Windows service install using the external winservice.js
if (obj.args.install == true) {
console.log('Installing MeshCentral as Windows Service...');
if (obj.fs.existsSync(servicepath) == false) { try { obj.fs.mkdirSync(servicepath); } catch (ex) { console.log('ERROR: Unable to create WinService folder: ' + ex); process.exit(); return; } }
try { obj.fs.createReadStream(obj.path.join(__dirname, 'winservice.js')).pipe(obj.fs.createWriteStream(obj.path.join(servicepath, 'winservice.js'))); } catch (ex) { console.log('ERROR: Unable to copy winservice.js: ' + ex); process.exit(); return; }
require('child_process').exec('node winservice.js --install', { maxBuffer: 512000, timeout: 120000, cwd: servicepath }, function (error, stdout, stderr) {
if ((error != null) && (error != '')) { console.log('ERROR: Unable to install MeshCentral as a service: ' + error); process.exit(); return; }
console.log(stdout);
});
return;
} else if (obj.args.uninstall == true) {
console.log('Uninstalling MeshCentral Windows Service...');
if (obj.fs.existsSync(servicepath) == true) {
require('child_process').exec('node winservice.js --uninstall', { maxBuffer: 512000, timeout: 120000, cwd: servicepath }, function (error, stdout, stderr) {
if ((error != null) && (error != '')) { console.log('ERROR: Unable to uninstall MeshCentral service: ' + error); process.exit(); return; }
console.log(stdout);
try { obj.fs.unlinkSync(obj.path.join(servicepath, 'winservice.js')); } catch (ex) { }
try { obj.fs.rmdirSync(servicepath); } catch (ex) { }
});
} else if (obj.fs.existsSync(obj.path.join(__dirname, '../WinService')) == true) {
require('child_process').exec('node winservice.js --uninstall', { maxBuffer: 512000, timeout: 120000, cwd: obj.path.join(__dirname, '../WinService') }, function (error, stdout, stderr) {
if ((error != null) && (error != '')) { console.log('ERROR: Unable to uninstall MeshCentral service: ' + error); process.exit(); return; }
console.log(stdout);
try { obj.fs.unlinkSync(obj.path.join(__dirname, '../WinService/winservice.js')); } catch (ex) { }
try { obj.fs.rmdirSync(obj.path.join(__dirname, '../WinService')); } catch (ex) { }
});
} else {
require('child_process').exec('node winservice.js --uninstall', { maxBuffer: 512000, timeout: 120000, cwd: __dirname }, function (error, stdout, stderr) {
if ((error != null) && (error != '')) { console.log('ERROR: Unable to uninstall MeshCentral service: ' + error); process.exit(); return; }
console.log(stdout);
});
}
return;
}
}
// If "--launch" is in the arguments, launch now
if (obj.args.launch) {
if (obj.args.vault) { obj.StartVault(); } else { obj.StartEx(); }
} else {
// if "--launch" is not specified, launch the server as a child process.
const startArgs = [];
for (i in process.argv) {
if (i > 0) {
const arg = process.argv[i];
if ((arg.length > 0) && ((arg.indexOf(' ') >= 0) || (arg.indexOf('&') >= 0))) { startArgs.push(arg); } else { startArgs.push(arg); }
}
}
startArgs.push('--launch', process.pid);
obj.launchChildServer(startArgs);
}
};
// Launch MeshCentral as a child server and monitor it.
obj.launchChildServer = function (startArgs) {
const child_process = require('child_process');
try { if (process.traceDeprecation === true) { startArgs.unshift('--trace-deprecation'); } } catch (ex) { }
try { if (process.traceProcessWarnings === true) { startArgs.unshift('--trace-warnings'); } } catch (ex) { }
childProcess = child_process.execFile(process.argv[0], startArgs, { maxBuffer: Infinity, cwd: obj.parentpath }, function (error, stdout, stderr) {
if (childProcess.xrestart == 1) {
setTimeout(function () { obj.launchChildServer(startArgs); }, 500); // This is an expected restart.
} else if (childProcess.xrestart == 2) {
console.log('Expected exit...');
process.exit(); // User CTRL-C exit.
} else if (childProcess.xrestart == 3) {
// Server self-update exit
var version = '';
if (typeof obj.args.selfupdate == 'string') { version = '@' + obj.args.selfupdate; }
else if (typeof obj.args.specificupdate == 'string') { version = '@' + obj.args.specificupdate; delete obj.args.specificupdate; }
const child_process = require('child_process');
const npmpath = ((typeof obj.args.npmpath == 'string') ? obj.args.npmpath : 'npm');
const npmproxy = ((typeof obj.args.npmproxy == 'string') ? (' --proxy ' + obj.args.npmproxy) : '');
const env = Object.assign({}, process.env); // Shallow clone
if (typeof obj.args.npmproxy == 'string') { env['HTTP_PROXY'] = env['HTTPS_PROXY'] = env['http_proxy'] = env['https_proxy'] = obj.args.npmproxy; }
// always use --save-exact - https://stackoverflow.com/a/64507176/1210734
const xxprocess = child_process.exec(npmpath + ' install --save-exact --no-audit meshcentral' + version + npmproxy, { maxBuffer: Infinity, cwd: obj.parentpath, env: env }, function (error, stdout, stderr) {
if ((error != null) && (error != '')) { console.log('Update failed: ' + error); }
});
xxprocess.data = '';
xxprocess.stdout.on('data', function (data) { xxprocess.data += data; });
xxprocess.stderr.on('data', function (data) { xxprocess.data += data; });
xxprocess.on('close', function (code) {
if (code == 0) { console.log('Update completed...'); }
// Run the server updated script if present
if (typeof obj.config.settings.runonserverupdated == 'string') {
const child_process = require('child_process');
var parentpath = __dirname;
if ((__dirname.endsWith('/node_modules/meshcentral')) || (__dirname.endsWith('\\node_modules\\meshcentral')) || (__dirname.endsWith('/node_modules/meshcentral/')) || (__dirname.endsWith('\\node_modules\\meshcentral\\'))) { parentpath = require('path').join(__dirname, '../..'); }
child_process.exec(obj.config.settings.runonserverupdated + ' ' + getCurrentVersion(), { maxBuffer: 512000, timeout: 120000, cwd: parentpath }, function (error, stdout, stderr) { });
}
if (obj.args.cleannpmcacheonupdate === true) {
// Perform NPM cache clean
console.log('Cleaning NPM cache...');
const xxxprocess = child_process.exec(npmpath + ' cache clean --force', { maxBuffer: Infinity, cwd: obj.parentpath, env: env }, function (error, stdout, stderr) { });
xxxprocess.on('close', function (code) { setTimeout(function () { obj.launchChildServer(startArgs); }, 1000); });
} else {
// Run the updated server
setTimeout(function () { obj.launchChildServer(startArgs); }, 1000);
}
});
} else {
if (error != null) {
// This is an un-expected restart
console.log(error);
console.log('ERROR: MeshCentral failed with critical error, check mesherrors.txt. Restarting in 5 seconds...');
setTimeout(function () { obj.launchChildServer(startArgs); }, 5000);
// Run the server error script if present
if (typeof obj.config.settings.runonservererror == 'string') {
const child_process = require('child_process');
var parentpath = __dirname;
if ((__dirname.endsWith('/node_modules/meshcentral')) || (__dirname.endsWith('\\node_modules\\meshcentral')) || (__dirname.endsWith('/node_modules/meshcentral/')) || (__dirname.endsWith('\\node_modules\\meshcentral\\'))) { parentpath = require('path').join(__dirname, '../..'); }
child_process.exec(obj.config.settings.runonservererror + ' ' + getCurrentVersion(), { maxBuffer: 512000, timeout: 120000, cwd: parentpath }, function (error, stdout, stderr) { });
}
}
}
});
childProcess.stdout.on('data', function (data) {
if (data[data.length - 1] == '\n') { data = data.substring(0, data.length - 1); }
if (data.indexOf('Updating settings folder...') >= 0) { childProcess.xrestart = 1; }
else if (data.indexOf('Updating server certificates...') >= 0) { childProcess.xrestart = 1; }
else if (data.indexOf('Server Ctrl-C exit...') >= 0) { childProcess.xrestart = 2; }
else if (data.indexOf('Starting self upgrade...') >= 0) { childProcess.xrestart = 3; }
else if (data.indexOf('Server restart...') >= 0) { childProcess.xrestart = 1; }
else if (data.indexOf('Starting self upgrade to: ') >= 0) { obj.args.specificupdate = data.substring(26).split('\r')[0].split('\n')[0]; childProcess.xrestart = 3; }
var datastr = data;
while (datastr.endsWith('\r') || datastr.endsWith('\n')) { datastr = datastr.substring(0, datastr.length - 1); }
console.log(datastr);
});
childProcess.stderr.on('data', function (data) {
var datastr = data;
while (datastr.endsWith('\r') || datastr.endsWith('\n')) { datastr = datastr.substring(0, datastr.length - 1); }
console.log('ERR: ' + datastr);
if (data.startsWith('le.challenges[tls-sni-01].loopback')) { return; } // Ignore this error output from GreenLock
if (data[data.length - 1] == '\n') { data = data.substring(0, data.length - 1); }
obj.logError(data);
});
childProcess.on('close', function (code) { if ((code != 0) && (code != 123)) { /* console.log("Exited with code " + code); */ } });
};
obj.logError = function (err) {
try {
var errlogpath = null;
if (typeof obj.args.mesherrorlogpath == 'string') { errlogpath = obj.path.join(obj.args.mesherrorlogpath, 'mesherrors.txt'); } else { errlogpath = obj.getConfigFilePath('mesherrors.txt'); }
obj.fs.appendFileSync(errlogpath, '-------- ' + new Date().toLocaleString() + ' ---- ' + getCurrentVersion() + ' --------\r\n\r\n' + err + '\r\n\r\n\r\n');
} catch (ex) { console.log('ERROR: Unable to write to mesherrors.txt.'); }
};
// Get current and latest MeshCentral server versions using NPM
obj.getLatestServerVersion = function (callback) {
if (callback == null) return;
try {
if (typeof obj.args.selfupdate == 'string') { callback(getCurrentVersion(), obj.args.selfupdate); return; } // If we are targetting a specific version, return that one as current.
const child_process = require('child_process');
const npmpath = ((typeof obj.args.npmpath == 'string') ? obj.args.npmpath : 'npm');
const npmproxy = ((typeof obj.args.npmproxy == 'string') ? (' --proxy ' + obj.args.npmproxy) : '');
const env = Object.assign({}, process.env); // Shallow clone
if (typeof obj.args.npmproxy == 'string') { env['HTTP_PROXY'] = env['HTTPS_PROXY'] = env['http_proxy'] = env['https_proxy'] = obj.args.npmproxy; }
const xxprocess = child_process.exec(npmpath + npmproxy + ' view meshcentral dist-tags.latest', { maxBuffer: 512000, cwd: obj.parentpath, env: env }, function (error, stdout, stderr) { });
xxprocess.data = '';
xxprocess.stdout.on('data', function (data) { xxprocess.data += data; });
xxprocess.stderr.on('data', function (data) { });
xxprocess.on('close', function (code) {
var latestVer = null;
if (code == 0) { try { latestVer = xxprocess.data.split(' ').join('').split('\r').join('').split('\n').join(''); } catch (ex) { } }
callback(getCurrentVersion(), latestVer);
});
} catch (ex) { callback(getCurrentVersion(), null, ex); } // If the system is running out of memory, an exception here can easily happen.
};
// Get current version and all MeshCentral server tags using NPM
obj.getServerTags = function (callback) {
if (callback == null) return;
try {
if (typeof obj.args.selfupdate == 'string') { callback({ current: getCurrentVersion(), latest: obj.args.selfupdate }); return; } // If we are targetting a specific version, return that one as current.
const child_process = require('child_process');
const npmpath = ((typeof obj.args.npmpath == 'string') ? obj.args.npmpath : 'npm');
const npmproxy = ((typeof obj.args.npmproxy == 'string') ? (' --proxy ' + obj.args.npmproxy) : '');
const env = Object.assign({}, process.env); // Shallow clone
if (typeof obj.args.npmproxy == 'string') { env['HTTP_PROXY'] = env['HTTPS_PROXY'] = env['http_proxy'] = env['https_proxy'] = obj.args.npmproxy; }
const xxprocess = child_process.exec(npmpath + npmproxy + ' dist-tag ls meshcentral', { maxBuffer: 512000, cwd: obj.parentpath, env: env }, function (error, stdout, stderr) { });
xxprocess.data = '';
xxprocess.stdout.on('data', function (data) { xxprocess.data += data; });
xxprocess.stderr.on('data', function (data) { });
xxprocess.on('close', function (code) {
var tags = { current: getCurrentVersion() };
if (code == 0) {
try {
var lines = xxprocess.data.split('\r\n').join('\n').split('\n');
for (var i in lines) { var s = lines[i].split(': '); if ((s.length == 2) && (obj.args.npmtag == null) || (obj.args.npmtag == s[0])) { tags[s[0]] = s[1]; } }
} catch (ex) { }
}
callback(tags);
});
} catch (ex) { callback({ current: getCurrentVersion() }, ex); } // If the system is running out of memory, an exception here can easily happen.
};
// Use NPM to get list of versions
obj.getServerVersions = function (callback) {
try {
const child_process = require('child_process');
const npmpath = ((typeof obj.args.npmpath == 'string') ? obj.args.npmpath : 'npm');
const npmproxy = ((typeof obj.args.npmproxy == 'string') ? (' --proxy ' + obj.args.npmproxy) : '');
const env = Object.assign({}, process.env); // Shallow clone
if (typeof obj.args.npmproxy == 'string') { env['HTTP_PROXY'] = env['HTTPS_PROXY'] = env['http_proxy'] = env['https_proxy'] = obj.args.npmproxy; }
const xxprocess = child_process.exec(npmpath + npmproxy + ' view meshcentral versions --json', { maxBuffer: 512000, cwd: obj.parentpath, env: env }, function (error, stdout, stderr) { });
xxprocess.data = '';
xxprocess.stdout.on('data', function (data) { xxprocess.data += data; });
xxprocess.stderr.on('data', function (data) { });
xxprocess.on('close', function (code) {
(code == 0) ? callback(xxprocess.data) : callback('{}');
});
} catch (ex) { callback('{}'); }
};
// Initiate server self-update
obj.performServerUpdate = function (version) {
if (obj.serverSelfWriteAllowed != true) return false;
if ((version == null) || (version == '') || (typeof version != 'string')) { console.log('Starting self upgrade...'); } else { console.log('Starting self upgrade to: ' + version); }
process.exit(200);
return true;
};
// Initiate server self-update
obj.performServerCertUpdate = function () { console.log('Updating server certificates...'); process.exit(200); };
// Start by loading configuration from Vault
obj.StartVault = function () {
// Check that the configuration can only be loaded from one place
if ((obj.args.vault != null) && (obj.args.loadconfigfromdb != null)) { console.log("Can't load configuration from both database and Vault."); process.exit(); return; }
// Fix arguments if needed
if (typeof obj.args.vault == 'string') {
obj.args.vault = { endpoint: obj.args.vault };
if (typeof obj.args.token == 'string') { obj.args.vault.token = obj.args.token; }
if (typeof obj.args.unsealkey == 'string') { obj.args.vault.unsealkey = obj.args.unsealkey; }
if (typeof obj.args.name == 'string') { obj.args.vault.name = obj.args.name; }
}
// Load configuration for HashiCorp's Vault if needed
if (obj.args.vault) {
if (obj.args.vault.endpoint == null) { console.log('Missing Vault endpoint.'); process.exit(); return; }
if (obj.args.vault.token == null) { console.log('Missing Vault token.'); process.exit(); return; }
if (obj.args.vault.unsealkey == null) { console.log('Missing Vault unsealkey.'); process.exit(); return; }
if (obj.args.vault.name == null) { obj.args.vault.name = 'meshcentral'; }
// Get new instance of the client
const vault = require("node-vault")({ endpoint: obj.args.vault.endpoint, token: obj.args.vault.token });
vault.unseal({ key: obj.args.vault.unsealkey })
.then(function () {
if (obj.args.vaultdeleteconfigfiles) {
vault.delete('secret/data/' + obj.args.vault.name)
.then(function (r) { console.log('Done.'); process.exit(); })
.catch(function (x) { console.log(x); process.exit(); });
} else if (obj.args.vaultpushconfigfiles) {
// Push configuration files into Vault
if ((obj.args.vaultpushconfigfiles == '*') || (obj.args.vaultpushconfigfiles === true)) { obj.args.vaultpushconfigfiles = obj.datapath; }
obj.fs.readdir(obj.args.vaultpushconfigfiles, function (err, files) {
if (err != null) { console.log('ERROR: Unable to read from folder ' + obj.args.vaultpushconfigfiles); process.exit(); return; }
var configFound = false;
for (var i in files) { if (files[i] == 'config.json') { configFound = true; } }
if (configFound == false) { console.log('ERROR: No config.json in folder ' + obj.args.vaultpushconfigfiles); process.exit(); return; }
var configFiles = {};
for (var i in files) {
const file = files[i];
if ((file == 'config.json') || file.endsWith('.key') || file.endsWith('.crt') || (file == 'terms.txt') || file.endsWith('.jpg') || file.endsWith('.png')) {
const path = obj.path.join(obj.args.vaultpushconfigfiles, files[i]), binary = Buffer.from(obj.fs.readFileSync(path, { encoding: 'binary' }), 'binary');
console.log('Pushing ' + file + ', ' + binary.length + ' bytes.');
if (file.endsWith('.json') || file.endsWith('.key') || file.endsWith('.crt')) { configFiles[file] = binary.toString(); } else { configFiles[file] = binary.toString('base64'); }
}
}
vault.write('secret/data/' + obj.args.vault.name, { "data": configFiles })
.then(function (r) { console.log('Done.'); process.exit(); })
.catch(function (x) { console.log(x); process.exit(); });
});
} else {
// Read configuration files from Vault
vault.read('secret/data/' + obj.args.vault.name)
.then(function (r) {
if ((r == null) || (r.data == null) || (r.data.data == null)) { console.log('Unable to read configuration from Vault.'); process.exit(); return; }
var configFiles = obj.configurationFiles = r.data.data;
// Decode Base64 when needed
for (var file in configFiles) { if (!file.endsWith('.json') && !file.endsWith('.key') && !file.endsWith('.crt')) { configFiles[file] = Buffer.from(configFiles[file], 'base64'); } }
// Save all of the files
if (obj.args.vaultpullconfigfiles) {
for (var i in configFiles) {
var fullFileName = obj.path.join(obj.args.vaultpullconfigfiles, i);
try { obj.fs.writeFileSync(fullFileName, configFiles[i]); } catch (ex) { console.log('Unable to write to ' + fullFileName); process.exit(); return; }
console.log('Pulling ' + i + ', ' + configFiles[i].length + ' bytes.');
}
console.log('Done.');
process.exit();
}
// Parse the new configuration file
var config2 = null;
try { config2 = JSON.parse(configFiles['config.json']); } catch (ex) { console.log('Error, unable to parse config.json from Vault.'); process.exit(); return; }
// Set the command line arguments to the config file if they are not present
if (!config2.settings) { config2.settings = {}; }
for (var i in args) { config2.settings[i] = args[i]; }
obj.args = args = config2.settings;
// Lower case all keys in the config file
obj.common.objKeysToLower(config2, ['ldapoptions', 'defaultuserwebstate', 'forceduserwebstate', 'httpheaders', 'telegram/proxy']);
// Grad some of the values from the original config.json file if present.
if ((config.settings.vault != null) && (config2.settings != null)) { config2.settings.vault = config.settings.vault; }
// We got a new config.json from the database, let's use it.
config = obj.config = config2;
obj.StartEx();
})
.catch(function (x) { console.log(x); process.exit(); });
}
}).catch(function (x) { console.log(x); process.exit(); });
return;
}
}
// Look for easy command line instructions and do them here.
obj.StartEx = function () {
var i;
//var wincmd = require('node-windows');
//wincmd.list(function (svc) { console.log(svc); }, true);
// Setup syslog support. Not supported on Windows.
if ((require('os').platform() != 'win32') && ((config.settings.syslog != null) || (config.settings.syslogjson != null) || (config.settings.syslogauth != null))) {
if (config.settings.syslog === true) { config.settings.syslog = 'meshcentral'; }
if (config.settings.syslogjson === true) { config.settings.syslogjson = 'meshcentral-json'; }
if (config.settings.syslogauth === true) { config.settings.syslogauth = 'meshcentral-auth'; }
if (typeof config.settings.syslog == 'string') {
obj.syslog = require('modern-syslog');
console.log('Starting ' + config.settings.syslog + ' syslog.');
obj.syslog.init(config.settings.syslog, obj.syslog.LOG_PID | obj.syslog.LOG_ODELAY, obj.syslog.LOG_LOCAL0);
obj.syslog.log(obj.syslog.LOG_INFO, "MeshCentral v" + getCurrentVersion() + " Server Start");
}
if (typeof config.settings.syslogjson == 'string') {
obj.syslogjson = require('modern-syslog');
console.log('Starting ' + config.settings.syslogjson + ' JSON syslog.');
obj.syslogjson.init(config.settings.syslogjson, obj.syslogjson.LOG_PID | obj.syslogjson.LOG_ODELAY, obj.syslogjson.LOG_LOCAL0);
obj.syslogjson.log(obj.syslogjson.LOG_INFO, "MeshCentral v" + getCurrentVersion() + " Server Start");
}
if (typeof config.settings.syslogauth == 'string') {
obj.syslogauth = require('modern-syslog');
console.log('Starting ' + config.settings.syslogauth + ' auth syslog.');
obj.syslogauth.init(config.settings.syslogauth, obj.syslogauth.LOG_PID | obj.syslogauth.LOG_ODELAY, obj.syslogauth.LOG_LOCAL0);
obj.syslogauth.log(obj.syslogauth.LOG_INFO, "MeshCentral v" + getCurrentVersion() + " Server Start");
}
}
// Setup TCP syslog support, this works on all OS's.
if (config.settings.syslogtcp != null) {
const syslog = require('syslog');
if (config.settings.syslogtcp === true) {
obj.syslogtcp = syslog.createClient(514, 'localhost');
} else {
const sp = config.settings.syslogtcp.split(':');
obj.syslogtcp = syslog.createClient(parseInt(sp[1]), sp[0]);
}
obj.syslogtcp.log("MeshCentral v" + getCurrentVersion() + " Server Start", obj.syslogtcp.LOG_INFO);
}
// Check top level configuration for any unrecognized values
if (config) { for (var i in config) { if ((typeof i == 'string') && (i.length > 0) && (i[0] != '_') && (['settings', 'domaindefaults', 'domains', 'configfiles', 'smtp', 'letsencrypt', 'peers', 'sms', 'messaging', 'sendgrid', 'sendmail', 'firebase', 'firebaserelay', '$schema'].indexOf(i) == -1)) { addServerWarning('Unrecognized configuration option \"' + i + '\".', 3, [i]); } } }
// Read IP lists from files if applicable
config.settings.userallowedip = obj.args.userallowedip = readIpListFromFile(obj.args.userallowedip);
config.settings.userblockedip = obj.args.userblockedip = readIpListFromFile(obj.args.userblockedip);
config.settings.agentallowedip = obj.args.agentallowedip = readIpListFromFile(obj.args.agentallowedip);
config.settings.agentblockedip = obj.args.agentblockedip = readIpListFromFile(obj.args.agentblockedip);
config.settings.swarmallowedip = obj.args.swarmallowedip = readIpListFromFile(obj.args.swarmallowedip);
// Check IP lists and ranges
if (typeof obj.args.userallowedip == 'string') { if (obj.args.userallowedip == '') { config.settings.userallowedip = obj.args.userallowedip = null; } else { config.settings.userallowedip = obj.args.userallowedip = obj.args.userallowedip.split(' ').join('').split(','); } }
if (typeof obj.args.userblockedip == 'string') { if (obj.args.userblockedip == '') { config.settings.userblockedip = obj.args.userblockedip = null; } else { config.settings.userblockedip = obj.args.userblockedip = obj.args.userblockedip.split(' ').join('').split(','); } }
if (typeof obj.args.agentallowedip == 'string') { if (obj.args.agentallowedip == '') { config.settings.agentallowedip = obj.args.agentallowedip = null; } else { config.settings.agentallowedip = obj.args.agentallowedip = obj.args.agentallowedip.split(' ').join('').split(','); } }
if (typeof obj.args.agentblockedip == 'string') { if (obj.args.agentblockedip == '') { config.settings.agentblockedip = obj.args.agentblockedip = null; } else { config.settings.agentblockedip = obj.args.agentblockedip = obj.args.agentblockedip.split(' ').join('').split(','); } }
if (typeof obj.args.swarmallowedip == 'string') { if (obj.args.swarmallowedip == '') { obj.args.swarmallowedip = null; } else { obj.args.swarmallowedip = obj.args.swarmallowedip.split(' ').join('').split(','); } }
if ((typeof obj.args.agentupdateblocksize == 'number') && (obj.args.agentupdateblocksize >= 1024) && (obj.args.agentupdateblocksize <= 65531)) { obj.agentUpdateBlockSize = obj.args.agentupdateblocksize; }
if (typeof obj.args.trustedproxy == 'string') { obj.args.trustedproxy = obj.args.trustedproxy.split(' ').join('').split(','); }
if (typeof obj.args.tlsoffload == 'string') { obj.args.tlsoffload = obj.args.tlsoffload.split(' ').join('').split(','); }
// Check the "cookieIpCheck" value
if ((obj.args.cookieipcheck === false) || (obj.args.cookieipcheck == 'none')) { obj.args.cookieipcheck = 'none'; }
else if ((typeof obj.args.cookieipcheck != 'string') || (obj.args.cookieipcheck.toLowerCase() != 'strict')) { obj.args.cookieipcheck = 'lax'; }
else { obj.args.cookieipcheck = 'strict'; }
// Check the "cookieSameSite" value
if (typeof obj.args.cookiesamesite != 'string') { delete obj.args.cookiesamesite; }
else if (['none', 'lax', 'strict'].indexOf(obj.args.cookiesamesite.toLowerCase()) == -1) { delete obj.args.cookiesamesite; } else { obj.args.cookiesamesite = obj.args.cookiesamesite.toLowerCase(); }
// Check if WebSocket compression is supported. It's known to be broken in NodeJS v11.11 to v12.15, and v13.2
const verSplit = process.version.substring(1).split('.');
const ver = parseInt(verSplit[0]) + (parseInt(verSplit[1]) / 100);
if (((ver >= 11.11) && (ver <= 12.15)) || (ver == 13.2)) {
if ((obj.args.wscompression === true) || (obj.args.agentwscompression === true)) { addServerWarning('WebSocket compression is disabled, this feature is broken in NodeJS v11.11 to v12.15 and v13.2', 4); }
obj.args.wscompression = obj.args.agentwscompression = false;
obj.config.settings.wscompression = obj.config.settings.agentwscompression = false;
}
// Local console tracing
if (typeof obj.args.debug == 'string') { obj.debugSources = obj.args.debug.toLowerCase().split(','); }
else if (typeof obj.args.debug == 'object') { obj.debugSources = obj.args.debug; }
else if (obj.args.debug === true) { obj.debugSources = '*'; }
require('./db.js').CreateDB(obj,
function (db) {
obj.db = db;
obj.db.SetupDatabase(function (dbversion) {
// See if any database operations needs to be completed
if (obj.args.deletedomain) { obj.db.DeleteDomain(obj.args.deletedomain, function () { console.log('Deleted domain ' + obj.args.deletedomain + '.'); process.exit(); }); return; }
if (obj.args.deletedefaultdomain) { obj.db.DeleteDomain('', function () { console.log('Deleted default domain.'); process.exit(); }); return; }
if (obj.args.showall) { obj.db.GetAll(function (err, docs) { console.log(JSON.stringify(docs, null, 2)); process.exit(); }); return; }
if (obj.args.showusers) { obj.db.GetAllType('user', function (err, docs) { console.log(JSON.stringify(docs, null, 2)); process.exit(); }); return; }
if (obj.args.showitem) { obj.db.Get(obj.args.showitem, function (err, docs) { console.log(JSON.stringify(docs, null, 2)); process.exit(); }); return; }
if (obj.args.listuserids) { obj.db.GetAllType('user', function (err, docs) { for (var i in docs) { console.log(docs[i]._id); } process.exit(); }); return; }
if (obj.args.showusergroups) { obj.db.GetAllType('ugrp', function (err, docs) { console.log(JSON.stringify(docs, null, 2)); process.exit(); }); return; }
if (obj.args.shownodes) { obj.db.GetAllType('node', function (err, docs) { console.log(JSON.stringify(docs, null, 2)); process.exit(); }); return; }
if (obj.args.showallmeshes) { obj.db.GetAllType('mesh', function (err, docs) { console.log(JSON.stringify(docs, null, 2)); process.exit(); }); return; }
if (obj.args.showmeshes) { obj.db.GetAllType('mesh', function (err, docs) { var x = []; for (var i in docs) { if (docs[i].deleted == null) { x.push(docs[i]); } } console.log(JSON.stringify(x, null, 2)); process.exit(); }); return; }
if (obj.args.showevents) { obj.db.GetAllEvents(function (err, docs) { console.log(JSON.stringify(docs, null, 2)); process.exit(); }); return; }
if (obj.args.showsmbios) { obj.db.GetAllSMBIOS(function (err, docs) { console.log(JSON.stringify(docs, null, 2)); process.exit(); }); return; }
if (obj.args.showpower) { obj.db.getAllPower(function (err, docs) { console.log(JSON.stringify(docs, null, 2)); process.exit(); }); return; }
if (obj.args.clearpower) { obj.db.removeAllPowerEvents(function () { process.exit(); }); return; }
if (obj.args.showiplocations) { obj.db.GetAllType('iploc', function (err, docs) { console.log(docs); process.exit(); }); return; }
if (obj.args.logintoken) { obj.getLoginToken(obj.args.logintoken, function (r) { console.log(r); process.exit(); }); return; }
if (obj.args.logintokenkey) { obj.showLoginTokenKey(function (r) { console.log(r); process.exit(); }); return; }
if (obj.args.recordencryptionrecode) { obj.db.performRecordEncryptionRecode(function (count) { console.log('Re-encoded ' + count + ' record(s).'); process.exit(); }); return; }
if (obj.args.dbstats) { obj.db.getDbStats(function (stats) { console.log(stats); process.exit(); }); return; }
if (obj.args.createaccount) { // Create a new user account
if ((typeof obj.args.createaccount != 'string') || ((obj.args.pass == null) && (obj.args.hashpass == null)) || (obj.args.pass == '') || (obj.args.hashpass == '') || (obj.args.createaccount.indexOf(' ') >= 0)) { console.log("Usage: --createaccount [userid] --pass [password] --domain (domain) --email (email) --name (name)."); process.exit(); return; }
var userid = 'user/' + (obj.args.domain ? obj.args.domain : '') + '/' + obj.args.createaccount.toLowerCase(), domainid = obj.args.domain ? obj.args.domain : '';
if (obj.args.createaccount.startsWith('user/')) { userid = obj.args.createaccount; domainid = obj.args.createaccount.split('/')[1]; }
if (userid.split('/').length != 3) { console.log("Invalid userid."); process.exit(); return; }
obj.db.Get(userid, function (err, docs) {
if (err != null) { console.log("Database error: " + err); process.exit(); return; }
if ((docs != null) && (docs.length != 0)) { console.log('User already exists.'); process.exit(); return; }
if ((domainid != '') && ((config.domains == null) || (config.domains[domainid] == null))) { console.log("Invalid domain."); process.exit(); return; }
const user = { _id: userid, type: 'user', name: (typeof obj.args.name == 'string') ? obj.args.name : (userid.split('/')[2]), domain: domainid, creation: Math.floor(Date.now() / 1000), links: {} };
if (typeof obj.args.email == 'string') { user.email = obj.args.email; user.emailVerified = true; }
if (obj.args.hashpass) {
// Create an account using a pre-hashed password. Use --hashpassword to pre-hash a password.
var hashpasssplit = obj.args.hashpass.split(',');
if (hashpasssplit.length != 2) { console.log("Invalid hashed password."); process.exit(); return; }
user.salt = hashpasssplit[0];
user.hash = hashpasssplit[1];
obj.db.Set(user, function () { console.log("Done. This command will only work if MeshCentral is stopped."); process.exit(); return; });
} else {
// Hash the password and create the account.
require('./pass').hash(obj.args.pass, function (err, salt, hash, tag) { if (err) { console.log("Unable create account password: " + err); process.exit(); return; } user.salt = salt; user.hash = hash; obj.db.Set(user, function () { console.log("Done."); process.exit(); return; }); }, 0);
}
});
return;
}
if (obj.args.resetaccount) { // Unlock a user account, set a new password and remove 2FA
if ((typeof obj.args.resetaccount != 'string') || (obj.args.resetaccount.indexOf(' ') >= 0)) { console.log("Usage: --resetaccount [userid] --domain (domain) --pass [password]."); process.exit(); return; }
var userid = 'user/' + (obj.args.domain ? obj.args.domain : '') + '/' + obj.args.resetaccount.toLowerCase();
if (obj.args.resetaccount.startsWith('user/')) { userid = obj.args.resetaccount; }
if (userid.split('/').length != 3) { console.log("Invalid userid."); process.exit(); return; }
obj.db.Get(userid, function (err, docs) {
if (err != null) { console.log("Database error: " + err); process.exit(); return; }
if ((docs == null) || (docs.length == 0)) { console.log("Unknown userid, usage: --resetaccount [userid] --domain (domain) --pass [password]."); process.exit(); return; }
const user = docs[0]; if ((user.siteadmin) && (user.siteadmin != 0xFFFFFFFF) && (user.siteadmin & 32) != 0) { user.siteadmin -= 32; } // Unlock the account.
delete user.phone; delete user.otpekey; delete user.otpsecret; delete user.otpkeys; delete user.otphkeys; delete user.otpdev; delete user.otpsms; delete user.otpmsg; // Disable 2FA
delete user.msghandle; // Disable users 2fa messaging too
var config = getConfig(false);
if (config.domains[user.domain].auth || config.domains[user.domain].authstrategies) {