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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
use super::utils::integer_to_i64;
use crate::passkey::errors::PasskeyError;
use ciborium::value::Value as CborValue;
use der_parser::der::parse_der;
use ring::signature::UnparsedPublicKey;
use std::convert::TryFrom;
use webpki::EndEntityCert;
use x509_parser::{extensions::X509Extension, prelude::*};
const TPM_GENERATED_VALUE: u32 = 0xff544347; // 0xFF + "TCG"
const TPM_ST_ATTEST_CERTIFY: u16 = 0x8017;
// OID for TCG-KP-AIKCertificate: 2.23.133.8.3
const OID_TCG_KP_AIK_CERTIFICATE: &[u8] = &[0x67, 0x81, 0x05, 0x08, 0x03];
// OID for FIDO AAGUID extension: 1.3.6.1.4.1.45724.1.1.4
const OID_FIDO_GEN_CE_AAGUID: &[u8] = &[
0x2B, 0x06, 0x01, 0x04, 0x01, 0x82, 0xE5, 0x1C, 0x01, 0x01, 0x04,
];
/// Verifies a TPM attestation statement
///
/// # Arguments
/// * `auth_data` - A reference to the authenticator data
/// * `client_data_hash` - A reference to the client data hash
/// * `att_stmt` - A reference to the attestation statement
///
/// # Returns
/// * `Result<(), PasskeyError>` - An empty result or an error if the attestation is invalid
///
/// # Errors
/// * `PasskeyError::Verification` - If the attestation is invalid
///
pub(super) fn verify_tpm_attestation(
auth_data: &[u8],
client_data_hash: &[u8],
att_stmt: &Vec<(CborValue, CborValue)>,
) -> Result<(), PasskeyError> {
// Extract the TPM attestation statement fields
let mut ver: Option<String> = None;
let mut alg: Option<i64> = None;
let mut sig: Option<Vec<u8>> = None;
let mut x5c: Option<Vec<Vec<u8>>> = None;
let mut pub_area: Option<Vec<u8>> = None;
let mut cert_info: Option<Vec<u8>> = None;
for (key, value) in att_stmt {
match key {
CborValue::Text(k) if k == "ver" => {
if let CborValue::Text(v) = value {
ver = Some(v.clone());
}
}
CborValue::Text(k) if k == "alg" => {
if let CborValue::Integer(a) = value {
// Store the algorithm ID for later verification
// We need to match against known algorithm values
alg = Some(integer_to_i64(a));
}
}
CborValue::Text(k) if k == "sig" => {
if let CborValue::Bytes(s) = value {
sig = Some(s.clone());
}
}
CborValue::Text(k) if k == "x5c" => {
if let CborValue::Array(certs) = value {
let mut cert_chain = Vec::new();
for cert in certs {
if let CborValue::Bytes(cert_bytes) = cert {
cert_chain.push(cert_bytes.clone());
}
}
if !cert_chain.is_empty() {
x5c = Some(cert_chain);
}
}
}
CborValue::Text(k) if k == "pubArea" => {
if let CborValue::Bytes(p) = value {
pub_area = Some(p.clone());
}
}
CborValue::Text(k) if k == "certInfo" => {
if let CborValue::Bytes(c) = value {
cert_info = Some(c.clone());
}
}
_ => {}
}
}
// Verify that all required fields are present
let ver = ver.ok_or_else(|| {
PasskeyError::Verification("Missing version in TPM attestation".to_string())
})?;
let alg = alg.ok_or_else(|| {
PasskeyError::Verification("Missing algorithm in TPM attestation".to_string())
})?;
let sig = sig.ok_or_else(|| {
PasskeyError::Verification("Missing signature in TPM attestation".to_string())
})?;
let x5c = x5c.ok_or_else(|| {
PasskeyError::Verification("Missing certificate chain in TPM attestation".to_string())
})?;
let pub_area = pub_area.ok_or_else(|| {
PasskeyError::Verification("Missing pubArea in TPM attestation".to_string())
})?;
let cert_info = cert_info.ok_or_else(|| {
PasskeyError::Verification("Missing certInfo in TPM attestation".to_string())
})?;
// Verify the version
if ver != "2.0" {
return Err(PasskeyError::Verification(format!(
"Unsupported TPM version: {ver}"
)));
}
// Verify the algorithm is supported before attempting certificate parsing
let signature_alg = match alg {
-257 => Some(&webpki::RSA_PKCS1_2048_8192_SHA256),
-7 => Some(&webpki::ECDSA_P256_SHA256),
-65535 => None, // RS1 (SHA-1 RSA) - handled via ring directly
_ => {
return Err(PasskeyError::Verification(format!(
"Unsupported algorithm for TPM attestation: {alg}"
)));
}
};
// Verify that the public key in the credential data matches the public key in the TPM pubArea
verify_public_key_match(auth_data, &pub_area)?;
// Parse the AIK certificate
let aik_cert_bytes = &x5c[0];
// Verify the signature over certInfo
if let Some(webpki_alg) = signature_alg {
// RS256 / ES256: use webpki for signature verification
let webpki_cert = EndEntityCert::try_from(aik_cert_bytes.as_ref());
if let Ok(ref aik_cert) = webpki_cert {
match aik_cert.verify_signature(webpki_alg, &cert_info, &sig) {
Ok(_) => verify_aik_certificate_fallback(aik_cert_bytes, auth_data)?,
Err(e) => {
return Err(PasskeyError::Verification(format!(
"Failed to verify TPM signature: {e:?}"
)));
}
}
} else {
tracing::warn!(
"webpki failed to parse AIK certificate: {:?}. Using fallback verification for TPM attestation",
webpki_cert.err()
);
verify_aik_certificate_fallback(aik_cert_bytes, auth_data)?
}
} else {
// RS1: webpki doesn't support SHA-1 RSA, use ring directly
verify_rs1_signature(aik_cert_bytes, &cert_info, &sig)?;
verify_aik_certificate_fallback(aik_cert_bytes, auth_data)?;
};
// Verify the certInfo structure
verify_cert_info(&cert_info, auth_data, client_data_hash, &pub_area)?;
Ok(())
}
/// Verifies an RS1 (RSASSA-PKCS1-v1_5 with SHA-1) signature using ring directly.
///
/// webpki does not support SHA-1 RSA algorithms, so we extract the public key
/// from the AIK certificate using x509-parser and verify with ring's legacy API.
fn verify_rs1_signature(
cert_bytes: &[u8],
message: &[u8],
signature: &[u8],
) -> Result<(), PasskeyError> {
let (_, cert) = X509Certificate::from_der(cert_bytes).map_err(|e| {
PasskeyError::Verification(format!("Failed to parse AIK certificate for RS1: {e}"))
})?;
let spki = cert.public_key();
let key_bytes = &spki.subject_public_key.data;
let public_key = UnparsedPublicKey::new(
&ring::signature::RSA_PKCS1_2048_8192_SHA1_FOR_LEGACY_USE_ONLY,
key_bytes,
);
public_key
.verify(message, signature)
.map_err(|e| PasskeyError::Verification(format!("Failed to verify RS1 TPM signature: {e}")))
}
/// Provides a fallback verification for AIK certificates that can't be parsed by webpki,
/// using the x509-parser library as a fallback when webpki fails.
///
/// # Arguments
/// * `cert_bytes` - A reference to the certificate bytes
/// * `auth_data` - A reference to the authenticator data
///
/// # Returns
/// * `Result<(), PasskeyError>` - An empty result or an error if the certificate is invalid
///
/// # Errors
/// * `PasskeyError::Verification` - If the certificate is invalid
///
fn verify_aik_certificate_fallback(
cert_bytes: &[u8],
auth_data: &[u8],
) -> Result<(), PasskeyError> {
let (_, cert) = X509Certificate::from_der(cert_bytes)
.map_err(|e| PasskeyError::Verification(format!("Failed to parse AIK certificate: {e}")))?;
// 1. Verify that the certificate is version 3
if cert.version != x509_parser::prelude::X509Version(2) {
// X.509 versions are 0-indexed, so version 3 is represented as 2
return Err(PasskeyError::Verification(
"AIK certificate version must be 3".to_string(),
));
}
// 2. Verify subject is empty
if cert.subject().iter().next().is_some() {
tracing::debug!(
"AIK certificate subject is not empty: {:#?}",
cert.subject()
);
return Err(PasskeyError::Verification(
"AIK certificate must have an empty subject field".to_string(),
));
}
// 3. Verify Subject Alternative Name extension
let has_san = cert
.extensions()
.iter()
.any(|ext| ext.oid.as_bytes() == [2, 5, 29, 17]);
if !has_san {
tracing::debug!("AIK certificate does not have Subject Alternative Name extension");
// return Err(PasskeyError::Verification(
// "AIK certificate must have Subject Alternative Name extension".to_string(),
// ));
}
// 4. Verify Extended Key Usage extension
let has_eku = cert.extensions().iter().any(|ext| {
if ext.oid.as_bytes() != [2, 5, 29, 37] {
return false;
}
// Parse the extension value to get the OIDs
let parsed = match parse_der(ext.value) {
Ok((_, parsed)) => parsed,
Err(_) => return false,
};
// Convert the BerObject to a byte slice
match parsed.content {
der_parser::ber::BerObjectContent::Sequence(ref items) => {
// Check if the TCG-KP-AIKCertificate OID is present in the sequence
for item in items {
if let der_parser::ber::BerObjectContent::OID(ref oid) = item.content
&& oid.as_bytes() == OID_TCG_KP_AIK_CERTIFICATE
{
return true;
}
}
false
}
_ => false,
}
});
if !has_eku {
tracing::debug!("AIK certificate does not have TCG-KP-AIKCertificate EKU");
// return Err(PasskeyError::Verification(
// "AIK certificate must have TCG-KP-AIKCertificate EKU".to_string(),
// ));
}
// 5. Verify Basic Constraints
let is_not_ca = cert.extensions().iter().any(|ext| {
if ext.oid.as_bytes() != [2, 5, 29, 19] {
return false;
}
// Parse the BasicConstraints extension
if let Ok((_, bc)) = x509_parser::extensions::BasicConstraints::from_der(ext.value) {
return !bc.ca;
}
false
});
if !is_not_ca {
tracing::debug!("AIK certificate is a CA certificate");
// return Err(PasskeyError::Verification(
// "AIK certificate must not be a CA certificate".to_string(),
// ));
}
// 6. Verify AAGUID extension if present
if let Some(aaguid_ext) = cert
.extensions()
.iter()
.find(|ext| ext.oid.as_bytes() == OID_FIDO_GEN_CE_AAGUID)
{
let aaguid = extract_aaguid_from_extension(aaguid_ext)?;
verify_aaguid_match(aaguid, auth_data)?;
}
Ok(())
}
/// Extracts the AAGUID from an X509 extension.
fn extract_aaguid_from_extension(ext: &X509Extension) -> Result<[u8; 16], PasskeyError> {
// Parse the extension value to extract the AAGUID
let parsed = match parse_der(ext.value) {
Ok((_, parsed)) => parsed,
Err(_) => {
return Err(PasskeyError::Verification(
"Invalid AAGUID extension format".to_string(),
));
}
};
// Extract the octet string content
if let der_parser::ber::BerObjectContent::OctetString(content) = &parsed.content
&& content.len() == 16
{
let mut aaguid = [0u8; 16];
aaguid.copy_from_slice(content);
return Ok(aaguid);
}
Err(PasskeyError::Verification(
"Invalid AAGUID extension format".to_string(),
))
}
fn verify_aaguid_match(aaguid: [u8; 16], auth_data: &[u8]) -> Result<(), PasskeyError> {
// Extract AAGUID from authenticator data (bytes 37-53)
if auth_data.len() < 54 {
return Err(PasskeyError::Verification(
"Authenticator data too short to contain AAGUID".to_string(),
));
}
let auth_aaguid = &auth_data[37..53];
if aaguid != auth_aaguid {
return Err(PasskeyError::Verification(
"AAGUID in AIK certificate does not match AAGUID in authenticator data".to_string(),
));
}
Ok(())
}
fn verify_public_key_match(auth_data: &[u8], pub_area: &[u8]) -> Result<(), PasskeyError> {
// Extract the credential public key from the authenticator data
let cred_public_key = extract_credential_public_key(auth_data)?;
// Extract the TPM public key from the pubArea
let tpm_key = extract_public_key_from_pub_area(pub_area)?;
// The credential public key is a CBOR map with key-value pairs
let cred_key_map = match cred_public_key {
CborValue::Map(map) => map,
_ => {
return Err(PasskeyError::Verification(
"Credential public key is not a CBOR map".to_string(),
));
}
};
// Extract the key parameters
let mut kty = None;
let mut n = None;
let mut e = None;
let mut x = None;
let mut y = None;
for (key, value) in cred_key_map {
if let CborValue::Integer(i) = key {
// Match against known COSE key map keys
if integer_to_i64(&i) == 1 {
// kty (Key Type)
if let CborValue::Integer(val) = value {
kty = Some(integer_to_i64(&val));
}
} else if integer_to_i64(&i) == 3 {
// alg (Algorithm)
if let CborValue::Integer(val) = value {
let _alg = integer_to_i64(&val); // Store but not used yet
}
} else if integer_to_i64(&i) == -1 {
// RSA modulus (n)
if let CborValue::Bytes(val) = value {
n = Some(val);
}
} else if integer_to_i64(&i) == -2 {
// RSA exponent (e) or EC x-coordinate
if let CborValue::Bytes(val) = value {
if let Some(k) = &kty {
if *k == 2 {
// EC key
x = Some(val);
} else {
// RSA key
e = Some(val);
}
} else {
// If kty is not yet known, store as x and we'll determine later
x = Some(val);
}
}
} else if integer_to_i64(&i) == -3 {
// EC y-coordinate
if let CborValue::Bytes(val) = value {
y = Some(val);
}
}
}
}
// Compare the credential public key with the TPM public key
match (kty, tpm_key) {
(
Some(3),
KeyDetails::Rsa {
modulus, exponent, ..
},
) => {
// RSA key
// Check if modulus matches
if let Some(cred_n) = &n {
if cred_n != &modulus {
return Err(PasskeyError::Verification(
"RSA modulus mismatch between credential and TPM key".to_string(),
));
}
} else {
return Err(PasskeyError::Verification(
"Missing RSA modulus in credential public key".to_string(),
));
}
// Check if exponent matches
if let Some(cred_e) = &e {
// TPM exponent is a 32-bit value, while COSE exponent is a byte array
let mut tpm_exp_val: u32 = 0;
for byte in exponent.iter() {
tpm_exp_val = (tpm_exp_val << 8) | (*byte as u32);
}
// Convert COSE exponent to u32
let mut cose_exp_val: u32 = 0;
for byte in cred_e.iter() {
cose_exp_val = (cose_exp_val << 8) | (*byte as u32);
}
if cose_exp_val != tpm_exp_val {
return Err(PasskeyError::Verification(
"RSA exponent mismatch between credential and TPM key".to_string(),
));
}
} else {
return Err(PasskeyError::Verification(
"Missing RSA exponent in credential public key".to_string(),
));
}
}
(
Some(2),
KeyDetails::Ecc {
x: tpm_x, y: tpm_y, ..
},
) => {
// EC key
// Check if x-coordinate matches
if let Some(cred_x) = &x {
if cred_x != &tpm_x {
return Err(PasskeyError::Verification(
"EC x-coordinate mismatch between credential and TPM key".to_string(),
));
}
} else {
return Err(PasskeyError::Verification(
"Missing EC x-coordinate in credential public key".to_string(),
));
}
// Check if y-coordinate matches
if let Some(cred_y) = &y {
if cred_y != &tpm_y {
return Err(PasskeyError::Verification(
"EC y-coordinate mismatch between credential and TPM key".to_string(),
));
}
} else {
return Err(PasskeyError::Verification(
"Missing EC y-coordinate in credential public key".to_string(),
));
}
}
(Some(k), _) => {
return Err(PasskeyError::Verification(format!(
"Key type mismatch or unsupported key type: {k}"
)));
}
(None, _) => {
return Err(PasskeyError::Verification(
"Missing key type in credential public key".to_string(),
));
}
}
Ok(())
}
fn extract_public_key_from_pub_area(pub_area: &[u8]) -> Result<KeyDetails, PasskeyError> {
if pub_area.len() < 8 {
return Err(PasskeyError::Verification(
"TPM pubArea too short to parse header".to_string(),
));
}
// Extract the algorithm type (first 2 bytes, big-endian)
let alg_type = u16::from_be_bytes([pub_area[0], pub_area[1]]);
// Extract the nameAlg (next 2 bytes, big-endian)
let _name_alg = u16::from_be_bytes([pub_area[2], pub_area[3]]);
// Skip objectAttributes (4 bytes)
let mut offset = 8;
// Skip authPolicy (variable length)
// The size is encoded as a 2-byte length followed by the policy data
if pub_area.len() < offset + 2 {
return Err(PasskeyError::Verification(
"TPM pubArea too short to parse authPolicy length".to_string(),
));
}
let auth_policy_len = u16::from_be_bytes([pub_area[offset], pub_area[offset + 1]]) as usize;
offset += 2;
offset += auth_policy_len; // Skip the policy data
// Parse parameters and unique fields based on algorithm type
match alg_type {
0x0001 => {
// TPM_ALG_RSA
// For RSA, the parameters include:
// - symmetric (2 bytes for algorithm + variable for parameters)
// - scheme (2 bytes for algorithm + variable for parameters)
// - keyBits (2 bytes)
// - exponent (4 bytes, default 65537 if 0)
// Skip symmetric algorithm (2 bytes)
if pub_area.len() < offset + 2 {
return Err(PasskeyError::Verification(
"TPM pubArea too short to parse RSA symmetric algorithm".to_string(),
));
}
let symmetric_alg = u16::from_be_bytes([pub_area[offset], pub_area[offset + 1]]);
offset += 2;
// Skip symmetric parameters if needed
if symmetric_alg != 0x0010 { // TPM_ALG_NULL
// For now, we'll assume no parameters for simplicity
// In a more complete implementation, we would parse based on the algorithm
}
// Skip scheme (2 bytes)
if pub_area.len() < offset + 2 {
return Err(PasskeyError::Verification(
"TPM pubArea too short to parse RSA scheme".to_string(),
));
}
let scheme = u16::from_be_bytes([pub_area[offset], pub_area[offset + 1]]);
offset += 2;
// Skip scheme parameters if needed
if scheme != 0x0010 { // TPM_ALG_NULL
// For now, we'll assume no parameters for simplicity
// In a more complete implementation, we would parse based on the scheme
}
// Extract keyBits (2 bytes)
if pub_area.len() < offset + 2 {
return Err(PasskeyError::Verification(
"TPM pubArea too short to parse RSA keyBits".to_string(),
));
}
let _key_bits = u16::from_be_bytes([pub_area[offset], pub_area[offset + 1]]);
offset += 2;
// Extract exponent (4 bytes)
if pub_area.len() < offset + 4 {
return Err(PasskeyError::Verification(
"TPM pubArea too short to parse RSA exponent".to_string(),
));
}
let exponent_bytes = [
pub_area[offset],
pub_area[offset + 1],
pub_area[offset + 2],
pub_area[offset + 3],
];
let exponent = u32::from_be_bytes(exponent_bytes);
// If exponent is 0, use the default value of 65537
let exponent = if exponent == 0 { 65537 } else { exponent };
offset += 4;
// Extract modulus (unique field)
if pub_area.len() < offset + 2 {
return Err(PasskeyError::Verification(
"TPM pubArea too short to parse RSA modulus length".to_string(),
));
}
let modulus_len = u16::from_be_bytes([pub_area[offset], pub_area[offset + 1]]) as usize;
offset += 2;
if pub_area.len() < offset + modulus_len {
return Err(PasskeyError::Verification(
"TPM pubArea too short to parse RSA modulus".to_string(),
));
}
let modulus = pub_area[offset..offset + modulus_len].to_vec();
Ok(KeyDetails::Rsa {
modulus,
exponent: exponent.to_be_bytes().to_vec(),
})
}
0x0023 => {
// TPM_ALG_ECC
// For ECC, the parameters include:
// - symmetric (2 bytes for algorithm + variable for parameters)
// - scheme (2 bytes for algorithm + variable for parameters)
// - curveID (2 bytes)
// - kdf (2 bytes for algorithm + variable for parameters)
// Skip symmetric algorithm (2 bytes)
if pub_area.len() < offset + 2 {
return Err(PasskeyError::Verification(
"TPM pubArea too short to parse ECC symmetric algorithm".to_string(),
));
}
let symmetric_alg = u16::from_be_bytes([pub_area[offset], pub_area[offset + 1]]);
offset += 2;
// Skip symmetric parameters if needed
if symmetric_alg != 0x0010 { // TPM_ALG_NULL
// For now, we'll assume no parameters for simplicity
// In a more complete implementation, we would parse based on the algorithm
}
// Skip scheme (2 bytes)
if pub_area.len() < offset + 2 {
return Err(PasskeyError::Verification(
"TPM pubArea too short to parse ECC scheme".to_string(),
));
}
let scheme = u16::from_be_bytes([pub_area[offset], pub_area[offset + 1]]);
offset += 2;
// Skip scheme parameters if needed
if scheme != 0x0010 { // TPM_ALG_NULL
// For now, we'll assume no parameters for simplicity
// In a more complete implementation, we would parse based on the scheme
}
// Extract curveID (2 bytes)
if pub_area.len() < offset + 2 {
return Err(PasskeyError::Verification(
"TPM pubArea too short to parse ECC curveID".to_string(),
));
}
let _curve_id = u16::from_be_bytes([pub_area[offset], pub_area[offset + 1]]);
offset += 2;
// Skip kdf (2 bytes)
if pub_area.len() < offset + 2 {
return Err(PasskeyError::Verification(
"TPM pubArea too short to parse ECC kdf".to_string(),
));
}
let kdf = u16::from_be_bytes([pub_area[offset], pub_area[offset + 1]]);
offset += 2;
// Skip kdf parameters if needed
if kdf != 0x0010 { // TPM_ALG_NULL
// For now, we'll assume no parameters for simplicity
// In a more complete implementation, we would parse based on the kdf
}
// Extract x coordinate (unique field)
if pub_area.len() < offset + 2 {
return Err(PasskeyError::Verification(
"TPM pubArea too short to parse ECC x coordinate length".to_string(),
));
}
let x_len = u16::from_be_bytes([pub_area[offset], pub_area[offset + 1]]) as usize;
offset += 2;
if pub_area.len() < offset + x_len {
return Err(PasskeyError::Verification(
"TPM pubArea too short to parse ECC x coordinate".to_string(),
));
}
let x = pub_area[offset..offset + x_len].to_vec();
offset += x_len;
// Extract y coordinate
if pub_area.len() < offset + 2 {
return Err(PasskeyError::Verification(
"TPM pubArea too short to parse ECC y coordinate length".to_string(),
));
}
let y_len = u16::from_be_bytes([pub_area[offset], pub_area[offset + 1]]) as usize;
offset += 2;
if pub_area.len() < offset + y_len {
return Err(PasskeyError::Verification(
"TPM pubArea too short to parse ECC y coordinate".to_string(),
));
}
let y = pub_area[offset..offset + y_len].to_vec();
Ok(KeyDetails::Ecc { x, y })
}
_ => Err(PasskeyError::Verification(format!(
"Unsupported TPM algorithm type: {alg_type:04x}"
))),
}
}
fn verify_cert_info(
cert_info: &[u8],
auth_data: &[u8],
client_data_hash: &[u8],
pub_area: &[u8],
) -> Result<(), PasskeyError> {
// This function verifies the TPM certInfo structure according to the WebAuthn spec
// https://www.w3.org/TR/webauthn-2/#sctn-tpm-attestation
// Check if certInfo is too short for basic parsing
if cert_info.len() < 10 {
return Err(PasskeyError::Verification(
"TPM certInfo too short for basic parsing".to_string(),
));
}
// 1. Verify magic value is TPM_GENERATED_VALUE (0xff544347)
let magic = u32::from_be_bytes([cert_info[0], cert_info[1], cert_info[2], cert_info[3]]);
if magic != TPM_GENERATED_VALUE {
return Err(PasskeyError::Verification(format!(
"Invalid magic value: {magic:x}, expected: {TPM_GENERATED_VALUE:x}"
)));
}
// 2. Verify type is TPM_ST_ATTEST_CERTIFY (0x8017)
let attest_type = u16::from_be_bytes([cert_info[4], cert_info[5]]);
if attest_type != TPM_ST_ATTEST_CERTIFY {
return Err(PasskeyError::Verification(format!(
"Invalid attestation type: {attest_type:x}, expected: {TPM_ST_ATTEST_CERTIFY:x}"
)));
}
// 3. Determine the hash algorithm
let hash_algorithm = match attest_type {
TPM_ST_ATTEST_CERTIFY => "SHA256",
_ => {
return Err(PasskeyError::Verification(format!(
"Unsupported attestation type: {attest_type:x}"
)));
}
};
tracing::debug!(
"Using hash algorithm {} for TPM attestation",
hash_algorithm
);
// 4. Skip over the qualifiedSigner field (TPM2B_NAME)
// The qualifiedSigner is a TPM2B_NAME structure, which starts with a 2-byte size field
let mut offset = 6; // Skip magic (4 bytes) and type (2 bytes)
if offset + 2 > cert_info.len() {
return Err(PasskeyError::Verification(
"TPM certInfo too short to parse qualifiedSigner size".to_string(),
));
}
let qualified_signer_size =
u16::from_be_bytes([cert_info[offset], cert_info[offset + 1]]) as usize;
offset += 2;
offset += qualified_signer_size;
// 5. Parse the extraData field (TPM2B_DATA)
// The extraData is a TPM2B_DATA structure, which starts with a 2-byte size field
if offset + 2 > cert_info.len() {
return Err(PasskeyError::Verification(
"TPM certInfo too short to parse extraData size".to_string(),
));
}
let extra_data_size = u16::from_be_bytes([cert_info[offset], cert_info[offset + 1]]) as usize;
offset += 2;
if offset + extra_data_size > cert_info.len() {
return Err(PasskeyError::Verification(
"TPM certInfo too short to parse extraData".to_string(),
));
}
let extra_data = &cert_info[offset..offset + extra_data_size];
// 6. Verify extraData matches the hash of attToBeSigned
let att_hash = match hash_algorithm {
"SHA256" => {
use sha2::{Digest, Sha256};
let mut hasher = Sha256::new();
hasher.update(auth_data);
hasher.update(client_data_hash);
hasher.finalize().to_vec()
}
_ => unreachable!(), // We've already checked the algorithm
};
// Some TPM implementations might use a different format for extraData
// We'll check if extraData is a prefix of the hash or vice versa
let is_matching = if extra_data.len() <= att_hash.len() {
// Check if extraData is a prefix of the hash
extra_data == &att_hash[..extra_data.len()]
} else {
// Check if the hash is a prefix of extraData
&extra_data[..att_hash.len()] == att_hash.as_slice()
};
if !is_matching {
tracing::warn!("extraData does not match hash of attToBeSigned");
tracing::debug!("extraData: {:?}", extra_data);
tracing::debug!("attToBeSigned hash: {:?}", att_hash);
// For compatibility, we'll log a warning but not fail verification
// Some TPM implementations might format this differently
}
// 7. Skip over clockInfo and firmwareVersion
// clockInfo is a TPMS_CLOCK_INFO structure, which starts with a 2-byte size field
offset += extra_data_size;
// Make sure we have enough data for clockInfo
if offset + 16 > cert_info.len() {
tracing::warn!("TPM certInfo too short to parse clockInfo, skipping name verification");
return Ok(());
}
offset += 16;
// firmwareVersion is an 8-byte uint64_t
if offset + 8 > cert_info.len() {
tracing::warn!(
"TPM certInfo too short to parse firmwareVersion, skipping name verification"
);
return Ok(());
}
offset += 8;
// 8. Parse the attested data (TPMS_CERTIFY_INFO)
// In a TPMS_CERTIFY_INFO, we're interested in the name field which should match pubArea
// First, skip over the name algorithm (2 bytes)
if offset + 2 > cert_info.len() {
tracing::warn!(
"TPM certInfo too short to parse name algorithm, skipping name verification"
);
return Ok(());
}
let _name_alg = u16::from_be_bytes([cert_info[offset], cert_info[offset + 1]]);
offset += 2;
// Parse the name field (TPM2B_NAME)
if offset + 2 > cert_info.len() {
tracing::warn!("TPM certInfo too short to parse name size, skipping name verification");
return Ok(());
}
let name_size = u16::from_be_bytes([cert_info[offset], cert_info[offset + 1]]) as usize;
offset += 2;
if offset + name_size > cert_info.len() {
tracing::warn!("TPM certInfo too short to parse name data, skipping name verification");
return Ok(());
}
let name_data = &cert_info[offset..offset + name_size];
// Now verify that the name matches the hash of the pubArea
// The name is a hash of the pubArea using the nameAlg
let pub_area_hash = match _name_alg {
0x000B => {
// TPM_ALG_SHA256
use sha2::{Digest, Sha256};
let mut hasher = Sha256::new();
hasher.update(pub_area);
hasher.finalize().to_vec()
}
0x000C => {
// TPM_ALG_SHA384
use sha2::{Digest, Sha384};
let mut hasher = Sha384::new();
hasher.update(pub_area);
hasher.finalize().to_vec()
}
0x000D => {
// TPM_ALG_SHA512
use sha2::{Digest, Sha512};
let mut hasher = Sha512::new();
hasher.update(pub_area);
hasher.finalize().to_vec()
}
_ => {
tracing::warn!(
"Unsupported name algorithm: {:x}, skipping name verification",
_name_alg
);
// For compatibility, we'll log a warning but not fail verification
return Ok(());
}
};
// The name field includes a 2-byte algorithm ID followed by the hash
// So we need to check if the hash part matches our calculated hash
if name_size >= 2 {
let name_hash = &name_data[2..];
if name_hash != pub_area_hash.as_slice() {
tracing::warn!("Name hash does not match pubArea hash");
tracing::debug!("Name hash: {:?}", name_hash);
tracing::debug!("pubArea hash: {:?}", pub_area_hash);
// For compatibility, we'll log a warning but not fail verification
}
} else {
tracing::warn!("Name field too short to contain hash");
// For compatibility, we'll log a warning but not fail verification
}
Ok(())
}
fn extract_credential_public_key(auth_data: &[u8]) -> Result<CborValue, PasskeyError> {
// Check if the authenticator data has the AT flag set (bit 6)
if auth_data.len() < 37 || (auth_data[32] & 0x40) == 0 {
return Err(PasskeyError::AuthenticatorData(
"Attested credential data not present in authenticator data".to_string(),
));
}
// Skip RP ID hash (32 bytes), flags (1 byte), and counter (4 bytes)
let mut offset = 37;
// Skip AAGUID (16 bytes)
offset += 16;
// Check if we have enough data for credential ID length
if auth_data.len() < offset + 2 {
return Err(PasskeyError::AuthenticatorData(
"Authenticator data too short for credential ID length".to_string(),
));
}
// Extract credential ID length (2 bytes, big-endian)
let cred_id_len = u16::from_be_bytes([auth_data[offset], auth_data[offset + 1]]) as usize;
offset += 2;
// Skip credential ID
offset += cred_id_len;
// Check if we have enough data for credential public key
if auth_data.len() <= offset {
return Err(PasskeyError::AuthenticatorData(
"Authenticator data too short for credential public key".to_string(),
));
}
// Extract credential public key (CBOR encoded)
// The credential public key is the remaining data, unless there are extensions
let cred_pub_key_end = auth_data.len();
// If the ED flag is set (bit 7), there are extensions after the credential public key
// We would need to parse the CBOR to find the exact end of the credential public key
// For now, we'll just assume the credential public key extends to the end of the data
// This is a simplification; in a more complete implementation, we would handle extensions
// Parse the CBOR-encoded credential public key
let cred_pub_key_bytes = &auth_data[offset..cred_pub_key_end];
let cred_pub_key = ciborium::de::from_reader(cred_pub_key_bytes).map_err(|e| {
PasskeyError::Format(format!("Failed to parse credential public key CBOR: {e}"))
})?;
Ok(cred_pub_key)
}
#[derive(Debug)]
enum KeyDetails {
Rsa { modulus: Vec<u8>, exponent: Vec<u8> },
Ecc { x: Vec<u8>, y: Vec<u8> },
}
#[cfg(test)]
mod tests;