-
-
Notifications
You must be signed in to change notification settings - Fork 276
Expand file tree
/
Copy pathuser-handler.js
More file actions
4043 lines (3557 loc) · 133 KB
/
user-handler.js
File metadata and controls
4043 lines (3557 loc) · 133 KB
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
'use strict';
const config = require('@zone-eu/wild-config');
const log = require('npmlog');
const hashes = require('./hashes');
const speakeasy = require('speakeasy');
const QRCode = require('qrcode');
const tools = require('./tools');
const consts = require('./consts');
const counters = require('./counters');
const ObjectId = require('mongodb').ObjectId;
const generatePassword = require('generate-password');
const os = require('os');
const crypto = require('crypto');
const mailboxTranslations = require('./translations');
const MailComposer = require('nodemailer/lib/mail-composer');
const humanname = require('humanname');
const UserCache = require('./user-cache');
const isemail = require('isemail');
const util = require('util');
const TaskHandler = require('./task-handler');
const { SettingsHandler } = require('./settings-handler');
const { encrypt, decrypt } = require('./encrypt');
const { Fido2Lib } = require('fido2-lib');
const {
publish,
ASP_CREATED,
ASP_DELETED,
USER_CREATED,
USER_DELETE_STARTED,
MFA_TOTP_ENABLED,
MFA_TOTP_DISABLED,
MFA_CUSTOM_ENABLED,
MFA_CUSTOM_DISABLED,
MFA_FIDO_REGISTERED,
MFA_FIDO_REMOVED,
MFA_DISABLED,
USER_PASSWORD_CHANGED,
USER_DELETE_CANCELLED
} = require('./events');
const TOTP_SETUP_TTL = 6 * 3600 * 1000;
class UserHandler {
constructor(options) {
this.database = options.database;
this.users = options.users || options.database;
this.redis = options.redis;
this.loggelf = options.loggelf || (() => false);
this.messageHandler = options.messageHandler;
this.counters = this.messageHandler ? this.messageHandler.counters : counters(this.redis);
this.settingsHandler = new SettingsHandler({ db: this.database });
this.userCache = new UserCache({
users: this.users,
redis: this.redis,
settingsHandler: this.settingsHandler
});
this.flushUserCache = util.promisify(this.userCache.flush.bind(this.userCache));
this.taskHandler = new TaskHandler({ database: this.database });
}
resolveAddress(address, options, callback) {
if (!callback) {
return this.asyncResolveAddress(address, options);
}
this.asyncResolveAddress(address, options)
.catch(err => callback(err))
.then(result => callback(null, result));
}
async asyncResolveAddress(address, options) {
options = options || {};
let wildcard = !!options.wildcard;
address = tools.normalizeAddress(address, false, {
removeLabel: true,
removeDots: true
});
let atPos = address.indexOf('@');
let username = address.substr(0, atPos);
let domain = address.substr(atPos + 1);
let projection = {
user: true,
targets: true
};
Object.keys(options.projection || {}).forEach(key => {
projection[key] = true;
});
if (options.projection === false) {
// do not use projection
projection = false;
}
try {
let addressData;
// try exact match
addressData = await this.users.collection('addresses').findOne(
{
addrview: username + '@' + domain
},
{
projection,
maxTimeMS: consts.DB_MAX_TIME_USERS
}
);
if (addressData) {
return addressData;
}
// try an alias
let aliasDomain;
let aliasData = await this.users.collection('domainaliases').findOne(
{ alias: domain },
{
maxTimeMS: consts.DB_MAX_TIME_USERS
}
);
if (aliasData) {
aliasDomain = aliasData.domain;
addressData = await this.users.collection('addresses').findOne(
{
addrview: username + '@' + aliasDomain
},
{
projection,
maxTimeMS: consts.DB_MAX_TIME_USERS
}
);
if (addressData) {
return addressData;
}
}
if (!wildcard) {
// wildcard not allowed, so there is nothing else to check for
return false;
}
// Add addrview to projection as we will need it down further for
// matching the right wildcard partial address.
projection.addrview = true;
let partialWildcards = tools.getWildcardAddresses(username, domain);
let query = {
addrview: { $in: partialWildcards }
};
let sortedDomainPartials = partialWildcards.map(addr => addr.replace(/^\*/, '')).sort((a, b) => b.length - a.length);
let sortedAliasPartials = [];
if (aliasDomain) {
// search for alias domain as well
let aliasWildcards = tools.getWildcardAddresses(username, aliasDomain);
query.addrview.$in = query.addrview.$in.concat(aliasWildcards);
sortedAliasPartials = aliasWildcards.map(addr => addr.replace(/^\*/, '')).sort((a, b) => a.length - b.length);
}
let sortedPartials = sortedDomainPartials.concat(sortedAliasPartials);
// try to find a catch-all address while preferring the longest match
let addressMatches = await this.users
.collection('addresses')
.find(query, {
projection,
maxTimeMS: consts.DB_MAX_TIME_USERS
})
.toArray();
if (addressMatches && addressMatches.length) {
let matchingPartials = new WeakMap();
addressMatches.forEach(addressData => {
let partialMatch = sortedPartials.find(partial => addressData.addrview.indexOf(partial) >= 0);
if (partialMatch) {
matchingPartials.set(addressData, sortedPartials.indexOf(partialMatch));
}
});
addressData = addressMatches.sort((a, b) => {
let aPos = matchingPartials.has(a) ? matchingPartials.get(a) : Infinity;
let bPos = matchingPartials.has(b) ? matchingPartials.get(b) : Infinity;
return aPos - bPos;
})[0];
}
if (addressData) {
return addressData;
}
// try to find a catch-all user (eg. "postmaster@*")
addressData = await this.users.collection('addresses').findOne(
{
addrview: username + '@*'
},
{
projection,
maxTimeMS: consts.DB_MAX_TIME_USERS
}
);
if (addressData) {
return addressData;
}
} catch (err) {
err.responseCode = 500;
err.code = 'InternalDatabaseError';
throw err;
}
// no match was found
return false;
}
/**
* Resolve user by username/address
*
* @param {String} username Either username or email address
* @param {Object} [extraFields] Optional projection fields object
*/
get(username, extraFields, callback) {
if (!callback && typeof extraFields === 'function') {
callback = extraFields;
extraFields = false;
}
if (!callback) {
return this.asyncGet(username, extraFields);
}
this.asyncGet(username, extraFields)
.catch(err => callback(err))
.then(result => callback(null, result));
}
async asyncGet(username, extraFields) {
let fields = {
_id: true,
quota: true,
storageUsed: true,
disabled: true,
suspended: true
};
Object.keys(extraFields || {}).forEach(field => {
fields[field] = true;
});
let addressData;
let query;
if (tools.isId(username)) {
query = { _id: new ObjectId(username) };
} else if (username.indexOf('@') < 0) {
// assume regular username
query = { unameview: tools.uview(username) };
} else {
addressData = await this.asyncResolveAddress(username, { projection: { name: true } });
if (addressData.user) {
query = { _id: addressData.user };
}
}
if (!query) {
return false;
}
try {
let userData = await this.users.collection('users').findOne(query, {
projection: fields,
maxTimeMS: consts.DB_MAX_TIME_USERS
});
if (userData && fields.name && addressData && addressData.name) {
// override name
userData.name = addressData.name;
}
return userData;
} catch (err) {
err.responseCode = 500;
err.code = 'InternalDatabaseError';
throw err;
}
}
// Get user from deletedusers
async asyncGetDeleted(username, extraFields) {
let fields = {
_id: true,
quota: true,
storageUsed: true,
disabled: true,
suspended: true
};
Object.keys(extraFields || {}).forEach(field => {
fields[field] = true;
});
let addressData;
let query;
if (tools.isId(username)) {
query = { _id: new ObjectId(username) };
} else if (username.indexOf('@') < 0) {
// assume regular username
query = { unameview: tools.uview(username) };
} else {
// assume main address
query = { address: tools.uview(username) };
}
if (!query) {
return false;
}
try {
let userData = await this.users.collection('deletedusers').findOne(query, {
projection: fields,
maxTimeMS: consts.DB_MAX_TIME_USERS
});
if (userData && fields.name && addressData && addressData.name) {
// override name
userData.name = addressData.name;
}
return userData;
} catch (err) {
err.responseCode = 500;
err.code = 'InternalDatabaseError';
throw err;
}
}
/**
* rateLimitIP
* if ip is not available will always return success object
* @param {Object} meta
* @param {String} meta.ip request remote ip address
* @param {Integer} count
*/
async rateLimitIP(meta, count) {
if (!meta || !meta.ip || !consts.IP_AUTH_FAILURES) {
return { success: true };
}
let wlKey = 'rl-wl';
// $ redis-cli
// > SADD "rl-wl" "1.2.3.4"
try {
let isMember = await this.redis.sismember(wlKey, meta.ip);
if (isMember) {
// whitelisted IP
return { success: true };
}
} catch (err) {
log.error('Redis', 'SMFAIL key=%s value=%s error=%s', wlKey, meta.ip, err.message);
// ignore errors
return { success: true };
}
return await this.counters.asyncTTLCounter('auth_ip:' + meta.ip, count, consts.IP_AUTH_FAILURES, consts.IP_AUTH_WINDOW);
}
/**
* rateLimitUser
* @param {String} tokenID user identifier
* @param {Object} meta
* @param {Integer} count
*/
async rateLimitUser(tokenID, meta, count) {
if (meta && meta.ip) {
// check if whitelisted IP
let wlKey = 'rl-wl';
// $ redis-cli
// > SADD "rl-wl" "1.2.3.4"
try {
let isMember = await this.redis.sismember(wlKey, meta.ip);
if (isMember) {
// whitelisted IP, allow authentication attempt without rate limits
return { success: true };
}
} catch (err) {
log.error('Redis', 'SMFAIL key=%s value=%s error=%s', wlKey, meta.ip, err.message);
// ignore errors
}
}
return await this.counters.asyncTTLCounter('auth_user:' + tokenID, count, consts.USER_AUTH_FAILURES, consts.USER_AUTH_WINDOW);
}
/**
* rateLimitReleaseUser
* @param {String} tokenID user identifier
* @param {Integer} count
*/
async rateLimitReleaseUser(tokenID) {
await this.redis.del('auth_user:' + tokenID);
}
/**
* rateLimit
* @param {String} tokenID user identifier
* @param {Object} meta
* @param {String} meta.ip request remote ip address
* @param {Integer} count
*/
async rateLimit(tokenID, meta, count) {
let ipRes = await this.rateLimitIP(meta, count);
let userRes = await this.rateLimitUser(tokenID, meta, count);
if (!ipRes.success) {
return ipRes;
}
return userRes;
}
/**
* Authenticate user
*
* @param {String} username Either username or email address
* @param {String} password Password for authentication
* @param {String} [requiredScope="master"] Which scope to use
* @param {Object} [meta] Additional meta info
* @param {String} [meta.ip] IP address of the client
* @param {String} [meta.session] Session ID
*/
authenticate(username, password, requiredScope, meta, callback) {
if (!callback) {
return this.asyncAuthenticate(username, password, requiredScope, meta);
}
this.asyncAuthenticate(username, password, requiredScope, meta)
.then(result => {
if (!Array.isArray(result)) {
result = [].concat(result || [false, false]);
}
callback(null, ...result);
})
.catch(err => callback(err));
}
async asyncAuthenticate(username, password, requiredScope, meta) {
meta = meta || {};
requiredScope = requiredScope || 'master';
username = (username || '').toString();
let userDomain = username.indexOf('@') >= 0 ? username.split('@').pop() : '';
let now = new Date();
let passwordType = 'master'; // try 'master' first and 'asp' later
let passwordId;
meta = meta || {};
meta.requiredScope = requiredScope;
if (!password) {
// do not allow signing in without a password
this.loggelf({
short_message: '[AUTHFAIL] ' + username,
_error: 'Empty password',
_auth_result: 'fail',
_username: username,
_domain: userDomain,
_scope: requiredScope,
_ip: meta.ip,
_sess: meta.sess
});
return [false, false];
}
// first check if client IP is not used too much
let rateLimitRes;
try {
rateLimitRes = await this.rateLimitIP(meta, 0);
} catch (err) {
err.responseCode = 500;
err.code = 'InternalDatabaseError';
this.loggelf({
short_message: '[AUTHFAIL] ' + username,
_stack: err.stack,
_error: err.message,
_code: err.code,
_auth_result: 'error',
_username: username,
_domain: userDomain,
_scope: requiredScope,
_ip: meta.ip,
_sess: meta.sess
});
// return as failed auth
return [false, false];
}
if (!rateLimitRes.success) {
// too many failed attempts from this IP
this.loggelf({
short_message: '[AUTHFAIL] ' + username,
_error: 'Rate limited',
_auth_result: 'ratelimited',
_username: username,
_domain: userDomain,
_scope: requiredScope,
_ip: meta.ip,
_sess: meta.sess
});
throw rateLimitResponse(rateLimitRes);
}
let userQuery;
try {
userQuery = await this.checkAddress(username);
} catch (err) {
this.loggelf({
short_message: '[AUTHFAIL] ' + username,
_error: 'Unknown user',
_auth_result: 'unknown',
_username: username,
_domain: userDomain,
_scope: requiredScope,
_ip: meta.ip,
_sess: meta.sess
});
return [false, false];
}
if (!userQuery) {
// nothing to do here
return [false, false];
}
let userData;
try {
userData = await this.users.collection('users').findOne(userQuery, {
projection: {
_id: true,
username: true,
address: true,
tempPassword: true,
password: true,
enabled2fa: true,
webauthn: true,
disabled: true,
suspended: true,
disabledScopes: true,
lastPwnedCheck: true,
passwordPwned: true
},
maxTimeMS: consts.DB_MAX_TIME_USERS
});
} catch (err) {
err.responseCode = 500;
err.code = 'InternalDatabaseError';
this.loggelf({
short_message: '[AUTHFAIL] ' + username,
_stack: err.stack,
_error: err.message,
_code: err.code,
_auth_result: 'error',
_username: username,
_domain: userDomain,
_scope: requiredScope,
_ip: meta.ip,
_sess: meta.sess
});
// return as failed auth
return [false, false];
}
if (!userData) {
// User was not found
// rate limit failed authentication attempts against non-existent users as well
try {
let ustring = (userQuery.unameview || userQuery._id || '').toString();
rateLimitRes = await this.rateLimit(ustring, meta, 1);
} catch (err) {
err.responseCode = 500;
err.code = 'InternalDatabaseError';
this.loggelf({
short_message: '[AUTHFAIL] ' + username,
_stack: err.stack,
_error: err.message,
_code: err.code,
_auth_result: 'error',
_username: username,
_domain: userDomain,
_scope: requiredScope,
_ip: meta.ip,
_sess: meta.sess
});
}
if (!rateLimitRes.success) {
// does not really matter but respond with a rate limit error, not auth fail error
this.loggelf({
short_message: '[AUTHFAIL] ' + username,
_error: 'Rate limited',
_auth_result: 'ratelimited',
_username: username,
_domain: userDomain,
_scope: requiredScope,
_ip: meta.ip,
_sess: meta.sess
});
throw rateLimitResponse(rateLimitRes);
}
this.loggelf({
short_message: '[AUTHFAIL] ' + username,
_error: 'Unknown user',
_auth_result: 'unknown',
_username: username,
_domain: userDomain,
_scope: requiredScope,
_ip: meta.ip,
_sess: meta.sess
});
// return as failed auth
return [false, false];
}
// make sure we use the primary domain if available
userDomain = (userData.address || '').split('@').pop() || userDomain;
try {
// check if there are not too many auth attempts for that user
rateLimitRes = await this.rateLimitUser(userData._id, meta, 0);
} catch (err) {
err.responseCode = 500;
err.code = 'InternalDatabaseError';
err.user = userData._id;
this.loggelf({
short_message: '[AUTHFAIL] ' + username,
_stack: err.stack,
_error: err.message,
_code: err.code,
_auth_result: 'error',
_username: username,
_domain: userDomain,
_user: userData._id,
_scope: requiredScope,
_ip: meta.ip,
_sess: meta.sess
});
throw err;
}
if (!rateLimitRes.success) {
// too many failed attempts for this user
this.loggelf({
short_message: '[AUTHFAIL] ' + username,
_error: 'Rate limited',
_auth_result: 'ratelimited',
_username: username,
_domain: userDomain,
_user: userData._id,
_scope: requiredScope,
_ip: meta.ip,
_sess: meta.sess
});
let err = rateLimitResponse(rateLimitRes);
err.user = userData._id;
throw err;
}
if (userData.disabled) {
// disabled users can not log in
meta.result = 'disabled';
// TODO: should we send some specific error message?
this.loggelf({
short_message: '[AUTHFAIL] ' + username,
_error: 'User is disabled',
_auth_result: 'disabled',
_username: username,
_domain: userDomain,
_user: userData._id,
_scope: requiredScope,
_ip: meta.ip,
_sess: meta.sess
});
await this.logAuthEvent(userData._id, meta);
return [false, userData._id];
}
if (userData.suspended) {
// disabled users can not log in
meta.result = 'suspended';
// TODO: should we send some specific error message?
this.loggelf({
short_message: '[AUTHFAIL] ' + username,
_error: 'User is suspended',
_auth_result: 'suspended',
_username: username,
_domain: userDomain,
_user: userData._id,
_scope: requiredScope,
_ip: meta.ip,
_sess: meta.sess
});
await this.logAuthEvent(userData._id, meta);
return [false, userData._id];
}
let disabledScopes = userData.disabledScopes || [];
if (disabledScopes.includes(requiredScope)) {
this.loggelf({
short_message: '[AUTHFAIL] ' + username,
_error: 'Required scope is disabled',
_auth_result: 'scope_disabled',
_username: username,
_domain: userDomain,
_user: userData._id,
_scope: requiredScope,
_ip: meta.ip,
_sess: meta.sess
});
await this.logAuthEvent(userData._id, meta);
let err = new Error('Access to requested service disabled');
err.response = 'NO';
err.responseCode = 403;
err.code = 'InvalidAuthScope';
err.user = userData._id;
throw err;
}
try {
let authSuccess = async authResponse => {
let isPasswordPwned = !!userData.passwordPwned;
const twoWeeksMS = 14 * 24 * 60 * 60 * 1000;
if (
config.pwned &&
config.pwned.enabled &&
config.pwned.type &&
config.pwned.type !== 'none' &&
(!userData.lastPwnedCheck || new Date() - userData.lastPwnedCheck >= twoWeeksMS)
) {
try {
const opts = {};
if (config.pwned.apiUrl) {
opts.url = config.pwned.apiUrl;
}
isPasswordPwned = await this.checkPwnedPasswordForUser(password, opts);
await this.users.collection('users').updateOne(userQuery, { $set: { lastPwnedCheck: new Date(), passwordPwned: isPasswordPwned } });
// error can be ignored, in which case the value is not set and another pwned check will be conducted but it will be cached
if (isPasswordPwned && (config.pwned.type === 'fail' || config.pwned.type === 'hardfail')) {
// Hard fail the Pwned password check
this.loggelf({
short_message: '[AUTHFAIL] ' + username,
_error: 'Pwned password found',
_auth_result: 'fail',
_user: userData._id,
_username: username,
_domain: userDomain,
_scope: requiredScope,
_ip: meta.ip,
_sess: meta.sess,
_pwned: 'yes'
});
return [false, userData._id];
}
} catch {
if (config.pwned.type === 'hardfail') {
// do not ignore errors, hard fail auth
this.loggelf({
short_message: '[AUTHFAIL] ' + username,
_error: 'Pwned password - API Error',
_auth_result: 'fail',
_user: userData._id,
_username: username,
_domain: userDomain,
_scope: requiredScope,
_ip: meta.ip,
_sess: meta.sess
});
return [false, userData._id];
}
// ignore errors, soft check only
}
}
// clear rate limit counter on success
try {
await this.rateLimitReleaseUser(userData._id);
} catch {
//ignore
}
const log = {
short_message: '[AUTHOK] ' + username,
_mail_action: 'auth',
_auth_result: 'success',
_username: username,
_domain: userDomain,
_user: userData._id,
_password_type: passwordType,
_password_id: passwordId,
_scope: requiredScope,
_ip: meta.ip,
_sess: meta.sess
};
if (isPasswordPwned) {
// soft fail for pwned check
log._pwned = 'yes';
}
authResponse.passwordPwned = isPasswordPwned;
this.loggelf(log);
return [authResponse, userData._id];
};
let enabled2fa = tools.getEnabled2fa(userData.enabled2fa);
let requirePasswordChange = false;
let usingTemporaryPassword = false;
let success;
if (userData.tempPassword && userData.tempPassword.created > new Date(now.getTime() - consts.TEMP_PASS_WINDOW)) {
// try temporary password first
try {
success = await hashes.compare(password, userData.tempPassword.password);
} catch (err) {
err.responseCode = 500;
err.code = 'HashError';
throw err;
}
if (success) {
if (userData.tempPassword.validAfter && userData.tempPassword.validAfter > now) {
let err = new Error('Temporary password is not yet activated');
err.responseCode = 403;
err.code = 'TempPasswordNotYetValid';
throw err;
}
requirePasswordChange = true;
usingTemporaryPassword = true;
}
}
if (!success && userData.password) {
try {
// temporary password did not match, try actual password
success = await hashes.compare(password, userData.password);
} catch (err) {
err.responseCode = 500;
err.code = 'HashError';
throw err;
}
}
if (success) {
// master password matched
meta.result = 'success';
meta.source = !usingTemporaryPassword ? 'master' : 'temporary';
if (enabled2fa.length) {
meta.require2fa = enabled2fa.length ? enabled2fa.join(',') : false;
}
if (hashes.shouldRehash(userData.password)) {
// master password needs rehashing
let { algo } = hashes.checkHashSupport(userData.password);
let hash;
try {
hash = await hashes.hash(password);
if (!hash) {
// should this even happen???
throw new Error('Failed to rehash password');
}
try {
let r = await this.users.collection('users').updateOne(
{
_id: userData._id
},
{
$set: {
password: hash
}
},
{ writeConcern: 'majority' }
);
if (r.modifiedCount) {
log.info('DB', 'REHASHED user=%s algo_from=%s algo_to=%s', userData._id, algo, consts.DEFAULT_HASH_ALGO);
this.loggelf({
short_message: '[REHASH] ' + username,
_mail_action: 'rehash',
_username: username,
_domain: userDomain,
_user: userData._id,
_password_type: passwordType,
_password_id: passwordId,
_scope: requiredScope,
_algo_from: algo,
_algo_to: consts.DEFAULT_HASH_ALGO,
_ip: meta.ip,
_sess: meta.sess
});
}
} catch (err) {
log.error('DB', 'DBFAIL rehash user=%s error=%s', userData._id, err.message);
}
} catch (err) {
log.error('DB', 'HASHFAIL rehash user=%s algo_from=%s algo_to=%s error=%s', userData._id, algo, consts.DEFAULT_HASH_ALGO, err.message);
// ignore DB error, rehash some other time
}
}
if (requiredScope !== 'master' && (enabled2fa.length || usingTemporaryPassword)) {
// master password can not be used for other scopes than 'master' if 2FA is enabled
// temporary password is also only valid for master
meta.result = 'fail';
await this.logAuthEvent(userData._id, meta);
let err = new Error('Authentication failed. Invalid scope');
err.responseCode = 403;
err.code = 'InvalidAuthScope';
err.response = 'NO'; // imap response code
throw err;
}
try {
let authEvent = await this.logAuthEvent(userData._id, meta);
await this.users.collection('users').updateOne(
{
_id: userData._id
},
{
$set: {
lastLogin: {
time: now,
authEvent,
ip: meta.ip
}
}
},
{
maxTimeMS: consts.DB_MAX_TIME_USERS
}
);
} catch (err) {
// ignore
}
const authResponse = {
user: userData._id,
username: userData.username,
scope: meta.requiredScope,
address: userData.address,
// if 2FA is enabled then require token validation
require2fa: enabled2fa.length && !usingTemporaryPassword ? enabled2fa : false,
requirePasswordChange // true, if password was reset and using temporary password
};
if (enabled2fa.length && !usingTemporaryPassword) {
authResponse.enabled2fa = enabled2fa;
}
return await authSuccess(authResponse);
}
if (requiredScope === 'master') {
// only master password can be used for management tasks
meta.result = 'fail';
meta.source = 'master';
await this.logAuthEvent(userData._id, meta);
let err = new Error('Invalid Auth');
err.responseCode = 403;
err.code = 'AuthFail'; // will be returned as failed auth, not an error
throw err;
}
// try application specific passwords
password = password.replace(/\s+/g, '').toLowerCase();
if (!/^[a-z]{16}$/.test(password)) {