Skip to content

Commit

Permalink
Rewrite translated code to use the pcsc crate
Browse files Browse the repository at this point in the history
This commit contains a "big bang" refactor/rewrite which does the
following:

- Replaces all `SCard*` FFI calls with the `pcsc` crate, which provides
  a safe, portable PC/SC API across Windows, macOS, and Linux
- Refactors the `util` module into modules representing the various
  device functions and concepts, e.g. `certificate`, `key`, `mgm`
- Replaces all usage of `libc` with `std` functionality, and in many
  places rewriting functionality to use safe code.
- Removes `ykpiv_` from all function names, and `Piv*` from type names.

In 20/20 hindsight I wish I had done this commit more incrementally so
as to make it easier to review. Que sera sera.

However, realistically we need to test all functionality on the device
to ensure that it actually works. Going forward I would like to put
pretty much all of the current code behind an `untested` cargo feature,
and then remove it for each bit of functionality we test.
  • Loading branch information
tarcieri committed Nov 25, 2019
1 parent 96cd5d0 commit ebbf043
Show file tree
Hide file tree
Showing 23 changed files with 3,505 additions and 4,141 deletions.
40 changes: 37 additions & 3 deletions .github/workflows/rust.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,20 +21,51 @@ jobs:
toolchain: stable
override: true

- name: Install libpcsclite-dev
run: sudo apt-get install libpcsclite-dev

- name: Run cargo check
uses: actions-rs/cargo@v1
with:
command: check

# Need to install `libpscslite-dev` on Linux
linux:
name: Test Suite
strategy:
matrix:
toolchain:
- 1.39.0
- stable
runs-on: ubuntu-latest
steps:
- name: Checkout sources
uses: actions/checkout@v1

- name: Install stable toolchain
uses: actions-rs/toolchain@v1
with:
toolchain: ${{ matrix.toolchain }}
override: true

- name: Install libpcsclite-dev
run: sudo apt-get install libpcsclite-dev

- name: Run cargo test
uses: actions-rs/cargo@v1
env:
RUSTFLAGS: -D warnings
with:
command: test
args: --release

test:
name: Test Suite
strategy:
matrix:
platform:
- ubuntu-latest
- macos-latest
# TODO: support Windows after eliminating C legacy
# - windows-latest
- windows-latest
toolchain:
- 1.39.0
- stable
Expand Down Expand Up @@ -92,6 +123,9 @@ jobs:
toolchain: stable
override: true

- name: Install libpcsclite-dev
run: sudo apt-get install libpcsclite-dev

- name: Install clippy
run: rustup component add clippy

Expand Down
3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,9 @@ keywords = ["ccid", "ecdsa", "rsa", "piv", "yubikey"]
des = "0.3"
getrandom = "0.1"
hmac = "0.7"
libc = "0.2"
log = "0.4"
pbkdf2 = "0.3"
pcsc = "2"
sha-1 = "0.8"
subtle = "2"
zeroize = "1"
32 changes: 18 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ to store a number of RSA (2048/1024) and ECC (NIST P-256/P-384) private keys
with configurable access control policies. Both the signing (RSASSA/ECDSA) and
encryption (PKCS#1v1.5/ECIES) use cases are supported for either key type.

See [Yubico's guide to PIV-enabled YubiKeys][2] for more information
on which devices support PIV and the available functionality.

If you've been wanting to use Rust to sign and/or encrypt stuff using a
private key generated and stored on a Yubikey (with option PIN-based access),
this is the crate you've been after!
Expand All @@ -32,12 +35,12 @@ But it might be close?

## History

This library is a Rust translation of the [yubico-piv-tool][2] utility by
This library is a Rust translation of the [yubico-piv-tool][3] utility by
Yubico, which was originally written in C. It was mechanically translated
from C into Rust using [Corrode][3], and then subsequently heavily
from C into Rust using [Corrode][4], and then subsequently heavily
refactored into safer, more idiomatic Rust§.

Note that while this project started as a fork of a [Yubico][4] project,
Note that while this project started as a fork of a [Yubico][5] project,
this fork is **NOT** an official Yubico project and is in no way supported or
endorsed by Yubico.

Expand All @@ -59,15 +62,15 @@ USE AT YOUR OWN RISK!

## Code of Conduct

We abide by the [Contributor Covenant][5] and ask that you do as well.
We abide by the [Contributor Covenant][6] and ask that you do as well.

For more information, please see [CODE_OF_CONDUCT.md][6].
For more information, please see [CODE_OF_CONDUCT.md][7].

## License

**yubikey-piv.rs** is a fork of and originally a mechanical translation from
Yubico's [`yubico-piv-tool`][2], a C library/CLI program. The original library
was licensed under a [2-Clause BSD License][5], which this library inherits
Yubico's [`yubico-piv-tool`][3], a C library/CLI program. The original library
was licensed under a [2-Clause BSD License][8], which this library inherits
as a derived work.

Copyright (c) 2014-2019 Yubico AB, Tony Arcieri
Expand Down Expand Up @@ -101,7 +104,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Unless you explicitly state otherwise, any contribution intentionally
submitted for inclusion in the work by you shall be licensed under the
[2-Clause BSD License][5] as shown above, without any additional terms
[2-Clause BSD License][8] as shown above, without any additional terms
or conditions.

[//]: # (badges)
Expand All @@ -121,9 +124,10 @@ or conditions.
[//]: # (general links)

[1]: https://piv.idmanagement.gov/
[2]: https://github.com/Yubico/yubico-piv-tool/
[3]: https://github.com/jameysharp/corrode
[4]: https://www.yubico.com/
[5]: https://contributor-covenant.org/
[6]: https://github.com/tarcieri/yubikey-piv.rs/blob/develop/CODE_OF_CONDUCT.md
[7]: https://opensource.org/licenses/BSD-2-Clause
[2]: https://developers.yubico.com/PIV/Introduction/YubiKey_and_PIV.html
[3]: https://github.com/Yubico/yubico-piv-tool/
[4]: https://github.com/jameysharp/corrode
[5]: https://www.yubico.com/
[6]: https://contributor-covenant.org/
[7]: https://github.com/tarcieri/yubikey-piv.rs/blob/develop/CODE_OF_CONDUCT.md
[8]: https://opensource.org/licenses/BSD-2-Clause
12 changes: 8 additions & 4 deletions src/apdu.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,18 @@
//! Application Protocol Data Unit (APDU)
use crate::{error::Error, response::Response, transaction::Transaction, Buffer};
use std::fmt::{self, Debug};
use zeroize::{Zeroize, Zeroizing};

/// Size of a serialized APDU (5 byte header + 255 bytes data)
pub const APDU_SIZE: usize = 260;

/// Buffer type (self-zeroizing byte vector)
pub(crate) type Buffer = Zeroizing<Vec<u8>>;

/// Application Protocol Data Unit (APDU).
///
/// These messages are packets used to communicate with the YubiKey using the
/// Chip Card Interface Device (CCID) protocol.
#[derive(Clone)]
pub struct APDU {
pub(crate) struct APDU {
/// Instruction class - indicates the type of command, e.g. interindustry or proprietary
cla: u8,

Expand Down Expand Up @@ -81,6 +79,12 @@ impl APDU {
self
}

/// Transmit this APDU using the given card transaction
pub fn transmit(&self, txn: &Transaction<'_>, recv_len: usize) -> Result<Response, Error> {
let response_bytes = txn.transmit(&self.to_bytes(), recv_len)?;
Ok(Response::from_bytes(response_bytes))
}

/// Consume this APDU and return a self-zeroizing buffer
pub fn to_bytes(&self) -> Buffer {
let mut bytes = Vec::with_capacity(APDU_SIZE);
Expand Down
85 changes: 85 additions & 0 deletions src/cccid.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
//! Cardholder Capability Container (CCC) ID Support
// Adapted from yubico-piv-tool:
// <https://github.com/Yubico/yubico-piv-tool/>
//
// Copyright (c) 2014-2016 Yubico AB
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

use crate::{consts::*, error::Error, yubikey::YubiKey};
use getrandom::getrandom;

/// Cardholder Capability Container (CCC) Template
///
/// f0: Card Identifier
///
/// - 0xa000000116 == GSC-IS RID
/// - 0xff == Manufacturer ID (dummy)
/// - 0x02 == Card type (javaCard)
/// - next 14 bytes: card ID
const CCC_TMPL: &[u8] = &[
0xf0, 0x15, 0xa0, 0x00, 0x00, 0x01, 0x16, 0xff, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf1, 0x01, 0x21, 0xf2, 0x01, 0x21, 0xf3, 0x00, 0xf4,
0x01, 0x00, 0xf5, 0x01, 0x10, 0xf6, 0x00, 0xf7, 0x00, 0xfa, 0x00, 0xfb, 0x00, 0xfc, 0x00, 0xfd,
0x00, 0xfe, 0x00,
];

/// Cardholder Capability Container (CCC) Identifier
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct CCCID([u8; YKPIV_CCCID_SIZE]);

impl CCCID {
/// Generate a random CCCID
pub fn generate() -> Result<Self, Error> {
let mut id = [0u8; YKPIV_CCCID_SIZE];
getrandom(&mut id).map_err(|_| Error::RandomnessError)?;
Ok(CCCID(id))
}

/// Get Cardholder Capability Container (CCC) ID
pub fn get(yubikey: &mut YubiKey) -> Result<Self, Error> {
let txn = yubikey.begin_transaction()?;
let response = txn.fetch_object(YKPIV_OBJ_CAPABILITY)?;

if response.len() != CCC_TMPL.len() {
return Err(Error::GenericError);
}

let mut cccid = [0u8; YKPIV_CCCID_SIZE];
cccid.copy_from_slice(&response[CHUID_GUID_OFFS..(CHUID_GUID_OFFS + YKPIV_CCCID_SIZE)]);
Ok(CCCID(cccid))
}

/// Get Cardholder Capability Container (CCC) ID
pub fn set(&self, yubikey: &mut YubiKey) -> Result<(), Error> {
let mut buf = CCC_TMPL.to_vec();
buf[CCC_ID_OFFS..(CCC_ID_OFFS + self.0.len())].copy_from_slice(&self.0);

let txn = yubikey.begin_transaction()?;
txn.save_object(YKPIV_OBJ_CAPABILITY, &buf)
}
}
Loading

0 comments on commit ebbf043

Please sign in to comment.