yubikey 0.8.0

Pure Rust cross-platform host-side driver for YubiKey devices from Yubico with support for hardware-backed public-key decryption and digital signatures using the Personal Identity Verification (PIV) application. Supports RSA (1024/2048) or ECC (NIST P-256/P-384) algorithms e.g, PKCS#1v1.5, ECDSA
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
//! YubiKey PC/SC transactions

use crate::{
    apdu::Response,
    apdu::{Apdu, Ins, StatusWords},
    consts::{CB_BUF_MAX, CB_OBJ_MAX},
    error::{Error, Result},
    otp,
    piv::{self, AlgorithmId, SlotId},
    serialization::*,
    yubikey::*,
    Buffer, ObjectId,
};
use log::{error, trace};
use zeroize::Zeroizing;

#[cfg(feature = "untested")]
use crate::mgm::{MgmKey, DES_LEN_3DES};

const CB_PIN_MAX: usize = 8;

#[cfg(feature = "untested")]
pub(crate) enum ChangeRefAction {
    ChangePin,
    ChangePuk,
    UnblockPin,
}

/// Exclusive transaction with the YubiKey's PC/SC card.
pub(crate) struct Transaction<'tx> {
    inner: pcsc::Transaction<'tx>,
}

impl<'tx> Transaction<'tx> {
    /// Create a new transaction with the given card.
    pub fn new(card: &'tx mut pcsc::Card) -> Result<Self> {
        Ok(Transaction {
            inner: card.transaction()?,
        })
    }

    /// Transmit a single serialized APDU to the card this transaction is open
    /// with and receive a response.
    ///
    /// This is a wrapper for the raw `SCardTransmit` function and operates on
    /// single APDU messages at a time. For larger messages that need to be
    /// split into multiple APDUs, use the [`Transaction::transfer_data`]
    /// method instead.
    pub fn transmit(&self, send_buffer: &[u8], recv_len: usize) -> Result<Vec<u8>> {
        trace!(">>> {:?}", send_buffer);

        let mut recv_buffer = vec![0u8; recv_len];

        let len = self
            .inner
            .transmit(send_buffer, recv_buffer.as_mut())?
            .len();

        recv_buffer.truncate(len);
        Ok(recv_buffer)
    }

    /// Select application.
    pub fn select_application(&self) -> Result<()> {
        let response = Apdu::new(Ins::SelectApplication)
            .p1(0x04)
            .data(piv::APPLET_ID)
            .transmit(self, 0xFF)
            .map_err(|e| {
                error!("failed communicating with card: '{}'", e);
                e
            })?;

        if !response.is_success() {
            error!(
                "failed selecting application: {:04x}",
                response.status_words().code()
            );
            return Err(match response.status_words() {
                StatusWords::NotFoundError => Error::AppletNotFound {
                    applet_name: piv::APPLET_NAME,
                },
                _ => Error::GenericError,
            });
        }

        Ok(())
    }

    /// Get the version of the PIV application installed on the YubiKey.
    pub fn get_version(&self) -> Result<Version> {
        // get version from device
        let response = Apdu::new(Ins::GetVersion).transmit(self, 261)?;

        if !response.is_success() {
            return Err(Error::GenericError);
        }

        Ok(response.data()[..3].try_into().map(Version::new)?)
    }

    /// Get YubiKey device serial number.
    pub fn get_serial(&self, version: Version) -> Result<Serial> {
        match version.major {
            // YK4 requires switching to the YK applet to retrieve the serial
            4 => {
                let sw = Apdu::new(Ins::SelectApplication)
                    .p1(0x04)
                    .data(otp::APPLET_ID)
                    .transmit(self, 0xFF)?
                    .status_words();

                if !sw.is_success() {
                    error!("failed selecting yk application: {:04x}", sw.code());
                    return Err(match sw {
                        StatusWords::NotFoundError => Error::AppletNotFound {
                            applet_name: otp::APPLET_NAME,
                        },
                        _ => Error::GenericError,
                    });
                }

                let response = Apdu::new(0x01).p1(0x10).transmit(self, 0xFF)?;

                if !response.is_success() {
                    // TODO(tarcieri): still reselect the PIV applet in this case?
                    error!(
                        "failed retrieving serial number: {:04x}",
                        response.status_words().code()
                    );
                    return Err(Error::GenericError);
                }

                // reselect the PIV applet
                let sw = Apdu::new(Ins::SelectApplication)
                    .p1(0x04)
                    .data(piv::APPLET_ID)
                    .transmit(self, 0xFF)?
                    .status_words();

                if !sw.is_success() {
                    error!("failed selecting application: {:04x}", sw.code());
                    return Err(match sw {
                        StatusWords::NotFoundError => Error::AppletNotFound {
                            applet_name: piv::APPLET_NAME,
                        },
                        _ => Error::GenericError,
                    });
                }

                response.data().try_into()
            }

            // YK5 implements getting the serial as a PIV applet command (0xf8)
            5 => {
                let response = Apdu::new(Ins::GetSerial).transmit(self, 0xFF)?;

                if !response.is_success() {
                    error!(
                        "failed retrieving serial number: {:04x}",
                        response.status_words().code()
                    );
                    return Err(Error::GenericError);
                }

                response.data().try_into()
            }

            // Other versions unsupported
            _ => Err(Error::NotSupported),
        }
    }

    /// Verify device PIN.
    pub fn verify_pin(&self, pin: &[u8]) -> Result<()> {
        if pin.len() > CB_PIN_MAX {
            return Err(Error::SizeError);
        }

        let mut query = Apdu::new(Ins::Verify);
        query.params(0x00, 0x80);

        // Empty pin means we are querying the number of retries. We set no data in this
        // case; if we instead sent [0xff; CB_PIN_MAX] it would count as an attempt and
        // decrease the retry counter.
        if !pin.is_empty() {
            let mut data = Zeroizing::new([0xff; CB_PIN_MAX]);
            data[0..pin.len()].copy_from_slice(pin);
            query.data(data.as_ref());
        }

        let response = query.transmit(self, 261)?;

        match response.status_words() {
            StatusWords::Success => Ok(()),
            StatusWords::AuthBlockedError => Err(Error::WrongPin { tries: 0 }),
            StatusWords::VerifyFailError { tries } => Err(Error::WrongPin { tries }),
            _ => Err(Error::GenericError),
        }
    }

    /// Change the PIN.
    #[cfg(feature = "untested")]
    pub fn change_ref(
        &self,
        action: ChangeRefAction,
        current_pin: &[u8],
        new_pin: &[u8],
    ) -> Result<()> {
        if current_pin.len() > CB_PIN_MAX || new_pin.len() > CB_PIN_MAX {
            return Err(Error::SizeError);
        }

        const PIN: u8 = 0x80;
        const PUK: u8 = 0x81;

        let templ = match action {
            ChangeRefAction::ChangePin => [0, Ins::ChangeReference.code(), 0, PIN],
            ChangeRefAction::ChangePuk => [0, Ins::ChangeReference.code(), 0, PUK],
            ChangeRefAction::UnblockPin => [0, Ins::ResetRetry.code(), 0, PIN],
        };

        let mut indata = Zeroizing::new([0xff; CB_PIN_MAX * 2]);
        indata[0..current_pin.len()].copy_from_slice(current_pin);
        indata[CB_PIN_MAX..CB_PIN_MAX + new_pin.len()].copy_from_slice(new_pin);

        let status_words = self
            .transfer_data(&templ, indata.as_ref(), 0xFF)?
            .status_words();

        match status_words {
            StatusWords::Success => Ok(()),
            StatusWords::AuthBlockedError => Err(Error::PinLocked),
            StatusWords::VerifyFailError { tries } => Err(Error::WrongPin { tries }),
            _ => {
                error!(
                    "failed changing pin, token response code: {:x}.",
                    status_words.code()
                );
                Err(Error::GenericError)
            }
        }
    }

    /// Set the management key (MGM).
    #[cfg(feature = "untested")]
    pub fn set_mgm_key(&self, new_key: &MgmKey, require_touch: bool) -> Result<()> {
        let p2 = if require_touch { 0xfe } else { 0xff };

        let mut data = [0u8; DES_LEN_3DES + 3];
        data[0] = ALGO_3DES;
        data[1] = KEY_CARDMGM;
        data[2] = DES_LEN_3DES as u8;
        data[3..3 + DES_LEN_3DES].copy_from_slice(new_key.as_ref());

        let status_words = Apdu::new(Ins::SetMgmKey)
            .params(0xff, p2)
            .data(data)
            .transmit(self, 261)?
            .status_words();

        if !status_words.is_success() {
            return Err(Error::GenericError);
        }

        Ok(())
    }

    /// Perform a YubiKey operation which requires authentication.
    ///
    /// This is the common backend for all public key encryption and signing
    /// operations.
    // TODO(tarcieri): refactor this to be less gross/coupled.
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn authenticated_command(
        &self,
        sign_in: &[u8],
        algorithm: AlgorithmId,
        key: SlotId,
        decipher: bool,
    ) -> Result<Buffer> {
        let in_len = sign_in.len();
        let mut indata = [0u8; 1024];
        let templ = [0, Ins::Authenticate.code(), algorithm.into(), key.into()];

        match algorithm {
            AlgorithmId::Rsa1024 | AlgorithmId::Rsa2048 => {
                let key_len = if let AlgorithmId::Rsa1024 = algorithm {
                    128
                } else {
                    256
                };

                if in_len != key_len {
                    return Err(Error::SizeError);
                }
            }
            AlgorithmId::EccP256 | AlgorithmId::EccP384 => {
                let key_len = if let AlgorithmId::EccP256 = algorithm {
                    32
                } else {
                    48
                };

                if (!decipher && (in_len > key_len)) || (decipher && (in_len != (key_len * 2) + 1))
                {
                    return Err(Error::SizeError);
                }
            }
        }

        let bytes = if in_len < 0x80 {
            1
        } else if in_len < 0xff {
            2
        } else {
            3
        };

        let offset = Tlv::write_as(&mut indata, 0x7c, in_len + bytes + 3, |buf| {
            assert_eq!(Tlv::write(buf, 0x82, &[]).expect("large enough"), 2);
            assert_eq!(
                Tlv::write(
                    &mut buf[2..],
                    match (algorithm, decipher) {
                        (AlgorithmId::EccP256, true) | (AlgorithmId::EccP384, true) => 0x85,
                        _ => 0x81,
                    },
                    sign_in
                )
                .expect("large enough"),
                1 + bytes + in_len
            );
        })?;

        let response = self
            .transfer_data(&templ, &indata[..offset], 1024)
            .map_err(|e| {
                error!("sign command failed to communicate: {}", e);
                e
            })?;

        if !response.is_success() {
            error!("failed sign command with code {:x}", response.code());

            if response.status_words() == StatusWords::SecurityStatusError {
                return Err(Error::AuthenticationError);
            } else {
                return Err(Error::GenericError);
            }
        }

        let (_, outer_tlv) = Tlv::parse(response.data())?;

        // skip the first 7c tag
        if outer_tlv.tag != 0x7c {
            error!("failed parsing signature reply (0x7c byte)");
            return Err(Error::ParseError);
        }

        let (_, inner_tlv) = Tlv::parse(outer_tlv.value)?;

        // skip the 82 tag
        if inner_tlv.tag != 0x82 {
            error!("failed parsing signature reply (0x82 byte)");
            return Err(Error::ParseError);
        }

        Ok(Buffer::new(inner_tlv.value.into()))
    }

    /// Send/receive large amounts of data to/from the YubiKey, splitting long
    /// messages into smaller APDU-sized messages (using the provided APDU
    /// template to construct them), and then sending those via
    /// [`Transaction::transmit`].
    pub fn transfer_data(&self, templ: &[u8], in_data: &[u8], max_out: usize) -> Result<Response> {
        let mut in_offset = 0;
        let mut out_data = vec![];
        let mut sw;

        loop {
            let mut this_size = 0xff;

            let cla = if in_offset + 0xff < in_data.len() {
                0x10
            } else {
                this_size = in_data.len() - in_offset;
                templ[0]
            };

            trace!("going to send {} bytes in this go", this_size);

            let response = Apdu::new(templ[1])
                .cla(cla)
                .params(templ[2], templ[3])
                .data(&in_data[in_offset..(in_offset + this_size)])
                .transmit(self, 261)?;

            sw = response.status_words();

            match sw {
                StatusWords::Success | StatusWords::BytesRemaining { .. } => (),
                // TODO(tarcieri): is this really OK?
                _ => return Ok(Response::new(sw, out_data)),
            }

            if !out_data.is_empty() && (out_data.len() - response.data().len() > max_out) {
                error!(
                    "output buffer too small: wanted to write {}, max was {}",
                    out_data.len() - response.data().len(),
                    max_out
                );

                return Err(Error::SizeError);
            }

            out_data.extend_from_slice(&response.data()[..response.data().len()]);

            in_offset += this_size;
            if in_offset >= in_data.len() {
                break;
            }
        }

        while let StatusWords::BytesRemaining { len } = sw {
            trace!("The card indicates there is {} bytes more data for us", len);

            let response = Apdu::new(Ins::GetResponseApdu).transmit(self, 261)?;
            sw = response.status_words();

            match sw {
                StatusWords::Success | StatusWords::BytesRemaining { .. } => (),
                _ => return Ok(Response::new(sw, vec![])),
            }

            if out_data.len() + response.data().len() > max_out {
                error!(
                    "output buffer too small: wanted to write {}, max was {}",
                    out_data.len() + response.data().len(),
                    max_out
                );

                return Err(Error::SizeError);
            }

            out_data.extend_from_slice(&response.data()[..response.data().len()]);
        }

        Ok(Response::new(sw, out_data))
    }

    /// Fetch an object.
    pub fn fetch_object(&self, object_id: ObjectId) -> Result<Buffer> {
        let mut indata = [0u8; 5];
        let templ = [0, Ins::GetData.code(), 0x3f, 0xff];

        let mut inlen = indata.len();
        let indata_remaining = set_object(object_id, &mut indata);
        inlen -= indata_remaining.len();

        let response = self.transfer_data(&templ, &indata[..inlen], CB_BUF_MAX)?;

        if !response.is_success() {
            if response.status_words() == StatusWords::NotFoundError {
                return Err(Error::NotFound);
            } else {
                return Err(Error::GenericError);
            }
        }

        let (remaining, tlv) = Tlv::parse(response.data())?;

        if !remaining.is_empty() {
            error!(
                "invalid length indicated in object: total len is {} but indicated length is {}",
                tlv.value.len() + remaining.len(),
                tlv.value.len()
            );

            return Err(Error::SizeError);
        }

        Ok(Zeroizing::new(tlv.value.to_vec()))
    }

    /// Save an object.
    pub fn save_object(&self, object_id: ObjectId, indata: &[u8]) -> Result<()> {
        let templ = [0, Ins::PutData.code(), 0x3f, 0xff];

        // TODO(tarcieri): replace with vector
        let mut data = [0u8; CB_BUF_MAX];

        if indata.len() > CB_OBJ_MAX {
            return Err(Error::SizeError);
        }

        let mut len = data.len();
        let mut data_remaining = set_object(object_id, &mut data);

        let offset = Tlv::write(data_remaining, 0x53, indata)?;
        data_remaining = &mut data_remaining[offset..];
        len -= data_remaining.len();

        let status_words = self
            .transfer_data(&templ, &data[..len], 255)?
            .status_words();

        match status_words {
            StatusWords::Success => Ok(()),
            StatusWords::SecurityStatusError => Err(Error::AuthenticationError),
            _ => Err(Error::GenericError),
        }
    }
}