From 8ba43f8c6b8d871c6b35733ebbb97535d3ac93f0 Mon Sep 17 00:00:00 2001 From: Hatter Jiang Date: Sun, 9 Jun 2024 16:52:53 +0800 Subject: [PATCH] feat: ecdh support p384 --- Cargo.lock | 2 +- Cargo.toml | 2 +- src/cmd_pivdecrypt.rs | 2 +- src/cmd_pivecdh.rs | 147 +++++++++++++++++++++++++++++------------- 4 files changed, 104 insertions(+), 49 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 184a444..84798bf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -368,7 +368,7 @@ dependencies = [ [[package]] name = "card-cli" -version = "1.9.1" +version = "1.9.2" dependencies = [ "authenticator", "base64 0.21.7", diff --git a/Cargo.toml b/Cargo.toml index da6f8c0..ff85b3f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "card-cli" -version = "1.9.1" +version = "1.9.2" authors = ["Hatter Jiang "] edition = "2018" diff --git a/src/cmd_pivdecrypt.rs b/src/cmd_pivdecrypt.rs index 784b8b6..b55826c 100644 --- a/src/cmd_pivdecrypt.rs +++ b/src/cmd_pivdecrypt.rs @@ -12,7 +12,7 @@ impl Command for CommandImpl { fn name(&self) -> &str { "piv-decrypt" } fn subcommand<'a>(&self) -> App<'a, 'a> { - SubCommand::with_name(self.name()).about("PIV Decrypt subcommand (RSA)") + SubCommand::with_name(self.name()).about("PIV Decrypt(RSA) subcommand") .arg(Arg::with_name("pin").short("p").long("pin").takes_value(true).default_value("123456").help("OpenPGP card user pin")) .arg(Arg::with_name("encrypted-data").long("encrypted-data").takes_value(true).help("Encrypted data")) .arg(Arg::with_name("json").long("json").help("JSON output")) diff --git a/src/cmd_pivecdh.rs b/src/cmd_pivecdh.rs index 46dfc4e..8326eb6 100644 --- a/src/cmd_pivecdh.rs +++ b/src/cmd_pivecdh.rs @@ -1,17 +1,18 @@ use std::collections::BTreeMap; use std::fs; -use std::str::FromStr; use clap::{App, Arg, ArgMatches, SubCommand}; -use p256::{EncodedPoint, PublicKey}; -use p256::ecdh::EphemeralSecret; -use p256::elliptic_curve::sec1::{FromEncodedPoint, ToEncodedPoint}; +use p256::{EncodedPoint as P256EncodedPoint, PublicKey as P256PublicKey}; +use p256::ecdh::EphemeralSecret as P256EphemeralSecret; +use p384::{EncodedPoint as P384EncodedPoint, PublicKey as P384PublicKey}; +use p384::ecdh::EphemeralSecret as P384EphemeralSecret; use rand::rngs::OsRng; use rust_util::util_clap::{Command, CommandError}; use rust_util::util_msg; use yubikey::{PinPolicy, YubiKey}; -use yubikey::piv::{AlgorithmId, decrypt_data, metadata, RetiredSlotId, SlotId}; +use yubikey::piv::{AlgorithmId, decrypt_data, metadata}; +use crate::pivutil; use crate::pivutil::get_algorithm_id; pub struct CommandImpl; @@ -20,10 +21,11 @@ impl Command for CommandImpl { fn name(&self) -> &str { "piv-ecdh" } fn subcommand<'a>(&self) -> App<'a, 'a> { - SubCommand::with_name(self.name()).about("PIV ECDH subcommand (P-256)") + SubCommand::with_name(self.name()).about("PIV ECDH subcommand") .arg(Arg::with_name("pin").short("p").long("pin").takes_value(true).help("PIV card user pin")) .arg(Arg::with_name("slot").short("s").long("slot").takes_value(true).help("PIV slot, e.g. 82, 83 ...")) - .arg(Arg::with_name("public").long("public").help("Public key")) + .arg(Arg::with_name("public-256").long("public-256").help("Public key (P-256)")) + .arg(Arg::with_name("public-384").long("public-384").help("Public key (P-384)")) .arg(Arg::with_name("private").long("private").help("Private key(PIV)")) .arg(Arg::with_name("epk").long("epk").takes_value(true).help("E-Public key")) .arg(Arg::with_name("public-key").long("public-key").takes_value(true).help("Public key")) @@ -36,12 +38,17 @@ impl Command for CommandImpl { let json_output = sub_arg_matches.is_present("json"); if json_output { util_msg::set_logger_std_out(false); } - let public = sub_arg_matches.is_present("public"); + let public256 = sub_arg_matches.is_present("public-256"); + let public384 = sub_arg_matches.is_present("public-384"); + let public = public256 || public384; + if public256 && public384 { + failure_and_exit!("--public-256 and --public-384 only allow one"); + } let private = sub_arg_matches.is_present("private"); if !public && !private { - failure_and_exit!("--public and --private requires one"); + failure_and_exit!("--public-256, --public-384 or --private requires one"); } else if public && private { - failure_and_exit!("--public and --private only allow one"); + failure_and_exit!("--public-256, --public-384 and --private only allow one"); } let mut json = BTreeMap::<&'_ str, String>::new(); @@ -59,32 +66,62 @@ impl Command for CommandImpl { debugging!("Public key: {}", public_key_pem); } - let public_key; - if let Some(public_key_pem) = public_key_pem_opt { - public_key = opt_result!(public_key_pem.parse::(), "Parse public key failed: {}"); + if public256 { + use p256::elliptic_curve::sec1::{FromEncodedPoint, ToEncodedPoint}; + let public_key; + if let Some(public_key_pem) = public_key_pem_opt { + public_key = opt_result!(public_key_pem.parse::(), "Parse public key failed: {}"); + } else { + let public_key_point_hex = sub_arg_matches.value_of("public-key-point-hex").unwrap_or_else(|| + failure_and_exit!("--public-key, --public-key-file or --public-key-point-hex must require one")); + let public_key_point_bytes = opt_result!(hex::decode(public_key_point_hex), "Parse public key point hex failed: {}"); + let encoded_point = opt_result!(P256EncodedPoint::from_bytes(public_key_point_bytes), "Parse public key point failed: {}"); + public_key = P256PublicKey::from_encoded_point(&encoded_point).unwrap(); + }; + let esk = P256EphemeralSecret::random(&mut OsRng); + let epk = esk.public_key(); + let epk_bytes = P256EphemeralKeyBytes::from_public_key(&epk); + + let public_key_encoded_point = public_key.to_encoded_point(false); + + let shared_secret = esk.diffie_hellman(&public_key); + if json_output { + json.insert("shared_secret_hex", hex::encode(shared_secret.raw_secret_bytes())); + json.insert("epk_point_hex", hex::encode(epk_bytes.decompress().as_bytes())); + json.insert("pk_point_hex", hex::encode(public_key_encoded_point.as_bytes())); + } else { + information!("Shared secret: {}", hex::encode(shared_secret.raw_secret_bytes())); + information!("EPK point: {}", hex::encode(epk_bytes.decompress().as_bytes())); + information!("Public key point: {}", hex::encode(public_key_encoded_point.as_bytes())); + } } else { - let public_key_point_hex = sub_arg_matches.value_of("public-key-point-hex").unwrap_or_else(|| - failure_and_exit!("--public-key, --public-key-file or --public-key-point-hex must require one")); - let public_key_point_bytes = opt_result!(hex::decode(public_key_point_hex), "Parse public key point hex failed: {}"); - let encoded_point = opt_result!(EncodedPoint::from_bytes(public_key_point_bytes), "Parse public key point failed: {}"); - public_key = PublicKey::from_encoded_point(&encoded_point).unwrap(); - }; + use p384::elliptic_curve::sec1::{FromEncodedPoint, ToEncodedPoint}; + let public_key; + if let Some(public_key_pem) = public_key_pem_opt { + public_key = opt_result!(public_key_pem.parse::(), "Parse public key failed: {}"); + } else { + let public_key_point_hex = sub_arg_matches.value_of("public-key-point-hex").unwrap_or_else(|| + failure_and_exit!("--public-key, --public-key-file or --public-key-point-hex must require one")); + let public_key_point_bytes = opt_result!(hex::decode(public_key_point_hex), "Parse public key point hex failed: {}"); + let encoded_point = opt_result!(P384EncodedPoint::from_bytes(public_key_point_bytes), "Parse public key point failed: {}"); + public_key = P384PublicKey::from_encoded_point(&encoded_point).unwrap(); + }; + let esk = P384EphemeralSecret::random(&mut OsRng); + let epk = esk.public_key(); + let epk_bytes = P384EphemeralKeyBytes::from_public_key(&epk); - let esk = EphemeralSecret::random(&mut OsRng); - let epk = esk.public_key(); - let epk_bytes = EphemeralKeyBytes::from_public_key(&epk); + let public_key_encoded_point = public_key.to_encoded_point(false); - let public_key_encoded_point = public_key.to_encoded_point(false); - - let shared_secret = esk.diffie_hellman(&public_key); - if json_output { - json.insert("shared_secret_hex", hex::encode(shared_secret.raw_secret_bytes())); - json.insert("epk_point_hex", hex::encode(epk_bytes.decompress().as_bytes())); - json.insert("pk_point_hex", hex::encode(public_key_encoded_point.as_bytes())); - } else { - information!("Shared secret: {}", hex::encode(shared_secret.raw_secret_bytes())); - information!("EPK point: {}", hex::encode(epk_bytes.decompress().as_bytes())); - information!("Public key point: {}", hex::encode(public_key_encoded_point.as_bytes())); + let shared_secret = esk.diffie_hellman(&public_key); + if json_output { + json.insert("shared_secret_hex", hex::encode(shared_secret.raw_secret_bytes())); + json.insert("epk_point_hex", hex::encode(epk_bytes.decompress().as_bytes())); + json.insert("pk_point_hex", hex::encode(public_key_encoded_point.as_bytes())); + } else { + information!("Shared secret: {}", hex::encode(shared_secret.raw_secret_bytes())); + information!("EPK point: {}", hex::encode(epk_bytes.decompress().as_bytes())); + information!("Public key point: {}", hex::encode(public_key_encoded_point.as_bytes())); + } } } @@ -95,9 +132,8 @@ impl Command for CommandImpl { let epk = opt_value_result!(sub_arg_matches.value_of("epk"), "--epk must assigned"); let mut yk = opt_result!(YubiKey::open(), "YubiKey not found: {}"); - let retired_slot_id = opt_result!(RetiredSlotId::from_str(slot), "Slot not found: {}"); - debugging!("Slot id: {}", retired_slot_id); - let slot_id = SlotId::Retired(retired_slot_id); + let slot_id = pivutil::get_slot_id(slot)?; + debugging!("Slot id: {}", slot_id); if let Ok(meta) = metadata(&mut yk, slot_id) { debugging!("PIV meta: {:?}", meta); if let Some((pin_policy, _touch_policy)) = meta.policy { @@ -130,10 +166,12 @@ impl Command for CommandImpl { } let epk_bytes = opt_result!(hex::decode(epk), "Parse epk failed: {}"); + let epk_bits = (epk_bytes.len() - 1) * 8; + debugging!("Epk {} bits", epk_bits); let decrypted_shared_secret = opt_result!(decrypt_data( &mut yk, &epk_bytes, - AlgorithmId::EccP256, + iff!(epk_bits == 256, AlgorithmId::EccP256, AlgorithmId::EccP384), slot_id, ), "Decrypt piv failed: {}"); @@ -151,19 +189,36 @@ impl Command for CommandImpl { } } -// const EPK_BYTES: usize = 33; - #[derive(Debug)] -pub struct EphemeralKeyBytes(EncodedPoint); +pub struct P256EphemeralKeyBytes(P256EncodedPoint); -impl EphemeralKeyBytes { - fn from_public_key(epk: &PublicKey) -> Self { - EphemeralKeyBytes(epk.to_encoded_point(true)) +impl P256EphemeralKeyBytes { + fn from_public_key(epk: &P256PublicKey) -> Self { + use p256::elliptic_curve::sec1::ToEncodedPoint; + P256EphemeralKeyBytes(epk.to_encoded_point(true)) } - fn decompress(&self) -> EncodedPoint { - // EphemeralKeyBytes is a valid compressed encoding by construction. - let p = PublicKey::from_encoded_point(&self.0).unwrap(); + fn decompress(&self) -> P256EncodedPoint { + // EphemeralKeyBytes is a valid-compressed encoding by construction. + use p256::elliptic_curve::sec1::{FromEncodedPoint, ToEncodedPoint}; + let p = P256PublicKey::from_encoded_point(&self.0).unwrap(); + p.to_encoded_point(false) + } +} + +#[derive(Debug)] +pub struct P384EphemeralKeyBytes(P384EncodedPoint); + +impl P384EphemeralKeyBytes { + fn from_public_key(epk: &P384PublicKey) -> Self { + use p384::elliptic_curve::sec1::ToEncodedPoint; + P384EphemeralKeyBytes(epk.to_encoded_point(true)) + } + + fn decompress(&self) -> P384EncodedPoint { + // EphemeralKeyBytes is a valid-compressed encoding by construction. + use p384::elliptic_curve::sec1::{FromEncodedPoint, ToEncodedPoint}; + let p = P384PublicKey::from_encoded_point(&self.0).unwrap(); p.to_encoded_point(false) } }