Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update the yubikey crate #190

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
277 changes: 77 additions & 200 deletions Cargo.lock

Large diffs are not rendered by default.

8 changes: 4 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,20 +26,20 @@ age-core = "0.10"
age-plugin = "0.5"
base64 = "0.21"
bech32 = "0.9"
chrono = "0.4"
console = { version = "0.15", default-features = false }
dialoguer = { version = "0.11", default-features = false, features = ["password"] }
env_logger = "0.10"
gumdrop = "0.8"
hex = "0.4"
log = "0.4"
p256 = { version = "0.13", features = ["ecdh"] }
p256 = { version = "0.13", features = ["ecdh", "pkcs8"] }
pcsc = "2.4"
rand = "0.8"
sha2 = "0.10"
which = "5"
x509 = "0.2"
x509-parser = "0.14"
yubikey = { version = "=0.8.0-pre.0", features = ["untested"] }
x509-cert = "0.2"
yubikey = { version = "0.8", features = ["untested"] }

# Translations
i18n-embed = { version = "0.15", features = ["desktop-requester", "fluent-system"] }
Expand Down
2 changes: 2 additions & 0 deletions i18n/en-US/age_plugin_yubikey.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,8 @@ plugin-err-pin-required = A PIN is required for {-yubikey} with serial {$yub

## Errors

err-build = Failed to build identity: {$err}

err-mgmt-key-auth = Failed to authenticate with the PIN-protected management key.
rec-mgmt-key-auth =
Check whether your management key is using the TDES algorithm.
Expand Down
64 changes: 42 additions & 22 deletions src/builder.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use std::time::SystemTime;

use dialoguer::Password;
use rand::{rngs::OsRng, RngCore};
use x509::RelativeDistinguishedName;
use x509_cert::{der::referenced::OwnedToRef, serial_number::SerialNumber, time::Validity};
use yubikey::{
certificate::Certificate,
piv::{generate as yubikey_generate, AlgorithmId, RetiredSlotId, SlotId},
Expand All @@ -12,7 +14,7 @@ use crate::{
fl,
key::{self, Stub},
p256::Recipient,
util::{Metadata, POLICY_EXTENSION_OID},
util::{Metadata, UsagePolicies},
BINARY_NAME, USABLE_SLOTS,
};

Expand Down Expand Up @@ -85,8 +87,10 @@ impl IdentityBuilder {
}
};

let pin_policy = self.pin_policy.unwrap_or(DEFAULT_PIN_POLICY);
let touch_policy = self.touch_policy.unwrap_or(DEFAULT_TOUCH_POLICY);
let policies = UsagePolicies {
pin: self.pin_policy.unwrap_or(DEFAULT_PIN_POLICY),
touch: self.touch_policy.unwrap_or(DEFAULT_TOUCH_POLICY),
};

eprintln!("{}", fl!("builder-gen-key"));

Expand All @@ -100,25 +104,34 @@ impl IdentityBuilder {
yubikey,
SlotId::Retired(slot),
AlgorithmId::EccP256,
pin_policy,
touch_policy,
policies.pin,
policies.touch,
)?;

let recipient = Recipient::from_spki(&generated).expect("YubiKey generates a valid pubkey");
// TODO: https://github.com/RustCrypto/formats/issues/1488
// Document `OwnedToRef` usage in top-level docs somewhere (either of the
// crate, or of `SubjectPublicKeyInfoOwned` so we know how to get a reference).
let recipient = Recipient::from_spki(generated.owned_to_ref())
.expect("YubiKey generates a valid pubkey");
let stub = Stub::new(yubikey.serial(), slot, &recipient);

eprintln!();
eprintln!("{}", fl!("builder-gen-cert"));

// Pick a random serial for the new self-signed certificate.
let mut serial = [0; 20];
OsRng.fill_bytes(&mut serial);
let serial = {
// TODO: https://github.com/RustCrypto/formats/pull/1270
// adds `SerialNumber::generate`; use it when available.
let mut serial = [0; 20];
OsRng.fill_bytes(&mut serial);
SerialNumber::new(&serial).expect("valid")
};

let name = self
.name
.unwrap_or(format!("age identity {}", hex::encode(stub.tag)));

if let PinPolicy::Always = pin_policy {
if let PinPolicy::Always = policies.pin {
// We need to enter the PIN again.
let pin = Password::new()
.with_prompt(fl!(
Expand All @@ -129,27 +142,34 @@ impl IdentityBuilder {
.interact()?;
yubikey.verify_pin(pin.as_bytes())?;
}
if let TouchPolicy::Never = touch_policy {
if let TouchPolicy::Never = policies.touch {
// No need to touch YubiKey
} else {
eprintln!("{}", fl!("builder-touch-yk"));
}

let cert = Certificate::generate_self_signed(
// TODO: https://github.com/iqlusioninc/yubikey.rs/issues/581
let cert = Certificate::generate_self_signed::<_, p256::NistP256>(
yubikey,
SlotId::Retired(slot),
serial,
None,
&[
RelativeDistinguishedName::organization(BINARY_NAME),
RelativeDistinguishedName::organizational_unit(env!("CARGO_PKG_VERSION")),
RelativeDistinguishedName::common_name(&name),
],
Validity {
not_before: SystemTime::now().try_into().map_err(Error::Build)?,
not_after: x509_cert::time::Time::INFINITY,
},
// TODO: https://github.com/RustCrypto/formats/issues/1489
format!("O={BINARY_NAME},OU={},CN={name}", env!("CARGO_PKG_VERSION"))
.parse()
.map_err(Error::Build)?,
generated,
&[x509::Extension::regular(
POLICY_EXTENSION_OID,
&[pin_policy.into(), touch_policy.into()],
)],
// TODO: https://github.com/RustCrypto/formats/issues/1490
// TODO: https://github.com/iqlusioninc/yubikey.rs/issues/580
|builder| {
builder.add_extension(&policies).map_err(|e| match e {
x509_cert::builder::Error::Asn1(error) => error,
e => panic!("Cannot handle this error with the yubikey 0.8 crate: {e}"),
})
},
)?;

let metadata = Metadata::extract(yubikey, slot, &cert, false).unwrap();
Expand Down
4 changes: 4 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use std::fmt;
use std::io;

use x509_cert::der;
use yubikey::{piv::RetiredSlotId, Serial};

use crate::util::slot_to_ui;
Expand All @@ -14,6 +16,7 @@ macro_rules! wlnfl {
}

pub enum Error {
Build(der::Error),
CustomManagementKey,
Dialog(dialoguer::Error),
InvalidFlagCommand(String, String),
Expand Down Expand Up @@ -63,6 +66,7 @@ impl fmt::Debug for Error {
const CHANGE_MGMT_KEY_URL: &str = "https://developers.yubico.com/yubikey-manager/";

match self {
Error::Build(e) => wlnfl!(f, "err-build", err = e.to_string())?,
Error::CustomManagementKey => {
wlnfl!(f, "err-custom-mgmt-key")?;
wlnfl!(
Expand Down
15 changes: 6 additions & 9 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -399,15 +399,12 @@ fn main() -> Result<(), Error> {
.map(|(key, _, recipient)| {
recipient.as_ref().map(|_| {
// Cache the details we need to display to the user.
let (_, cert) =
x509_parser::parse_x509_certificate(key.certificate().as_ref())
.unwrap();
let (name, _) = util::extract_name(&cert, true).unwrap();
let created = cert
.validity()
.not_before
.to_rfc2822()
.unwrap_or_else(|e| format!("Invalid date: {e}"));
let cert = &key.certificate().cert;
let (name, _) = util::extract_name(cert, true).unwrap();
let created = chrono::DateTime::<chrono::Utc>::from(
cert.tbs_certificate.validity.not_before.to_system_time(),
)
.to_rfc2822();

format!("{name}, created: {created}")
})
Expand Down
15 changes: 8 additions & 7 deletions src/p256.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
use bech32::{ToBase32, Variant};
use p256::elliptic_curve::sec1::{FromEncodedPoint, ToEncodedPoint};
use p256::{
elliptic_curve::sec1::{FromEncodedPoint, ToEncodedPoint},
pkcs8::SubjectPublicKeyInfoRef,
};
use sha2::{Digest, Sha256};
use yubikey::{certificate::PublicKeyInfo, Certificate};
use yubikey::Certificate;

use std::fmt;

Expand Down Expand Up @@ -48,11 +51,9 @@ impl Recipient {
Self::from_spki(cert.subject_pki())
}

pub(crate) fn from_spki(spki: &PublicKeyInfo) -> Option<Self> {
match spki {
PublicKeyInfo::EcP256(pubkey) => Self::from_encoded(pubkey),
_ => None,
}
pub(crate) fn from_spki(spki: SubjectPublicKeyInfoRef<'_>) -> Option<Self> {
// TODO: https://github.com/RustCrypto/formats/issues/1604
p256::PublicKey::try_from(spki).ok().map(Recipient)
}

/// Attempts to parse a valid YubiKey recipient from its SEC-1 encoding.
Expand Down
Loading
Loading