/
verify_gateway_entry.js
1619 lines (1399 loc) · 67.3 KB
/
verify_gateway_entry.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
importClass(Packages.com.tivoli.am.fim.trustserver.sts.utilities.IDMappingExtUtils);
importClass(Packages.com.tivoli.am.fim.trustserver.sts.utilities.OAuthMappingExtUtils);
importClass(Packages.com.tivoli.am.fim.registrations.MechanismRegistrationHelper);
importClass(Packages.com.ibm.security.access.user.UserLookupHelper);
importClass(Packages.com.ibm.security.access.scimclient.ScimClient);
importClass(Packages.com.tivoli.am.fim.base64.BASE64Utility);
importClass(Packages.com.tivoli.am.fim.authsvc.local.client.AuthSvcClient);
/**
* Copyright contributors to the IBM Security Verify Access AAC Mapping Rules project.
*
* This mapping rule allows a IBM Security Verify Gateway user to authenticate using
* on-premise registered authentication methods.
*
* Updates to this file will also be made available at:
* https://github.com/IBM-Security/verify-access-aac-mapping-rules
*
*/
var PERSISTENT_CACHE_TIMEOUT = 300; // 5 mins
/*
* These parameters likely need to be changed per deployment
*/
var POINT_OF_CONTACT_URL = "https://www.mmfa.ibm.com";
//
// The set of permitted ISVA OAuth clients that can invoke this Infomap/policy.
// You need to put your OAuth client in this list, or create one called VerifyGatewayClient.
//
var allowedClients = [ "VerifyGatewayClient" ];
//
// This variable determines what group(s) an end-user must be in for a particular allowedClient.
// It can be set to null, in which case no group checking is performed.
//
//var clientToAllowedGroups = {
// "VerifyGatewayClient": [ "windowsgroup" ]
//}
var clientToAllowedGroups = null;
//
// Simple config used to control which ISVA 2FA methods are allowed to be returned
//
var ENABLED_2FA_METHODS = {
totp: true,
emailotp: true,
smsotp: true,
mobilepush: true
}
//
// Special config for determining which IBM Verify mobile push signature methods
// will be returned.
//
// If ENABLED_2FA_METHODS.mobilepush is true, this will enable specific types
// there is a special case if "bestAvailable" is true, then userPresence
// and fingerprint flags are ignored. If a user has fingerprint signature
// capabilities, only those will be returned, otherwise any available userPresence
// capabilities will be returned.
//
// If you want "everything", set bestAvailable to false, and the others to true.
//
var ENABLED_MOBILE_PUSH_METHODS = {
bestAvailable: false,
userPresence: true,
fingerprint: true
}
//
// These are policy URIs defined as per the MMFA cookbook. Your environment might use
// something different, so check the configuration and adjust here as needed.
//
var AUTHSVC_POLICYURI_RESPONSE_USERPRESENCE = "urn:ibm:security:authentication:asf:verify_gateway_mmfa_userpresence_resp";
var AUTHSVC_POLICYURI_RESPONSE_FINGERPRINT = "urn:ibm:security:authentication:asf:verify_gateway_mmfa_fingerprint_resp";
/*
* Utility functions for temporary state storage.
*/
var AuthSvcState = {
/*
* Uses IDMappingExtCache to store session state objects.
* Note that keys are hashed because they can be too long.
*/
"shakey": function(s) {
return BASE64Utility.encode(OAuthMappingExtUtils.SHA512Sum(s), false);
},
"storeState": function(k,o) {
let cache = IDMappingExtUtils.getIDMappingExtCache();
let jsk = this.shakey(k);
let strval = JSON.stringify(o);
cache.put(jsk, strval, PERSISTENT_CACHE_TIMEOUT);
},
"getState": function(k) {
let cache = IDMappingExtUtils.getIDMappingExtCache();
let result = null;
let jsk = this.shakey(k);
let jstr = cache.get(jsk);
if (jstr != null) {
result = JSON.parse(jstr);
}
return result;
},
"getAndRemoveState": function(k) {
let cache = IDMappingExtUtils.getIDMappingExtCache();
let result = null;
let jsk = this.shakey(k);
let jstr = cache.getAndRemove(jsk);
if (jstr != null) {
result = JSON.parse(jstr);
}
return result;
}
};
//
// Utility functions
//
function debugLog(str) {
if (typeof (console) != "undefined") {
console.log(str);
} else {
IDMappingExtUtils.traceString(str);
}
}
function createUUID() {
return ''+OAuthMappingExtUtils.createUUID();
}
function emptyIfNull(s) {
return (s == null ? '' : ''+s);
}
function arrayToLogStr(a) {
let result = null;
if (a != null) {
let result = '[';
for (let i = 0; i < a.length; i++) {
result += a[i];
if (i < (a.length-1)) {
result += ',';
}
}
result += ']';
}
return result;
}
// Used for debugging
function dumpContext() {
debugLog("request attributes: " +context.get(Scope.REQUEST, "urn:ibm:security:asf:request", "attributes"));
debugLog("request headers: " +context.get(Scope.REQUEST, "urn:ibm:security:asf:request", "headers"));
let cookieValues = context.get(Scope.REQUEST, "urn:ibm:security:asf:request:headers", "cookie");
debugLog("cookie headers: " + arrayToLogStr(cookieValues));
let parameters = context.get(Scope.REQUEST, "urn:ibm:security:asf:request", "parameters");
debugLog("request parameters: " +parameters);
if (parameters != null) {
for (let i = parameters.iterator(); i.hasNext();) {
let paramName = i.next();
let paramValues = context.get(Scope.REQUEST, "urn:ibm:security:asf:request:parameters", paramName);
debugLog("paramName: " + paramName + " paramValues: " + arrayToLogStr(paramValues));
}
}
//debugLog("response attrs: " +context.get(Scope.SESSION, "urn:ibm:security:asf:response", "attributes"));
}
function throwSCIMError(methodName, errorText, httpStatusCode) {
debugLog("throwSCIMError being called for methodName: " + methodName + " httpStatusCode: " + httpStatusCode + " errorText: " + errorText);
let msg = methodName + ": " + errorText;
let code = "400";
if (httpStatusCode != null && httpStatusCode != "") {
code = httpStatusCode;
}
let e = {
"httpStatusCode": code,
"httpContentType": "application/scim+json",
"status":code,
"detail":msg,
"schemas":["urn:ietf:params:scim:api:messages:2.0:Error"]
};
throw e;
}
function throwErrorWithCode(methodName, errorText, httpStatusCode) {
debugLog("throwErrorWithCode being called for methodName: " + methodName + " errorText: " + errorText);
let msg = methodName + ": " + errorText;
throw {"httpStatusCode": httpStatusCode,"error":msg,"messageId":msg,"messageDescription":msg};
}
function throwError(methodName, errorText) {
debugLog("throwError being called for methodName: " + methodName + " errorText: " + errorText);
let msg = methodName + ": " + errorText;
throw {"error":msg};
}
//
// Function which determines if a particular user is allowed to authenticate from the current client based on group memberships.
//
function checkUserAuthorization(currentClient, user) {
let result = false;
// if clientToAllowedGroups is null, or there is no entry for the current client, then by definition we are not doing group-based authorization
if (clientToAllowedGroups == null || clientToAllowedGroups[currentClient] == null) {
debugLog("checkUserAuthorization: no group access for client: " + currentClient + " Allowing access for user: " + user.getId());
result = true;
}
if (!result) {
// if any of the user's groups is in the allowed list of this client, permit
let userGroups = user.getGroups();
for (let i = 0; i < userGroups.length && result == false; i++) {
if (clientToAllowedGroups[currentClient].indexOf(''+userGroups[i]) >= 0) {
debugLog("checkUserAuthorization: client: " + currentClient + " Allowing access for user: " + user.getId() + " in group: " + userGroups[i]);
result = true;
}
}
}
// if not permitted, log why, then throw an error
if (!result) {
debugLog("checkUserAuthorization: client: " + currentClient + " Denying access for user: " + user.getId() + " not in any allowed group: " + JSON.stringify(clientToAllowedGroups[currentClient]));
throwErrorWithCode("checkUserAuthorization", "User not authorized", "401");
}
}
function prepareUserResponse(user) {
let u = {
"id": "XXXX",
"userName": "XXXX",
"active": true,
"emails": [],
"phoneNumbers": [],
"meta": {
"created": "2019-01-01T00:00:000Z",
"lastModified": "2019-01-01T00:00:000Z"
},
"name": {
"formatted": "Firstname Surname",
"familyName": "Surname",
"givenName": "Firstname"
},
"urn:ietf:params:scim:schemas:extension:ibm:2.0:User": {
"userCategory": "regular",
"twoFactorAuthentication": false,
"realm": "cloudIdentityRealm",
"pwdChangedTime": "2019-01-01T00:00:000Z"
}
/*,
"groups": [
{
"displayName": "group1",
"id": "50DFJQ6C1T",
"$ref": "https://myidp.ice.ibmcloud.com/v2.0/Groups/50DFJQ6C1T"
}
]
*/
};
u.id = ''+ScimClient.computeIDForUsername(user.getId());
u.userName = ''+user.getId();
// add email if we have it, and emailotp is enabled
if (ENABLED_2FA_METHODS.emailotp) {
let email = user.getAttribute("mail");
if (email != null) {
u.emails.push({"type":"work","value":''+email});
}
}
// add phone number if we have it and smsotp is enabled
if (ENABLED_2FA_METHODS.smsotp) {
let phone = user.getAttribute("mobile");
if (phone != null) {
u.phoneNumbers.push({"type":"mobile","value":''+phone});
}
}
// if the user is in any groups, add them. These might be used for radius server access policy
var groups = user.getGroups();
if (groups != null && groups.length > 0) {
u["groups"] = [];
for (let i = 0; i < groups.length; i++) {
let groupId = ScimClient.computeIDForUsername(groups[i]);
u.groups.push({"displayName":''+groups[i],"id":''+groupId,"$ref":''+groupId})
}
}
return u;
}
function processUsersRequest(ulh, currentClient, uri) {
// start with empty user search result
let result = {"httpContentType":"application/scim+json","totalResults":0,
"schemas":["urn:ietf:params:scim:api:messages:2.0:ListResponse"],"Resources":[]};
let regex = /^\/v2.0\/Users\?filter=userName eq "([^"]*)"$/;
let m = unescape(uri).match(regex);
if (m != null && m.length == 2) {
let username = m[1];
// lets see if we have this user
debugLog("Attempting to lookup user: " + username);
let user = ulh.getUser(username);
if (user != null) {
try {
// perform authorizatin check - error thrown if this user is not allowed to be used from this client
// in which case we wrap and re-throw as a SCIM error
checkUserAuthorization(currentClient, user);
} catch (e) {
throwSCIMError("processUsersRequest", e.error, "401");
}
// populate skeleton user, then update with information from ldap user
result.totalResults = 1;
let u = prepareUserResponse(user);
result.Resources.push(u);
} else {
debugLog("processUsersRequest: User not found: " + username);
}
} else {
throwSCIMError("processUsersRequest", "Invalid uri", "400");;
}
return result;
}
function processUserLookup(ulh, currentClient, uri) {
let result = {};
let regex = /^\/v2.0\/Users\/(.*)$/;
let m = unescape(uri).match(regex);
if (m != null && m.length == 2) {
let scimID = m[1];
let user = ulh.getUser(ScimClient.computeUsernameFromID(scimID));
if (user != null) {
try {
// perform authorizatin check - error thrown if this user is not allowed to be used from this client
// in which case we wrap and re-throw as a SCIM error
checkUserAuthorization(currentClient, user);
} catch (e) {
throwSCIMError("processUserLookup", e.error, "401");
}
result = prepareUserResponse(user);
} else {
throwSCIMError("processUserLookup", "User does not exist", "404");
}
} else {
throwSCIMError("processUserLookup", "Invalid uri", "400");
}
return result;
}
function processFactorsLookup(ulh, currentClient, uri) {
let result = {"total": 0,"factors":[],"count":200,"limit":200,"page":1};
let regex = /^\/v2.0\/factors\?search=userId\s*=\s*"([^"]*)"$/;
let m = unescape(uri).match(regex);
if (m != null && m.length == 2) {
let scimID = m[1];
let username = ScimClient.computeUsernameFromID(scimID);
let user = ulh.getUser(username);
if (user != null) {
// perform authorizatin check - error thrown if this user is not allowed to be used from this client
checkUserAuthorization(currentClient, user);
// if TOTP is enabled, and this user has TOTP, indicate that
if (ENABLED_2FA_METHODS.totp) {
let canDoTOTP = (IDMappingExtUtils.retrieveSecretKey("otpfed","jdbc_userinfo",username,"otp.hmac.totp.secret.key","urn:ibm:security:otp:hmac") != null);
if (canDoTOTP) {
result.total++;
result.factors.push({
"id": scimID,
"userId": scimID,
"type": "totp",
"creationTime": "2019-01-01T00:00:00.000Z",
"updated": "2019-01-01T00:00:00.000Z",
"attempted": "2019-01-01T00:00:00.000Z",
"enabled": true,
"validated": true,
"attributes": {
"algorithm": "SHA1",
"digits": 6,
"period": 30
}
});
}
}
} else {
// just return an empty list for unknown user
debugLog("processFactorsLookup: User not found: " + username);
}
} else {
throwError("processFactorsLookup", "Invalid uri");
}
return result;
}
function processFactorsTOTPLookup(ulh, currentClient, uri) {
/* subtly different from processFactorsLookup in response body and regex */
var result = {"total": 0,"totp":[],"count":200,"limit":200,"page":1};
var regex = /^\/v2.0\/factors\/totp\?search=userId\s*=\s*"([^"]*)"$/;
var m = unescape(uri).match(regex);
if (m != null && m.length == 2) {
var scimID = m[1];
var username = ScimClient.computeUsernameFromID(scimID);
var user = ulh.getUser(username);
if (user != null) {
// perform authorizatin check - error thrown if this user is not allowed to be used from this client
checkUserAuthorization(currentClient, user);
// if TOTP is enabled, and this user has TOTP, indicate that
if (ENABLED_2FA_METHODS.totp) {
var canDoTOTP = (IDMappingExtUtils.retrieveSecretKey("otpfed", "jdbc_userinfo", username, "otp.hmac.totp.secret.key","urn:ibm:security:otp:hmac") != null);
if (canDoTOTP) {
result.total++;
result.totp.push({
"id": scimID,
"userId": scimID,
"type": "totp",
"creationTime": "2019-01-01T00:00:00.000Z",
"updated": "2019-01-01T00:00:00.000Z",
"attempted": "2019-01-01T00:00:00.000Z",
"enabled": true,
"validated": true,
"attributes": {
"algorithm": "SHA1",
"digits": 6,
"period": 30
}
});
}
}
} else {
// just return an empty list for unknown user
debugLog("processFactorsTOTPLookup: User not found: " + username);
}
} else {
throwError("processFactorsTOTPLookup", "Invalid uri");
}
return result;
}
function processFactorsTOTPVerification(ulh, currentClient, uri, totp) {
debugLog("processFactorsTOTPVerification called for uri: " + uri + " totp: " + totp);
let result = null; // to eventually return a 204 on success
let totpVerified = false;
let regex = /^\/v2.0\/factors\/totp\/([^\/]*)$/;
let m = unescape(uri).match(regex);
if (m != null && m.length == 2) {
let scimID = m[1];
let username = ScimClient.computeUsernameFromID(scimID);
let user = ulh.getUser(username);
if (user != null) {
// perform authorizatin check - error thrown if this user is not allowed to be used from this client
checkUserAuthorization(currentClient, user);
let body = {
"PolicyId": "urn:ibm:security:authentication:asf:verify_gateway_totp",
"username": ''+username,
"otp": totp,
"operation": "verify"
};
debugLog("processFactorsTOTPVerification AuthSvcClient sending to verify_gateway_totp: " + JSON.stringify(body));
let authsvcResponseStr = AuthSvcClient.execute(JSON.stringify(body));
debugLog("processFactorsTOTPVerification AuthSvcClient result: " + authsvcResponseStr);
let authSvcResponse = JSON.parse(''+authsvcResponseStr);
if (authSvcResponse.status == "success") {
// success
totpVerified = true;
}
}
}
if (!totpVerified) {
let error = {"httpStatusCode":"400","messageId":"CSIBN0021E","messageDescription":"The verification attempt failed."};
throw error;
}
return result;
}
function processFactorsMACOTPStart(ulh, currentClient, uri, deliveryType, deliveryAttribute) {
let result = {};
let body = {
"PolicyId": "urn:ibm:security:authentication:asf:verify_gateway_macotp",
"username": "transient",
"deliveryType": "TBD"
};
if (uri == "/v2.0/factors/emailotp/transient/verifications") {
body.deliveryType = "Email";
body.emailAddress = deliveryAttribute;
} else if (uri == "/v2.0/factors/smsotp/transient/verifications") {
body.deliveryType = "SMS";
body.mobileNumber = deliveryAttribute;
} else
throwError("processFactorsMACOTPStart", "Invalid uri");{
}
debugLog("processFactorsMACOTPStart AuthSvcClient sending to verify_gateway_macotp: " + JSON.stringify(body));
let authsvcResponseStr = AuthSvcClient.execute(JSON.stringify(body));
debugLog("processFactorsMACOTPStart AuthSvcClient result: " + authsvcResponseStr);
let authsvcResponse = JSON.parse(''+authsvcResponseStr);
if (authsvcResponse.status == "pause") {
let jsonBody = authsvcResponse.response;
// store state information based on initial stateId of this policy invocation
// that's because the stateid sent to the client in the factors-like response is
// static for the lifetime of this attempt at MAC OTP, however the user may try
// multiple times and each time the ISVA-based StateId will change
let stateObj = {
"stateId": jsonBody["stateId"]
}
AuthSvcState.storeState(jsonBody["stateId"] + "_StateObj", stateObj);
// emailotp and smsotp are almost identical
let now = new Date();
// 5 minutes
let expiry = new Date(now.getTime() + PERSISTENT_CACHE_TIMEOUT * 1000);
let methodType = (uri == "/v2.0/factors/emailotp/transient/verifications" ? "emailotp" : "smsotp");
// need to build a response similar to this one (captured from ISV)
// response code 201 (Created)
result = {
"httpStatusCode": "201",
"id": jsonBody["stateId"],
"type": methodType,
"created": now.toISOString(),
"updated": now.toISOString(),
"expiry": expiry.toISOString(),
"state": "PENDING",
"correlation": jsonBody["otp.user.otp-hint"],
"attempts": 0,
"retries": 4
};
if (methodType == "emailotp") {
result["emailAddress"] = deliveryAttribute;
} else {
result["phoneNumber"] = deliveryAttribute;
}
} else {
// response status not "pause"
throwError("processFactorsMACOTPStart", "Bad AuthSvcClient response status: " + authsvcResponse.status);;
}
return result;
}
function processFactorsMACOTPSubmit(ulh, currentClient, uri, deliveryType, otp) {
let result = null;
// extract stateid from uri
let otpVerified = false;
let stateId = null;
// this regexp matches both emailotp and smsotp transient verification URLs
let regex = /^\/v2.0\/factors\/[^\/]*\/transient\/verifications\/([^\/]*)$/;
let m = unescape(uri).match(regex);
if (m != null && m.length == 2) {
stateId = m[1];
// retrieve state object - this is to get the "current" authsvc policy stateid
let stateObj = AuthSvcState.getState(stateId + "_StateObj");
if (stateObj == null || stateObj.stateId == null) {
throwError("processFactorsMACOTPSubmit", "Unable to retrieve authsvc session state");
}
// now time to verify against ISVA
let body = {
"StateId": stateObj.stateId,
"otp.user.otp": otp,
"operation": "verify"
};
debugLog("processFactorsMACOTPSubmit AuthSvcClient sending to verify_gateway_macotp: " + JSON.stringify(body));
let authsvcResponseStr = AuthSvcClient.execute(JSON.stringify(body));
debugLog("processFactorsMACOTPSubmit AuthSvcClient result: " + authsvcResponseStr);
let authsvcResponse = JSON.parse(''+authsvcResponseStr);
if (authsvcResponse.status == "success") {
// success - may as well remove state
stateObj = AuthSvcState.getAndRemoveState(stateId + "_StateObj");
otpVerified = true;
} else if (authsvcResponse.status == "pause") {
// probably an OTP entry error, need to retain updated stateId and return an error
let jsonBody = authsvcResponse.response;
stateObj["stateId"] = jsonBody.stateId;
AuthSvcState.storeState(stateId + "_StateObj", stateObj);
}
}
if (!otpVerified) {
let error = {"messageId":"CSIBN0021E","messageDescription":"The verification attempt failed."};
throw error;
}
return result;
}
function processAuthenticationMethodsSearch(ulh, currentClient, uri) {
let result = {"total":0, "authnmethods": [],"count":200,"limit":200,"page":1};
let regex = /^\/v1.0\/authnmethods\?search=owner\s*=\s*"([^"]*)"$/;
let m = unescape(uri).match(regex);
if (m != null && m.length == 2) {
let scimID = m[1];
let username = ScimClient.computeUsernameFromID(scimID);
let user = ulh.getUser(username);
if (user != null) {
// perform authorizatin check - error thrown if this user is not allowed to be used from this client
checkUserAuthorization(currentClient, user);
// if TOTP is enabled, and this user has TOTP, indicate that
if (ENABLED_2FA_METHODS.totp) {
let canDoTOTP = (IDMappingExtUtils.retrieveSecretKey("otpfed","jdbc_userinfo",username,"otp.hmac.totp.secret.key","urn:ibm:security:otp:hmac") != null);
if (canDoTOTP) {
result.total = 1;
result.authnmethods.push({
"owner": scimID,
"methodType": "totp",
"isValidated": true,
"creationTime": "2019-01-01T00:00:00.000Z",
"isEnabled": true,
"attributes": {
"period": 30,
"digits": 6,
"algorithm": "SHA1"
},
"id": scimID
});
}
}
} else {
debugLog("processAuthenticationMethodsSearch: User not found");
}
} else {
throwError("processAuthenticationMethodsSearch", "Invalid uri");
}
return result;
}
function processAuthenticationMethodsTOTPSearch(ulh, currentClient, uri) {
/* subtly different from processAuthenticationMethodsSearch in result body and regex */
let result = {"total":0, "totp": [],"count":200,"limit":200,"page":1};
let regex = /^\/v1.0\/authnmethods\/totp\?search=owner\s*=\s*"([^"]*)"$/;
let m = unescape(uri).match(regex);
if (m != null && m.length == 2) {
let scimID = m[1];
let username = ScimClient.computeUsernameFromID(scimID);
let user = ulh.getUser(username);
if (user != null) {
// perform authorizatin check - error thrown if this user is not allowed to be used from this client
checkUserAuthorization(currentClient, user);
// if TOTP is enabled, and this user has TOTP, indicate that
if (ENABLED_2FA_METHODS.totp) {
let canDoTOTP = (IDMappingExtUtils.retrieveSecretKey("otpfed","jdbc_userinfo",username,"otp.hmac.totp.secret.key","urn:ibm:security:otp:hmac") != null);
if (canDoTOTP) {
result.total = 1;
result.totp.push({
"owner": scimID,
"methodType": "totp",
"isValidated": true,
"creationTime": "2019-01-01T00:00:00.000Z",
"isEnabled": true,
"attributes": {
"period": 30,
"digits": 6,
"algorithm": "SHA1"
},
"id": scimID
});
}
}
}
} else {
throwError("processAuthenticationMethodsTOTPSearch", "Invalid uri");
}
return result;
}
function processTOTPVerification(ulh, currentClient, uri, totp) {
let result = {"messageId":"CSIBN0022I","messageDescription":"The authentication factor [TOTP] is verified."};
let error = {"messageId":"CSIBN0021E","messageDescription":"The system cannot verify the authentication factor [TOTP]."};
let totpVerified = false;
let regex = /^\/v1.0\/authnmethods\/totp\/([^\/]*)$/;
let m = unescape(uri).match(regex);
if (m != null && m.length == 2) {
let scimID = m[1];
let username = ScimClient.computeUsernameFromID(scimID);
let user = ulh.getUser(username);
if (user != null) {
// perform authorizatin check - error thrown if this user is not allowed to be used from this client
checkUserAuthorization(currentClient, user);
debugLog("Verifying TOTP for username: " + username + " totp: " + totp);
let body = {
"PolicyId": "urn:ibm:security:authentication:asf:verify_gateway_totp",
"username": ''+username,
"otp": totp,
"operation": "verify"
};
debugLog("processTOTPVerification AuthSvcClient sending to verify_gateway_totp: " + JSON.stringify(body));
let authsvcResponseStr = AuthSvcClient.execute(JSON.stringify(body));
debugLog("processTOTPVerification AuthSvcClient result: " + authsvcResponseStr);
let authSvcResponse = JSON.parse(''+authsvcResponseStr);
if (authSvcResponse.status == "success") {
// success
totpVerified = true;
}
}
}
if (!totpVerified) {
throw error;
}
return result;
}
function processUserAuthentication(ulh, currentClient, uri, username, pwd) {
let result = {
"httpContentType": "application/scim+json",
"schemas": [
"urn:ietf:params:scim:schemas:core:2.0:User"
],
"id": "XXXXX"
};
let error = {
"httpStatusCode": "400",
"httpContentType": "application/scim+json",
"schemas": [
"urn:ietf:params:scim:api:messages:2.0:Error"
],
"status": "400",
"detail": "CSIAI0160E Authentication failed.",
"scimType": "INVALID_CREDS"
};
let pwVerified = false;
let user = ulh.getUser(username);
if (user != null) {
// perform authorizatin check - error thrown if this user is not allowed to be used from this client
checkUserAuthorization(currentClient, user);
//debugLog("Verifying password for username: " + username + " password: " + pwd);
let isAuthenticated = user.authenticate(pwd);
//debugLog("Password Valid: " + isAuthenticated);
if (isAuthenticated) {
// success
pwVerified = true;
}
} else {
debugLog("processUserAuthentication: unable to find user: " + username);
}
if (!pwVerified) {
throw error;
}
result.id = ''+ScimClient.computeIDForUsername(username);
return result;
}
function processMACOTPStart(ulh, currentClient, uri, deliveryType, deliveryAttribute) {
let result = {};
// now time to kick it off with ISVA
let body = {
"PolicyId": "urn:ibm:security:authentication:asf:verify_gateway_macotp",
"username": 'transient',
"deliveryType": 'TBD'
};
if (uri == "/v1.0/authnmethods/emailotp/transient/verification") {
body.deliveryType = "Email";
body.emailAddress = deliveryAttribute;
} else if (uri == "/v1.0/authnmethods/smsotp/transient/verification") {
body.deliveryType = "SMS";
body.mobileNumber = deliveryAttribute;
} else {
let error = { "error": "processMACOTPStart bad uri provided" };
throw error;
}
debugLog("processMACOTPStart AuthSvcClient sending to verify_gateway_macotp: " + JSON.stringify(body));
let authsvcResponseStr = AuthSvcClient.execute(JSON.stringify(body));
debugLog("processMACOTPStart AuthSvcClient result: " + authsvcResponseStr);
let authsvcResponse = JSON.parse(''+authsvcResponseStr);
if (authsvcResponse.status == "pause") {
let jsonBody = authsvcResponse.response;
// store state information based on initial stateId of this policy invocation
// that's because the stateid sent to the client in the ISV-like response is
// static for the lifetime of this attempt at MAC OTP, however the user may try
// multiple times and each time the ISVA-based StateId will change
let stateObj = {
"stateId": jsonBody["stateId"]
}
AuthSvcState.storeState(jsonBody["stateId"] + "_StateObj", stateObj);
// emailotp and smsotp are almost identical
let now = new Date();
// 5 minutes
let expiry = new Date(now.getTime() + PERSISTENT_CACHE_TIMEOUT * 1000);
let methodType = (uri == "/v1.0/authnmethods/emailotp/transient/verification" ? "emailotp" : "smsotp");
// need to build a response similar to this one (captured from CI)
// response code 202 (Accepted)
result = {
"httpStatusCode": "202",
"owner": "unavailable",
"transactionType": "transient",
"maxTries": 5,
"sentTo": deliveryAttribute,
"methodType": methodType,
"correlation": jsonBody["otp.user.otp-hint"],
"creationTime": now.toISOString(),
"expiryTime": expiry.toISOString(),
"numberOfAttempts": 0,
"id": jsonBody["stateId"]
};
} else {
// response status not "pause"
throwError("processMACOTPStart", "Bad AuthSvcClient response status: " + authsvcResponse.status);
}
return result;
}
function processMACOTPSubmit(ulh, currentClient, uri, deliveryType, otp) {
let result = {"messageId":"CSIAH0620I","messageDescription":"The authentication attempt was successful."};
// extract stateid from uri
let otpVerified = false;
let stateId = null;
// this regexp matches both emailotp and smsotp transient verification URLs
let regex = /^\/v1.0\/authnmethods\/[^\/]*\/transient\/verification\/([^\/]*)$/;
let m = unescape(uri).match(regex);
if (m != null && m.length == 2) {
stateId = m[1];
// retrieve state object - this is to get the "current" authsvc policy stateid
let stateObj = AuthSvcState.getState(stateId + "_StateObj");
if (stateObj == null || stateObj.stateId == null) {
throwError("processMACOTPSubmit", "Unable to retrieve authsvc session state");
}
// now time to verify against ISVA
let body = {
"StateId": stateObj.stateId,
"otp.user.otp": otp,
"operation": "verify"
};
debugLog("processMACOTPSubmit AuthSvcClient sending to verify_gateway_macotp: " + JSON.stringify(body));
let authsvcResponseStr = AuthSvcClient.execute(JSON.stringify(body));
debugLog("processMACOTPSubmit AuthSvcClient result: " + authsvcResponseStr);
let authsvcResponse = JSON.parse(''+authsvcResponseStr);
if (authsvcResponse.status == "success") {
// success - may as well remove state
stateObj = AuthSvcState.getAndRemoveState(stateId + "_StateObj");
otpVerified = true;
result = {"messageId":"CSIAH0620I","messageDescription":"The authentication attempt for the method [" + deliveryType + "] was successful."};
} else if (authsvcResponse.status == "pause") {
// probably an OTP entry error, need to retain updated stateId and return an error
let jsonBody = authsvcResponse.response;
stateObj["stateId"] = jsonBody.stateId;
AuthSvcState.storeState(stateId + "_StateObj", stateObj);
}
}
if (!otpVerified) {
let error = {"messageId":"CSIAH0619E","messageDescription":"The authentication attempt for the method ["
+ deliveryType + "] failed."};
throw error;
}
return result;
}
function getDeviceObjFromRegistration(scimID, username, reg, regid, fingerprintSupport) {
// whilst the device.id attribute populated below is logically the authenticator id, for
// the ISVA integration we set it to the logical fingerprintMethod id or userPresenceMethod id
// so that when returned as part of mobile push kick-off we know precisely
// which response policy (userpresence or fingerprint) to auto-select for invocation.
// It allows mobilePushKickoff to select userpresence or fingerprint response
// policy in the case where the same authenticator registration has both.
//
// also deviceType is used in the display to human about what method to select.
// If ISVA has both biometric (e.g. fingerprint) and user-presence registered, there
// is no way for the user to see the difference, so we annotate the deviceType
//
let result = {
"id": regid,
"owner": scimID,
"enabled": reg.isEnabled(),
"clientId": "AuthenticatorClient",
"creationTime": "2019-01-01T00:00:00.000Z",
"state": "ACTIVE",
"attributes": {
"applicationVersion": "unavaialble",
"deviceType": IDMappingExtUtils.escapeHtml(emptyIfNull(reg.getDeviceType())) + (fingerprintSupport ? "-biometric" : "-userPresence"),
"accountName": username,
"platformType": "unavailable",
"pushToken": "unavailable",
"deviceName": "" + IDMappingExtUtils.escapeHtml(emptyIfNull(reg.getDeviceName())),
"deviceId": "unavailable",
"fingerprintSupport": fingerprintSupport,
"verifySdkVersion": "unavailable",
"osVersion": "" + IDMappingExtUtils.escapeHtml(emptyIfNull(reg.getOSVersion())),
"frontCameraSupport": true,
"faceSupport": false,
"applicationId": "com.ibm.security.verifyapp"
}
};
return result;
}
function processGetSignatures(ulh, currentClient, uri) {
let result = {
"total": 0,
"limit": 200,
"count": 200,
"page": 1,
"signatures": []
};
if (ENABLED_2FA_METHODS.mobilepush) {
let regex = /^\/v1.0\/authnmethods\/signatures\?search=owner = "([^"]*)"&_embedded=true&sort=-signatures\/_embedded\/id$/;
let m = unescape(uri).match(regex);
if (m != null && m.length == 2) {
let scimID = m[1];
let username = ''+ScimClient.computeUsernameFromID(scimID);
let user = ulh.getUser(username);
if (user != null) {
// perform authorizatin check - error thrown if this user is not allowed to be used from this client
checkUserAuthorization(currentClient, user);
// look up MMFA registrations for user using API available from 10.0.4.0
let mmfaRegistrations = MechanismRegistrationHelper.getMmfaRegistrationsForUser(username);
if (mmfaRegistrations != null && mmfaRegistrations.length > 0) {
// build state information about registrations - we decide what to do with them afterward
let fingerprintMethods = [];
let userPresenceMethods = [];
debugLog("mmfaRegistrations: " + mmfaRegistrations.length);
for (let i = 0; i < mmfaRegistrations.length; i++) {
let reg = mmfaRegistrations[i];
debugLog("["+i+"]: " + reg.toJson());
// only process if this registration is enabled
if (reg.isEnabled()) {
if (reg.hasFingerprintEnrolled()) {
let regid = createUUID();
let deviceObj = getDeviceObjFromRegistration(scimID, username, reg, regid, true);
fingerprintMethods.push({
"id": regid,
"owner": scimID,
"enabled": true,
"validated": true,