libwebauthn 0.8.0

FIDO2 (WebAuthn) and FIDO U2F platform library for Linux written in Rust
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
use apdu::core::HandleError;
use apdu::{command, Command, Response};
use apdu_core;
use async_trait::async_trait;
use std::fmt;
use std::fmt::{Debug, Display, Formatter};
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::broadcast;
use tokio::sync::mpsc::{self, Sender};
#[allow(unused_imports)]
use tracing::{debug, instrument, trace, warn, Level};

use crate::pin::persistent_token::PersistentTokenStore;
use crate::proto::ctap1::apdu::{ApduRequest, ApduResponse};
use crate::proto::ctap2::cbor::{CborRequest, CborResponse};
use crate::proto::ctap2::Ctap2;
use crate::transport::channel::{
    AuthTokenData, Channel, ChannelSettings, ChannelStatus, Ctap2AuthTokenStore,
};
use crate::transport::device::SupportedProtocols;
use crate::transport::error::TransportError;
use crate::webauthn::Error;
use crate::UvUpdate;

use super::commands::{command_ctap_msg, command_get_response};

const SELECT_P1: u8 = 0x04;
const SELECT_P2: u8 = 0x00;
const FIDO2_AID: &[u8; 8] = b"\xa0\x00\x00\x06\x47\x2f\x00\x01";
const SW1_MORE_DATA: u8 = 0x61;

/// Returns true if `version` is a known FIDO2 version string returned by an
/// authenticator's FIDO AID SELECT response. See CTAP 2.2 section 11.3.1.
fn is_fido2_version(version: &[u8]) -> bool {
    matches!(
        version,
        b"FIDO_2_0" | b"FIDO_2_1_PRE" | b"FIDO_2_1" | b"FIDO_2_2"
    )
}

pub type CancelNfcOperation = ();

#[derive(thiserror::Error)]
pub enum NfcError {
    /// APDU error returned by the card.
    Apdu(#[from] apdu::Error),

    /// Unexpected error occurred on the device.
    Device(#[from] HandleError),
}

impl From<NfcError> for Error {
    fn from(input: NfcError) -> Self {
        trace!("{:?}", input);
        let output = match input {
            NfcError::Apdu(_apdu_error) => TransportError::InvalidFraming,
            NfcError::Device(_) => TransportError::ConnectionLost,
        };
        Error::Transport(output)
    }
}

impl Debug for NfcError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        Display::fmt(self, f)
    }
}

impl Display for NfcError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            NfcError::Apdu(e) => Display::fmt(e, f),
            NfcError::Device(e) => Display::fmt(e, f),
        }
    }
}

pub trait HandlerInCtx<Ctx> {
    /// Handles the APDU command in a specific context.
    /// Implementations must transmit the command to the card through a reader,
    /// then receive the response from them, returning length of the data written.
    fn handle_in_ctx(&mut self, ctx: Ctx, command: &[u8], response: &mut [u8])
        -> apdu_core::Result;
}

pub trait NfcBackend<Ctx>: HandlerInCtx<Ctx> + Display {}

#[derive(Debug, Clone)]
pub struct NfcChannelHandle {
    tx: Sender<CancelNfcOperation>,
}

impl NfcChannelHandle {
    pub async fn cancel_ongoing_operation(&self) {
        let _ = self.tx.send(()).await;
    }
}

pub struct NfcChannel<Ctx>
where
    Ctx: Copy + Sync,
{
    delegate: Box<dyn NfcBackend<Ctx> + Send + Sync>,
    auth_token_data: Option<AuthTokenData>,
    cred_mgmt_preview: bool,
    persistent_token_store: Option<Arc<dyn PersistentTokenStore>>,
    ux_update_sender: broadcast::Sender<UvUpdate>,
    handle: NfcChannelHandle,
    ctx: Ctx,
    apdu_response: Option<ApduResponse>,
    cbor_response: Option<CborResponse>,
    supported: SupportedProtocols,
    status: ChannelStatus,
}

impl<Ctx> Display for NfcChannel<Ctx>
where
    Ctx: Copy + Send + Sync,
{
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        write!(f, "{}", self.delegate)
    }
}

impl<Ctx> NfcChannel<Ctx>
where
    Ctx: fmt::Debug + Display + Copy + Send + Sync,
{
    pub fn new(
        delegate: Box<dyn NfcBackend<Ctx> + Send + Sync>,
        ctx: Ctx,
        settings: ChannelSettings,
    ) -> Self {
        let (ux_update_sender, _) = broadcast::channel(16);
        let (handle_tx, _handle_rx) = mpsc::channel(1);
        let handle = NfcChannelHandle { tx: handle_tx };
        NfcChannel {
            delegate,
            auth_token_data: None,
            cred_mgmt_preview: false,
            persistent_token_store: settings.persistent_token_store,
            ux_update_sender,
            handle,
            ctx,
            apdu_response: None,
            cbor_response: None,
            supported: SupportedProtocols {
                fido2: false,
                u2f: false,
            },
            status: ChannelStatus::Ready,
        }
    }

    pub fn get_handle(&self) -> NfcChannelHandle {
        self.handle.clone()
    }

    #[instrument(skip_all)]
    pub async fn wink(&mut self, _timeout: Duration) -> Result<bool, Error> {
        warn!("WINK capability is not supported");
        Ok(false)
    }

    pub async fn select_fido2(&mut self) -> Result<(), Error> {
        // Given legacy support for CTAP1/U2F, the client MUST determine the capabilities of the device at the selection stage.
        let command = command::select_file(SELECT_P1, SELECT_P2, FIDO2_AID);
        let response = self.handle(self.ctx, command)?;
        let mut u2f = false;
        let mut fido2 = false;
        if is_fido2_version(&response) {
            //     If the authenticator ONLY implements CTAP2, the device SHALL respond with "FIDO_2_0", or 0x4649444f5f325f30.
            //     Stricter CTAP 2.1+ authenticators may instead return "FIDO_2_1_PRE", "FIDO_2_1", or "FIDO_2_2".
            fido2 = true;
            // NOTE: Yubikeys seem to ignore this part of the specification and always return U2F_V2, even if U2F-NFC is disabled.
        } else if response == b"U2F_V2" {
            //     If the authenticator implements CTAP1/U2F, the version information SHALL be the string "U2F_V2", or 0x5532465f5632, to maintain backwards-compatibility with CTAP1/U2F-only clients.
            u2f = true;
            //     If the authenticator implements both CTAP1/U2F and CTAP2, the version information SHALL be the string "U2F_V2", or 0x5532465f5632, to maintain backwards-compatibility with CTAP1/U2F-only clients. CTAP2-aware clients MAY then issue a CTAP authenticatorGetInfo command to determine if the device supports CTAP2 or not.
            fido2 = self.ctap2_get_info().await.is_ok();
        }

        self.supported = SupportedProtocols { u2f, fido2 };

        Ok(())
    }

    fn handle_in_ctx(
        &mut self,
        ctx: Ctx,
        command_buf: &[u8],
        buf: &mut [u8],
    ) -> Result<usize, NfcError> {
        let res = self.delegate.handle_in_ctx(ctx, command_buf, buf)?;
        Ok(res)
    }

    /// Returns the full response, payload plus SW1/SW2 trailer, without interpreting the status.
    fn handle_raw<'a>(
        &'a mut self,
        ctx: Ctx,
        command: impl Into<Command<'a>>,
    ) -> Result<Vec<u8>, NfcError> {
        let command = command.into();
        let command_buf = Vec::from(command);

        let mut buf = [0u8; 1024];
        let mut rapdu = Vec::new();

        let len = self.handle_in_ctx(ctx, &command_buf, &mut buf)?;
        let resp_bytes = buf.get(..len).ok_or(HandleError::NotEnoughBuffer(len))?;
        let mut resp = Response::from(resp_bytes);

        let (mut sw1, mut sw2) = resp.trailer;
        rapdu.extend_from_slice(resp.payload);

        while sw1 == SW1_MORE_DATA {
            let get_response_cmd = command_get_response(0x00, 0x00, sw2);
            let get_response_buf = Vec::from(get_response_cmd);
            let len = self.handle_in_ctx(ctx, &get_response_buf, &mut buf)?;
            let resp_bytes = buf.get(..len).ok_or(HandleError::NotEnoughBuffer(len))?;
            resp = Response::from(resp_bytes);
            (sw1, sw2) = resp.trailer;
            rapdu.extend_from_slice(resp.payload);
        }

        rapdu.extend_from_slice(&[sw1, sw2]);
        Ok(rapdu)
    }

    pub fn handle<'a>(
        &'a mut self,
        ctx: Ctx,
        command: impl Into<Command<'a>>,
    ) -> Result<Vec<u8>, NfcError> {
        let rapdu = self.handle_raw(ctx, command)?;
        Result::from(Response::from(rapdu.as_slice()))
            .map(|p| p.to_vec())
            .map_err(|e| {
                trace!("map_err {:?}", e);
                apdu::Error::from(e).into()
            })
    }

    #[instrument(skip_all)]
    pub async fn blink_and_wait_for_user_presence(
        &mut self,
        _timeout: Duration,
    ) -> Result<bool, Error> {
        unimplemented!()
    }
}

#[async_trait]
impl<Ctx> Channel for NfcChannel<Ctx>
where
    Ctx: Copy + Send + Sync + fmt::Debug + Display,
{
    type UxUpdate = UvUpdate;

    async fn supported_protocols(&self) -> Result<SupportedProtocols, Error> {
        Ok(self.supported)
    }

    async fn status(&self) -> ChannelStatus {
        self.status
    }

    async fn close(&mut self) {}

    #[instrument(level = Level::DEBUG, skip_all)]
    async fn apdu_send(&mut self, request: &ApduRequest, _timeout: Duration) -> Result<(), Error> {
        let resp = self.handle_raw(self.ctx, request)?;
        trace!("apdu_send {:?}", resp);

        let apdu_response = ApduResponse::try_from(&resp)
            .or(Err(Error::Transport(TransportError::InvalidFraming)))?;
        self.apdu_response = Some(apdu_response);
        Ok(())
    }

    #[instrument(level = Level::DEBUG, skip_all)]
    async fn apdu_recv(&mut self, _timeout: Duration) -> Result<ApduResponse, Error> {
        self.apdu_response
            .take()
            .ok_or(Error::Transport(TransportError::InvalidFraming))
    }

    #[instrument(level = Level::DEBUG, skip_all)]
    async fn cbor_send(
        &mut self,
        request: &CborRequest,
        _timeout: std::time::Duration,
    ) -> Result<(), Error> {
        let data = &request.ctap_hid_data();
        let mut rest: &[u8] = data;

        while rest.len() > 250 {
            let (to_send, remaining) = rest.split_at(250);
            rest = remaining;
            let ctap_msg = command_ctap_msg(true, to_send);
            let resp = self.handle(self.ctx, ctap_msg)?;
            trace!("cbor_send has_more {:?} {:?}", to_send, resp);
        }

        let ctap_msg = command_ctap_msg(false, rest);
        let resp = self.handle(self.ctx, ctap_msg)?;
        trace!("cbor_send {:?} {:?}", rest, resp);

        // FIXME check for SW_UPDATE?

        // let mut rapdu_buf = [0; pcsc::MAX_BUFFER_SIZE_EXTENDED];
        // let (mut resp, mut sw1, mut sw2) = self.card
        //     .chain_apdus(0x80, 0x10, 0x80, 0x00, data, &mut rapdu_buf)
        //     .expect("APDU exchange failed");

        // loop {
        //     while (sw1, sw2) == SW_UPDATE {
        //         // ka_status = STATUS(resp[0])
        //         // if on_keepalive and last_ka != ka_status:
        //         //     last_ka = ka_status
        //         //     on_keepalive(ka_status)
        //         // NFCCTAP_GETRESPONSE

        //         (resp, sw1, sw2) = self.card
        //             .chain_apdus(0x80, 0x11, 0x00, 0x00, &[], &mut rapdu_buf).expect("APDU chained exchange failed");
        //         debug!("Error {:?} {:?}", sw1, sw2);
        //     }

        //     if (sw1, sw2) != SW_SUCCESS {
        //         return Err(Error::Transport(TransportError::InvalidFraming));
        //     }

        let cbor_response = CborResponse::try_from(&resp)
            .or(Err(Error::Transport(TransportError::InvalidFraming)))?;
        self.cbor_response = Some(cbor_response);
        Ok(())
    }

    #[instrument(level = Level::DEBUG, skip_all)]
    async fn cbor_recv(&mut self, _timeout: std::time::Duration) -> Result<CborResponse, Error> {
        self.cbor_response
            .take()
            .ok_or(Error::Transport(TransportError::InvalidFraming))
    }

    fn get_ux_update_sender(&self) -> &broadcast::Sender<UvUpdate> {
        &self.ux_update_sender
    }
}

impl<Ctx> Ctap2AuthTokenStore for NfcChannel<Ctx>
where
    Ctx: Copy + Send + Sync,
{
    fn store_auth_data(&mut self, auth_token_data: AuthTokenData) {
        self.auth_token_data = Some(auth_token_data);
    }

    fn get_auth_data(&self) -> Option<&AuthTokenData> {
        self.auth_token_data.as_ref()
    }

    fn clear_uv_auth_token_store(&mut self) {
        self.auth_token_data = None;
    }

    fn set_cred_mgmt_preview(&mut self, uses_preview: bool) {
        self.cred_mgmt_preview = uses_preview;
    }

    fn cred_mgmt_preview(&self) -> bool {
        self.cred_mgmt_preview
    }

    fn persistent_token_store(&self) -> Option<Arc<dyn PersistentTokenStore>> {
        self.persistent_token_store.clone()
    }
}

#[cfg(test)]
mod tests {
    use std::fmt::{Display, Formatter};
    use std::time::Duration;

    use super::{is_fido2_version, ChannelSettings, HandlerInCtx, NfcBackend, NfcChannel};
    use crate::proto::ctap1::apdu::{ApduRequest, ApduResponseStatus};
    use crate::proto::CtapError;
    use crate::transport::channel::Channel;

    #[test]
    fn fido2_versions_are_recognised() {
        assert!(is_fido2_version(b"FIDO_2_0"));
        assert!(is_fido2_version(b"FIDO_2_1_PRE"));
        assert!(is_fido2_version(b"FIDO_2_1"));
        assert!(is_fido2_version(b"FIDO_2_2"));
    }

    #[test]
    fn u2f_v2_is_not_classified_as_fido2() {
        // U2F_V2 is handled by a separate fallback path that probes via
        // ctap2_get_info, so the version-string classifier must report false.
        assert!(!is_fido2_version(b"U2F_V2"));
    }

    #[test]
    fn unknown_versions_are_rejected() {
        assert!(!is_fido2_version(b""));
        assert!(!is_fido2_version(b"FIDO_2"));
        assert!(!is_fido2_version(b"FIDO_2_3"));
        assert!(!is_fido2_version(b"FIDO_3_0"));
        assert!(!is_fido2_version(b"fido_2_0"));
        assert!(!is_fido2_version(b"FIDO_2_0\0"));
    }

    /// Backend that echoes a fixed APDU response regardless of the command.
    struct FixedResponseBackend {
        response: Vec<u8>,
    }

    impl Display for FixedResponseBackend {
        fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
            write!(f, "FixedResponseBackend")
        }
    }

    impl HandlerInCtx<u8> for FixedResponseBackend {
        fn handle_in_ctx(
            &mut self,
            _ctx: u8,
            _command: &[u8],
            response: &mut [u8],
        ) -> apdu_core::Result {
            let n = self.response.len();
            response[..n].copy_from_slice(&self.response);
            Ok(n)
        }
    }

    impl NfcBackend<u8> for FixedResponseBackend {}

    #[tokio::test]
    async fn u2f_wrong_data_status_word_is_preserved() {
        // SW_WRONG_DATA (0x6A80) must surface as NoCredentials, not InvalidFraming.
        let backend = FixedResponseBackend {
            response: vec![0x6A, 0x80],
        };
        let mut channel = NfcChannel::new(Box::new(backend), 0u8, ChannelSettings::default());
        let request = ApduRequest::new(0x02, 0x00, 0x00, None, None);

        channel
            .apdu_send(&request, Duration::from_secs(1))
            .await
            .expect("non-success SW must not collapse to InvalidFraming");
        let response = channel.apdu_recv(Duration::from_secs(1)).await.unwrap();

        assert_eq!(
            response.status().unwrap(),
            ApduResponseStatus::InvalidKeyHandle
        );
        assert_eq!(
            CtapError::from(response.status().unwrap()),
            CtapError::NoCredentials
        );
    }
}