-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
2565 lines (2262 loc) · 92.6 KB
/
main.js
File metadata and controls
2565 lines (2262 loc) · 92.6 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
const base64url = require('base64url');
const crypto = require('crypto');
const fs = require('fs');
const log4js = require('log4js');
const utils = require("./fido2-node-lib/utils")
require('dotenv').config();
const { v4: uuidv4 } = require('uuid');
const { env } = require("process");
log4js.configure('log4js-conf.json');
const logger = log4js.getLogger();
//logger.level = process.env.LOG4JS_LEVEL;
//console.log(process.version)
logger.info('Running on nodejs:' + process.version)
const port = process.env.PORT || 443;
const mysql = require('mysql2');
const mysql_pool = mysql.createPool({
waitForConnections: true, // Wait for a connection to be available if the pool is full
queueLimit: 0, // Maximum number of queued connection requests (0 = unlimited)
connectTimeout: process.env.MYSQL_CONNECTION_TIMEOUT || 10000, // Connection timeout in milliseconds
//idleTimeoutMillis: Idle connection timeout in milliseconds. Ignored in mysql2 version > 2.0.0.
connectionLimit : process.env.MYSQL_POOL_LIMIT || 10,
host: process.env.MYSQL_HOST || 'localhost',
database: process.env.MYSQL_DATABASE || 'fido2_node_db',
user: process.env.MYSQL_USER || 'root',
password: process.env.MYSQL_PASSWD || '',
stringifyObjects: true,
});
var SqlString = require('sqlstring');
// Helper function to safely build parameterized IN clauses
function buildInClause(values) {
if (!Array.isArray(values) || values.length === 0) {
return { clause: '(NULL)', params: [] };
}
const placeholders = values.map(() => '?').join(',');
return {
clause: `(${placeholders})`,
params: Array.from(values)
};
}
// Helper function to check if origin is allowed
function isOriginAllowed(origin, registeredRps) {
if (!origin) return false;
try {
const originUrl = new URL(origin);
const hostname = originUrl.hostname;
// Check exact match
if (registeredRps.includes(hostname)) {
return true;
}
// Check wildcard domains (domains starting with .)
for (const rp of registeredRps) {
if (rp.startsWith('.') && hostname.endsWith(rp)) {
return true;
}
}
return false;
} catch (e) {
return false;
}
}
var server
if(process.env.SSLKEY && process.env.SSLCRT){
const options = {
key: fs.readFileSync(process.env.SSLKEY),
cert: fs.readFileSync(process.env.SSLCRT)
};
const https = require("https");
server = https.createServer(options)
}else{
const http = require("http");
server = http.createServer({})
}
const DEFAULT_FIDO_RPID = process.env.DEFAULT_FIDO_RPID
const FIDO_ORIGIN = process.env.FIDO_ORIGIN
const DOMAIN_JSON_FN = 'domain.json';
var domains_conf
var registeredRps
var enterpriseRps
var enterpriseAaguids
var deviceBindedKeys
var userSessionActiveTimeout
var userSessionHardTimeout
var processTimeout
var regSessionTimeout
var registerableDeviceLimit
let database = new Map();//use json as DB, all data will lost after restart program.
let user_sessions = new Map();
loadDomains();
let mapCredidUsername = {};//Link cred ids with usernames
let sessions = {};
const {mds3_client} = require("./mds3.js")
// Extension features toggle and handler bootstrap
const EXT_FEATURES_ENABLED = (process.env.EXT_FEATURES === '1' || (process.env.EXT_FEATURES && process.env.EXT_FEATURES.toLowerCase && process.env.EXT_FEATURES.toLowerCase() === 'true'));
let extensionHandler = null;
if (EXT_FEATURES_ENABLED) {
try {
let ex;
try {
ex = require('../fido2-node-ex');
} catch (e1) {
ex = require('fido2-node-ex');
}
extensionHandler = ex.createHandler({
loadJsonBody,
checkRpId,
checkUserSession,
delUserSession,
listUserDevices,
delUserDevices,
generateRegSession,
getRegSessionUsername,
logger,
// MCPlet: expose internals for /auth/verify-assertion (fido2-node-ex)
getSessions: () => sessions,
getAttestationData,
discoverUserName,
getUserData,
recordUserAction,
getFido2LibForRpId: (rpId, body) => getFido2Lib(rpId, body),
checkResultRequest,
});
logger.info('Extension features enabled.');
} catch (e) {
logger.warn('Failed to load extension features lib: ' + e.message);
}
}
server.on('request', AppController);
server.listen(port);
//console.log(`Started server: ${port}`);
logger.info(`Started server: ${port}`);
setInterval(function(){
clearTimeoutSessions();
},
60*1000);
function loadDomains(){
domains_conf = JSON.parse(fs.readFileSync(DOMAIN_JSON_FN, 'utf8'));
registeredRps = [];
enterpriseRps = [];
passkeySync = new Map();
enterpriseAaguids = new Map();
deviceBindedKeys = new Map();
userSessionActiveTimeout = new Map(); //Seconds
userSessionHardTimeout = new Map(); //Seconds
processTimeout = new Map(); //ms
regSessionTimeout = new Map(); //Seconds
userVerificationReg = new Map();
userVerificationAuth = new Map();
registerableDeviceLimit = new Map();
authenticatorAttachment = new Map(); // platform, cross-platform, or undefined
domains_conf.domains.forEach(element => {
registeredRps.push(element.domain)
if(element.passkey_sync){
passkeySync.set(element.domain, element.passkey_sync)
deviceBindedKeys.set(element.domain, false)
}else{
passkeySync.set(element.domain, false)
if(element.device_bind_key)deviceBindedKeys.set(element.domain, element.device_bind_key)
else deviceBindedKeys.set(element.domain, false)
if(element.enterprise){
enterpriseRps.push(element.domain)
if(element.enterprise_aaguids){
enterpriseAaguids.set(element.domain, element.enterprise_aaguids)
}
}
}
if(element.uv_reg)userVerificationReg.set(element.domain, element.uv_reg)
else userVerificationReg.set(element.domain, "preferred")
if(element.uv_auth)userVerificationAuth.set(element.domain, element.uv_auth)
else userVerificationAuth.set(element.domain, "preferred")
// Load authenticatorAttachment setting (platform/cross-platform/both)
if(element.authenticator_attachment){
authenticatorAttachment.set(element.domain, element.authenticator_attachment);
} else {
authenticatorAttachment.set(element.domain, undefined); // undefined = both allowed
}
if(element.device_limit && 0 < element.device_limit)registerableDeviceLimit.set(element.domain, element.device_limit)
if(element.user_session_active_timeout)userSessionActiveTimeout.set(element.domain, element.user_session_active_timeout)
else userSessionActiveTimeout.set(element.domain, 15*60) //Seconds
if(element.user_session_hard_timeout)userSessionHardTimeout.set(element.domain, element.user_session_hard_timeout)
else userSessionHardTimeout.set(element.domain, 24*60*60) //Seconds
if(element.process_timeout)processTimeout.set(element.domain, element.process_timeout*1000)
else processTimeout.set(element.domain, 10*60*1000) //ms
if(element.registration_session_timeout)regSessionTimeout.set(element.domain, element.registration_session_timeout)
else regSessionTimeout.set(element.domain, 15*60) //Seconds
});
if('mem' == process.env.STORAGE_TYPE){
registeredRps.forEach(element => {
if(!database.get(element)) database.set(element, new Map());
});
for (const key of database.keys()) {
if( 0 > registeredRps.indexOf(key) ){
database.delete(key)
}
}
}else if('mysql' == process.env.STORAGE_TYPE){
setRps(registeredRps);
}
}
function getDomainJSON(domain){
var rtn = null
domains_conf = JSON.parse(fs.readFileSync(DOMAIN_JSON_FN, 'utf8'));
for(let i = 0 ; i < domains_conf.domains.length ; i++){
if(domains_conf.domains[i].domain == domain){
rtn = domains_conf.domains[i]
break
}
}
return rtn
}
async function AppController(request, response) {
const url = new URL(request.url, `https://${request.headers.host}`)
if(request.method === 'GET') {
// ====== heartbeat method ======
if( url.pathname.startsWith('/isworking') ){
if(process.env.STORAGE_TYPE !== 'mysql'){
response.end("fido2-node is Working.");
return
}
var connection;
try {
connection = await new Promise((resolve, reject) => {
mysql_pool.getConnection((error, connection) => {
if (error) reject(error)
resolve(connection)
})
})
const results = await new Promise((resolve, reject) => {
connection.query('SELECT rp_id from registered_rps limit 1',
(error, results) => {
if (error) reject(error)
resolve(results)
})
})
response.end("fido2-node is Working.");
}catch (err) {
logger.error('DB err:'+err)
response.writeHead(404, {"Content-Type": "text/html"});
response.write("<html><body><h1>404 Not Found</h1></body></html>");
response.end();
} finally {
if (connection) connection.release()
}
}else{
let html=""
try{
/*let real_path;
if(url.pathname === '/')real_path='fido2.html'
else real_path = url.pathname
html = require('fs').readFileSync('views/'+real_path);*/
html = require('fs').readFileSync('views/'+url.pathname);
}catch(ex){
html=ex.message
}
response.writeHead(200, {'Content-Type': 'text/html'});
response.end(html);
}
} else if(request.method === 'OPTIONS') {
try{
const origin = request.headers['origin'] || request.headers['referer'];
if (origin && isOriginAllowed(origin, registeredRps)) {
response.setHeader("Access-Control-Allow-Origin", origin);
response.setHeader("Access-Control-Allow-Methods", "POST");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, access_token");
response.setHeader("Access-Control-Allow-Credentials", "true");
} else {
response.statusCode = 403;
response.end(JSON.stringify({ status: 'failed', errorMessage: 'Origin not allowed' }));
logger.warn("Origin not allowed(Strangers want to access): " + origin)
return;
}
response.end('OK');
return
}catch(ex){
logger.error("EX: " + ex.message + ";" + ex.stack)
let rtn={};
rtn.status ='failed',
rtn.errorMessage = 'SvrErr999:Exception:' + ex.message
response.end(JSON.stringify(rtn));
}
} else if(request.method === 'POST') {
try{
var req_origin = FIDO_ORIGIN, req_host
if(request.headers['referer']){
const remoteURL = new URL(request.headers['referer'])
req_host = remoteURL.hostname
req_origin = remoteURL.protocol + "//" + req_host
}
let real_path;
// Secure CORS - validate origin against registered domains
const origin = request.headers['origin'] || req_origin;
if (origin && isOriginAllowed(origin, registeredRps)) {
response.setHeader("Access-Control-Allow-Origin", origin);
} else {
response.setHeader("Access-Control-Allow-Origin", FIDO_ORIGIN);
}
response.setHeader("Access-Control-Allow-Methods", "POST");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, access_token");
response.setHeader("Access-Control-Allow-Credentials", "true");
// Extension Features APIs gate and delegation
if (url.pathname.startsWith('/usr/') || url.pathname === '/mng/user/regsession' || url.pathname.startsWith('/reg/username') || url.pathname.startsWith('/auth/')) {
if (!(EXT_FEATURES_ENABLED && extensionHandler)) {
response.end(JSON.stringify({ status: 'failed', errorMessage: 'SvrErr200: Extension features disabled' }));
return;
}
const handled = await extensionHandler(url, request, response, { req_host });
if (handled) return;
}
if(url.pathname == '/assertion/options'){
const body = await loadJsonBody(request)
logger.debug(body);
let username = body.username;
//Client-side discoverable Credential does not pass username
let rpId=checkRpId(body, req_host, response)
if(null==rpId)return
let user = await getUserData(rpId, username)
if(username && username.length > 0 && (!user || !user.registered)) {
response.end(JSON.stringify({
'status': 'failed',
'errorMessage': `SvrErr105:Username ${username} does not exist!`
}));
return
}
let fido2Lib = getFido2Lib(rpId, body)
let authnOptions = await fido2Lib.assertionOptions(body);
/* dqj: set by lib
if(!username){//Try discoverable
authnOptions["mediation"] = "conditional"
}*/
var userVerification = body.userVerification;
if(!userVerification && body.authenticatorSelection){
userVerification = body.authenticatorSelection.userVerification
}
const authenticatorSelection = setUserVerification(rpId, body.authenticatorSelection,
userVerificationAuth, userVerification);
authnOptions.userVerification = authenticatorSelection.userVerification;//assertion need set userVerification in root of authnOptions
/*var uv = 'preferred'
if (process.env.FIDO_CONFORMANCE_TEST && body.userVerification) {
uv = body.userVerification
} else {//Server can force userVerification in our system.
if (userVerificationAuth.get(rpId)) {
if (userVerificationAuth.get(rpId) != '_client') {
uv = userVerificationAuth.get(rpId)
} else if (body.userVerification) uv = body.userVerification
}
}
authnOptions.userVerification = uv;
*/
// Ensure UV flag is set when userVerification is required
/*if (authnOptions.authenticatorSelection.userVerification === "required") {
authnOptions.flags = authnOptions.flags || new Set();
authnOptions.flags.add("UV");
}*/
let challengeTxt = uuidv4()
let challengeBase64 = base64url.encode(challengeTxt) //To fit to the challenge of CollectedClientData
authnOptions.challenge = challengeBase64 //Array.from(new TextEncoder().encode(challengeTxt))
let allowCredentials = [];
if( username && username.length > 0 ){
let attestations = await getAttestationData(rpId, username)
for(let authr of attestations) {
let credential = {
type: 'public-key',
id: base64url.encode(authr.credId) //Array.from(new Uint8Array(authr.credId))
};
// Use saved transports if available, otherwise provide all options
if(authr.transports && authr.transports.length > 0) {
credential.transports = authr.transports;
} else {
credential.transports = ['internal', 'hybrid', 'usb', 'nfc', 'ble'];
}
logger.debug('Allow credential added: ' + JSON.stringify(credential));
allowCredentials.push(credential);
}
authnOptions.allowCredentials = allowCredentials;
if(passkeySync.get(rpId)){
authnOptions.extensions.passkeySync = true
authnOptions.extensions.deviceBinded = false
}else if(deviceBindedKeys.get(rpId)){
authnOptions.extensions.deviceBinded = true
}
//console.log(authnOptions);
logger.debug(authnOptions);
}
sessions[challengeBase64] = {
'challenge': authnOptions.challenge,
'username': username?username:"",
'fido2lib': fido2Lib,
};
authnOptions.status = 'ok';
authnOptions.errorMessage = '';
if(authnOptions.rpId && authnOptions.rpId.startsWith('.')){
logger.debug('Changed authnOptions.rpId from:'+authnOptions.rpId+' to:'+req_host);
authnOptions.rpId = req_host;
}
response.end(JSON.stringify(authnOptions));
}else if(url.pathname == '/assertion/result'){
const body = await loadJsonBody(request)
const clientData = JSON.parse(stringfy(body.response.clientDataJSON))
if(!body.response.authenticatorData){
let rtn = {
'status': 'failed',
'errorMessage': 'SvrErr115:authenticatorData is not found!'
}
response.end(JSON.stringify(rtn));
return
} else if(!utils.isBase64Url(body.response.authenticatorData)){
let rtn = {
'status': 'failed',
'errorMessage': 'SvrErr116:authenticatorData is not base64 url encoded!'
}
response.end(JSON.stringify(rtn));
return
}
if(!body.response.signature){
let rtn = {
'status': 'failed',
'errorMessage': 'SvrErr117:signature is not found!'
}
response.end(JSON.stringify(rtn));
return
} else if(!utils.isBase64Url(body.response.signature)){
let rtn = {
'status': 'failed',
'errorMessage': 'SvrErr118:signature is not base64 url encoded!'
}
response.end(JSON.stringify(rtn));
return
}
body.response.authenticatorData = new Uint8Array(base64url.toBuffer(body.response.authenticatorData)).buffer; //bufferKeepBase64(body.response.authenticatorData)
body.response.signature = new Uint8Array(base64url.toBuffer(body.response.signature)).buffer; //bufferKeepBase64((body.response.signature))
body.response.userHandle = base64url.toBuffer(body.response.userHandle); //new TextDecoder().decode(new Uint8Array(base64url.toBuffer(body.response.userHandle)).buffer)
body.response.userHandle = stringfy(body.response.userHandle)//new TextDecoder().decode(body.response.userHandle)
body.response.clientDataJSON = new Uint8Array(base64url.toBuffer(body.response.clientDataJSON)).buffer; //bufferKeepBase64(body.response.clientDataJSON)
let attestation = null;
let chkReq = checkResultRequest(body)
if(0 < Object.keys(chkReq).length){
response.end(JSON.stringify(chkReq));
return;
}
//let debugId=new Uint8Array(base64url.toBuffer(body.id)).buffer//for debug
var reqId
if( body.rawId ){
reqId = new Uint8Array(body.rawId);
}
if( !reqId || reqId.length == 0){
reqId = new Uint8Array(base64url.toBuffer(body.id))
}
body.rawId = reqId.buffer;
var challenge = stringfy(clientData.challenge)
if(!utils.isBase64(challenge))challenge = clientData.challenge //Client may encodebase64 the challenge
var realUsername;
var attestations;
if(sessions[challenge].username && sessions[challenge].username.length > 0){
realUsername = sessions[challenge].username
}else {
realUsername = await discoverUserName(reqId)//Client-side discoverable Credential process
}
if(null==sessions[challenge].fido2lib)return
if(realUsername){
attestations = await getAttestationData(sessions[challenge].fido2lib.config.rpId, realUsername)
for( let i = 0 ; attestations && i < attestations.length ; i++ ){
let dbId = attestations[i].credId
if (dbId.byteLength == reqId.byteLength && equlsArrayBuffer(reqId, dbId)) {
attestation = attestations[i];
break;
}
}
}
if( !attestation ){
let rtn = {
'status': 'failed',
'errorMessage': 'SvrErr104:key is not found!'
}
if(realUsername){
await recordUserAction(sessions[challenge].fido2lib.config.rpId, realUsername, 1, challenge, "SvrErr104")
}
response.end(JSON.stringify(rtn));
return
}
const cur_session = sessions[challenge]
delete sessions[challenge]
let user = await getUserData(cur_session.fido2lib.config.rpId, realUsername)
let assertionExpectations = {
challenge: cur_session.challenge,
origin: req_origin, //FIDO_ORIGIN,
rpId: cur_session.fido2lib.config.rpId,
config: cur_session.fido2lib.config,
factor: "either",
publicKey: attestation.publickey,
prevCounter: attestation.counter,
userHandle: user.id
};
if(assertionExpectations.rpId && assertionExpectations.rpId.startsWith('.')){
logger.debug('Changed assertionExpectations.rpId from:'+assertionExpectations.rpId+' to:'+req_host);
assertionExpectations.rpId = req_host;
}
body.userVerification = cur_session.fido2lib.config.authenticatorUserVerification
let authnResult = await cur_session.fido2lib.assertionResult(body, assertionExpectations);
//console.log(authnResult);
logger.debug(authnResult)
let rtn='';
if(authnResult.audit.complete) {
const unique_device_id =
authnResult.authnrData.get('extensions') ? (authnResult.authnrData.get('extensions').get('dfido2_device_unique_id') ? authnResult.authnrData.get('extensions').get('dfido2_device_unique_id') : null) : null;
if(deviceBindedKeys.get(cur_session.fido2lib.config.rpId) && null==unique_device_id ){
rtn = {
'status': 'failed',
'errorMessage': 'SvrErr106:Unique device id is null!'
}
await recordUserAction(cur_session.fido2lib.config.rpId, realUsername, 1, challenge, "SvrErr106")
} else {
if(deviceBindedKeys.get(cur_session.fido2lib.config.rpId) && null != unique_device_id &&
attestation.unique_device_id !== unique_device_id){
//!bindedDeviceKey(cur_session.fido2lib.config.rpId, cur_session.username, attestation.publickey, unique_device_id)){
rtn = {
'status': 'failed',
'errorMessage': 'SvrErr102:Cannot auth with a unique device bound key from a different device!'
}
await recordUserAction(cur_session.fido2lib.config.rpId, realUsername, 1, challenge, "SvrErr102")
}else{
const session_id = await generateUserSession(cur_session.fido2lib.config.rpId, realUsername)
attestation.counter = authnResult.authnrData.get('counter');
rtn = {
status: 'ok',
credId: body.id,
counter: attestation.counter,
username: realUsername,
session: session_id,
errorMessage: ''
}
}
}
} else {
rtn = {
'status': 'failed',
'errorMessage': 'SvrErr103:Can not authenticate signature!'
}
await recordUserAction(cur_session.fido2lib.config.rpId, realUsername, 1, challenge, "SvrErr103")
}
await recordUserAction(cur_session.fido2lib.config.rpId, realUsername, 1, challenge)
response.end(JSON.stringify(rtn));
}else if(url.pathname === '/attestation/options'){
const body = await loadJsonBody(request)
logger.debug("/attestation/options body:" + body)
let rpId=checkRpId(body, req_host, response)
if(null==rpId)return
let username = body.username;
let userid;
let user = await getUserData(rpId, username)
if(user) {
userid = user.id;
}else{
userid = uuidv4();
}
let fido2Lib = getFido2Lib(rpId, body)
let registrationOptions = await fido2Lib.attestationOptions();
let challengeTxt = uuidv4()
let challengeBase64 = base64url.encode(challengeTxt) //To fit to the challenge of CollectedClientData
registrationOptions.challenge = challengeBase64//Array.from(new TextEncoder().encode(challengeTxt)) //base64url.encode(uuidv4())//use challenge as session id
var userVerification = body.userVerification;
if(!userVerification && body.authenticatorSelection){
userVerification = body.authenticatorSelection.userVerification
}
registrationOptions.authenticatorSelection = setUserVerification(rpId, body.authenticatorSelection,
userVerificationReg, userVerification);
// Apply authenticatorAttachment setting if configured
const authAttachment = authenticatorAttachment.get(rpId);
if(authAttachment && authAttachment !== 'both') {
registrationOptions.authenticatorSelection.authenticatorAttachment = authAttachment;
}
//Prevent register same authenticator
if(user){
user.attestation = await getAttestationData(rpId, username)
const dvclmt = registerableDeviceLimit.get(rpId)
if(dvclmt && dvclmt <= user.attestation.length){
response.end(JSON.stringify({
'status': 'failed',
'errorMessage': `SvrErr120:User has reached the device limit!`
}));
return
}
let excludeCredentials = [];
for(let authr of user.attestation) {
let credential = {
type: 'public-key',
id: base64url.encode(authr.credId) //Array.from(new Uint8Array(authr.credId))
};
// Use saved transports if available, otherwise provide all options
if(authr.transports && authr.transports.length > 0) {
credential.transports = authr.transports;
} else {
credential.transports = ['internal', 'hybrid', 'usb', 'nfc', 'ble'];
}
excludeCredentials.push(credential);
}
if(excludeCredentials.length > 0)registrationOptions.excludeCredentials = excludeCredentials
//console.log("excludeCredentials:" + username + " size:" + excludeCredentials.length);
}
registrationOptions.user.id = base64url.encode(userid);
registrationOptions.user.name = username;
registrationOptions.user.displayName = body.displayName?decodeURIComponent(body.displayName):username;
if(body.attestation)registrationOptions.attestation = body.attestation
else if(fido2Lib.config.attestation){
registrationOptions.attestation = fido2Lib.config.attestation
}
if(passkeySync.get(rpId)){
registrationOptions.extensions.passkeySync = true
registrationOptions.extensions.deviceBinded = false
registrationOptions.pubKeyCredParams = [
{type: "public-key", alg: -7},
{type: "public-key", alg: -257}
];
}else if(deviceBindedKeys.get(rpId)){
registrationOptions.extensions.deviceBinded = true
}
//console.log(registrationOptions);
logger.debug(registrationOptions);
if(!user){
await putUserData(rpId, username, userid, registrationOptions.user.displayName, false);
}
sessions[challengeBase64] = {
'challenge': registrationOptions.challenge,
'username': username,
'fido2lib': fido2Lib
};
registrationOptions.status = 'ok';
registrationOptions.errorMessage = '';
if(registrationOptions.rp.id && registrationOptions.rp.id.startsWith('.')){
logger.debug('Changed registrationOptions.rp.id from:'+registrationOptions.rp.id+' to:'+req_host);
registrationOptions.rp.id = req_host;
}
response.end(JSON.stringify(registrationOptions));
}else if( url.pathname == '/attestation/result'){
const body = await loadJsonBody(request)
logger.debug("/attestation/result body:" + body)
let rtn={};
let chkReq = checkResultRequest(body)
if(0 < Object.keys(chkReq).length){
response.end(JSON.stringify(chkReq));
return;
}
const clientData = JSON.parse(stringfy(body.response.clientDataJSON))
//For debug
/*const tpAtt = typeof body.response.attestationObject
const attobj=new Buffer.from(body.response.attestationObject)
var ab = new ArrayBuffer(attobj.length);
var view = new Uint8Array(ab);
for (var i = 0; i < attobj.length; ++i) {
view[i] = attobj[i];
}*/
//End of debug
body.rawId = new Uint8Array(base64url.toBuffer(body.rawId)).buffer; //bufferKeepBase64(body.rawId);
body.response.attestationObject = new Uint8Array(base64url.toBuffer(body.response.attestationObject)).buffer//bufferKeepBase64(body.response.attestationObject)
body.response.clientDataJSON = new Uint8Array(base64url.toBuffer(body.response.clientDataJSON)).buffer; //bufferKeepBase64(body.response.clientDataJSON)
//const attestationObject = parser.parseAttestationObject(body.response.attestationObject) //JSON.parse(stringfy(body.response.attestationObject))
var challenge = stringfy(clientData.challenge)
if(!utils.isBase64(challenge))challenge = clientData.challenge //Client may encodebase64 the challenge
const cur_session = sessions[challenge]
delete sessions[challenge]
//console.log("/attestation/result:" + cur_session.username)
if(null==cur_session.fido2lib)return
let attestationExpectations = {
challenge: cur_session.challenge,
origin: req_origin, //FIDO_ORIGIN,
rpId: cur_session.fido2lib.config.rpId,
config: cur_session.fido2lib.config,
factor: "either"
};
if(attestationExpectations.rpId && attestationExpectations.rpId.startsWith('.')){
logger.debug('Changed attestationExpectations.rpId from:'+attestationExpectations.rpId+' to:'+req_host);
attestationExpectations.rpId = req_host;
}
var regResult
try{
regResult = await cur_session.fido2lib.attestationResult(body, attestationExpectations);
}catch(exp){
//console.log("/attestation/result exp:" + cur_session.username + " msg="+exp.message)
throw exp
}
logger.debug(regResult);
const credId = regResult.authnrData.get('credId')
const aaguidData = regResult.authnrData.get('aaguid')
const aaguid = buf2hex(aaguidData)
logger.debug('aaguid:'+aaguid);
//const aaguidtxt = buf2text(aaguidData) // Buffer.from(aaguid, 'hex').toString('utf-8'); //String.fromCharCode.apply("", new Uint8Array(aaguidData))
if(cur_session.fido2lib.config.attestation == "enterprise"){
const guids = enterpriseAaguids.get(cur_session.fido2lib.config.rpId)
if(!guids || !guids.includes(aaguid) ){
rtn.status ='failed',
rtn.errorMessage = 'SvrErr101:Unregistered enterprise authenticator aaguid!'
}
await recordUserAction(cur_session.fido2lib.config.rpId, cur_session.username, 0, challenge, "SvrErr101")
}
const unique_device_id =
regResult.authnrData.get('extensions') ? (regResult.authnrData.get('extensions').get('dfido2_device_unique_id') ? regResult.authnrData.get('extensions').get('dfido2_device_unique_id') : null) : null;
if(deviceBindedKeys.get(cur_session.fido2lib.config.rpId) && null==unique_device_id ){
rtn = {
'status': 'failed',
'errorMessage': 'SvrErr106:Unique device id is null!'
}
await recordUserAction(cur_session.fido2lib.config.rpId, cur_session.username, 0, challenge, "SvrErr106")
} else {
//console.log("before pushAttestation status:" + JSON.stringify(rtn))
if(0 == Object.keys(rtn).length){
//console.log("before pushAttestation call:" + cur_session.username)
const counter = regResult.authnrData.get('counter');
// Capture transports from client request
const transports = body.transports ? JSON.stringify(body.transports) : null;
await pushAttestation(cur_session.fido2lib.config.rpId, cur_session.username,
regResult.authnrData.get('credentialPublicKeyPem'), counter, regResult.authnrData.get('fmt'),
new Uint8Array(credId), aaguid, unique_device_id, request.headers['user-agent']?request.headers['user-agent']:"", transports);
mapCredidUsername[new Uint8Array(credId)]=cur_session.username;
if(regResult.audit.complete) {
await setRegistered(cur_session.fido2lib.config.rpId, cur_session.username, true)
const session_id = await generateUserSession(cur_session.fido2lib.config.rpId, cur_session.username)
rtn.status = 'ok',
rtn.counter = counter
rtn.credId = Array.from(new Uint8Array(regResult.authnrData.get('credId')))
rtn.errorMessage = '';
rtn.session = session_id;
} else {
rtn.status ='failed',
rtn.errorMessage = 'SvrErr103:Can not authenticate signature!'
await recordUserAction(cur_session.fido2lib.config.rpId, cur_session.username, 0, challenge, "SvrErr103")
}
}
}
//console.log("result end:" + cur_session.username + " rtn=" + JSON.stringify(rtn))
await recordUserAction(cur_session.fido2lib.config.rpId, cur_session.username, 0, challenge)
response.end(JSON.stringify(rtn));
}
// ====== User Management methods (moved to fido2-node-ex) ======
// ====== System Management methods ======
// There are json examples in examples folder
else if( url.pathname.startsWith('/mng/') ){
const body = await loadJsonBody(request)
if(body.MNG_TOKEN && body.MNG_TOKEN==process.env.MNG_TOKEN){
if( url.pathname == '/mng/domain/conf' ){
//backup json file
const backupFileName = DOMAIN_JSON_FN + Date.now();
fs.copyFileSync(DOMAIN_JSON_FN, backupFileName);
logger.info('Backuped ' + DOMAIN_JSON_FN + ' to ' + backupFileName);
domains_conf.backupfile = backupFileName;
if(body.del){//Del domains first
body.del.forEach(element => {
for (let i = 0; i < domains_conf.domains.length; ++i) {
if( element == domains_conf.domains[i].domain){
domains_conf.domains.splice(i, 1);
i--;
}
}
});
}
if(body.set){//Set domains
body.set.forEach(element => {
let i = 0
for (; i < domains_conf.domains.length; ++i) {
if( element.domain == domains_conf.domains[i].domain){
domains_conf.domains[i]=element;
break;
}
}
if(i==domains_conf.domains.length){
domains_conf.domains.push(element);
}
});
}
//Write new json
fs.unlinkSync(DOMAIN_JSON_FN);
fs.writeFileSync(DOMAIN_JSON_FN, JSON.stringify(domains_conf), 'utf8');
logger.info('Created new ' + DOMAIN_JSON_FN);
loadDomains();
const rtn = {status:'OK'}
response.end(JSON.stringify(rtn));
} else if( url.pathname == '/mng/domain/rollback' ){
var rtn
if(domains_conf.backupfile && fs.existsSync(domains_conf.backupfile)){
fs.unlinkSync(DOMAIN_JSON_FN);
fs.copyFileSync(domains_conf.backupfile, DOMAIN_JSON_FN);
fs.unlinkSync(domains_conf.backupfile);
loadDomains();
rtn = {status:'OK'}
}else{
rtn = {status:'fail'}
logger.warn('Backup file does not exist:' + (domains_conf.backupFileName?domains_conf.backupFileName:'null'));
}
response.end(JSON.stringify(rtn));
} else if( url.pathname == '/mng/domain/get' ){
var rtn = {status:'fail'}
if(body.domain){
let conf = getDomainJSON(body.domain)
if(conf){
rtn = conf
rtn.status='OK'
}
}
response.end(JSON.stringify(rtn));
} else if( url.pathname == '/mng/domain/data' ){
var rtn = {status:'fail'}
if(body.domains && null!=body.start && null!=body.end){
rtn = await getDomainData(body.domains, body.start, body.end)
rtn.status='OK'
}
response.end(JSON.stringify(rtn));
} else if( url.pathname == '/mng/action/data' ){
var rtn = {status:'fail'}
if(body.domains && null!=body.start && null!=body.end){
rtn = await getActionData(body.domains, body.start, body.end)
rtn.status='OK'
}
response.end(JSON.stringify(rtn));
} else if( url.pathname == '/mng/data/users' ){
var rtn = {status:'fail'}
if(body.domains){
rtn = await listUsers(body.domains, body.start?body.start:0, body.end?body.end:Number.MAX_SAFE_INTEGER,
body.search?decodeURIComponent(body.search):body.search, body.last_created, body.limit?body.limit:20);
rtn.status='OK'
}
response.end(JSON.stringify(rtn));
} else if( url.pathname == '/mng/data/actions' ){
var rtn = {status:'fail'}
if(body.domains){
rtn = await listActions(body.domains, body.start?body.start:0, body.end?body.end:Number.MAX_SAFE_INTEGER,
body.search?decodeURIComponent(body.search):body.search, body.last_created, body.fail_only, body.limit?body.limit:20);
rtn.status='OK'
}
response.end(JSON.stringify(rtn));
} else if( url.pathname == '/mng/user/delacc' ){
var rtn = {status:'fail'}
if(body.domains && body.user_id){
rtn = await delUser(body.domains, body.user_id);
rtn.status='OK'
}
response.end(JSON.stringify(rtn));
} else if( url.pathname == '/mng/user/deldvc' ){
var rtn = {status:'fail'}
if(body.domains && body.attest_id){
rtn = await delDevice(body.domains, body.attest_id);
}
rtn.status='OK'
response.end(JSON.stringify(rtn));
}
} else{
logger.warn('Somebody tried to access mng path:('+request.socket.remoteAddress+') with token='+
(body.MNG_TOKEN?body.MNG_TOKEN:'null'));
response.end("");
}
}
// ====== Registration method (moved to fido2-node-ex)======
}catch(ex){