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

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())
}
}