authenticator-ctap2-2021 0.3.2-dev.1

Library for interacting with CTAP1/2 security keys for Web Authentication. Used by Firefox.
Documentation
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
use super::{get_info::AuthenticatorInfo, Command, CommandError, RequestCtap2, StatusCode};
use crate::crypto::{
    authenticate, decrypt, encapsulate, encrypt, BackendError, COSEKey, CryptoError, ECDHSecret,
};
use crate::transport::errors::HIDError;
use crate::u2ftypes::U2FDevice;
use serde::{
    de::{Error as SerdeError, MapAccess, Visitor},
    ser::SerializeMap,
    Deserialize, Deserializer, Serialize, Serializer,
};
use serde_bytes::ByteBuf;
use serde_cbor::de::from_slice;
use serde_cbor::ser::to_vec;
use serde_cbor::Value;
use sha2::{Digest, Sha256};
use std::error::Error as StdErrorT;
use std::fmt;

// use serde::Deserialize; cfg[test]

#[derive(Debug, Copy, Clone)]
#[repr(u8)]
pub enum PINSubcommand {
    GetRetries = 0x01,
    GetKeyAgreement = 0x02,
    SetPIN = 0x03,
    ChangePIN = 0x04,
    GetPINToken = 0x05,
}

#[derive(Debug)]
pub struct ClientPIN {
    pin_protocol: Option<u8>,
    subcommand: PINSubcommand,
    key_agreement: Option<COSEKey>,
    pin_auth: Option<PinAuth>,
    new_pin_enc: Option<ByteBuf>,
    pin_hash_enc: Option<ByteBuf>,
}

impl Default for ClientPIN {
    fn default() -> Self {
        ClientPIN {
            pin_protocol: None,
            subcommand: PINSubcommand::GetRetries,
            key_agreement: None,
            pin_auth: None,
            new_pin_enc: None,
            pin_hash_enc: None,
        }
    }
}

impl Serialize for ClientPIN {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        // Need to define how many elements are going to be in the map
        // beforehand
        let mut map_len = 1;
        if self.pin_protocol.is_some() {
            map_len += 1;
        }
        if self.key_agreement.is_some() {
            map_len += 1;
        }
        if self.pin_auth.is_some() {
            map_len += 1;
        }
        if self.new_pin_enc.is_some() {
            map_len += 1;
        }
        if self.pin_hash_enc.is_some() {
            map_len += 1;
        }

        let mut map = serializer.serialize_map(Some(map_len))?;
        if let Some(ref pin_protocol) = self.pin_protocol {
            map.serialize_entry(&1, pin_protocol)?;
        }
        let command: u8 = self.subcommand as u8;
        map.serialize_entry(&2, &command)?;
        if let Some(ref key_agreement) = self.key_agreement {
            map.serialize_entry(&3, key_agreement)?;
        }
        if let Some(ref pin_auth) = self.pin_auth {
            map.serialize_entry(&4, &ByteBuf::from(pin_auth.as_ref()))?;
        }
        if let Some(ref new_pin_enc) = self.new_pin_enc {
            map.serialize_entry(&5, new_pin_enc)?;
        }
        if let Some(ref pin_hash_enc) = self.pin_hash_enc {
            map.serialize_entry(&6, pin_hash_enc)?;
        }

        map.end()
    }
}

pub trait ClientPINSubCommand {
    type Output;
    fn as_client_pin(&self) -> Result<ClientPIN, CommandError>;
    fn parse_response_payload(&self, input: &[u8]) -> Result<Self::Output, CommandError>;
}

struct ClientPinResponse {
    key_agreement: Option<COSEKey>,
    pin_token: Option<EncryptedPinToken>,
    /// Number of PIN attempts remaining before lockout.
    retries: Option<u8>,
}

impl<'de> Deserialize<'de> for ClientPinResponse {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct ClientPinResponseVisitor;

        impl<'de> Visitor<'de> for ClientPinResponseVisitor {
            type Value = ClientPinResponse;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("a map")
            }

            fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error>
            where
                M: MapAccess<'de>,
            {
                let mut key_agreement = None;
                let mut pin_token = None;
                let mut retries = None;
                while let Some(key) = map.next_key()? {
                    match key {
                        1 => {
                            if key_agreement.is_some() {
                                return Err(SerdeError::duplicate_field("key_agreement"));
                            }
                            key_agreement = map.next_value()?;
                        }
                        2 => {
                            if pin_token.is_some() {
                                return Err(SerdeError::duplicate_field("pin_token"));
                            }
                            pin_token = map.next_value()?;
                        }
                        3 => {
                            if retries.is_some() {
                                return Err(SerdeError::duplicate_field("retries"));
                            }
                            retries = Some(map.next_value()?);
                        }
                        k => return Err(M::Error::custom(format!("unexpected key: {:?}", k))),
                    }
                }
                Ok(ClientPinResponse {
                    key_agreement,
                    pin_token,
                    retries,
                })
            }
        }
        deserializer.deserialize_bytes(ClientPinResponseVisitor)
    }
}

#[derive(Debug)]
pub struct GetKeyAgreement {
    pin_protocol: u8,
}

impl GetKeyAgreement {
    pub fn new(info: &AuthenticatorInfo) -> Result<Self, CommandError> {
        if info.pin_protocols.contains(&1) {
            Ok(GetKeyAgreement { pin_protocol: 1 })
        } else {
            Err(CommandError::UnsupportedPinProtocol)
        }
    }
}

impl ClientPINSubCommand for GetKeyAgreement {
    type Output = KeyAgreement;

    fn as_client_pin(&self) -> Result<ClientPIN, CommandError> {
        Ok(ClientPIN {
            pin_protocol: Some(self.pin_protocol),
            subcommand: PINSubcommand::GetKeyAgreement,
            ..ClientPIN::default()
        })
    }

    fn parse_response_payload(&self, input: &[u8]) -> Result<Self::Output, CommandError> {
        let value: Value = from_slice(input).map_err(CommandError::Deserializing)?;
        debug!("GetKeyAgreement::parse_response_payload {:?}", value);

        let get_pin_response: ClientPinResponse =
            from_slice(input).map_err(CommandError::Deserializing)?;
        if let Some(key_agreement) = get_pin_response.key_agreement {
            Ok(KeyAgreement(key_agreement))
        } else {
            Err(CommandError::MissingRequiredField("key_agreement"))
        }
    }
}

#[derive(Debug)]
pub struct GetPinToken<'sc, 'pin> {
    pin_protocol: u8,
    shared_secret: &'sc ECDHSecret,
    pin: &'pin Pin,
}

impl<'sc, 'pin> GetPinToken<'sc, 'pin> {
    pub fn new(
        info: &AuthenticatorInfo,
        shared_secret: &'sc ECDHSecret,
        pin: &'pin Pin,
    ) -> Result<Self, CommandError> {
        if info.pin_protocols.contains(&1) {
            Ok(GetPinToken {
                pin_protocol: 1,
                shared_secret,
                pin,
            })
        } else {
            Err(CommandError::UnsupportedPinProtocol)
        }
    }
}

impl<'sc, 'pin> ClientPINSubCommand for GetPinToken<'sc, 'pin> {
    type Output = PinToken;

    fn as_client_pin(&self) -> Result<ClientPIN, CommandError> {
        let input = self.pin.for_pin_token();
        trace!("pin_hash = {:#04X?}", &input.as_ref());
        let pin_hash_enc = encrypt(self.shared_secret.shared_secret(), input.as_ref())
            .map_err(|e| CryptoError::Backend(e))?;
        trace!("pin_hash_enc = {:#04X?}", &pin_hash_enc);

        Ok(ClientPIN {
            pin_protocol: Some(self.pin_protocol),
            subcommand: PINSubcommand::GetPINToken,
            key_agreement: Some(self.shared_secret.my_public_key().clone()),
            pin_hash_enc: Some(ByteBuf::from(pin_hash_enc)),
            ..ClientPIN::default()
        })
    }

    fn parse_response_payload(&self, input: &[u8]) -> Result<Self::Output, CommandError> {
        let value: Value = from_slice(input).map_err(CommandError::Deserializing)?;
        debug!("GetKeyAgreement::parse_response_payload {:?}", value);

        let get_pin_response: ClientPinResponse =
            from_slice(input).map_err(CommandError::Deserializing)?;
        match get_pin_response.pin_token {
            Some(encrypted_pin_token) => {
                let pin_token = decrypt(
                    self.shared_secret.shared_secret(),
                    encrypted_pin_token.as_ref(),
                )
                .map_err(|e| CryptoError::Backend(e))?;
                let pin_token = PinToken(pin_token);
                Ok(pin_token)
            }
            None => Err(CommandError::MissingRequiredField("key_agreement")),
        }
    }
}

#[derive(Debug)]
pub struct GetRetries {}

impl GetRetries {
    pub fn new() -> Self {
        GetRetries {}
    }
}

impl ClientPINSubCommand for GetRetries {
    type Output = u8;

    fn as_client_pin(&self) -> Result<ClientPIN, CommandError> {
        Ok(ClientPIN {
            subcommand: PINSubcommand::GetRetries,
            ..ClientPIN::default()
        })
    }

    fn parse_response_payload(&self, input: &[u8]) -> Result<Self::Output, CommandError> {
        let value: Value = from_slice(input).map_err(CommandError::Deserializing)?;
        debug!("GetKeyAgreement::parse_response_payload {:?}", value);

        let get_pin_response: ClientPinResponse =
            from_slice(input).map_err(CommandError::Deserializing)?;
        match get_pin_response.retries {
            Some(retries) => Ok(retries),
            None => Err(CommandError::MissingRequiredField("retries")),
        }
    }
}

#[derive(Debug)]
pub struct SetNewPin<'sc, 'pin> {
    pin_protocol: u8,
    shared_secret: &'sc ECDHSecret,
    new_pin: &'pin Pin,
}

impl<'sc, 'pin> SetNewPin<'sc, 'pin> {
    pub fn new(
        info: &AuthenticatorInfo,
        shared_secret: &'sc ECDHSecret,
        new_pin: &'pin Pin,
    ) -> Result<Self, CommandError> {
        if info.pin_protocols.contains(&1) {
            Ok(SetNewPin {
                pin_protocol: 1,
                shared_secret,
                new_pin,
            })
        } else {
            Err(CommandError::UnsupportedPinProtocol)
        }
    }
}

impl<'sc, 'pin> ClientPINSubCommand for SetNewPin<'sc, 'pin> {
    type Output = ();

    fn as_client_pin(&self) -> Result<ClientPIN, CommandError> {
        if self.new_pin.as_bytes().len() > 63 {
            return Err(CommandError::StatusCode(
                StatusCode::PinPolicyViolation,
                None,
            ));
        }
        // Padding the PIN with trailing zeros, according to spec
        let input: Vec<u8> = self
            .new_pin
            .as_bytes()
            .iter()
            .chain(std::iter::repeat(&0x00))
            .take(64)
            .cloned()
            .collect();

        let shared_secret = self.shared_secret.shared_secret();
        // AES256-CBC(sharedSecret, IV=0, newPin)
        let new_pin_enc =
            encrypt(shared_secret, input.as_ref()).map_err(|e| CryptoError::Backend(e))?;

        // LEFT(HMAC-SHA-265(sharedSecret, newPinEnc), 16)
        let pin_auth = PinToken(shared_secret.to_vec())
            .auth(&new_pin_enc)
            .map_err(CommandError::Crypto)?;

        Ok(ClientPIN {
            pin_protocol: Some(self.pin_protocol),
            subcommand: PINSubcommand::SetPIN,
            key_agreement: Some(self.shared_secret.my_public_key().clone()),
            new_pin_enc: Some(ByteBuf::from(new_pin_enc)),
            pin_auth: Some(pin_auth),
            ..ClientPIN::default()
        })
    }

    fn parse_response_payload(&self, input: &[u8]) -> Result<Self::Output, CommandError> {
        // Should be an empty response or a valid cbor-value (which we ignore)
        if input.is_empty() {
            Ok(())
        } else {
            let _: Value = from_slice(input).map_err(CommandError::Deserializing)?;
            Ok(())
        }
    }
}

#[derive(Debug)]
pub struct ChangeExistingPin<'sc, 'pin> {
    pin_protocol: u8,
    shared_secret: &'sc ECDHSecret,
    current_pin: &'pin Pin,
    new_pin: &'pin Pin,
}

impl<'sc, 'pin> ChangeExistingPin<'sc, 'pin> {
    pub fn new(
        info: &AuthenticatorInfo,
        shared_secret: &'sc ECDHSecret,
        current_pin: &'pin Pin,
        new_pin: &'pin Pin,
    ) -> Result<Self, CommandError> {
        if info.pin_protocols.contains(&1) {
            Ok(ChangeExistingPin {
                pin_protocol: 1,
                shared_secret,
                current_pin,
                new_pin,
            })
        } else {
            Err(CommandError::UnsupportedPinProtocol)
        }
    }
}

impl<'sc, 'pin> ClientPINSubCommand for ChangeExistingPin<'sc, 'pin> {
    type Output = ();

    fn as_client_pin(&self) -> Result<ClientPIN, CommandError> {
        if self.new_pin.as_bytes().len() > 63 {
            return Err(CommandError::StatusCode(
                StatusCode::PinPolicyViolation,
                None,
            ));
        }
        // Padding the PIN with trailing zeros, according to spec
        let input: Vec<u8> = self
            .new_pin
            .as_bytes()
            .iter()
            .chain(std::iter::repeat(&0x00))
            .take(64)
            .cloned()
            .collect();

        let shared_secret = self.shared_secret.shared_secret();
        // AES256-CBC(sharedSecret, IV=0, newPin)
        let new_pin_enc =
            encrypt(shared_secret, input.as_ref()).map_err(|e| CryptoError::Backend(e))?;

        // AES256-CBC(sharedSecret, IV=0, LEFT(SHA-256(oldPin), 16))
        let input = self.current_pin.for_pin_token();
        let pin_hash_enc = encrypt(self.shared_secret.shared_secret(), input.as_ref())
            .map_err(|e| CryptoError::Backend(e))?;

        // LEFT(HMAC-SHA-265(sharedSecret, newPinEnc), 16)
        let pin_auth = PinToken(shared_secret.to_vec())
            .auth(&[new_pin_enc.as_slice(), pin_hash_enc.as_slice()].concat())
            .map_err(CommandError::Crypto)?;

        Ok(ClientPIN {
            pin_protocol: Some(self.pin_protocol),
            subcommand: PINSubcommand::ChangePIN,
            key_agreement: Some(self.shared_secret.my_public_key().clone()),
            new_pin_enc: Some(ByteBuf::from(new_pin_enc)),
            pin_hash_enc: Some(ByteBuf::from(pin_hash_enc)),
            pin_auth: Some(pin_auth),
        })
    }

    fn parse_response_payload(&self, input: &[u8]) -> Result<Self::Output, CommandError> {
        // Should be an empty response or a valid cbor-value (which we ignore)
        if input.is_empty() {
            Ok(())
        } else {
            let _: Value = from_slice(input).map_err(CommandError::Deserializing)?;
            Ok(())
        }
    }
}

impl<T> RequestCtap2 for T
where
    T: ClientPINSubCommand,
    T: fmt::Debug,
{
    type Output = <T as ClientPINSubCommand>::Output;

    fn command() -> Command {
        Command::ClientPin
    }

    fn wire_format<Dev>(&self, _dev: &mut Dev) -> Result<Vec<u8>, HIDError>
    where
        Dev: U2FDevice,
    {
        let client_pin = self.as_client_pin()?;
        let output = to_vec(&client_pin).map_err(CommandError::Serializing)?;
        trace!("client subcommmand: {:04X?}", &output);

        Ok(output)
    }

    fn handle_response_ctap2<Dev>(
        &self,
        _dev: &mut Dev,
        input: &[u8],
    ) -> Result<Self::Output, HIDError>
    where
        Dev: U2FDevice,
    {
        trace!("Client pin subcomand response:{:04X?}", &input);
        if input.is_empty() {
            return Err(CommandError::InputTooSmall.into());
        }

        let status: StatusCode = input[0].into();
        debug!("response status code: {:?}", status);
        if status.is_ok() {
            let res = <T as ClientPINSubCommand>::parse_response_payload(self, &input[1..])
                .map_err(HIDError::Command);
            res
        } else {
            let add_data = if input.len() > 1 {
                let data: Value = from_slice(&input[1..]).map_err(CommandError::Deserializing)?;
                Some(data)
            } else {
                None
            };
            Err(CommandError::StatusCode(status, add_data).into())
        }
    }
}

#[derive(Debug)]
pub struct KeyAgreement(COSEKey);

impl KeyAgreement {
    pub fn shared_secret(&self) -> Result<ECDHSecret, CommandError> {
        encapsulate(&self.0).map_err(|e| CommandError::Crypto(CryptoError::Backend(e)))
    }
}

#[derive(Debug, Deserialize)]
pub struct EncryptedPinToken(ByteBuf);

impl AsRef<[u8]> for EncryptedPinToken {
    fn as_ref(&self) -> &[u8] {
        self.0.as_ref()
    }
}

#[derive(Debug)]
pub struct PinToken(Vec<u8>);

impl PinToken {
    pub fn auth(&self, payload: &[u8]) -> Result<PinAuth, CryptoError> {
        let hmac = authenticate(self.as_ref(), payload)?;

        let mut out = [0u8; 16];
        out.copy_from_slice(&hmac[0..16]);

        Ok(PinAuth(out.to_vec()))
    }
}

impl AsRef<[u8]> for PinToken {
    fn as_ref(&self) -> &[u8] {
        self.0.as_ref()
    }
}

#[derive(Debug, Clone)]
#[cfg_attr(test, derive(Deserialize))]
pub struct PinAuth(Vec<u8>);

impl PinAuth {
    pub(crate) fn empty_pin_auth() -> Self {
        PinAuth(vec![])
    }
}

impl AsRef<[u8]> for PinAuth {
    fn as_ref(&self) -> &[u8] {
        &self.0
    }
}

impl Serialize for PinAuth {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serde_bytes::serialize(&self.0[..], serializer)
    }
}

#[derive(Clone)]
pub struct Pin(String);

impl fmt::Debug for Pin {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Pin(redacted)")
    }
}

impl Pin {
    pub fn new(value: &str) -> Pin {
        Pin(String::from(value))
    }

    pub fn for_pin_token(&self) -> PinAuth {
        let mut hasher = Sha256::new();
        hasher.update(&self.0.as_bytes());

        let mut output = [0u8; 16];
        let len = output.len();
        output.copy_from_slice(&hasher.finalize().as_slice()[..len]);

        PinAuth(output.to_vec())
    }

    pub fn as_bytes(&self) -> &[u8] {
        self.0.as_bytes()
    }
}

#[derive(Clone, Debug, Serialize)]
pub enum PinError {
    PinRequired,
    PinIsTooShort,
    PinIsTooLong(usize),
    InvalidKeyLen,
    InvalidPin(Option<u8>),
    PinAuthBlocked,
    PinBlocked,
    Backend(BackendError),
}

impl fmt::Display for PinError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            PinError::PinRequired => write!(f, "PinError: Pin required."),
            PinError::PinIsTooShort => write!(f, "PinError: pin is too short"),
            PinError::PinIsTooLong(len) => write!(f, "PinError: pin is too long ({})", len),
            PinError::InvalidKeyLen => write!(f, "PinError: invalid key len"),
            PinError::InvalidPin(ref e) => {
                let mut res = write!(f, "PinError: Invalid Pin.");
                if let Some(retries) = e {
                    res = write!(f, " Retries left: {:?}", retries)
                }
                res
            }
            PinError::PinAuthBlocked => write!(
                f,
                "PinError: Pin authentication blocked. Device needs power cycle."
            ),
            PinError::PinBlocked => write!(
                f,
                "PinError: No retries left. Pin blocked. Device needs reset."
            ),
            PinError::Backend(ref e) => write!(f, "PinError: Crypto backend error: {:?}", e),
        }
    }
}

impl StdErrorT for PinError {}

impl From<BackendError> for PinError {
    fn from(e: BackendError) -> Self {
        PinError::Backend(e)
    }
}