feat: v1.9.13, support ssh-piv-cert, but not works

This commit is contained in:
2024-09-06 23:06:21 +08:00
parent 1d2a00a0c8
commit cbf127a297
6 changed files with 769 additions and 103 deletions

687
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
[package]
name = "card-cli"
version = "1.9.12"
version = "1.9.13"
authors = ["Hatter Jiang <jht5945@gmail.com>"]
edition = "2018"
@@ -44,6 +44,7 @@ pinentry = "0.5.0"
rpassword = "7.3.1"
secrecy = "0.8.0"
der-parser = "9.0.0"
sshcerts = "0.13.2"
#lazy_static = "1.4.0"
#ssh-key = "0.4.0"
#ctap-hid-fido2 = "2.1.3"

154
src/cmd_sshpivcert.rs Normal file
View File

@@ -0,0 +1,154 @@
use clap::{App, Arg, ArgMatches, SubCommand};
use ecdsa::elliptic_curve::pkcs8::der::Encode;
use rand::random;
use rust_util::util_clap::{Command, CommandError};
use rust_util::XResult;
use sshcerts::ssh::{CurveKind, PublicKeyKind, SSHCertificateSigner};
use sshcerts::utils::format_signature_for_ssh;
use sshcerts::x509::extract_ssh_pubkey_from_x509_certificate;
use sshcerts::{CertType, Certificate, PublicKey};
use std::sync::Mutex;
use std::time::SystemTime;
use yubikey::piv::{sign_data, AlgorithmId, SlotId};
use yubikey::{Key, YubiKey};
use crate::digest::{sha256_bytes, sha384_bytes};
use crate::pivutil::slot_equals;
use crate::{pinutil, pivutil, util};
pub struct CommandImpl;
// https://github.com/RustCrypto/SSH
// https://github.com/obelisk/sshcerts/
impl Command for CommandImpl {
fn name(&self) -> &str { "ssh-piv-cert" }
fn subcommand<'a>(&self) -> App<'a, 'a> {
SubCommand::with_name(self.name()).about("SSH PIV sign cert 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 ... 95, 9a, 9c, 9d, 9e"))
.arg(Arg::with_name("key-id").short("k").long("key-id").takes_value(true).help("SSH user CA key id"))
.arg(Arg::with_name("principal").short("P").long("principal").takes_value(true).help("SSH user CA principal"))
.arg(Arg::with_name("pub").long("pub").required(true).takes_value(true).help("SSH public key file"))
}
fn run(&self, _arg_matches: &ArgMatches, sub_arg_matches: &ArgMatches) -> CommandError {
let ssh_pub = util::read_file_or_stdin(sub_arg_matches.value_of("pub").unwrap())?;
let ssh_pub_str = String::from_utf8(ssh_pub).expect("Read SSh pub file failed: {}");
let slot = opt_value_result!(sub_arg_matches.value_of("slot"), "--slot must assigned, e.g. 82, 83 ... 95, 9a, 9c, 9d, 9e");
let mut yk = opt_result!(YubiKey::open(), "YubiKey not found: {}");
let slot_id = pivutil::get_slot_id(slot)?;
let pin_opt = sub_arg_matches.value_of("pin");
let pin_opt = pinutil::get_pin(pin_opt);
let pin_opt = pin_opt.as_deref();
let cert_der = find_cert(&mut yk, slot_id)?;
let ca_ssh_pub_key = opt_result!(extract_ssh_pubkey_from_x509_certificate(&cert_der), "Extract SSH public key failed: {}");
let tobe_signed_ssh_pub_key = opt_result!(PublicKey::from_string(&ssh_pub_str), "Parse tobe signed SSH public key failed: {}");
let ca_ssh_pub_algorithm_id = get_ssh_key_type(&ca_ssh_pub_key)?;
let ssh_yubikey_signer = SshYubikeySinger::new(
yk,
pin_opt.map(ToString::to_string),
slot_id,
ca_ssh_pub_key.clone(),
ca_ssh_pub_algorithm_id,
);
let serial: u64 = random();
let key_id = sub_arg_matches.value_of("key-id").unwrap_or("default_key_id");
let principals = sub_arg_matches.values_of("principal")
.map(|ps| ps.map(|p| p.to_string()).collect::<Vec<_>>())
.unwrap_or_else(|| vec!["default_principal".to_string()]);
debugging!("Serial: {}", serial);
debugging!("Key ID: {}", key_id);
debugging!("Principals: {:?}", principals);
let now_secs = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs();
let user_cert_result = Certificate::builder(&tobe_signed_ssh_pub_key, CertType::User, &ca_ssh_pub_key)
.unwrap()
.serial(serial)
.key_id(key_id)
.set_principals(&principals)
.valid_after(now_secs - 100)
.valid_before(now_secs + 60000)
.set_extensions(Certificate::standard_extensions())
.sign(&ssh_yubikey_signer);
let user_cert = opt_result!(user_cert_result, "Sign SSH user CA failed: {}");
println!("{}", user_cert.to_string());
Ok(None)
}
}
fn find_cert(yk: &mut YubiKey, slot_id: SlotId) -> XResult<Vec<u8>> {
match Key::list(yk) {
Err(e) => warning!("List keys failed: {}", e),
Ok(keys) => {
for k in &keys {
let slot_str = format!("{:x}", Into::<u8>::into(k.slot()));
if slot_equals(&slot_id, &slot_str) {
let cert_der = k.certificate().cert.to_der()?;
return Ok(cert_der);
}
}
}
}
simple_error!("Cannot find slot: {}", slot_id)
}
pub fn get_ssh_key_type(public_key: &PublicKey) -> XResult<AlgorithmId> {
match &public_key.kind {
PublicKeyKind::Ecdsa(x) => match x.curve.kind {
CurveKind::Nistp256 => Ok(AlgorithmId::EccP256),
CurveKind::Nistp384 => Ok(AlgorithmId::EccP384),
CurveKind::Nistp521 => simple_error!("NIST P521 is not supported."),
},
PublicKeyKind::Rsa(_) => simple_error!("RSA is not supported."),
PublicKeyKind::Ed25519(_) => simple_error!("Ed25519 is not supported."),
}
}
struct SshYubikeySinger {
yubikey: Mutex<YubiKey>,
pin_opt: Option<String>,
ca_ssh_pub_slot_id: SlotId,
ca_ssh_pub_key: PublicKey,
ca_ssh_pub_algorithm_id: AlgorithmId,
}
impl SshYubikeySinger {
fn new(yubikey: YubiKey, pin_opt: Option<String>, ca_ssh_pub_slot_id: SlotId, ca_ssh_pub_key: PublicKey, ca_ssh_pub_algorithm_id: AlgorithmId) -> Self {
Self {
yubikey: Mutex::new(yubikey),
pin_opt,
ca_ssh_pub_slot_id,
ca_ssh_pub_key,
ca_ssh_pub_algorithm_id,
}
}
}
impl SSHCertificateSigner for SshYubikeySinger {
fn sign(&self, buffer: &[u8]) -> Option<Vec<u8>> {
let digest = match self.ca_ssh_pub_algorithm_id {
AlgorithmId::Rsa1024 | AlgorithmId::Rsa2048 => { panic!("Should not reach here.") }
AlgorithmId::EccP256 => sha256_bytes(buffer),
AlgorithmId::EccP384 => sha384_bytes(buffer),
};
let mut yubikey = self.yubikey.lock().unwrap();
if let Some(pin) = &self.pin_opt {
yubikey.verify_pin(pin.as_bytes()).expect("Verify PIN failed: {}");
}
let signature = sign_data(&mut yubikey, &digest, self.ca_ssh_pub_algorithm_id, self.ca_ssh_pub_slot_id).expect("SSH user CA sign failed: {}");
format_signature_for_ssh(&self.ca_ssh_pub_key, &signature.to_vec())
}
}

View File

@@ -16,7 +16,7 @@ impl Command for CommandImpl {
fn name(&self) -> &str { "ssh-piv-sign" }
fn subcommand<'a>(&self) -> App<'a, 'a> {
SubCommand::with_name(self.name()).about("SSH parse sign subcommand")
SubCommand::with_name(self.name()).about("SSH piv sign 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 ... 95, 9a, 9c, 9d, 9e"))
.arg(Arg::with_name("namespace").short("n").long("namespace").takes_value(true).help("Namespace"))

View File

@@ -1,3 +1,7 @@
use crate::digest::sha256_bytes;
use crate::pivutil;
use crate::pivutil::{get_algorithm_id_by_certificate, slot_equals, ToStr};
use crate::sshutil::SshVecWriter;
use base64::engine::general_purpose::STANDARD;
use base64::Engine;
use clap::{App, Arg, ArgMatches, SubCommand};
@@ -5,10 +9,6 @@ use rust_util::util_clap::{Command, CommandError};
use yubikey::piv::AlgorithmId;
use yubikey::{Key, YubiKey};
use crate::pivutil;
use crate::pivutil::{get_algorithm_id_by_certificate, slot_equals, ToStr};
use crate::sshutil::SshVecWriter;
pub struct CommandImpl;
impl Command for CommandImpl {
@@ -17,10 +17,12 @@ impl Command for CommandImpl {
fn subcommand<'a>(&self) -> App<'a, 'a> {
SubCommand::with_name(self.name()).about("SSH public key subcommand")
.arg(Arg::with_name("slot").short("s").long("slot").takes_value(true).help("PIV slot, e.g. 82, 83 ... 95, 9a, 9c, 9d, 9e"))
.arg(Arg::with_name("ca").long("ca").help("SSH cert-authority"))
}
fn run(&self, _arg_matches: &ArgMatches, sub_arg_matches: &ArgMatches) -> CommandError {
let slot = opt_value_result!(sub_arg_matches.value_of("slot"), "--slot must assigned, e.g. 82, 83 ... 95, 9a, 9c, 9d, 9e");
let ca = sub_arg_matches.is_present("ca");
let mut yk = opt_result!(YubiKey::open(), "YubiKey not found: {}");
let slot_id = pivutil::get_slot_id(slot)?;
@@ -59,7 +61,6 @@ impl Command for CommandImpl {
information!("SSH algorithm: {}", ssh_algorithm);
information!("ECDSA public key: {}", hex::encode(&ec_key_point));
println!();
// ECDSA SSH public key format:
// string ecdsa-sha2-[identifier]
@@ -77,7 +78,18 @@ impl Command for CommandImpl {
ecc_key_blob.write_string(&ec_key_point);
ssh_pub_key.write_bytes(&ecc_key_blob);
println!("ecdsa-sha2-{} {} Yubikey-PIV-{}", ssh_algorithm, STANDARD.encode(&ssh_pub_key), slot_id);
let ssh_pub_key_sha256 = sha256_bytes(&ssh_pub_key);
information!("SSH key SHA256: {} (base64)", STANDARD.encode(&ssh_pub_key_sha256));
information!("SSH key SHA256: {} (hex)", hex::encode(&ssh_pub_key_sha256));
println!();
println!(
"{}ecdsa-sha2-{} {} Yubikey-PIV-{}",
if ca { "cert-authority " } else { "" },
ssh_algorithm,
STANDARD.encode(&ssh_pub_key),
slot_id
);
Ok(None)
}

View File

@@ -42,6 +42,7 @@ mod cmd_challconfig;
mod cmd_sshagent;
mod cmd_sshparsesign;
mod cmd_sshpivsign;
mod cmd_sshpivcert;
mod cmd_sshpubkey;
mod cmd_pgpageaddress;
mod cmd_signjwt;
@@ -104,6 +105,7 @@ fn inner_main() -> CommandError {
Box::new(cmd_sshagent::CommandImpl),
Box::new(cmd_sshparsesign::CommandImpl),
Box::new(cmd_sshpivsign::CommandImpl),
Box::new(cmd_sshpivcert::CommandImpl),
Box::new(cmd_sshpubkey::CommandImpl),
Box::new(cmd_pgpageaddress::CommandImpl),
Box::new(cmd_signjwt::CommandImpl),