-
Notifications
You must be signed in to change notification settings - Fork 289
/
mod.rs
2249 lines (2086 loc) · 88.3 KB
/
mod.rs
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
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
pub mod apdu;
pub mod command;
#[cfg(feature = "with_ctap1")]
mod ctap1;
pub mod data_formats;
pub mod hid;
mod key_material;
mod pin_protocol_v1;
pub mod response;
pub mod status_code;
mod storage;
mod timed_permission;
#[cfg(feature = "with_ctap2_1")]
use self::command::MAX_CREDENTIAL_COUNT_IN_LIST;
use self::command::{
AuthenticatorClientPinParameters, AuthenticatorGetAssertionParameters,
AuthenticatorMakeCredentialParameters, AuthenticatorVendorConfigureParameters, Command,
};
#[cfg(feature = "with_ctap2_1")]
use self::data_formats::AuthenticatorTransport;
use self::data_formats::{
CredentialProtectionPolicy, GetAssertionHmacSecretInput, PackedAttestationStatement,
PublicKeyCredentialDescriptor, PublicKeyCredentialParameter, PublicKeyCredentialSource,
PublicKeyCredentialType, PublicKeyCredentialUserEntity, SignatureAlgorithm,
};
use self::hid::ChannelID;
#[cfg(feature = "with_ctap2_1")]
use self::pin_protocol_v1::PinPermission;
use self::pin_protocol_v1::PinProtocolV1;
use self::response::{
AuthenticatorGetAssertionResponse, AuthenticatorGetInfoResponse,
AuthenticatorMakeCredentialResponse, AuthenticatorVendorResponse, ResponseData,
};
use self::status_code::Ctap2StatusCode;
use self::storage::PersistentStore;
use self::timed_permission::TimedPermission;
#[cfg(feature = "with_ctap1")]
use self::timed_permission::U2fUserPresenceState;
use alloc::collections::BTreeMap;
use alloc::string::{String, ToString};
use alloc::vec;
use alloc::vec::Vec;
use arrayref::array_ref;
use byteorder::{BigEndian, ByteOrder};
use cbor::{cbor_map, cbor_map_options};
#[cfg(feature = "debug_ctap")]
use core::fmt::Write;
use crypto::cbc::{cbc_decrypt, cbc_encrypt};
use crypto::hmac::{hmac_256, verify_hmac_256};
use crypto::rng256::Rng256;
use crypto::sha256::Sha256;
use crypto::Hash256;
#[cfg(feature = "debug_ctap")]
use libtock_drivers::console::Console;
use libtock_drivers::crp;
use libtock_drivers::timer::{ClockValue, Duration};
// This flag enables or disables basic attestation for FIDO2. U2F is unaffected by
// this setting. The basic attestation uses the signing key from key_material.rs
// as a batch key. Turn it on if you want attestation. In this case, be aware that
// it is your responsibility to generate your own key material and keep it secret.
const USE_BATCH_ATTESTATION: bool = false;
// The signature counter is currently implemented as a global counter, if you set
// this flag to true. The spec strongly suggests to have per-credential-counters,
// but it means you can't have an infinite amount of credentials anymore. Also,
// since this is the only piece of information that needs writing often, we might
// need a flash storage friendly way to implement this feature. The implemented
// solution is a compromise to be compatible with U2F and not wasting storage.
const USE_SIGNATURE_COUNTER: bool = true;
pub const INITIAL_SIGNATURE_COUNTER: u32 = 1;
// Our credential ID consists of
// - 16 byte initialization vector for AES-256,
// - 32 byte ECDSA private key for the credential,
// - 32 byte relying party ID hashed with SHA256,
// - 32 byte HMAC-SHA256 over everything else.
pub const CREDENTIAL_ID_SIZE: usize = 112;
// Set this bit when checking user presence.
const UP_FLAG: u8 = 0x01;
// Set this bit when checking user verification.
const UV_FLAG: u8 = 0x04;
// Set this bit when performing attestation.
const AT_FLAG: u8 = 0x40;
// Set this bit when an extension is used.
const ED_FLAG: u8 = 0x80;
pub const TOUCH_TIMEOUT_MS: isize = 30000;
#[cfg(feature = "with_ctap1")]
const U2F_UP_PROMPT_TIMEOUT: Duration<isize> = Duration::from_ms(10000);
const RESET_TIMEOUT_DURATION: Duration<isize> = Duration::from_ms(10000);
const STATEFUL_COMMAND_TIMEOUT_DURATION: Duration<isize> = Duration::from_ms(30000);
pub const FIDO2_VERSION_STRING: &str = "FIDO_2_0";
#[cfg(feature = "with_ctap1")]
pub const U2F_VERSION_STRING: &str = "U2F_V2";
// TODO(#106) change to final string when ready
#[cfg(feature = "with_ctap2_1")]
pub const FIDO2_1_VERSION_STRING: &str = "FIDO_2_1_PRE";
// We currently only support one algorithm for signatures: ES256.
// This algorithm is requested in MakeCredential and advertized in GetInfo.
pub const ES256_CRED_PARAM: PublicKeyCredentialParameter = PublicKeyCredentialParameter {
cred_type: PublicKeyCredentialType::PublicKey,
alg: SignatureAlgorithm::ES256,
};
// You can change this value to one of the following for more privacy.
// - Some(CredentialProtectionPolicy::UserVerificationOptionalWithCredentialIdList)
// - Some(CredentialProtectionPolicy::UserVerificationRequired)
const DEFAULT_CRED_PROTECT: Option<CredentialProtectionPolicy> = None;
// This function is adapted from https://doc.rust-lang.org/nightly/src/core/str/mod.rs.html#2110
// (as of 2020-01-20) and truncates to "max" bytes, not breaking the encoding.
// We change the return value, since we don't need the bool.
fn truncate_to_char_boundary(s: &str, mut max: usize) -> &str {
if max >= s.len() {
s
} else {
while !s.is_char_boundary(max) {
max -= 1;
}
&s[..max]
}
}
#[derive(Clone)]
struct AssertionInput {
client_data_hash: Vec<u8>,
auth_data: Vec<u8>,
hmac_secret_input: Option<GetAssertionHmacSecretInput>,
has_uv: bool,
}
struct AssertionState {
assertion_input: AssertionInput,
// Sorted by ascending order of creation, so the last element is the most recent one.
next_credentials: Vec<PublicKeyCredentialSource>,
}
enum StatefulCommand {
Reset,
GetAssertion(AssertionState),
}
// This struct currently holds all state, not only the persistent memory. The persistent members are
// in the persistent store field.
pub struct CtapState<'a, R: Rng256, CheckUserPresence: Fn(ChannelID) -> Result<(), Ctap2StatusCode>>
{
rng: &'a mut R,
// A function to check user presence, ultimately returning true if user presence was detected,
// false otherwise.
check_user_presence: CheckUserPresence,
persistent_store: PersistentStore,
pin_protocol_v1: PinProtocolV1,
#[cfg(feature = "with_ctap1")]
pub u2f_up_state: U2fUserPresenceState,
// The state initializes to Reset and its timeout, and never goes back to Reset.
stateful_command_permission: TimedPermission,
stateful_command_type: Option<StatefulCommand>,
}
impl<'a, R, CheckUserPresence> CtapState<'a, R, CheckUserPresence>
where
R: Rng256,
CheckUserPresence: Fn(ChannelID) -> Result<(), Ctap2StatusCode>,
{
pub const PIN_PROTOCOL_VERSION: u64 = 1;
pub fn new(
rng: &'a mut R,
check_user_presence: CheckUserPresence,
now: ClockValue,
) -> CtapState<'a, R, CheckUserPresence> {
let persistent_store = PersistentStore::new(rng);
let pin_protocol_v1 = PinProtocolV1::new(rng);
CtapState {
rng,
check_user_presence,
persistent_store,
pin_protocol_v1,
#[cfg(feature = "with_ctap1")]
u2f_up_state: U2fUserPresenceState::new(
U2F_UP_PROMPT_TIMEOUT,
Duration::from_ms(TOUCH_TIMEOUT_MS),
),
stateful_command_permission: TimedPermission::granted(now, RESET_TIMEOUT_DURATION),
stateful_command_type: Some(StatefulCommand::Reset),
}
}
pub fn update_command_permission(&mut self, now: ClockValue) {
self.stateful_command_permission = self.stateful_command_permission.check_expiration(now);
}
fn check_command_permission(&mut self, now: ClockValue) -> Result<(), Ctap2StatusCode> {
self.update_command_permission(now);
if self.stateful_command_permission.is_granted(now) {
Ok(())
} else {
Err(Ctap2StatusCode::CTAP2_ERR_NOT_ALLOWED)
}
}
pub fn increment_global_signature_counter(&mut self) -> Result<(), Ctap2StatusCode> {
if USE_SIGNATURE_COUNTER {
let increment = self.rng.gen_uniform_u32x8()[0] % 8 + 1;
self.persistent_store
.incr_global_signature_counter(increment)?;
}
Ok(())
}
// Encrypts the private key and relying party ID hash into a credential ID. Other
// information, such as a user name, are not stored, because encrypted credential IDs
// are used for credentials stored server-side. Also, we want the key handle to be
// compatible with U2F.
pub fn encrypt_key_handle(
&mut self,
private_key: crypto::ecdsa::SecKey,
application: &[u8; 32],
) -> Result<Vec<u8>, Ctap2StatusCode> {
let master_keys = self.persistent_store.master_keys()?;
let aes_enc_key = crypto::aes256::EncryptionKey::new(&master_keys.encryption);
let mut sk_bytes = [0; 32];
private_key.to_bytes(&mut sk_bytes);
let mut iv = [0; 16];
iv.copy_from_slice(&self.rng.gen_uniform_u8x32()[..16]);
let mut blocks = [[0u8; 16]; 4];
blocks[0].copy_from_slice(&sk_bytes[..16]);
blocks[1].copy_from_slice(&sk_bytes[16..]);
blocks[2].copy_from_slice(&application[..16]);
blocks[3].copy_from_slice(&application[16..]);
cbc_encrypt(&aes_enc_key, iv, &mut blocks);
let mut encrypted_id = Vec::with_capacity(0x70);
encrypted_id.extend(&iv);
for b in &blocks {
encrypted_id.extend(b);
}
let id_hmac = hmac_256::<Sha256>(&master_keys.hmac, &encrypted_id[..]);
encrypted_id.extend(&id_hmac);
Ok(encrypted_id)
}
// Decrypts a credential ID and writes the private key into a PublicKeyCredentialSource.
// None is returned if the HMAC test fails or the relying party does not match the
// decrypted relying party ID hash.
pub fn decrypt_credential_source(
&self,
credential_id: Vec<u8>,
rp_id_hash: &[u8],
) -> Result<Option<PublicKeyCredentialSource>, Ctap2StatusCode> {
if credential_id.len() != CREDENTIAL_ID_SIZE {
return Ok(None);
}
let master_keys = self.persistent_store.master_keys()?;
let payload_size = credential_id.len() - 32;
if !verify_hmac_256::<Sha256>(
&master_keys.hmac,
&credential_id[..payload_size],
array_ref![credential_id, payload_size, 32],
) {
return Ok(None);
}
let aes_enc_key = crypto::aes256::EncryptionKey::new(&master_keys.encryption);
let aes_dec_key = crypto::aes256::DecryptionKey::new(&aes_enc_key);
let mut iv = [0; 16];
iv.copy_from_slice(&credential_id[..16]);
let mut blocks = [[0u8; 16]; 4];
for i in 0..4 {
blocks[i].copy_from_slice(&credential_id[16 * (i + 1)..16 * (i + 2)]);
}
cbc_decrypt(&aes_dec_key, iv, &mut blocks);
let mut decrypted_sk = [0; 32];
let mut decrypted_rp_id_hash = [0; 32];
decrypted_sk[..16].clone_from_slice(&blocks[0]);
decrypted_sk[16..].clone_from_slice(&blocks[1]);
decrypted_rp_id_hash[..16].clone_from_slice(&blocks[2]);
decrypted_rp_id_hash[16..].clone_from_slice(&blocks[3]);
if rp_id_hash != decrypted_rp_id_hash {
return Ok(None);
}
let sk_option = crypto::ecdsa::SecKey::from_bytes(&decrypted_sk);
Ok(sk_option.map(|sk| PublicKeyCredentialSource {
key_type: PublicKeyCredentialType::PublicKey,
credential_id,
private_key: sk,
rp_id: String::from(""),
user_handle: vec![],
user_display_name: None,
cred_protect_policy: None,
creation_order: 0,
user_name: None,
user_icon: None,
}))
}
pub fn process_command(
&mut self,
command_cbor: &[u8],
cid: ChannelID,
now: ClockValue,
) -> Vec<u8> {
let cmd = Command::deserialize(command_cbor);
#[cfg(feature = "debug_ctap")]
writeln!(&mut Console::new(), "Received command: {:#?}", cmd).unwrap();
match cmd {
Ok(command) => {
// Correct behavior between CTAP1 and CTAP2 isn't defined yet. Just a guess.
#[cfg(feature = "with_ctap1")]
{
self.u2f_up_state = U2fUserPresenceState::new(
U2F_UP_PROMPT_TIMEOUT,
Duration::from_ms(TOUCH_TIMEOUT_MS),
);
}
match (&command, &self.stateful_command_type) {
(
Command::AuthenticatorGetNextAssertion,
Some(StatefulCommand::GetAssertion(_)),
) => (),
(Command::AuthenticatorReset, Some(StatefulCommand::Reset)) => (),
// GetInfo does not reset stateful commands.
(Command::AuthenticatorGetInfo, _) => (),
// AuthenticatorSelection does not reset stateful commands.
#[cfg(feature = "with_ctap2_1")]
(Command::AuthenticatorSelection, _) => (),
(_, _) => {
self.stateful_command_type = None;
}
}
let response = match command {
Command::AuthenticatorMakeCredential(params) => {
self.process_make_credential(params, cid)
}
Command::AuthenticatorGetAssertion(params) => {
self.process_get_assertion(params, cid, now)
}
Command::AuthenticatorGetNextAssertion => self.process_get_next_assertion(now),
Command::AuthenticatorGetInfo => self.process_get_info(),
Command::AuthenticatorClientPin(params) => self.process_client_pin(params),
Command::AuthenticatorReset => self.process_reset(cid, now),
#[cfg(feature = "with_ctap2_1")]
Command::AuthenticatorSelection => self.process_selection(cid),
// TODO(kaczmarczyck) implement FIDO 2.1 commands
// Vendor specific commands
Command::AuthenticatorVendorConfigure(params) => {
self.process_vendor_configure(params, cid)
}
};
#[cfg(feature = "debug_ctap")]
writeln!(&mut Console::new(), "Sending response: {:#?}", response).unwrap();
match response {
Ok(response_data) => {
let mut response_vec = vec![0x00];
if let Some(value) = response_data.into() {
if !cbor::write(value, &mut response_vec) {
response_vec = vec![
Ctap2StatusCode::CTAP2_ERR_VENDOR_RESPONSE_CANNOT_WRITE_CBOR
as u8,
];
}
}
response_vec
}
Err(error_code) => vec![error_code as u8],
}
}
Err(error_code) => vec![error_code as u8],
}
}
fn pin_uv_auth_precheck(
&mut self,
pin_uv_auth_param: &Option<Vec<u8>>,
pin_uv_auth_protocol: Option<u64>,
cid: ChannelID,
) -> Result<(), Ctap2StatusCode> {
if let Some(auth_param) = &pin_uv_auth_param {
// This case was added in FIDO 2.1.
if auth_param.is_empty() {
(self.check_user_presence)(cid)?;
if self.persistent_store.pin_hash()?.is_none() {
return Err(Ctap2StatusCode::CTAP2_ERR_PIN_NOT_SET);
} else {
return Err(Ctap2StatusCode::CTAP2_ERR_PIN_INVALID);
}
}
match pin_uv_auth_protocol {
Some(CtapState::<R, CheckUserPresence>::PIN_PROTOCOL_VERSION) => Ok(()),
Some(_) => Err(Ctap2StatusCode::CTAP2_ERR_PIN_AUTH_INVALID),
None => Err(Ctap2StatusCode::CTAP2_ERR_MISSING_PARAMETER),
}
} else {
Ok(())
}
}
fn process_make_credential(
&mut self,
make_credential_params: AuthenticatorMakeCredentialParameters,
cid: ChannelID,
) -> Result<ResponseData, Ctap2StatusCode> {
let AuthenticatorMakeCredentialParameters {
client_data_hash,
rp,
user,
pub_key_cred_params,
exclude_list,
extensions,
options,
pin_uv_auth_param,
pin_uv_auth_protocol,
} = make_credential_params;
self.pin_uv_auth_precheck(&pin_uv_auth_param, pin_uv_auth_protocol, cid)?;
if !pub_key_cred_params.contains(&ES256_CRED_PARAM) {
return Err(Ctap2StatusCode::CTAP2_ERR_UNSUPPORTED_ALGORITHM);
}
let (use_hmac_extension, cred_protect_policy) = if let Some(extensions) = extensions {
let mut cred_protect = extensions.cred_protect;
if cred_protect.unwrap_or(CredentialProtectionPolicy::UserVerificationOptional)
< DEFAULT_CRED_PROTECT
.unwrap_or(CredentialProtectionPolicy::UserVerificationOptional)
{
cred_protect = DEFAULT_CRED_PROTECT;
}
(extensions.hmac_secret, cred_protect)
} else {
(false, DEFAULT_CRED_PROTECT)
};
let has_extension_output = use_hmac_extension || cred_protect_policy.is_some();
let rp_id = rp.rp_id;
let rp_id_hash = Sha256::hash(rp_id.as_bytes());
if let Some(exclude_list) = exclude_list {
for cred_desc in exclude_list {
if self
.persistent_store
.find_credential(&rp_id, &cred_desc.key_id, pin_uv_auth_param.is_none())?
.is_some()
|| self
.decrypt_credential_source(cred_desc.key_id, &rp_id_hash)?
.is_some()
{
// Perform this check, so bad actors can't brute force exclude_list
// without user interaction.
(self.check_user_presence)(cid)?;
return Err(Ctap2StatusCode::CTAP2_ERR_CREDENTIAL_EXCLUDED);
}
}
}
// MakeCredential always requires user presence.
// User verification depends on the PIN auth inputs, which are checked here.
let ed_flag = if has_extension_output { ED_FLAG } else { 0 };
let flags = match pin_uv_auth_param {
Some(pin_auth) => {
if self.persistent_store.pin_hash()?.is_none() {
// Specification is unclear, could be CTAP2_ERR_INVALID_OPTION.
return Err(Ctap2StatusCode::CTAP2_ERR_PIN_NOT_SET);
}
if !self
.pin_protocol_v1
.verify_pin_auth_token(&client_data_hash, &pin_auth)
{
return Err(Ctap2StatusCode::CTAP2_ERR_PIN_AUTH_INVALID);
}
#[cfg(feature = "with_ctap2_1")]
{
self.pin_protocol_v1
.has_permission(PinPermission::MakeCredential)?;
self.pin_protocol_v1.has_permission_for_rp_id(&rp_id)?;
}
UP_FLAG | UV_FLAG | AT_FLAG | ed_flag
}
None => {
if self.persistent_store.pin_hash()?.is_some() {
return Err(Ctap2StatusCode::CTAP2_ERR_PIN_REQUIRED);
}
if options.uv {
return Err(Ctap2StatusCode::CTAP2_ERR_INVALID_OPTION);
}
UP_FLAG | AT_FLAG | ed_flag
}
};
(self.check_user_presence)(cid)?;
let sk = crypto::ecdsa::SecKey::gensk(self.rng);
let pk = sk.genpk();
let credential_id = if options.rk {
let random_id = self.rng.gen_uniform_u8x32().to_vec();
let credential_source = PublicKeyCredentialSource {
key_type: PublicKeyCredentialType::PublicKey,
credential_id: random_id.clone(),
private_key: sk.clone(),
rp_id,
user_handle: user.user_id,
// This input is user provided, so we crop it to 64 byte for storage.
// The UTF8 encoding is always preserved, so the string might end up shorter.
user_display_name: user
.user_display_name
.map(|s| truncate_to_char_boundary(&s, 64).to_string()),
cred_protect_policy,
creation_order: self.persistent_store.new_creation_order()?,
user_name: user
.user_name
.map(|s| truncate_to_char_boundary(&s, 64).to_string()),
user_icon: user
.user_icon
.map(|s| truncate_to_char_boundary(&s, 64).to_string()),
};
self.persistent_store.store_credential(credential_source)?;
random_id
} else {
self.encrypt_key_handle(sk.clone(), &rp_id_hash)?
};
let mut auth_data = self.generate_auth_data(&rp_id_hash, flags)?;
auth_data.extend(&self.persistent_store.aaguid()?);
// The length is fixed to 0x20 or 0x70 and fits one byte.
if credential_id.len() > 0xFF {
return Err(Ctap2StatusCode::CTAP2_ERR_VENDOR_RESPONSE_TOO_LONG);
}
auth_data.extend(vec![0x00, credential_id.len() as u8]);
auth_data.extend(&credential_id);
let cose_key = match pk.to_cose_key() {
Some(cose_key) => cose_key,
None => return Err(Ctap2StatusCode::CTAP2_ERR_VENDOR_RESPONSE_CANNOT_WRITE_CBOR),
};
auth_data.extend(cose_key);
if has_extension_output {
let hmac_secret_output = if use_hmac_extension { Some(true) } else { None };
let extensions_output = cbor_map_options! {
"hmac-secret" => hmac_secret_output,
"credProtect" => cred_protect_policy,
};
if !cbor::write(extensions_output, &mut auth_data) {
return Err(Ctap2StatusCode::CTAP2_ERR_VENDOR_RESPONSE_CANNOT_WRITE_CBOR);
}
}
let mut signature_data = auth_data.clone();
signature_data.extend(client_data_hash);
let (signature, x5c) = if USE_BATCH_ATTESTATION {
let attestation_private_key = self
.persistent_store
.attestation_private_key()?
.ok_or(Ctap2StatusCode::CTAP2_ERR_VENDOR_INTERNAL_ERROR)?;
let attestation_key =
crypto::ecdsa::SecKey::from_bytes(&attestation_private_key).unwrap();
let attestation_certificate = self
.persistent_store
.attestation_certificate()?
.ok_or(Ctap2StatusCode::CTAP2_ERR_VENDOR_INTERNAL_ERROR)?;
(
attestation_key.sign_rfc6979::<crypto::sha256::Sha256>(&signature_data),
Some(vec![attestation_certificate]),
)
} else {
(
sk.sign_rfc6979::<crypto::sha256::Sha256>(&signature_data),
None,
)
};
let attestation_statement = PackedAttestationStatement {
alg: SignatureAlgorithm::ES256 as i64,
sig: signature.to_asn1_der(),
x5c,
ecdaa_key_id: None,
};
Ok(ResponseData::AuthenticatorMakeCredential(
AuthenticatorMakeCredentialResponse {
fmt: String::from("packed"),
auth_data,
att_stmt: attestation_statement,
},
))
}
// Generates a different per-credential secret for each UV mode.
// The computation is deterministic, and private_key expected to be unique.
fn generate_cred_random(
&mut self,
private_key: &crypto::ecdsa::SecKey,
has_uv: bool,
) -> Result<[u8; 32], Ctap2StatusCode> {
let mut private_key_bytes = [0u8; 32];
private_key.to_bytes(&mut private_key_bytes);
let key = self.persistent_store.cred_random_secret(has_uv)?;
Ok(hmac_256::<Sha256>(&key, &private_key_bytes))
}
// Processes the input of a get_assertion operation for a given credential
// and returns the correct Get(Next)Assertion response.
fn assertion_response(
&mut self,
credential: PublicKeyCredentialSource,
assertion_input: AssertionInput,
number_of_credentials: Option<usize>,
) -> Result<ResponseData, Ctap2StatusCode> {
let AssertionInput {
client_data_hash,
mut auth_data,
hmac_secret_input,
has_uv,
} = assertion_input;
// Process extensions.
if let Some(hmac_secret_input) = hmac_secret_input {
let cred_random = self.generate_cred_random(&credential.private_key, has_uv)?;
let encrypted_output = self
.pin_protocol_v1
.process_hmac_secret(hmac_secret_input, &cred_random)?;
let extensions_output = cbor_map! {
"hmac-secret" => encrypted_output,
};
if !cbor::write(extensions_output, &mut auth_data) {
return Err(Ctap2StatusCode::CTAP2_ERR_VENDOR_RESPONSE_CANNOT_WRITE_CBOR);
}
}
let mut signature_data = auth_data.clone();
signature_data.extend(client_data_hash);
let signature = credential
.private_key
.sign_rfc6979::<crypto::sha256::Sha256>(&signature_data);
let cred_desc = PublicKeyCredentialDescriptor {
key_type: PublicKeyCredentialType::PublicKey,
key_id: credential.credential_id,
transports: None, // You can set USB as a hint here.
};
let user = if !credential.user_handle.is_empty() {
Some(PublicKeyCredentialUserEntity {
user_id: credential.user_handle,
user_name: credential.user_name,
user_display_name: credential.user_display_name,
user_icon: credential.user_icon,
})
} else {
None
};
Ok(ResponseData::AuthenticatorGetAssertion(
AuthenticatorGetAssertionResponse {
credential: Some(cred_desc),
auth_data,
signature: signature.to_asn1_der(),
user,
number_of_credentials: number_of_credentials.map(|n| n as u64),
},
))
}
// Returns the first applicable credential from the allow list.
fn get_any_credential_from_allow_list(
&mut self,
allow_list: Vec<PublicKeyCredentialDescriptor>,
rp_id: &str,
rp_id_hash: &[u8],
has_uv: bool,
) -> Result<Option<PublicKeyCredentialSource>, Ctap2StatusCode> {
for allowed_credential in allow_list {
let credential = self.persistent_store.find_credential(
rp_id,
&allowed_credential.key_id,
!has_uv,
)?;
if credential.is_some() {
return Ok(credential);
}
let credential =
self.decrypt_credential_source(allowed_credential.key_id, &rp_id_hash)?;
if credential.is_some() {
return Ok(credential);
}
}
Ok(None)
}
fn process_get_assertion(
&mut self,
get_assertion_params: AuthenticatorGetAssertionParameters,
cid: ChannelID,
now: ClockValue,
) -> Result<ResponseData, Ctap2StatusCode> {
let AuthenticatorGetAssertionParameters {
rp_id,
client_data_hash,
allow_list,
extensions,
options,
pin_uv_auth_param,
pin_uv_auth_protocol,
} = get_assertion_params;
self.pin_uv_auth_precheck(&pin_uv_auth_param, pin_uv_auth_protocol, cid)?;
let hmac_secret_input = extensions.map(|e| e.hmac_secret).flatten();
if hmac_secret_input.is_some() && !options.up {
// The extension is actually supported, but we need user presence.
return Err(Ctap2StatusCode::CTAP2_ERR_UNSUPPORTED_EXTENSION);
}
// The user verification bit depends on the existance of PIN auth, since we do
// not support internal UV. User presence is requested as an option.
let has_uv = pin_uv_auth_param.is_some();
let mut flags = match pin_uv_auth_param {
Some(pin_auth) => {
if self.persistent_store.pin_hash()?.is_none() {
// Specification is unclear, could be CTAP2_ERR_UNSUPPORTED_OPTION.
return Err(Ctap2StatusCode::CTAP2_ERR_PIN_NOT_SET);
}
if !self
.pin_protocol_v1
.verify_pin_auth_token(&client_data_hash, &pin_auth)
{
return Err(Ctap2StatusCode::CTAP2_ERR_PIN_AUTH_INVALID);
}
#[cfg(feature = "with_ctap2_1")]
{
self.pin_protocol_v1
.has_permission(PinPermission::GetAssertion)?;
self.pin_protocol_v1.has_permission_for_rp_id(&rp_id)?;
}
UV_FLAG
}
None => {
if options.uv {
// The specification (inconsistently) wants CTAP2_ERR_UNSUPPORTED_OPTION.
return Err(Ctap2StatusCode::CTAP2_ERR_INVALID_OPTION);
}
0x00
}
};
if options.up {
flags |= UP_FLAG;
}
if hmac_secret_input.is_some() {
flags |= ED_FLAG;
}
let rp_id_hash = Sha256::hash(rp_id.as_bytes());
let mut applicable_credentials = if let Some(allow_list) = allow_list {
if let Some(credential) =
self.get_any_credential_from_allow_list(allow_list, &rp_id, &rp_id_hash, has_uv)?
{
vec![credential]
} else {
vec![]
}
} else {
self.persistent_store.filter_credential(&rp_id, !has_uv)?
};
// Remove user identifiable information without uv.
if !has_uv {
for credential in &mut applicable_credentials {
credential.user_name = None;
credential.user_display_name = None;
credential.user_icon = None;
}
}
applicable_credentials.sort_unstable_by_key(|c| c.creation_order);
// This check comes before CTAP2_ERR_NO_CREDENTIALS in CTAP 2.0.
// For CTAP 2.1, it was moved to a later protocol step.
if options.up {
(self.check_user_presence)(cid)?;
}
let credential = applicable_credentials
.pop()
.ok_or(Ctap2StatusCode::CTAP2_ERR_NO_CREDENTIALS)?;
self.increment_global_signature_counter()?;
let assertion_input = AssertionInput {
client_data_hash,
auth_data: self.generate_auth_data(&rp_id_hash, flags)?,
hmac_secret_input,
has_uv,
};
let number_of_credentials = if applicable_credentials.is_empty() {
None
} else {
let number_of_credentials = Some(applicable_credentials.len() + 1);
self.stateful_command_permission =
TimedPermission::granted(now, STATEFUL_COMMAND_TIMEOUT_DURATION);
self.stateful_command_type = Some(StatefulCommand::GetAssertion(AssertionState {
assertion_input: assertion_input.clone(),
next_credentials: applicable_credentials,
}));
number_of_credentials
};
self.assertion_response(credential, assertion_input, number_of_credentials)
}
fn process_get_next_assertion(
&mut self,
now: ClockValue,
) -> Result<ResponseData, Ctap2StatusCode> {
self.check_command_permission(now)?;
let (assertion_input, credential) =
if let Some(StatefulCommand::GetAssertion(assertion_state)) =
&mut self.stateful_command_type
{
let credential = assertion_state
.next_credentials
.pop()
.ok_or(Ctap2StatusCode::CTAP2_ERR_NOT_ALLOWED)?;
(assertion_state.assertion_input.clone(), credential)
} else {
return Err(Ctap2StatusCode::CTAP2_ERR_NOT_ALLOWED);
};
self.assertion_response(credential, assertion_input, None)
}
fn process_get_info(&self) -> Result<ResponseData, Ctap2StatusCode> {
let mut options_map = BTreeMap::new();
// TODO(kaczmarczyck) add authenticatorConfig and credProtect options
options_map.insert(String::from("rk"), true);
options_map.insert(String::from("up"), true);
options_map.insert(
String::from("clientPin"),
self.persistent_store.pin_hash()?.is_some(),
);
Ok(ResponseData::AuthenticatorGetInfo(
AuthenticatorGetInfoResponse {
versions: vec![
#[cfg(feature = "with_ctap1")]
String::from(U2F_VERSION_STRING),
String::from(FIDO2_VERSION_STRING),
#[cfg(feature = "with_ctap2_1")]
String::from(FIDO2_1_VERSION_STRING),
],
extensions: Some(vec![String::from("hmac-secret")]),
aaguid: self.persistent_store.aaguid()?,
options: Some(options_map),
max_msg_size: Some(1024),
pin_protocols: Some(vec![
CtapState::<R, CheckUserPresence>::PIN_PROTOCOL_VERSION,
]),
#[cfg(feature = "with_ctap2_1")]
max_credential_count_in_list: MAX_CREDENTIAL_COUNT_IN_LIST.map(|c| c as u64),
// #TODO(106) update with version 2.1 of HMAC-secret
#[cfg(feature = "with_ctap2_1")]
max_credential_id_length: Some(CREDENTIAL_ID_SIZE as u64),
#[cfg(feature = "with_ctap2_1")]
transports: Some(vec![AuthenticatorTransport::Usb]),
#[cfg(feature = "with_ctap2_1")]
algorithms: Some(vec![ES256_CRED_PARAM]),
default_cred_protect: DEFAULT_CRED_PROTECT,
#[cfg(feature = "with_ctap2_1")]
min_pin_length: self.persistent_store.min_pin_length()?,
#[cfg(feature = "with_ctap2_1")]
firmware_version: None,
},
))
}
fn process_client_pin(
&mut self,
client_pin_params: AuthenticatorClientPinParameters,
) -> Result<ResponseData, Ctap2StatusCode> {
self.pin_protocol_v1.process_subcommand(
self.rng,
&mut self.persistent_store,
client_pin_params,
)
}
fn process_reset(
&mut self,
cid: ChannelID,
now: ClockValue,
) -> Result<ResponseData, Ctap2StatusCode> {
// Resets are only possible in the first 10 seconds after booting.
// TODO(kaczmarczyck) 2.1 allows Reset after Reset and 15 seconds?
self.check_command_permission(now)?;
match &self.stateful_command_type {
Some(StatefulCommand::Reset) => (),
_ => return Err(Ctap2StatusCode::CTAP2_ERR_NOT_ALLOWED),
}
(self.check_user_presence)(cid)?;
self.persistent_store.reset(self.rng)?;
self.pin_protocol_v1.reset(self.rng);
#[cfg(feature = "with_ctap1")]
{
self.u2f_up_state = U2fUserPresenceState::new(
U2F_UP_PROMPT_TIMEOUT,
Duration::from_ms(TOUCH_TIMEOUT_MS),
);
}
Ok(ResponseData::AuthenticatorReset)
}
#[cfg(feature = "with_ctap2_1")]
fn process_selection(&self, cid: ChannelID) -> Result<ResponseData, Ctap2StatusCode> {
(self.check_user_presence)(cid)?;
Ok(ResponseData::AuthenticatorSelection)
}
fn process_vendor_configure(
&mut self,
params: AuthenticatorVendorConfigureParameters,
cid: ChannelID,
) -> Result<ResponseData, Ctap2StatusCode> {
(self.check_user_presence)(cid)?;
// Sanity checks
let current_priv_key = self.persistent_store.attestation_private_key()?;
let current_cert = self.persistent_store.attestation_certificate()?;
let response = match params.attestation_material {
// Only reading values.
None => AuthenticatorVendorResponse {
cert_programmed: current_cert.is_some(),
pkey_programmed: current_priv_key.is_some(),
},
// Device is already fully programmed. We don't leak information.
Some(_) if current_cert.is_some() && current_priv_key.is_some() => {
AuthenticatorVendorResponse {
cert_programmed: true,
pkey_programmed: true,
}
}
// Device is partially or not programmed. We complete the process.
Some(data) => {
if let Some(current_cert) = ¤t_cert {
if current_cert != &data.certificate {
return Err(Ctap2StatusCode::CTAP1_ERR_INVALID_PARAMETER);
}
}
if let Some(current_priv_key) = ¤t_priv_key {
if current_priv_key != &data.private_key {
return Err(Ctap2StatusCode::CTAP1_ERR_INVALID_PARAMETER);
}
}
if current_cert.is_none() {
self.persistent_store
.set_attestation_certificate(&data.certificate)?;
}
if current_priv_key.is_none() {
self.persistent_store
.set_attestation_private_key(&data.private_key)?;
}
AuthenticatorVendorResponse {
cert_programmed: true,
pkey_programmed: true,
}
}
};
if params.lockdown {
// To avoid bricking the authenticator, we only allow lockdown
// to happen if both values are programmed or if both U2F/CTAP1 and
// batch attestation are disabled.
#[cfg(feature = "with_ctap1")]
let need_certificate = true;
#[cfg(not(feature = "with_ctap1"))]
let need_certificate = USE_BATCH_ATTESTATION;
if (need_certificate && !(response.pkey_programmed && response.cert_programmed))
|| crp::set_protection(crp::ProtectionLevel::FullyLocked).is_err()
{
return Err(Ctap2StatusCode::CTAP2_ERR_VENDOR_INTERNAL_ERROR);
}
}
Ok(ResponseData::AuthenticatorVendor(response))
}
pub fn generate_auth_data(
&self,
rp_id_hash: &[u8],
flag_byte: u8,
) -> Result<Vec<u8>, Ctap2StatusCode> {
let mut auth_data = vec![];