forked from Ylianst/MeshCentral
-
Notifications
You must be signed in to change notification settings - Fork 0
/
webserver.js
9181 lines (8299 loc) · 621 KB
/
webserver.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 web server
* @author Ylian Saint-Hilaire
* @copyright Intel Corporation 2018-2022
* @license Apache-2.0
* @version v0.0.1
*/
/*jslint node: true */
/*jshint node: true */
/*jshint strict:false */
/*jshint -W097 */
/*jshint esversion: 6 */
'use strict';
// SerialTunnel object is used to embed TLS within another connection.
function SerialTunnel(options) {
var obj = new require('stream').Duplex(options);
obj.forwardwrite = null;
obj.updateBuffer = function (chunk) { this.push(chunk); };
obj._write = function (chunk, encoding, callback) { if (obj.forwardwrite != null) { obj.forwardwrite(chunk); } else { console.err("Failed to fwd _write."); } if (callback) callback(); }; // Pass data written to forward
obj._read = function (size) { }; // Push nothing, anything to read should be pushed from updateBuffer()
return obj;
}
// ExpressJS login sample
// https://github.com/expressjs/express/blob/master/examples/auth/index.js
// Polyfill startsWith/endsWith for older NodeJS
if (!String.prototype.startsWith) { String.prototype.startsWith = function (searchString, position) { position = position || 0; return this.substr(position, searchString.length) === searchString; }; }
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; }; }
// Construct a HTTP server object
module.exports.CreateWebServer = function (parent, db, args, certificates, doneFunc) {
var obj = {}, i = 0;
// Modules
obj.fs = require('fs');
obj.net = require('net');
obj.tls = require('tls');
obj.path = require('path');
obj.bodyParser = require('body-parser');
obj.exphbs = require('express-handlebars');
obj.crypto = require('crypto');
obj.common = require('./common.js');
obj.express = require('express');
obj.meshAgentHandler = require('./meshagent.js');
obj.meshRelayHandler = require('./meshrelay.js');
obj.meshDeviceFileHandler = require('./meshdevicefile.js');
obj.meshDesktopMultiplexHandler = require('./meshdesktopmultiplex.js');
obj.meshIderHandler = require('./amt/amt-ider.js');
obj.meshUserHandler = require('./meshuser.js');
obj.interceptor = require('./interceptor');
obj.uaparser = require('ua-parser-js');
const constants = (obj.crypto.constants ? obj.crypto.constants : require('constants')); // require('constants') is deprecated in Node 11.10, use require('crypto').constants instead.
// Setup WebAuthn / FIDO2
obj.webauthn = require('./webauthn.js').CreateWebAuthnModule();
// Variables
obj.args = args;
obj.parent = parent;
obj.filespath = parent.filespath;
obj.db = db;
obj.app = obj.express();
if (obj.args.agentport) { obj.agentapp = obj.express(); }
if (args.compression !== false) { obj.app.use(require('compression')()); }
obj.app.disable('x-powered-by');
obj.tlsServer = null;
obj.tcpServer = null;
obj.certificates = certificates;
obj.users = {}; // UserID --> User
obj.meshes = {}; // MeshID --> Mesh (also called device group)
obj.userGroups = {}; // UGrpID --> User Group
obj.userAllowedIp = args.userallowedip; // List of allowed IP addresses for users
obj.agentAllowedIp = args.agentallowedip; // List of allowed IP addresses for agents
obj.agentBlockedIp = args.agentblockedip; // List of blocked IP addresses for agents
obj.tlsSniCredentials = null;
obj.dnsDomains = {};
obj.relaySessionCount = 0;
obj.relaySessionErrorCount = 0;
obj.blockedUsers = 0;
obj.blockedAgents = 0;
obj.renderPages = null;
obj.renderLanguages = [];
obj.destroyedSessions = {}; // userid/req.session.x --> destroyed session time
// Web relay sessions
var webRelayNextSessionId = 1;
var webRelaySessions = {} // UserId/SessionId/Host --> Web Relay Session
var webRelayCleanupTimer = null;
// Monitor web relay session removals
parent.AddEventDispatch(['server-shareremove'], obj);
obj.HandleEvent = function (source, event, ids, id) {
if (event.action == 'removedDeviceShare') {
for (var relaySessionId in webRelaySessions) {
// A share was removed that matches an active session, close the web relay session.
if (webRelaySessions[relaySessionId].xpublicid === event.publicid) { webRelaySessions[relaySessionId].close(); }
}
}
}
// Mesh Rights
const MESHRIGHT_EDITMESH = 0x00000001;
const MESHRIGHT_MANAGEUSERS = 0x00000002;
const MESHRIGHT_MANAGECOMPUTERS = 0x00000004;
const MESHRIGHT_REMOTECONTROL = 0x00000008;
const MESHRIGHT_AGENTCONSOLE = 0x00000010;
const MESHRIGHT_SERVERFILES = 0x00000020;
const MESHRIGHT_WAKEDEVICE = 0x00000040;
const MESHRIGHT_SETNOTES = 0x00000080;
const MESHRIGHT_REMOTEVIEWONLY = 0x00000100;
const MESHRIGHT_NOTERMINAL = 0x00000200;
const MESHRIGHT_NOFILES = 0x00000400;
const MESHRIGHT_NOAMT = 0x00000800;
const MESHRIGHT_DESKLIMITEDINPUT = 0x00001000;
const MESHRIGHT_LIMITEVENTS = 0x00002000;
const MESHRIGHT_CHATNOTIFY = 0x00004000;
const MESHRIGHT_UNINSTALL = 0x00008000;
const MESHRIGHT_NODESKTOP = 0x00010000;
const MESHRIGHT_REMOTECOMMAND = 0x00020000;
const MESHRIGHT_RESETOFF = 0x00040000;
const MESHRIGHT_GUESTSHARING = 0x00080000;
const MESHRIGHT_ADMIN = 0xFFFFFFFF;
// Site rights
const SITERIGHT_SERVERBACKUP = 0x00000001;
const SITERIGHT_MANAGEUSERS = 0x00000002;
const SITERIGHT_SERVERRESTORE = 0x00000004;
const SITERIGHT_FILEACCESS = 0x00000008;
const SITERIGHT_SERVERUPDATE = 0x00000010;
const SITERIGHT_LOCKED = 0x00000020;
const SITERIGHT_NONEWGROUPS = 0x00000040;
const SITERIGHT_NOMESHCMD = 0x00000080;
const SITERIGHT_USERGROUPS = 0x00000100;
const SITERIGHT_RECORDINGS = 0x00000200;
const SITERIGHT_LOCKSETTINGS = 0x00000400;
const SITERIGHT_ALLEVENTS = 0x00000800;
const SITERIGHT_NONEWDEVICES = 0x00001000;
const SITERIGHT_ADMIN = 0xFFFFFFFF;
// Setup SSPI authentication if needed
if ((obj.parent.platform == 'win32') && (obj.args.nousers != true) && (obj.parent.config != null) && (obj.parent.config.domains != null)) {
for (i in obj.parent.config.domains) { if (obj.parent.config.domains[i].auth == 'sspi') { var nodeSSPI = require('node-sspi'); obj.parent.config.domains[i].sspi = new nodeSSPI({ retrieveGroups: false, offerBasic: false }); } }
}
// Perform hash on web certificate and agent certificate
obj.webCertificateHash = parent.certificateOperations.getPublicKeyHashBinary(obj.certificates.web.cert);
obj.webCertificateHashs = { '': obj.webCertificateHash };
obj.webCertificateHashBase64 = Buffer.from(obj.webCertificateHash, 'binary').toString('base64').replace(/\+/g, '@').replace(/\//g, '$');
obj.webCertificateFullHash = parent.certificateOperations.getCertHashBinary(obj.certificates.web.cert);
obj.webCertificateFullHashs = { '': obj.webCertificateFullHash };
obj.webCertificateExpire = { '': Date.parse(parent.certificateOperations.forge.pki.certificateFromPem(parent.certificates.web.cert).validity.notAfter) };
obj.agentCertificateHashHex = parent.certificateOperations.getPublicKeyHash(obj.certificates.agent.cert);
obj.agentCertificateHashBase64 = Buffer.from(obj.agentCertificateHashHex, 'hex').toString('base64').replace(/\+/g, '@').replace(/\//g, '$');
obj.agentCertificateAsn1 = parent.certificateOperations.forge.asn1.toDer(parent.certificateOperations.forge.pki.certificateToAsn1(parent.certificateOperations.forge.pki.certificateFromPem(parent.certificates.agent.cert))).getBytes();
obj.defaultWebCertificateHash = obj.certificates.webdefault ? parent.certificateOperations.getPublicKeyHashBinary(obj.certificates.webdefault.cert) : null;
obj.defaultWebCertificateFullHash = obj.certificates.webdefault ? parent.certificateOperations.getCertHashBinary(obj.certificates.webdefault.cert) : null;
// Compute the hash of all of the web certificates for each domain
for (var i in obj.parent.config.domains) {
if (obj.parent.config.domains[i].certhash != null) {
// If the web certificate hash is provided, use it.
obj.webCertificateHashs[i] = obj.webCertificateFullHashs[i] = Buffer.from(obj.parent.config.domains[i].certhash, 'hex').toString('binary');
if (obj.parent.config.domains[i].certkeyhash != null) { obj.webCertificateHashs[i] = Buffer.from(obj.parent.config.domains[i].certkeyhash, 'hex').toString('binary'); }
delete obj.webCertificateExpire[i]; // Expire time is not provided
} else if ((obj.parent.config.domains[i].dns != null) && (obj.parent.config.domains[i].certs != null)) {
// If the domain has a different DNS name, use a different certificate hash.
// Hash the full certificate
obj.webCertificateFullHashs[i] = parent.certificateOperations.getCertHashBinary(obj.parent.config.domains[i].certs.cert);
obj.webCertificateExpire[i] = Date.parse(parent.certificateOperations.forge.pki.certificateFromPem(obj.parent.config.domains[i].certs.cert).validity.notAfter);
try {
// Decode a RSA certificate and hash the public key.
obj.webCertificateHashs[i] = parent.certificateOperations.getPublicKeyHashBinary(obj.parent.config.domains[i].certs.cert);
} catch (ex) {
// This may be a ECDSA certificate, hash the entire cert.
obj.webCertificateHashs[i] = obj.webCertificateFullHashs[i];
}
} else if ((obj.parent.config.domains[i].dns != null) && (obj.certificates.dns[i] != null)) {
// If this domain has a DNS and a matching DNS cert, use it. This case works for wildcard certs.
obj.webCertificateFullHashs[i] = parent.certificateOperations.getCertHashBinary(obj.certificates.dns[i].cert);
obj.webCertificateHashs[i] = parent.certificateOperations.getPublicKeyHashBinary(obj.certificates.dns[i].cert);
obj.webCertificateExpire[i] = Date.parse(parent.certificateOperations.forge.pki.certificateFromPem(obj.certificates.dns[i].cert).validity.notAfter);
} else if (i != '') {
// For any other domain, use the default cert.
obj.webCertificateFullHashs[i] = obj.webCertificateFullHashs[''];
obj.webCertificateHashs[i] = obj.webCertificateHashs[''];
obj.webCertificateExpire[i] = obj.webCertificateExpire[''];
}
}
// If we are running the legacy swarm server, compute the hash for that certificate
if (parent.certificates.swarmserver != null) {
obj.swarmCertificateAsn1 = parent.certificateOperations.forge.asn1.toDer(parent.certificateOperations.forge.pki.certificateToAsn1(parent.certificateOperations.forge.pki.certificateFromPem(parent.certificates.swarmserver.cert))).getBytes();
obj.swarmCertificateHash384 = parent.certificateOperations.forge.pki.getPublicKeyFingerprint(parent.certificateOperations.forge.pki.certificateFromPem(obj.certificates.swarmserver.cert).publicKey, { md: parent.certificateOperations.forge.md.sha384.create(), encoding: 'binary' });
obj.swarmCertificateHash256 = parent.certificateOperations.forge.pki.getPublicKeyFingerprint(parent.certificateOperations.forge.pki.certificateFromPem(obj.certificates.swarmserver.cert).publicKey, { md: parent.certificateOperations.forge.md.sha256.create(), encoding: 'binary' });
}
// Main lists
obj.wsagents = {}; // NodeId --> Agent
obj.wsagentsWithBadWebCerts = {}; // NodeId --> Agent
obj.wsagentsDisconnections = {};
obj.wsagentsDisconnectionsTimer = null;
obj.duplicateAgentsLog = {};
obj.wssessions = {}; // UserId --> Array Of Sessions
obj.wssessions2 = {}; // "UserId + SessionRnd" --> Session (Note that the SessionId is the UserId + / + SessionRnd)
obj.wsPeerSessions = {}; // ServerId --> Array Of "UserId + SessionRnd"
obj.wsPeerSessions2 = {}; // "UserId + SessionRnd" --> ServerId
obj.wsPeerSessions3 = {}; // ServerId --> UserId --> [ SessionId ]
obj.sessionsCount = {}; // Merged session counters, used when doing server peering. UserId --> SessionCount
obj.wsrelays = {}; // Id -> Relay
obj.desktoprelays = {}; // Id -> Desktop Multiplexer Relay
obj.wsPeerRelays = {}; // Id -> { ServerId, Time }
var tlsSessionStore = {}; // Store TLS session information for quick resume.
var tlsSessionStoreCount = 0; // Number of cached TLS session information in store.
// Setup randoms
obj.crypto.randomBytes(48, function (err, buf) { obj.httpAuthRandom = buf; });
obj.crypto.randomBytes(16, function (err, buf) { obj.httpAuthRealm = buf.toString('hex'); });
obj.crypto.randomBytes(48, function (err, buf) { obj.relayRandom = buf; });
// Get non-english web pages and emails
getRenderList();
getEmailLanguageList();
// Setup DNS domain TLS SNI credentials
{
var dnscount = 0;
obj.tlsSniCredentials = {};
for (i in obj.certificates.dns) { if (obj.parent.config.domains[i].dns != null) { obj.dnsDomains[obj.parent.config.domains[i].dns.toLowerCase()] = obj.parent.config.domains[i]; obj.tlsSniCredentials[obj.parent.config.domains[i].dns] = obj.tls.createSecureContext(obj.certificates.dns[i]).context; dnscount++; } }
if (dnscount > 0) { obj.tlsSniCredentials[''] = obj.tls.createSecureContext({ cert: obj.certificates.web.cert, key: obj.certificates.web.key, ca: obj.certificates.web.ca }).context; } else { obj.tlsSniCredentials = null; }
}
function TlsSniCallback(name, cb) {
var c = obj.tlsSniCredentials[name];
if (c != null) {
cb(null, c);
} else {
cb(null, obj.tlsSniCredentials['']);
}
}
function EscapeHtml(x) { if (typeof x == 'string') return x.replace(/&/g, '&').replace(/>/g, '>').replace(/</g, '<').replace(/"/g, '"').replace(/'/g, '''); if (typeof x == 'boolean') return x; if (typeof x == 'number') return x; }
//function EscapeHtmlBreaks(x) { if (typeof x == "string") return x.replace(/&/g, '&').replace(/>/g, '>').replace(/</g, '<').replace(/"/g, '"').replace(/'/g, ''').replace(/\r/g, '<br />').replace(/\n/g, '').replace(/\t/g, ' '); if (typeof x == "boolean") return x; if (typeof x == "number") return x; }
// Fetch all users from the database, keep this in memory
obj.db.GetAllType('user', function (err, docs) {
obj.common.unEscapeAllLinksFieldName(docs);
var domainUserCount = {}, i = 0;
for (i in parent.config.domains) { domainUserCount[i] = 0; }
for (i in docs) { var u = obj.users[docs[i]._id] = docs[i]; domainUserCount[u.domain]++; }
for (i in parent.config.domains) {
if ((parent.config.domains[i].share == null) && (domainUserCount[i] == 0)) {
// If newaccounts is set to no new accounts, but no accounts exists, temporarily allow account creation.
//if ((parent.config.domains[i].newaccounts === 0) || (parent.config.domains[i].newaccounts === false)) { parent.config.domains[i].newaccounts = 2; }
console.log('Server ' + ((i == '') ? '' : (i + ' ')) + 'has no users, next new account will be site administrator.');
}
}
// Fetch all device groups (meshes) from the database, keep this in memory
// As we load things in memory, we will also be doing some cleaning up.
// We will not save any clean up in the database right now, instead it will be saved next time there is a change.
obj.db.GetAllType('mesh', function (err, docs) {
obj.common.unEscapeAllLinksFieldName(docs);
for (var i in docs) { obj.meshes[docs[i]._id] = docs[i]; } // Get all meshes, including deleted ones.
// Fetch all user groups from the database, keep this in memory
obj.db.GetAllType('ugrp', function (err, docs) {
obj.common.unEscapeAllLinksFieldName(docs);
// Perform user group link cleanup
for (var i in docs) {
const ugrp = docs[i];
if (ugrp.links != null) {
for (var j in ugrp.links) {
if (j.startsWith('user/') && (obj.users[j] == null)) { delete ugrp.links[j]; } // User group has a link to a user that does not exist
else if (j.startsWith('mesh/') && ((obj.meshes[j] == null) || (obj.meshes[j].deleted != null))) { delete ugrp.links[j]; } // User has a link to a device group that does not exist
}
}
obj.userGroups[docs[i]._id] = docs[i]; // Get all user groups
}
// Perform device group link cleanup
for (var i in obj.meshes) {
const mesh = obj.meshes[i];
if (mesh.links != null) {
for (var j in mesh.links) {
if (j.startsWith('ugrp/') && (obj.userGroups[j] == null)) { delete mesh.links[j]; } // Device group has a link to a user group that does not exist
else if (j.startsWith('user/') && (obj.users[j] == null)) { delete mesh.links[j]; } // Device group has a link to a user that does not exist
}
}
}
// Perform user link cleanup
for (var i in obj.users) {
const user = obj.users[i];
if (user.links != null) {
for (var j in user.links) {
if (j.startsWith('ugrp/') && (obj.userGroups[j] == null)) { delete user.links[j]; } // User has a link to a user group that does not exist
else if (j.startsWith('mesh/') && ((obj.meshes[j] == null) || (obj.meshes[j].deleted != null))) { delete user.links[j]; } // User has a link to a device group that does not exist
//else if (j.startsWith('node/') && (obj.nodes[j] == null)) { delete user.links[j]; } // TODO
}
//if (Object.keys(user.links).length == 0) { delete user.links; }
}
}
// We loaded the users, device groups and user group state, start the server
serverStart();
});
});
});
// Clean up a device, used before saving it in the database
obj.cleanDevice = function (device) {
// Check device links, if a link points to an unknown user, remove it.
if (device.links != null) {
for (var j in device.links) {
if ((obj.users[j] == null) && (obj.userGroups[j] == null)) {
delete device.links[j];
if (Object.keys(device.links).length == 0) { delete device.links; }
}
}
}
return device;
}
// Return statistics about this web server
obj.getStats = function () {
return {
users: Object.keys(obj.users).length,
meshes: Object.keys(obj.meshes).length,
dnsDomains: Object.keys(obj.dnsDomains).length,
relaySessionCount: obj.relaySessionCount,
relaySessionErrorCount: obj.relaySessionErrorCount,
wsagents: Object.keys(obj.wsagents).length,
wsagentsDisconnections: Object.keys(obj.wsagentsDisconnections).length,
wsagentsDisconnectionsTimer: Object.keys(obj.wsagentsDisconnectionsTimer).length,
wssessions: Object.keys(obj.wssessions).length,
wssessions2: Object.keys(obj.wssessions2).length,
wsPeerSessions: Object.keys(obj.wsPeerSessions).length,
wsPeerSessions2: Object.keys(obj.wsPeerSessions2).length,
wsPeerSessions3: Object.keys(obj.wsPeerSessions3).length,
sessionsCount: Object.keys(obj.sessionsCount).length,
wsrelays: Object.keys(obj.wsrelays).length,
wsPeerRelays: Object.keys(obj.wsPeerRelays).length,
tlsSessionStore: Object.keys(tlsSessionStore).length,
blockedUsers: obj.blockedUsers,
blockedAgents: obj.blockedAgents
};
}
// Agent counters
obj.agentStats = {
createMeshAgentCount: 0,
agentClose: 0,
agentBinaryUpdate: 0,
agentMeshCoreBinaryUpdate: 0,
coreIsStableCount: 0,
verifiedAgentConnectionCount: 0,
clearingCoreCount: 0,
updatingCoreCount: 0,
recoveryCoreIsStableCount: 0,
meshDoesNotExistCount: 0,
invalidPkcsSignatureCount: 0,
invalidRsaSignatureCount: 0,
invalidJsonCount: 0,
unknownAgentActionCount: 0,
agentBadWebCertHashCount: 0,
agentBadSignature1Count: 0,
agentBadSignature2Count: 0,
agentMaxSessionHoldCount: 0,
invalidDomainMeshCount: 0,
invalidMeshTypeCount: 0,
invalidDomainMesh2Count: 0,
invalidMeshType2Count: 0,
duplicateAgentCount: 0,
maxDomainDevicesReached: 0,
agentInTrouble: 0,
agentInBigTrouble: 0
}
obj.getAgentStats = function () { return obj.agentStats; }
// Traffic counters
obj.trafficStats = {
httpRequestCount: 0,
httpWebSocketCount: 0,
httpIn: 0,
httpOut: 0,
relayCount: {},
relayIn: {},
relayOut: {},
localRelayCount: {},
localRelayIn: {},
localRelayOut: {},
AgentCtrlIn: 0,
AgentCtrlOut: 0,
LMSIn: 0,
LMSOut: 0,
CIRAIn: 0,
CIRAOut: 0
}
obj.trafficStats.time = Date.now();
obj.getTrafficStats = function () { return obj.trafficStats; }
obj.getTrafficDelta = function (oldTraffic) { // Return the difference between the old and new data along with the delta time.
const data = obj.common.Clone(obj.trafficStats);
data.time = Date.now();
const delta = calcDelta(oldTraffic ? oldTraffic : {}, data);
if (oldTraffic && oldTraffic.time) { delta.delta = (data.time - oldTraffic.time); }
delta.time = data.time;
return { current: data, delta: delta }
}
function calcDelta(oldData, newData) { // Recursive function that computes the difference of all numbers
const r = {};
for (var i in newData) {
if (typeof newData[i] == 'object') { r[i] = calcDelta(oldData[i] ? oldData[i] : {}, newData[i]); }
if (typeof newData[i] == 'number') { if (typeof oldData[i] == 'number') { r[i] = (newData[i] - oldData[i]); } else { r[i] = newData[i]; } }
}
return r;
}
// Keep a record of the last agent issues.
obj.getAgentIssues = function () { return obj.agentIssues; }
obj.setAgentIssue = function (agent, issue) { obj.agentIssues.push([new Date().toLocaleString(), agent.remoteaddrport, issue]); while (obj.setAgentIssue.length > 50) { obj.agentIssues.shift(); } }
obj.agentIssues = [];
// Authenticate the user
obj.authenticate = function (name, pass, domain, fn) {
if ((typeof (name) != 'string') || (typeof (pass) != 'string') || (typeof (domain) != 'object')) { fn(new Error('invalid fields')); return; }
if (name.startsWith('~t:')) {
// Login token, try to fetch the token from the database
obj.db.Get('logintoken-' + name, function (err, docs) {
if (err != null) { fn(err); return; }
if ((docs == null) || (docs.length != 1)) { fn(new Error('login token not found')); return; }
const loginToken = docs[0];
if ((loginToken.expire != 0) && (loginToken.expire < Date.now())) { fn(new Error('login token expired')); return; }
// Default strong password hashing (pbkdf2 SHA384)
require('./pass').hash(pass, loginToken.salt, function (err, hash, tag) {
if (err) return fn(err);
if (hash == loginToken.hash) {
// Login username and password are valid.
var user = obj.users[loginToken.userid];
if (!user) { fn(new Error('cannot find user')); return; }
if ((user.siteadmin) && (user.siteadmin != 0xFFFFFFFF) && (user.siteadmin & 32) != 0) { fn('locked'); return; }
// Successful login token authentication
var loginOptions = { tokenName: loginToken.name, tokenUser: loginToken.tokenUser };
if (loginToken.expire != 0) { loginOptions.expire = loginToken.expire; }
return fn(null, user._id, null, loginOptions);
}
fn(new Error('invalid password'));
}, 0);
});
} else if (domain.auth == 'ldap') {
// This method will handle LDAP login
const ldapHandler = function ldapHandlerFunc(err, xxuser) {
if (err) { parent.debug('ldap', 'LDAP Error: ' + err); if (ldapHandlerFunc.ldapobj) { try { ldapHandlerFunc.ldapobj.close(); } catch (ex) { console.log(ex); } } fn(new Error('invalid password')); return; }
// Save this LDAP user to file if needed
if (typeof domain.ldapsaveusertofile == 'string') {
obj.fs.appendFile(domain.ldapsaveusertofile, JSON.stringify(xxuser, null, 2) + '\r\n\r\n', function (err) { });
}
// Work on getting the userid for this LDAP user
var shortname = null;
var username = xxuser['displayName'];
if (typeof domain.ldapusername == 'string') {
if (domain.ldapusername.indexOf('{{{') >= 0) { username = assembleStringFromObject(domain.ldapusername, xxuser); } else { username = xxuser[domain.ldapusername]; }
} else { username = xxuser['displayName'] ? xxuser['displayName'] : xxuser['name']; }
if (domain.ldapuserbinarykey) {
// Use a binary key as the userid
if (xxuser[domain.ldapuserbinarykey]) { shortname = Buffer.from(xxuser[domain.ldapuserbinarykey], 'binary').toString('hex').toLowerCase(); }
} else if (domain.ldapuserkey) {
// Use a string key as the userid
if (xxuser[domain.ldapuserkey]) { shortname = xxuser[domain.ldapuserkey]; }
} else {
// Use the default key as the userid
if (xxuser['objectSid']) { shortname = Buffer.from(xxuser['objectSid'], 'binary').toString('hex').toLowerCase(); }
else if (xxuser['objectGUID']) { shortname = Buffer.from(xxuser['objectGUID'], 'binary').toString('hex').toLowerCase(); }
else if (xxuser['name']) { shortname = xxuser['name']; }
else if (xxuser['cn']) { shortname = xxuser['cn']; }
}
if (shortname == null) { fn(new Error('no user identifier')); if (ldapHandlerFunc.ldapobj) { try { ldapHandlerFunc.ldapobj.close(); } catch (ex) { console.log(ex); } } return; }
if (username == null) { username = shortname; }
var userid = 'user/' + domain.id + '/' + shortname;
// Get the list of groups this user is a member of.
var userMemberships = xxuser[(typeof domain.ldapusergroups == 'string') ? domain.ldapusergroups : 'memberOf'];
if (typeof userMemberships == 'string') { userMemberships = [userMemberships]; }
if (Array.isArray(userMemberships) == false) { userMemberships = []; }
// See if the user is required to be part of an LDAP user group in order to log into this server.
if (typeof domain.ldapuserrequiredgroupmembership == 'string') { domain.ldapuserrequiredgroupmembership = [ domain.ldapuserrequiredgroupmembership ]; }
if (Array.isArray(domain.ldapuserrequiredgroupmembership)) {
// Look for a matching LDAP user group
var userMembershipMatch = false;
for (var i in domain.ldapuserrequiredgroupmembership) { if (userMemberships.indexOf(domain.ldapuserrequiredgroupmembership[i]) >= 0) { userMembershipMatch = true; } }
if (userMembershipMatch === false) { parent.debug('authlog', 'LDAP denying login to a user that is not a member of a LDAP required group.'); fn('denied'); return; } // If there is no match, deny the login
}
// Check if user is in an site administrator group
var siteAdminGroup = null;
if (typeof domain.ldapsiteadmingroups == 'string') { domain.ldapsiteadmingroups = [ domain.ldapsiteadmingroups ]; }
if (Array.isArray(domain.ldapsiteadmingroups)) {
siteAdminGroup = false;
for (var i in domain.ldapsiteadmingroups) {
if (userMemberships.indexOf(domain.ldapsiteadmingroups[i]) >= 0) { siteAdminGroup = domain.ldapsiteadmingroups[i]; }
}
}
// See if we need to sync LDAP user memberships with user groups
if (domain.ldapsyncwithusergroups === true) { domain.ldapsyncwithusergroups = {}; }
if (typeof domain.ldapsyncwithusergroups == 'object') {
// LDAP user memberships sync is enabled, see if there are any filters to apply
if (typeof domain.ldapsyncwithusergroups.filter == 'string') { domain.ldapsyncwithusergroups.filter = [domain.ldapsyncwithusergroups.filter]; }
if (Array.isArray(domain.ldapsyncwithusergroups.filter)) {
const g = [];
for (var i in userMemberships) {
var match = false;
for (var j in domain.ldapsyncwithusergroups.filter) {
if (userMemberships[i].indexOf(domain.ldapsyncwithusergroups.filter[j]) >= 0) { match = true; }
}
if (match) { g.push(userMemberships[i]); }
}
userMemberships = g;
}
} else {
// LDAP user memberships sync is disabled, sync the user with empty membership
userMemberships = [];
}
// Get the email address for this LDAP user
var email = null;
if (domain.ldapuseremail) { email = xxuser[domain.ldapuseremail]; } else if (xxuser['mail']) { email = xxuser['mail']; } // Use given field name or default
if (Array.isArray(email)) { email = email[0]; } // Mail may be multivalued in LDAP in which case, answer is an array. Use the 1st value.
if (email) { email = email.toLowerCase(); } // it seems some code elsewhere also lowercase the emailaddress, so let's be consistent.
// Get the real name for this LDAP user
var realname = null;
if (typeof domain.ldapuserrealname == 'string') {
if (domain.ldapuserrealname.indexOf('{{{') >= 0) { realname = assembleStringFromObject(domain.ldapuserrealname, xxuser); } else { realname = xxuser[domain.ldapuserrealname]; }
}
else { if (typeof xxuser['name'] == 'string') { realname = xxuser['name']; } }
// Get the phone number for this LDAP user
var phonenumber = null;
if (domain.ldapuserphonenumber) { phonenumber = xxuser[domain.ldapuserphonenumber]; }
else { if (typeof xxuser['telephoneNumber'] == 'string') { phonenumber = xxuser['telephoneNumber']; } }
// Work on getting the image of this LDAP user
var userimage = null, userImageBuffer = null;
if (xxuser._raw) { // Using _raw allows us to get data directly as buffer.
if (domain.ldapuserimage && xxuser[domain.ldapuserimage]) { userImageBuffer = xxuser._raw[domain.ldapuserimage]; }
else if (xxuser['thumbnailPhoto']) { userImageBuffer = xxuser._raw['thumbnailPhoto']; }
else if (xxuser['jpegPhoto']) { userImageBuffer = xxuser._raw['jpegPhoto']; }
if (userImageBuffer != null) {
if ((userImageBuffer[0] == 0xFF) && (userImageBuffer[1] == 0xD8) && (userImageBuffer[2] == 0xFF) && (userImageBuffer[3] == 0xE0)) { userimage = 'data:image/jpeg;base64,' + userImageBuffer.toString('base64'); }
if ((userImageBuffer[0] == 0x89) && (userImageBuffer[1] == 0x50) && (userImageBuffer[2] == 0x4E) && (userImageBuffer[3] == 0x47)) { userimage = 'data:image/png;base64,' + userImageBuffer.toString('base64'); }
}
}
// Display user information extracted from LDAP data
parent.debug('authlog', 'LDAP user login, id: ' + shortname + ', username: ' + username + ', email: ' + email + ', realname: ' + realname + ', phone: ' + phonenumber + ', image: ' + (userimage != null));
// If there is a testing userid, use that
if (ldapHandlerFunc.ldapShortName) {
shortname = ldapHandlerFunc.ldapShortName;
userid = 'user/' + domain.id + '/' + shortname;
}
// Save the user image
if (userimage != null) { parent.db.Set({ _id: 'im' + userid, image: userimage }); } else { db.Remove('im' + userid); }
// Close the LDAP object
if (ldapHandlerFunc.ldapobj) { try { ldapHandlerFunc.ldapobj.close(); } catch (ex) { console.log(ex); } }
// Check if the user already exists
var user = obj.users[userid];
if (user == null) {
// This user does not exist, create a new account.
var user = { type: 'user', _id: userid, name: username, creation: Math.floor(Date.now() / 1000), login: Math.floor(Date.now() / 1000), access: Math.floor(Date.now() / 1000), domain: domain.id };
if (email) { user['email'] = email; user['emailVerified'] = true; }
if (domain.newaccountsrights) { user.siteadmin = domain.newaccountsrights; }
if (obj.common.validateStrArray(domain.newaccountrealms)) { user.groups = domain.newaccountrealms; }
var usercount = 0;
for (var i in obj.users) { if (obj.users[i].domain == domain.id) { usercount++; } }
if (usercount == 0) { user.siteadmin = 4294967295; /*if (domain.newaccounts === 2) { delete domain.newaccounts; }*/ } // If this is the first user, give the account site admin.
// Auto-join any user groups
if (typeof domain.newaccountsusergroups == 'object') {
for (var i in domain.newaccountsusergroups) {
var ugrpid = domain.newaccountsusergroups[i];
if (ugrpid.indexOf('/') < 0) { ugrpid = 'ugrp/' + domain.id + '/' + ugrpid; }
var ugroup = obj.userGroups[ugrpid];
if (ugroup != null) {
// Add group to the user
if (user.links == null) { user.links = {}; }
user.links[ugroup._id] = { rights: 1 };
// Add user to the group
ugroup.links[user._id] = { userid: user._id, name: user.name, rights: 1 };
db.Set(ugroup);
// Notify user group change
var event = { etype: 'ugrp', ugrpid: ugroup._id, name: ugroup.name, desc: ugroup.desc, action: 'usergroupchange', links: ugroup.links, msgid: 71, msgArgs: [user.name, ugroup.name], msg: 'Added user ' + user.name + ' to user group ' + ugroup.name, addUserDomain: domain.id };
if (db.changeStream) { event.noact = 1; } // If DB change stream is active, don't use this event to change the user group. Another event will come.
parent.DispatchEvent(['*', ugroup._id, user._id], obj, event);
}
}
}
// Check the user real name
if (realname) { user.realname = realname; }
// Check the user phone number
if (phonenumber) { user.phone = phonenumber; }
// Indicate that this user has a image
if (userimage != null) { user.flags = 1; }
// See if the user is a member of the site admin group.
if (typeof siteAdminGroup === 'string') {
parent.debug('authlog', `LDAP: Granting site admin privilages to new user "${user.name}" found in admin group: ${siteAdminGroup}`);
user.siteadmin = 0xFFFFFFFF;
}
// Sync the user with LDAP matching user groups
if (syncExternalUserGroups(domain, user, userMemberships, 'ldap') == true) { userChanged = true; }
obj.users[user._id] = user;
obj.db.SetUser(user);
var event = { etype: 'user', userid: user._id, username: user.name, account: obj.CloneSafeUser(user), action: 'accountcreate', msgid: 128, msgArgs: [user.name], msg: 'Account created, name is ' + user.name, domain: domain.id };
if (obj.db.changeStream) { event.noact = 1; } // If DB change stream is active, don't use this event to create the user. Another event will come.
obj.parent.DispatchEvent(['*', 'server-users'], obj, event);
return fn(null, user._id);
} else {
var userChanged = false;
// This is an existing user
// If the display username has changes, update it.
if (user.name != username) { user.name = username; userChanged = true; }
// Check if user email has changed
if (user.email && !email) { // email unset in ldap => unset
delete user.email;
delete user.emailVerified;
userChanged = true;
} else if (user.email != email) { // update email
user['email'] = email;
user['emailVerified'] = true;
userChanged = true;
}
// Check the user real name
if (realname != user.realname) { user.realname = realname; userChanged = true; }
// Check the user phone number
if (phonenumber != user.phone) { user.phone = phonenumber; userChanged = true; }
// Check the user image flag
if ((userimage != null) && ((user.flags == null) || ((user.flags & 1) == 0))) { if (user.flags == null) { user.flags = 1; } else { user.flags += 1; } userChanged = true; }
if ((userimage == null) && (user.flags != null) && ((user.flags & 1) != 0)) { if (user.flags == 1) { delete user.flags; } else { user.flags -= 1; } userChanged = true; }
// See if the user is a member of the site admin group.
if ((typeof siteAdminGroup === 'string') && (user.siteadmin !== 0xFFFFFFFF)) {
parent.debug('authlog', `LDAP: Granting site admin privilages to user "${user.name}" found in administrator group: ${siteAdminGroup}`);
user.siteadmin = 0xFFFFFFFF;
userChanged = true;
} else if ((siteAdminGroup === false) && (user.siteadmin === 0xFFFFFFFF)) {
parent.debug('authlog', `LDAP: Revoking site admin privilages from user "${user.name}" since they are not found in any administrator groups.`);
delete user.siteadmin;
userChanged = true;
}
// Synd the user with LDAP matching user groups
if (syncExternalUserGroups(domain, user, userMemberships, 'ldap') == true) { userChanged = true; }
// If the user changed, save the changes to the database here
if (userChanged) {
obj.db.SetUser(user);
var event = { etype: 'user', userid: user._id, username: user.name, account: obj.CloneSafeUser(user), action: 'accountchange', msgid: 154, msg: 'Account changed to sync with LDAP data.', domain: domain.id };
if (obj.db.changeStream) { event.noact = 1; } // If DB change stream is active, don't use this event to change the user. Another event will come.
parent.DispatchEvent(['*', 'server-users', user._id], obj, event);
}
// If user is locker out, block here.
if ((user.siteadmin) && (user.siteadmin != 0xFFFFFFFF) && (user.siteadmin & 32) != 0) { fn('locked'); return; }
return fn(null, user._id);
}
}
if (domain.ldapoptions.url == 'test') {
// Test LDAP login
var xxuser = domain.ldapoptions[name.toLowerCase()];
if (xxuser == null) { fn(new Error('invalid password')); return; } else {
ldapHandler.ldapShortName = name.toLowerCase();
if (typeof xxuser == 'string') {
// The test LDAP user points to a JSON file where the user information is, load it.
ldapHandler(null, require(xxuser));
} else {
// The test user information is in the config.json, use it.
ldapHandler(null, xxuser);
}
}
} else {
// LDAP login
var LdapAuth = require('ldapauth-fork');
if (domain.ldapoptions == null) { domain.ldapoptions = {}; }
domain.ldapoptions.includeRaw = true; // This allows us to get data as buffers which is useful for images.
var ldap = new LdapAuth(domain.ldapoptions);
ldapHandler.ldapobj = ldap;
ldap.on('error', function (err) { parent.debug('ldap', 'LDAP OnError: ' + err); try { ldap.close(); } catch (ex) { console.log(ex); } }); // Close the LDAP object
ldap.authenticate(name, pass, ldapHandler);
}
} else {
// Regular login
var user = obj.users['user/' + domain.id + '/' + name.toLowerCase()];
// Query the db for the given username
if (!user) { fn(new Error('cannot find user')); return; }
// Apply the same algorithm to the POSTed password, applying the hash against the pass / salt, if there is a match we found the user
if (user.salt == null) {
fn(new Error('invalid password'));
} else {
if (user.passtype != null) {
// IIS default clear or weak password hashing (SHA-1)
require('./pass').iishash(user.passtype, pass, user.salt, function (err, hash) {
if (err) return fn(err);
if (hash == user.hash) {
// Update the password to the stronger format.
require('./pass').hash(pass, function (err, salt, hash, tag) { if (err) throw err; user.salt = salt; user.hash = hash; delete user.passtype; obj.db.SetUser(user); }, 0);
if ((user.siteadmin) && (user.siteadmin != 0xFFFFFFFF) && (user.siteadmin & 32) != 0) { fn('locked'); return; }
return fn(null, user._id);
}
fn(new Error('invalid password'), null, user.passhint);
});
} else {
// Default strong password hashing (pbkdf2 SHA384)
require('./pass').hash(pass, user.salt, function (err, hash, tag) {
if (err) return fn(err);
if (hash == user.hash) {
if ((user.siteadmin) && (user.siteadmin != 0xFFFFFFFF) && (user.siteadmin & 32) != 0) { fn('locked'); return; }
return fn(null, user._id);
}
fn(new Error('invalid password'), null, user.passhint);
}, 0);
}
}
}
};
/*
obj.restrict = function (req, res, next) {
console.log('restrict', req.url);
var domain = getDomain(req);
if (req.session.userid) {
next();
} else {
req.session.messageid = 111; // Access denied.
res.redirect(domain.url + 'login');
}
};
*/
// Check if the source IP address is in the IP list, return false if not.
function checkIpAddressEx(req, res, ipList, closeIfThis, redirectUrl) {
try {
if (req.connection) {
// HTTP(S) request
if (req.clientIp) { for (var i = 0; i < ipList.length; i++) { if (require('ipcheck').match(req.clientIp, ipList[i])) { if (closeIfThis === true) { if (typeof redirectUrl == 'string') { res.redirect(redirectUrl); } else { res.sendStatus(401); } } return true; } } }
if (closeIfThis === false) { if (typeof redirectUrl == 'string') { res.redirect(redirectUrl); } else { res.sendStatus(401); } }
} else {
// WebSocket request
if (res.clientIp) { for (var i = 0; i < ipList.length; i++) { if (require('ipcheck').match(res.clientIp, ipList[i])) { if (closeIfThis === true) { try { req.close(); } catch (e) { } } return true; } } }
if (closeIfThis === false) { try { req.close(); } catch (e) { } }
}
} catch (e) { console.log(e); } // Should never happen
return false;
}
// Check if the source IP address is allowed, return domain if allowed
// If there is a fail and null is returned, the request or connection is closed already.
function checkUserIpAddress(req, res) {
if ((parent.config.settings.userblockedip != null) && (checkIpAddressEx(req, res, parent.config.settings.userblockedip, true, parent.config.settings.ipblockeduserredirect) == true)) { obj.blockedUsers++; return null; }
if ((parent.config.settings.userallowedip != null) && (checkIpAddressEx(req, res, parent.config.settings.userallowedip, false, parent.config.settings.ipblockeduserredirect) == false)) { obj.blockedUsers++; return null; }
const domain = (req.url ? getDomain(req) : getDomain(res));
if (domain == null) { parent.debug('web', 'handleRootRequest: invalid domain.'); try { res.sendStatus(404); } catch (ex) { } return; }
if ((domain.userblockedip != null) && (checkIpAddressEx(req, res, domain.userblockedip, true, domain.ipblockeduserredirect) == true)) { obj.blockedUsers++; return null; }
if ((domain.userallowedip != null) && (checkIpAddressEx(req, res, domain.userallowedip, false, domain.ipblockeduserredirect) == false)) { obj.blockedUsers++; return null; }
return domain;
}
// Check if the source IP address is allowed, return domain if allowed
// If there is a fail and null is returned, the request or connection is closed already.
function checkAgentIpAddress(req, res) {
if ((parent.config.settings.agentblockedip != null) && (checkIpAddressEx(req, res, parent.config.settings.agentblockedip, null) == true)) { obj.blockedAgents++; return null; }
if ((parent.config.settings.agentallowedip != null) && (checkIpAddressEx(req, res, parent.config.settings.agentallowedip, null) == false)) { obj.blockedAgents++; return null; }
const domain = (req.url ? getDomain(req) : getDomain(res));
if ((domain.agentblockedip != null) && (checkIpAddressEx(req, res, domain.agentblockedip, null) == true)) { obj.blockedAgents++; return null; }
if ((domain.agentallowedip != null) && (checkIpAddressEx(req, res, domain.agentallowedip, null) == false)) { obj.blockedAgents++; return null; }
return domain;
}
// Return the current domain of the request
// Request or connection says open regardless of the response
function getDomain(req) {
if (req.xdomain != null) { return req.xdomain; } // Domain already set for this request, return it.
if ((req.hostname == 'localhost') && (req.query.domainid != null)) { const d = parent.config.domains[req.query.domainid]; if (d != null) return d; } // This is a localhost access with the domainid specified in the URL
if (req.hostname != null) { const d = obj.dnsDomains[req.hostname.toLowerCase()]; if (d != null) return d; } // If this is a DNS name domain, return it here.
const x = req.url.split('/');
if (x.length < 2) return parent.config.domains[''];
const y = parent.config.domains[x[1].toLowerCase()];
if ((y != null) && (y.dns == null)) { return parent.config.domains[x[1].toLowerCase()]; }
return parent.config.domains[''];
}
function handleLogoutRequest(req, res) {
const domain = checkUserIpAddress(req, res);
if (domain == null) { return; }
if (domain.auth == 'sspi') { parent.debug('web', 'handleLogoutRequest: failed checks.'); res.sendStatus(404); return; }
if ((domain.loginkey != null) && (domain.loginkey.indexOf(req.query.key) == -1)) { res.sendStatus(404); return; } // Check 3FA URL key
// If a HTTP header is required, check new UserRequiredHttpHeader
if (domain.userrequiredhttpheader && (typeof domain.userrequiredhttpheader == 'object')) { var ok = false; for (var i in req.headers) { if (domain.userrequiredhttpheader[i.toLowerCase()] == req.headers[i]) { ok = true; } } if (ok == false) { res.sendStatus(404); return; } }
res.set({ 'Cache-Control': 'no-store' });
// Destroy the user's session to log them out will be re-created next request
var userid = req.session.userid;
if (req.session.userid) {
var user = obj.users[req.session.userid];
if (user != null) {
obj.parent.authLog('https', 'User ' + user.name + ' logout from ' + req.clientIp + ' port ' + req.connection.remotePort, { sessionid: req.session.x, useragent: req.headers['user-agent'] });
obj.parent.DispatchEvent(['*'], obj, { etype: 'user', userid: user._id, username: user.name, action: 'logout', msgid: 2, msg: 'Account logout', domain: domain.id });
}
if (req.session.x) { clearDestroyedSessions(); obj.destroyedSessions[req.session.userid + '/' + req.session.x] = Date.now(); } // Destroy this session
}
req.session = null;
parent.debug('web', 'handleLogoutRequest: success.');
// If this user was logged in using an authentication strategy and there is a logout URL, use it.
if ((userid != null) && (domain.authstrategies != null)) {
const u = userid.split('/')[2];
if (u.startsWith('~twitter:') && (domain.authstrategies.twitter != null) && (typeof domain.authstrategies.twitter.logouturl == 'string')) { res.redirect(domain.authstrategies.twitter.logouturl); return; }
if (u.startsWith('~google:') && (domain.authstrategies.google != null) && (typeof domain.authstrategies.google.logouturl == 'string')) { res.redirect(domain.authstrategies.google.logouturl); return; }
if (u.startsWith('~github:') && (domain.authstrategies.github != null) && (typeof domain.authstrategies.github.logouturl == 'string')) { res.redirect(domain.authstrategies.github.logouturl); return; }
if (u.startsWith('~reddit:') && (domain.authstrategies.reddit != null) && (typeof domain.authstrategies.reddit.logouturl == 'string')) { res.redirect(domain.authstrategies.reddit.logouturl); return; }
if (u.startsWith('~azure:') && (domain.authstrategies.azure != null) && (typeof domain.authstrategies.azure.logouturl == 'string')) { res.redirect(domain.authstrategies.azure.logouturl); return; }
if (u.startsWith('~oidc:') && (domain.authstrategies.oidc != null) && (typeof domain.authstrategies.oidc.logouturl == 'string')) { res.redirect(domain.authstrategies.oidc.logouturl); return; }
if (u.startsWith('~jumpcloud:') && (domain.authstrategies.jumpcloud != null) && (typeof domain.authstrategies.jumpcloud.logouturl == 'string')) { res.redirect(domain.authstrategies.jumpcloud.logouturl); return; }
if (u.startsWith('~saml:') && (domain.authstrategies.saml != null) && (typeof domain.authstrategies.saml.logouturl == 'string')) { res.redirect(domain.authstrategies.saml.logouturl); return; }
if (u.startsWith('~intel:') && (domain.authstrategies.intel != null) && (typeof domain.authstrategies.intel.logouturl == 'string')) { res.redirect(domain.authstrategies.intel.logouturl); return; }
}
// This is the default logout redirect to the login page
if (req.query.key != null) { res.redirect(domain.url + 'login?key=' + req.query.key); } else { res.redirect(domain.url + 'login'); }
}
// Return an object with 2FA type if 2-step auth can be skipped
function checkUserOneTimePasswordSkip(domain, user, req, loginOptions) {
if (parent.config.settings.no2factorauth == true) return null;
// If this login occurred using a login token, no 2FA needed.
if ((loginOptions != null) && (typeof loginOptions.tokenName === 'string')) { return { twoFactorType: 'tokenlogin' }; }
// Check if we can skip 2nd factor auth because of the source IP address
if ((req != null) && (req.clientIp != null) && (domain.passwordrequirements != null) && (domain.passwordrequirements.skip2factor != null)) {
for (var i in domain.passwordrequirements.skip2factor) { if (require('ipcheck').match(req.clientIp, domain.passwordrequirements.skip2factor[i]) === true) { return { twoFactorType: 'ipaddr' }; } }
}
// Check if a 2nd factor cookie is present
if (typeof req.headers.cookie == 'string') {
const cookies = req.headers.cookie.split('; ');
for (var i in cookies) {
if (cookies[i].startsWith('twofactor=')) {
var twoFactorCookie = obj.parent.decodeCookie(decodeURIComponent(cookies[i].substring(10)), obj.parent.loginCookieEncryptionKey, (30 * 24 * 60)); // If the cookies does not have an expire field, assume 30 day timeout.
if ((twoFactorCookie != null) && ((twoFactorCookie.ip == null) || checkCookieIp(twoFactorCookie.ip, req.clientIp)) && (twoFactorCookie.userid == user._id)) { return { twoFactorType: 'cookie' }; }
}
}
}
return null;
}
// Return true if this user has 2-step auth active
function checkUserOneTimePasswordRequired(domain, user, req, loginOptions) {
// If this login occurred using a login token, no 2FA needed.
if ((loginOptions != null) && (typeof loginOptions.tokenName === 'string')) { return false; }
// Check if we can skip 2nd factor auth because of the source IP address
if ((req != null) && (req.clientIp != null) && (domain.passwordrequirements != null) && (domain.passwordrequirements.skip2factor != null)) {
for (var i in domain.passwordrequirements.skip2factor) { if (require('ipcheck').match(req.clientIp, domain.passwordrequirements.skip2factor[i]) === true) return false; }
}
// Check if a 2nd factor cookie is present
if (typeof req.headers.cookie == 'string') {
const cookies = req.headers.cookie.split('; ');
for (var i in cookies) {
if (cookies[i].startsWith('twofactor=')) {
var twoFactorCookie = obj.parent.decodeCookie(decodeURIComponent(cookies[i].substring(10)), obj.parent.loginCookieEncryptionKey, (30 * 24 * 60)); // If the cookies does not have an expire field, assume 30 day timeout.
if ((twoFactorCookie != null) && ((twoFactorCookie.ip == null) || checkCookieIp(twoFactorCookie.ip, req.clientIp)) && (twoFactorCookie.userid == user._id)) { return false; }
}
}
}
// See if SMS 2FA is available
var sms2fa = (((typeof domain.passwordrequirements != 'object') || (domain.passwordrequirements.sms2factor != false)) && (parent.smsserver != null) && (user.phone != null));
// See if Messenger 2FA is available
var msg2fa = (((typeof domain.passwordrequirements != 'object') || (domain.passwordrequirements.msg2factor != false)) && (parent.msgserver != null) && (parent.msgserver.providers != 0) && (user.msghandle != null));
// Check if a 2nd factor is present
return ((parent.config.settings.no2factorauth !== true) && (msg2fa || sms2fa || (user.otpsecret != null) || ((user.email != null) && (user.emailVerified == true) && (domain.mailserver != null) && (user.otpekey != null)) || ((user.otphkeys != null) && (user.otphkeys.length > 0))));
}
// Check the 2-step auth token
function checkUserOneTimePassword(req, domain, user, token, hwtoken, func) {
parent.debug('web', 'checkUserOneTimePassword()');
const twoStepLoginSupported = ((domain.auth != 'sspi') && (obj.parent.certificates.CommonName.indexOf('.') != -1) && (obj.args.nousers !== true) && (parent.config.settings.no2factorauth !== true));
if (twoStepLoginSupported == false) { parent.debug('web', 'checkUserOneTimePassword: not supported.'); func(true); return; };
// Check if we can use OTP tokens with email
var otpemail = (domain.mailserver != null);
if ((typeof domain.passwordrequirements == 'object') && (domain.passwordrequirements.email2factor == false)) { otpemail = false; }
var otpsms = (parent.smsserver != null);
if ((typeof domain.passwordrequirements == 'object') && (domain.passwordrequirements.sms2factor == false)) { otpsms = false; }
var otpmsg = ((parent.msgserver != null) && (parent.msgserver.providers != 0));
if ((typeof domain.passwordrequirements == 'object') && (domain.passwordrequirements.msg2factor == false)) { otpmsg = false; }
// Check 2FA login cookie
if ((token != null) && (token.startsWith('cookie='))) {
var twoFactorCookie = obj.parent.decodeCookie(decodeURIComponent(token.substring(7)), obj.parent.loginCookieEncryptionKey, (30 * 24 * 60)); // If the cookies does not have an expire field, assume 30 day timeout.
if ((twoFactorCookie != null) && ((twoFactorCookie.ip == null) || checkCookieIp(twoFactorCookie.ip, req.clientIp)) && (twoFactorCookie.userid == user._id)) { func(true, { twoFactorType: 'cookie' }); return; }
}
// Check email key
if ((otpemail) && (user.otpekey != null) && (user.otpekey.d != null) && (user.otpekey.k === token)) {
var deltaTime = (Date.now() - user.otpekey.d);
if ((deltaTime > 0) && (deltaTime < 300000)) { // Allow 5 minutes to use the email token (10000 * 60 * 5).
user.otpekey = {};
obj.db.SetUser(user);
parent.debug('web', 'checkUserOneTimePassword: success (email).');
func(true, { twoFactorType: 'email' });
return;
}
}
// Check SMS key
if ((otpsms) && (user.phone != null) && (user.otpsms != null) && (user.otpsms.d != null) && (user.otpsms.k === token)) {
var deltaTime = (Date.now() - user.otpsms.d);
if ((deltaTime > 0) && (deltaTime < 300000)) { // Allow 5 minutes to use the SMS token (10000 * 60 * 5).
delete user.otpsms;
obj.db.SetUser(user);
parent.debug('web', 'checkUserOneTimePassword: success (SMS).');
func(true, { twoFactorType: 'sms' });
return;
}
}
// Check messenger key
if ((otpmsg) && (user.msghandle != null) && (user.otpmsg != null) && (user.otpmsg.d != null) && (user.otpmsg.k === token)) {
var deltaTime = (Date.now() - user.otpmsg.d);
if ((deltaTime > 0) && (deltaTime < 300000)) { // Allow 5 minutes to use the Messenger token (10000 * 60 * 5).
delete user.otpmsg;
obj.db.SetUser(user);
parent.debug('web', 'checkUserOneTimePassword: success (Messenger).');
func(true, { twoFactorType: 'messenger' });
return;
}
}
// Check hardware key
if (user.otphkeys && (user.otphkeys.length > 0) && (typeof (hwtoken) == 'string') && (hwtoken.length > 0)) {
var authResponse = null;
try { authResponse = JSON.parse(hwtoken); } catch (ex) { }
if ((authResponse != null) && (authResponse.clientDataJSON)) {
// Get all WebAuthn keys
var webAuthnKeys = [];
for (var i = 0; i < user.otphkeys.length; i++) { if (user.otphkeys[i].type == 3) { webAuthnKeys.push(user.otphkeys[i]); } }
if (webAuthnKeys.length > 0) {
// Decode authentication response
var clientAssertionResponse = { response: {} };
clientAssertionResponse.id = authResponse.id;
clientAssertionResponse.rawId = Buffer.from(authResponse.id, 'base64');
clientAssertionResponse.response.authenticatorData = Buffer.from(authResponse.authenticatorData, 'base64');
clientAssertionResponse.response.clientDataJSON = Buffer.from(authResponse.clientDataJSON, 'base64');
clientAssertionResponse.response.signature = Buffer.from(authResponse.signature, 'base64');
clientAssertionResponse.response.userHandle = Buffer.from(authResponse.userHandle, 'base64');
// Look for the key with clientAssertionResponse.id
var webAuthnKey = null;
for (var i = 0; i < webAuthnKeys.length; i++) { if (webAuthnKeys[i].keyId == clientAssertionResponse.id) { webAuthnKey = webAuthnKeys[i]; } }
// If we found a valid key to use, let's validate the response
if (webAuthnKey != null) {
// Figure out the origin
var httpport = ((args.aliasport != null) ? args.aliasport : args.port);
var origin = 'https://' + (domain.dns ? domain.dns : parent.certificates.CommonName);
if (httpport != 443) { origin += ':' + httpport; }
var u2fchallenge = null;
if ((req.session != null) && (req.session.e != null)) { const sec = parent.decryptSessionData(req.session.e); if (sec != null) { u2fchallenge = sec.u2f; } }
var assertionExpectations = {