-
Notifications
You must be signed in to change notification settings - Fork 6
/
fidotools.js
2669 lines (2358 loc) · 90.5 KB
/
fidotools.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
(function(global) {
var GLOBALPOLICY = {
/*
* Allowed attestation types
*/
allowedAttestationTypes: [ "Basic", "None", "AttCA", "Self" ],
/*
* Supported attestation formats
*/
supportedAttestationFormats: [ "fido-u2f", "packed", "none", "tpm", "android-safetynet", "android-key", "apple" ],
/*
* Supported packed attestation signature algorithms
*/
// -7 ECDSA256
// -8 ALG_SIGN_ED25519_EDDSA_SHA256_RAW
// -35 ALG_SIGN_SECP384R1_ECDSA_SHA384_RAW
// -36 ALG_SIGN_SECP521R1_ECDSA_SHA512_RAW
// -37 ALG_SIGN_RSASSA_PSS_SHA256_RAW
// -38 ALG_SIGN_RSASSA_PSS_SHA384_RAW
// -39 ALG_SIGN_RSASSA_PSS_SHA512_RAW
// -257 ALG_SIGN_RSASSA_PKCSV15_SHA256_RAW
// -258 ALG_SIGN_RSASSA_PKCSV15_SHA384_RAW
// -259 ALG_SIGN_RSASSA_PKCSV15_SHA512_RAW
// -65535 ALG_SIGN_RSASSA_PKCSV15_SHA1_RAW
supportedPackedAttestationAlgorithms: [ -7, -35, -37, -38, -39, -257, -258, -259, -65535 ],
// I tried to do -36 however it seems KJUR does not support P521 for the Signature class
// Same problem for -8
// see: https://kjur.github.io/jsrsasign/api/symbols/KJUR.crypto.Signature.html#constructor
/* Permitted age of android-safetynet attestations in milliseconds. Set to -1 to disable */
androidSafetyNetMaxAttestationAgeMS: 60000
}
/**
* debug loggining within these tools
*/
function debugLog(str) {
console.log(str);
}
/**
* Compares two byte arrays, return true if they contain the same bytes
*/
function baEqual(ba1, ba2) {
var result = false;
if (Array.isArray(ba1) && Array.isArray(ba2)) {
if (ba1.length == ba2.length) {
var result = true;
for (var i = 0; i < ba1.length && result; i++) {
result = (ba1[i] == ba2[i]);
}
}
}
return result;
}
/**
* Utility function to check if all bytes in an array are zero
*/
function bytesZero(ba) {
var result = false;
if (Array.isArray(ba)) {
result = true;
for (var i = 0; i < ba.length && result; i++) {
if (ba[i] != 0x00) {
result = false;
}
}
}
return result;
}
/**
* Extracts the bytes from an array beginning at index start, and continuing until
* index end-1 or the end of the array is reached. Pass -1 for end if you want to
* parse till the end of the array.
*/
function bytesFromArray(o, start, end) {
// o may be a normal array of bytes, or it could be a JSON encoded Uint8Array
var len = o.length;
if (len == null) {
len = Object.keys(o).length;
}
var result = [];
for (var i = start; (end == -1 || i < end) && (i < len); i++) {
result.push(o[i]);
}
return result;
}
/**
* Convert a 4-byte array to a uint assuming big-endian encoding
*
* @param buf
*/
function bytesToUInt32BE(buf) {
var result = 0;
if (buf != null && buf.length == 4) {
result = ((buf[0] & 0xFF) << 24) | ((buf[1] & 0xFF) << 16) | ((buf[2] & 0xFF) << 8) | (buf[3] & 0xFF);
return result;
}
return result;
}
/**
* Uses the ASN1 parser to look for a OID in a PEM x509 cert and return it's value as a hex string
*/
function findCertOIDValueHex(certPEM, oid) {
var result = null;
try {
var x509Cert = new X509();
x509Cert.readCertPEM(certPEM);
var oidInfo = x509Cert.getExtInfo(oid);
debugLog("The oidInfo is: " + JSON.stringify(oidInfo));
if (oidInfo != null) {
result = ASN1HEX.getV(pemtohex(certPEM), oidInfo.vidx);
} else {
debugLog("Did not find OID: " + oid + " in cert: " + certPEM);
}
} catch(e) {
result = null;
debugLog("Error parsing cert and looking for oid: " + oid);
debugLog(e);
}
return result;
}
/**
* Returns the bytes of a sha1 message digest of either a string or byte array
* This is used when building the signature base string to verify
* registration data.
*/
function sha1(data) {
var md = new KJUR.crypto.MessageDigest({
alg : "sha1",
prov : "cryptojs"
});
if (Array.isArray(data)) {
md.updateHex(BAtohex(data));
} else {
md.updateString(data);
}
return b64toBA(hex2b64(md.digest()));
}
/**
* Returns the bytes of a sha256 message digest of either a string or byte array
* This is used when building the signature base string to verify
* registration data.
*/
function sha256(data) {
var md = new KJUR.crypto.MessageDigest({
alg : "sha256",
prov : "cryptojs"
});
if (Array.isArray(data)) {
md.updateHex(BAtohex(data));
} else {
md.updateString(data);
}
return b64toBA(hex2b64(md.digest()));
}
/**
* Returns the bytes of a sha384 message digest of either a string or byte array
* This is used when building the signature base string to verify
* registration data.
*/
function sha384(data) {
var md = new KJUR.crypto.MessageDigest({
alg : "sha384",
prov : "cryptojs"
});
if (Array.isArray(data)) {
md.updateHex(BAtohex(data));
} else {
md.updateString(data);
}
return b64toBA(hex2b64(md.digest()));
}
/**
* Returns the bytes of a sha512 message digest of either a string or byte array
* This is used when building the signature base string to verify
* registration data.
*/
function sha512(data) {
var md = new KJUR.crypto.MessageDigest({
alg : "sha512",
prov : "cryptojs"
});
if (Array.isArray(data)) {
md.updateHex(BAtohex(data));
} else {
md.updateString(data);
}
return b64toBA(hex2b64(md.digest()));
}
/**
* Converts the bytes of an asn1-encoded X509 ceritificate or raw public key
* into a PEM-encoded cert string
*/
function certToPEM(cert) {
var keyType = "CERTIFICATE";
asn1key = cert;
if (cert != null && cert.length == 65 && cert[0] == 0x04) {
// this is a raw public key - prefix with ASN1 metadata
// SEQUENCE {
// SEQUENCE {
// OBJECTIDENTIFIER 1.2.840.10045.2.1 (ecPublicKey)
// OBJECTIDENTIFIER 1.2.840.10045.3.1.7 (P-256)
// }
// BITSTRING <raw public key>
// }
// We just need to prefix it with constant 26 bytes of metadata
asn1key = b64toBA(hextob64("3059301306072a8648ce3d020106082a8648ce3d030107034200"));
Array.prototype.push.apply(asn1key, cert);
keyType = "PUBLIC KEY";
}
var result = "-----BEGIN " + keyType + "-----\n";
var b64cert = hextob64(BAtohex(asn1key));
for (; b64cert.length > 64; b64cert = b64cert.slice(64)) {
result += b64cert.slice(0, 64) + "\n";
}
if (b64cert.length > 0) {
result += b64cert + "\n";
}
result += "-----END " + keyType + "-----\n";
return result;
}
/**
* Performs signature validation as needed for FIDO registration and authenticate transactions.
*
* @param sigBase -
* signature base string bytes composed from the registration
* response or sign response
* @param cert -
* either an array of bytes of either the x509 attestation certificate
* from the registration data or the public key (for verifying sign responses),
* OR the JSON object of the COSE encoded public key (used for FIDO2
* signature validation).
* @param sig -
* bytes of the signature from the registration data or sign response
* @param alg -
* The COSE algorithm identifier. Can be null in which case ECDSA will be assumed.
*
* @returns true if the signature verified, false otherwise
*/
function verifyFIDOSignature(sigBase, cert, sig, alg) {
var result = false;
// default to ECDSA
if (alg == null) {
alg = -7;
}
var algMap = {
"-7" : "SHA256withECDSA",
"-35" : "SHA384withECDSA",
"-36" : "SHA512withECDSA",
"-37" : "SHA256withRSAandMGF1",
"-38" : "SHA384withRSAandMGF1",
"-39" : "SHA512withRSAandMGF1",
"-257" : "SHA256withRSA",
"-258" : "SHA384withRSA",
"-259" : "SHA512withRSA",
"-65535" : "SHA1withRSA"
};
var algStr = algMap['' + alg];
if (algStr != null) {
var verifier = new KJUR.crypto.Signature({
"alg" : algStr
});
// find out what kind of public key validation material we have
if (Array.isArray(cert)) {
// x509 cert bytes, or EC public key bytes, as typically used by
// FIDO-U2F
verifier.init(certToPEM(cert));
} else {
// assume COSE key format
verifier.init(coseKeyToPublicKey(cert));
}
verifier.updateHex(BAtohex(sigBase));
// debugLog("BEFORE: " + result);
result = verifier.verify(BAtohex(sig));
// debugLog("AFTER: " + result);
} else {
debugLog("Unsupported algorithm in verifyFIDOSignature: " + alg);
}
if (!result) {
// some extra debugging to try figure this out later
debugLog("verifyFIDOSignature failed: var sigBase="
+ JSON.stringify(sigBase) + "; var cert="
+ JSON.stringify(cert) + "; var sig=" + JSON.stringify(sig)
+ "; var alg=" + alg + ";");
}
return result;
}
/**
* Build a human-readable string from the aaguid bytes
*/
function aaguidBytesToUUID(b) {
var result = null;
if (b != null && b.length == 16) {
var s = BAtohex(b).toUpperCase();
result = s.substring(0,8).concat("-",s.substring(8,12),"-",s.substring(12,16),"-",s.substring(16,20),"-",s.substring(20,s.length));
}
return result;
}
function coseKeyToECDSA256PublicKeyBytes(k) {
var result = { "error": "unknown error", "keyBytes": null };
if (k != null) {
// see https://tools.ietf.org/html/rfc8152 for all these magic numbers
var kty = k["1"];
var alg = k["3"];
var crv = k["-1"];
// validate the key type is EC2
if (kty == 2) {
// validate the alg is ECDSA256
if (alg == -7) {
// validate the curve is P256
if (crv == 1) {
// obtain x and y coordinates for EC - these should each be 32 bytes long
var xCoordinateBytes = bytesFromArray(k["-2"], 0, -1);
var yCoordinateBytes = bytesFromArray(k["-3"], 0, -1);
if (xCoordinateBytes.length == 32 && yCoordinateBytes.length == 32) {
// seems ok build publicKey
result["error"] = null;
result["keyBytes"] = [ 0x04 ].concat(xCoordinateBytes, yCoordinateBytes);
} else {
result["error"] = "The size of the x or y co-ordinates is wrong";
}
} else {
result["error"] = "The crv of the credential public key is invalid";
}
} else {
result["error"] = "The alg of the credential public key is invalid";
}
} else {
result["error"] = "The key type of the credential public key is invalid";
}
} else {
result["error"] = "Credential public key is null";
}
return result;
}
function ECDSA256PublicKeyBytesToCoseKey(b) {
var result = { "error": "unknown error", "coseKey": null };
if (b != null && b.length == 65) {
if (b[0] == 0x04) {
var xCoordinateBytes = bytesFromArray(b, 1, 33);
var yCoordinateBytes = bytesFromArray(b, 33, -1);
// see https://tools.ietf.org/html/rfc8152 for all these magic numbers
// set kty, alg and crv statically
result["coseKey"] = { "1": 2, "3": -7, "-1": 1 };
// now the bytes from the x and y co-ordinates
result["coseKey"]["-2"] = new Uint8Array(xCoordinateBytes);
result["coseKey"]["-3"] = new Uint8Array(yCoordinateBytes);
result["error"] = null;
} else {
result["error"] = "The provided elyptic curve public key bytes do not start with 0x04";
}
} else {
result["error"] = "The provided elyptic curve public key bytes are of invalid length";
}
return result;
}
// see table 6.4 of https://trustedcomputinggroup.org/wp-content/uploads/TCG_TPM2_r1p59_Part2_Structures_pub.pdf
function tpmECCCurvetoCoseCurve(tpmCurveID) {
// default is no match
var result = -1;
if (tpmCurveID == 3) {
result = 1;
} else if (tpmCurveID == 4) {
result = 2;
} else if (tpmCurveID == 5) {
result = 3;
} else {
// we don't support it
result = -1;
}
return result;
}
function coseKeyToPublicKey(k) {
var result = null;
if (k != null) {
// see https://tools.ietf.org/html/rfc8152
// and https://www.iana.org/assignments/cose/cose.xhtml
var kty = k["1"];
var alg = k["3"];
if (kty == 1) {
// EdDSA key type
validEDAlgs = [ -8 ];
if (validEDAlgs.indexOf(alg) >= 0) {
var crvMap = {
"6" : "Ed25519",
"7" : "Ed448"
};
var crv = crvMap['' + k["-1"]];
if (crv != null) {
debugLog("No support for EdDSA keys");
} else {
debugLog("Invalid crv: " + k["-1"] + " for ED key type");
}
} else {
debugLog("Invalid alg: " + alg + " for ED key type");
}
} else if (kty == 2) {
// EC key type
validECAlgs = [ -7, -35, -36 ];
if (validECAlgs.indexOf(alg) >= 0) {
var crvMap = {
"1" : "P-256",
"2" : "P-384",
"3" : "P-521" // this is not a typo. It is 521
};
var crv = crvMap['' + k["-1"]];
if (crv != null) {
// ECDSA
var xCoordinate = bytesFromArray(k["-2"], 0, -1);
var yCoordinate = bytesFromArray(k["-3"], 0, -1);
if (xCoordinate != null && xCoordinate.length > 0
&& yCoordinate != null && yCoordinate.length > 0) {
result = KEYUTIL.getKey({
"kty" : "EC",
"crv" : crv,
"x" : hextob64(BAtohex(xCoordinate)),
"y" : hextob64(BAtohex(yCoordinate))
});
} else {
debugLog("Invalid x or y co-ordinates for EC key type");
}
} else {
debugLog("Invalid crv: " + k["-1"] + " for EC key type");
}
} else {
debugLog("Invalid alg: " + alg + " for EC key type");
}
} else if (kty == 3) {
// RSA key type
validRSAAlgs = [ -37, -38, -39, -257, -258, -259, -65535 ];
if (validRSAAlgs.indexOf(alg) >= 0) {
var n = bytesFromArray(k["-1"], 0, -1);
var e = bytesFromArray(k["-2"], 0, -1);
if (n != null && n.length > 0 && e != null && e.length > 0) {
result = KEYUTIL.getKey({
"kty" : "RSA",
"n" : hextob64(BAtohex(n)),
"e" : hextob64(BAtohex(e))
});
} else {
debugLog("Invalid n or e values for RSA key type");
}
} else {
debugLog("Invalid alg: " + alg + " for RSA key type");
}
} else {
debugLog("Unsupported key type: " + kty);
}
}
return result;
}
function padToEvenNumberOfHexDigits(s) {
let result = s;
if (s.length%2 == 1) {
result = '0'+s;
}
return result;
}
function publicKeyToCOSEKey(pk) {
// should be one of RSAKey, KJUR.crypto.ECDSA as these are all we support
let result = null;
try {
if (pk instanceof RSAKey) {
result = {
"1": 3,
"3": -257,
"-1": b64toBA(hextob64(padToEvenNumberOfHexDigits(pk.n.toString(16)))),
"-2": b64toBA(hextob64(padToEvenNumberOfHexDigits(pk.e.toString(16))))
};
} else if (pk instanceof KJUR.crypto.ECDSA) {
// see table 5: https://datatracker.ietf.org/doc/html/rfc8152#section-8.1
const curveNameToAlgID = {
"secp256r1": -7,
"secp384r1": -35,
"secp521r1": -36
};
let alg = (pk.curveName == null ? null : curveNameToAlgID[pk.curveName]);
if (alg == null) {
throw "Unrecognized ECDSA curve: " + pk.curveName;
}
// see Table 22: https://datatracker.ietf.org/doc/html/rfc8152#section-13.1
const curveNameToCurveKey = {
"secp256r1": 1,
"secp384r1": 2,
"secp521r1": 3
};
let keyID = curveNameToCurveKey[pk.curveName];
if (keyID == null) {
throw "Unrecognized ECDSA curve: " + pk.curveName;
}
// these keys come from Table 19: https://datatracker.ietf.org/doc/html/rfc8152#section-12.4.1
result = {
"1": 2,
"3": alg,
"-1": keyID,
"-2": b64toBA(hextob64(pk.getPublicKeyXYHex().x)),
"-3": b64toBA(hextob64(pk.getPublicKeyXYHex().y))
};
} else {
throw "Unknown key type";
}
} catch(e) {
console.log("Unsupported public key object: " + pk + " error: " + e);
}
return result;
}
function unpackAuthData(authDataBytes) {
debugLog("unpackAuthData enter");
var result = {
"status": false,
"rawBytes": null,
"rpIdHashBytes": null,
"flags": 0,
"counter": 0,
"attestedCredData": null,
"extensions": null
};
result["rawBytes"] = authDataBytes;
if (authDataBytes != null && authDataBytes.length >= 37) {
result["rpIdHashBytes"] = bytesFromArray(authDataBytes, 0, 32);
result["flags"] = authDataBytes[32];
result["counter"] = bytesToUInt32BE(bytesFromArray(authDataBytes, 33, 37));
var nextByteIndex = 37;
// check flags to see if there is attested cred data and/or extensions
// bit 6 of flags - Indicates whether the authenticator added attested credential data.
if (result["flags"] & 0x40) {
result["attestedCredData"] = {};
// are there enough bytes to read aaguid?
if (authDataBytes.length >= (nextByteIndex + 16)) {
result["attestedCredData"]["aaguid"] = bytesFromArray(authDataBytes, nextByteIndex, (nextByteIndex+16));
nextByteIndex += 16;
// are there enough bytes for credentialIdLength?
if (authDataBytes.length >= (nextByteIndex + 2)) {
var credentialIdLengthBytes = bytesFromArray(authDataBytes, nextByteIndex, (nextByteIndex+2));
nextByteIndex += 2;
var credentialIdLength = credentialIdLengthBytes[0] * 256 + credentialIdLengthBytes[1]
result["attestedCredData"]["credentialIdLength"] = credentialIdLength;
// are there enough bytes for the credentialId?
if (authDataBytes.length >= (nextByteIndex + credentialIdLength)) {
result["attestedCredData"]["credentialId"] = bytesFromArray(authDataBytes, nextByteIndex, (nextByteIndex+credentialIdLength));
nextByteIndex += credentialIdLength;
var remainingBytes = bytesFromArray(authDataBytes, nextByteIndex, -1);
//debugLog("remainingBytes: " + JSON.stringify(remainingBytes));
//
// try CBOR decoding the remaining bytes.
// NOTE: There could be both credentialPublicKey and extensions objects
// so we use this special decodeVariable that Shane wrote to deal with
// remaining bytes.
//
try {
var decodeResult = CBOR.decodeVariable((new Uint8Array(remainingBytes)).buffer);
result["attestedCredData"]["credentialPublicKey"] = decodeResult["decodedObj"];
nextByteIndex += (decodeResult["offset"] == -1 ? remainingBytes.length : decodeResult["offset"]);
} catch (e) {
debugLog("Error CBOR decoding credentialPublicKey: " + e);
nextByteIndex = -1; // to force error checking
}
} else {
debugLog("unPackAuthData encountered authDataBytes not containing enough bytes for credentialId in attested credential data");
}
} else {
debugLog("unPackAuthData encountered authDataBytes not containing enough bytes for credentialIdLength in attested credential data");
}
} else {
debugLog("unPackAuthData encountered authDataBytes not containing enough bytes for aaguid in attested credential data");
}
}
// bit 7 of flags - Indicates whether the authenticator has extensions.
if (nextByteIndex > 0 && result["flags"] & 0x80) {
try {
result["extensions"] = CBOR.decode((new Uint8Array(bytesFromArray(authDataBytes, nextByteIndex, -1))).buffer);
// must have worked
nextByteIndex = authDataBytes.length;
} catch (e) {
debugLog("Error CBOR decoding extensions");
}
}
// we should be done - make sure we processed all the bytes
if (nextByteIndex == authDataBytes.length) {
result["status"] = true;
} else {
debugLog("Remaining bytes in unPackAuthData. nextByteIndex: " + nextByteIndex + " authDataBytes.length: " + authDataBytes.length);
}
} else {
debugLog("unPackAuthData encountered authDataBytes not at least 37 bytes long. Actual length: " + authDataBytes.length);
}
debugLog("unpackAuthData returning: " + JSON.stringify(result));
return result;
}
/**
* Check that the fmt is one registered by IANA registry of WebAuthn-Registries
*
* @param fmt
*/
function validateAttestationStatementFormat(fmt) {
// based on policy (and capabilities)
return (fmt != null && GLOBALPOLICY["supportedAttestationFormats"]
.indexOf(fmt) >= 0);
}
function validateAttestationStatementNone(attestationObject, unpackedAuthData,
clientDataHashBytes) {
debugLog("validateAttestationStatementNone enter");
var result = {
"success" : false,
"attestationType" : null,
"attestationTrustPath" : null,
"aaguid" : null,
"error" : "Unknown Error validating Attestation Statement"
};
if (unpackedAuthData["attestedCredData"] != null) {
var attestedCredData = unpackedAuthData["attestedCredData"];
var aaguid = attestedCredData["aaguid"];
if (aaguid != null) {
var credentialId = attestedCredData["credentialId"];
if (credentialId != null) {
var credentialPublicKey = attestedCredData["credentialPublicKey"];
if (credentialPublicKey != null) {
// if all checks ok, fill in result
result["success"] = true;
result["attestationType"] = "None";
result["attestationTrustPath"] = [];
result["aaguid"] = aaguid;
result["credentialId"] = credentialId;
result["credentialPublicKey"] = credentialPublicKey;
result["format"] = attestationObject["fmt"];
result["error"] = null;
} else {
result["error"] = "attested credential data does not contain credentialPublicKey";
}
} else {
result["error"] = "attested credential data does not contain credentialId";
}
} else {
result["error"] = "attested credential data does not contain aaguid";
}
} else {
result["error"] = "authData does not contain attested credential data";
}
return result;
}
// s is a string similar to one of these:
// "/C=SE/O=Yubico AB/OU=Authenticator Attestation/CN=Yubico U2F EE Serial 1955003842"
// "/C=KR/ST=Seoul-Si/L=Gangnam-Gu/O=eWBM Co., Ltd./OU=Authenticator Attestation/CN=eWBM FIDO2 Certificate/E=info@e-wbm.com"
function unpackSubjectDN(s) {
var result = {};
if (s != null) {
var pieces = s.split('/');
for (var i = 0; i < pieces.length; i++) {
var nev = pieces[i].split(/=(.*)/);
if (nev != null && nev.length == 3) {
// ignore empty string at end of array
// make sure we have consistent (upper case) keys
result[nev[0].toUpperCase()] = nev[1];
}
}
}
return result;
}
function verifyPackedAttestationCertificateRequirements(certBytes) {
var result = true;
debugLog("verifyPackedAttestationCertificateRequirements enter");
// https://www.w3.org/TR/webauthn/#packed-attestation-cert-requirements
try {
var x509Cert = new X509();
x509Cert.readCertHex(BAtohex(certBytes));
// SHANE
debugLog("The attestation certificate is:");
debugLog(certToPEM(certBytes));
// check cert version
result = (x509Cert.getVersion() == 3);
if (!result) {
debugLog("cert version was not 3: " + x509Cert.getVersion());
}
// check subject DN
if (result) {
var subjectString = x509Cert.getSubjectString();
var subjectPieces = unpackSubjectDN(subjectString);
if ("C" in subjectPieces && "O" in subjectPieces && "OU" in subjectPieces && "CN" in subjectPieces) {
debugLog("Subject DN fields found. Country: " + subjectPieces["C"] + " Vendor: "
+ subjectPieces["O"] + " OU: " + subjectPieces["OU"]
+ " CN: " + subjectPieces["CN"]);
// really should do further validation of "C" in particular
// validate OU
if (result) {
if (subjectPieces["OU"] != "Authenticator Attestation") {
debugLog("Attestation certificate subject DN is not the literal string: 'Authenticator Attestation'");
result = false;
}
}
} else {
result = false;
}
if (!result) {
debugLog("subject DN does not contain required fields: "
+ subjectString);
}
}
// check for aaguid in attestation cert
if (result) {
// how should I know this - let's just say "false" until told
// otherwise. The eWMB attestation cert is such an example.
var isAttestationRootCertUsedForMultipleModels = false;
var oidInfo = x509Cert.getExtInfo("1.3.6.1.4.1.45724.1.1.4");
if (oidInfo != null) {
var aaguid = ASN1HEX.getV(BAtohex(certBytes), oidInfo.vidx);
// 16 bytes is 32 hex chars
if (aaguid != null && aaguid.length == 32) {
if (!oidInfo.critical) {
// ok so far
result = true;
} else {
debugLog("oid marked critical");
result = false;
}
} else {
debugLog("aaguid invalid: " + aaguid);
result = false;
}
} else {
debugLog("oid extension not found - we won't mark this as fatal unless it's required");
if (isAttestationRootCertUsedForMultipleModels) {
debugLog("oid extension not found and apparently it was required");
result = false;
}
}
if (!result) {
debugLog("certificate did not contain valid aaguid OID extenstion");
}
}
// check basic constraints
if (result) {
var basicConstraints = x509Cert.getExtBasicConstraints();
debugLog("************* basicConstraints: " + basicConstraints);
result = (basicConstraints == null || !(basicConstraints["cA"] == true));
if (!result) {
debugLog("CA flagged as true in BasicConstraints");
}
}
// no further checks since AIA and CRL distribution point are optional
} catch (e) {
debugLog("verifyPackedAttestationCertificateRequirements error parsing x509 certificate: "
+ e);
result = false;
}
debugLog("verifyPackedAttestationCertificateRequirements returning: "
+ result);
return result;
}
function verifyTPMAttestationCertificateRequirements(certBytes) {
var result = true;
debugLog("verifyTPMAttestationCertificateRequirements enter");
// https://www.w3.org/TR/webauthn/#tpm-cert-requirements
try {
var x509Cert = new X509();
x509Cert.readCertHex(BAtohex(certBytes));
// check cert version
result = (x509Cert.getVersion() == 3);
if (!result) {
debugLog("cert version was not 3: " + x509Cert.getVersion());
}
// check subject is empty
if (result) {
debugLog("about to call getSubjectHex");
var subjectHex = x509Cert.getSubjectHex();
if (subjectHex == null || subjectHex != "3000") {
result = false;
debugLog("subject DN is not empty: " + subjectString);
}
}
// The Subject Alternative Name extension MUST be set as defined in [TPMv2-EK-Profile] section 3.2.9.
// TODO - finish this
} catch (e) {
debugLog("verifyTPMAttestationCertificateRequirements error parsing x509 certificate: "
+ e);
result = false;
}
debugLog("verifyTPMAttestationCertificateRequirements returning: "
+ result);
return result;
}
/*
* Given the bytes of an x509 attestation certificate, per step 2, sub-bullet 3
* of https://www.w3.org/TR/webauthn/#packed-attestation check if it contains an
* OID "1.3.6.1.4.1.45724.1.1.4" and if it does, that it matches the aaguid from
* the authentication data
*/
function packedAttestationOIDCheck(x5cBytes, unpackedAuthData) {
var result = false;
var oidValueHex = findCertOIDValueHex(certToPEM(x5cBytes),
"1.3.6.1.4.1.45724.1.1.4");
if (oidValueHex != null) {
var aaguidHex = null;
if (unpackedAuthData["attestedCredData"]["aaguid"] != null) {
aaguidHex = BAtohex(unpackedAuthData["attestedCredData"]["aaguid"]);
}
debugLog("oidValueHex: " + oidValueHex + " aaguidHex: " + aaguidHex);
result = (aaguidHex != null && aaguidHex == oidValueHex);
} else {
debugLog("Warning: Did not find OID 1.3.6.1.4.1.45724.1.1.4 in x5cBytes");
// this is apparently ok since it only says to check against aaguid if
// the oid exists
result = true;
}
return result;
}
function tpmAttestationOIDCheck(x5cBytes, unpackedAuthData) {
// this is actually the same as the packed attestation oid check
return packedAttestationOIDCheck(x5cBytes, unpackedAuthData);
}
function validateAttestationStatementFIDOU2F(attestationObject,
unpackedAuthData, clientDataHashBytes) {
debugLog("validateAttestationStatementFIDOU2F enter");
var result = {
"success" : false,
"attestationType" : null,
"attestationTrustPath" : null,
"aaguid" : null,
"error" : "Unknown Error validating Attestation Statement"
};
// see https://www.w3.org/TR/webauthn/#fido-u2f-attestation
var attStmt = attestationObject["attStmt"];
if (attStmt != null) {
// let's validate the attested credential data
if (unpackedAuthData["attestedCredData"] != null) {
var attestedCredData = unpackedAuthData["attestedCredData"];
var aaguid = attestedCredData["aaguid"];
if (aaguid != null) {
if (bytesZero(aaguid)) {
var credentialId = attestedCredData["credentialId"];
if (credentialId != null) {
var credentialPublicKey = attestedCredData["credentialPublicKey"];
if (credentialPublicKey != null) {
// unpack and validate the cose key
// (https://tools.ietf.org/html/rfc8152)
var coseKeyValidationResult = coseKeyToECDSA256PublicKeyBytes(credentialPublicKey);
if (coseKeyValidationResult["keyBytes"] != null) {
/*
* obtain the signature bytes and x509 cert array from the attStmt
*/
var sig = attestationObject["attStmt"]["sig"];
if (sig != null) {
var attStmtSigBytes = bytesFromArray(sig, 0, -1);
var x5c = attestationObject["attStmt"]["x5c"];
if (x5c != null && x5c.length > 0) {
var attStmtx5c = [];
for (var i = 0; i < x5c.length; i++) {
attStmtx5c.push(bytesFromArray(x5c[i], 0, -1));
}
// verification procedure
/*
* part 1 of verification procedure: is to extract
* attStmt CBOR data - that was done before calling
* this method
*/
/*
* part 2 of verification procedure: verify that
* attCert public key is EC with P-256 curve
*/
var attCert = attStmtx5c[0];
var pemAttCert = certToPEM(attCert);
var x509AttCert = new X509();
x509AttCert.readCertPEM(pemAttCert);
var attCertPublicKey = x509AttCert
.getPublicKey();
if (attCertPublicKey.type == "EC"
&& attCertPublicKey
.getShortNISTPCurveName() == "P-256") {
/*
* part 3 of verification procedure: extract
* rpIdHash, credentialId and credential
* public key
*/
var rpidhashBytes = bytesFromArray(
attestationObject["authData"], 0,
32);
/*
* credentialId and credential public key
* have already been parsed above
*/
/*
* part 4 of verification procedure: build publicKeyU2F
*/
publicKeyU2F = coseKeyValidationResult["keyBytes"];
/*
* part 5 of verification procedure: build verificationData
*/
if (clientDataHashBytes != null && clientDataHashBytes.length > 0) {
var verificationData = [ 0x00 ].concat(
rpidhashBytes, clientDataHashBytes,
credentialId, publicKeyU2F);
// finally, let's verify the signature
result.success = verifyFIDOSignature(
verificationData, attCert,
attStmtSigBytes, null);
if (result.success) {