Skip to content
Merged
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
166 changes: 162 additions & 4 deletions pkgs/fleet/crates/fleet-cert/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ use crate::timeparse::{CalendarDuration, Rfc3339};
use rcgen::{BasicConstraints, CertificateParams, DnType, IsCa, KeyUsagePurpose};
use serde_json::{Value, json};
use std::collections::{BTreeMap, BTreeSet};
use std::fs::OpenOptions;
use std::io::Write;
use std::path::PathBuf;

/// Full usage for the cert domain (also what `fleet cert --help`
Expand All @@ -36,6 +38,7 @@ Groups and verbs (spec §6.1 tree; status as built):
ocsp sign | inspect | test
chain build | test
bundle inspect
key generate | inspect
profile list | show
algorithms list | describe
explain [topic]
Expand Down Expand Up @@ -228,6 +231,7 @@ fn run_inner(args: &[String]) -> Result<i32> {
"ocsp" => ocsp_cmd(rest, json_out),
"chain" => chain_cmd(rest, json_out),
"bundle" => bundle_cmd(rest, json_out),
"key" => key_cmd(rest, json_out),
"profile" => profile_cmd(rest, json_out),
"algorithms" => algorithms_cmd(rest, json_out),
"explain" => explain_cmd(rest, json_out),
Expand All @@ -238,6 +242,93 @@ fn run_inner(args: &[String]) -> Result<i32> {
}
}

// ---------------------------------------------------------------- standalone key ceremony

fn key_cmd(args: &[String], json_out: bool) -> Result<i32> {
let verb = args.first().map(|s| s.as_str()).unwrap_or("");
let rest = &args[1.min(args.len())..];
match verb {
"generate" => {
let p = parse_args(rest, &["algorithm", "out"], &["json"])?;
let algorithm = parse_key_algorithm(&p)?;
let out = PathBuf::from(p.require("out", "key generate")?);
let key = engine::generate_key(algorithm)?;
let der = key.serialize_der();
// Key generation is an explicit ceremony: create a new
// owner-readable file, and never replace an existing key.
let mut options = OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
let mut file = options.open(&out).map_err(|e| {
CertError::policy(format!(
"cannot create private key {} without replacing an existing file: {e}",
out.display()
))
})?;
file.write_all(&der)
.and_then(|_| file.sync_all())
.map_err(|e| {
let _ = std::fs::remove_file(&out);
CertError::engine(format!("writing private key {} failed: {e}", out.display()))
})?;
let value = json!({"algorithm": algorithm.info().name, "private_key": out.display().to_string(), "encoding": "PKCS#8 DER"});
Ok(emit(
json_out,
format!(
"Generated {} private key at {} (PKCS#8 DER)\n",
algorithm.info().name,
out.display()
),
value,
))
}
"inspect" => {
let p = parse_args(rest, &["algorithm", "in"], &["json"])?;
let algorithm = parse_key_algorithm(&p)?;
let path = PathBuf::from(p.require("in", "key inspect")?);
let pkcs8 = std::fs::read(&path).map_err(|e| {
CertError::policy(format!("cannot read private key {}: {e}", path.display()))
})?;
let public = engine::inspect_key(algorithm, &pkcs8)?;
let fingerprint = crate::bundle::sha256_hex(&public);
let value = json!({
"algorithm": algorithm.info().name,
"private_key": path.display().to_string(),
"encoding": "PKCS#8 DER",
"public_key_fingerprint_sha256": fingerprint,
"public_key_bytes": public.len(),
"private_material_emitted": false,
});
Ok(emit(
json_out,
format!(
"{} private key\n encoding: PKCS#8 DER\n public-key SHA-256: {fingerprint}\n public-key bytes: {}\n private material: redacted\n",
algorithm.info().name,
public.len()
),
value,
))
}
other => Err(CertError::usage(format!(
"unknown key verb '{other}' (generate | inspect)"
))),
}
}

fn parse_key_algorithm(p: &Parsed) -> Result<AlgorithmId> {
let name = p.require("algorithm", "key operation")?;
AlgorithmId::parse(&name).map(|(algorithm, warning)| {
if let Some(warning) = warning {
eprintln!("warning: {warning}");
}
algorithm
})
}

// ---------------------------------------------------------------- root

fn root_cmd(args: &[String], json_out: bool) -> Result<i32> {
Expand Down Expand Up @@ -861,8 +952,8 @@ const NOT_BUILT: &[(&str, &str)] = &[
"trust-store install/export (spec §3.5 follow-through)",
),
(
"key",
"key inspect/import/export/convert-public (spec §6.1)",
"key import/export/escrow/restore/rotate",
"remaining standalone key ceremonies (spec §6.1)",
),
("format", "format list/describe/export/convert (spec §7.5)"),
(
Expand Down Expand Up @@ -984,15 +1075,15 @@ fn doctor_cmd(_args: &[String], json_out: bool) -> Result<i32> {
" openssl (independent validator): {}\n",
openssl.as_deref().unwrap_or("not found")
));
text.push_str(" built: root, issuer, leaf, chain, bundle (inspect), profile (list/show), algorithms (list/describe), explain, doctor\n");
text.push_str(" built: root, issuer, leaf, key (generate/inspect), chain, bundle (inspect), profile (list/show), algorithms (list/describe), explain, doctor\n");
text.push_str(" not built yet (tracked as child issues under #9157):\n");
for (name, what) in NOT_BUILT {
text.push_str(&format!(" {name} — {what}\n"));
}
let value = json!({
"engine_self_test": algo_results.iter().map(|(i, ok)| json!({"algorithm": i.name, "ok": ok})).collect::<Vec<_>>(),
"openssl": openssl,
"built": ["root", "issuer", "leaf", "chain", "bundle-inspect", "profile-list/show", "algorithms-list/describe", "explain", "doctor"],
"built": ["root", "issuer", "leaf", "key-generate/inspect", "chain", "bundle-inspect", "profile-list/show", "algorithms-list/describe", "explain", "doctor"],
"not_built": NOT_BUILT.iter().map(|(n, w)| json!({"surface": n, "scope": w})).collect::<Vec<_>>(),
});
let code = emit(json_out, text, value);
Expand Down Expand Up @@ -1021,6 +1112,73 @@ fn engine_self_test(algo: AlgorithmId) -> bool {
}
}

#[cfg(test)]
mod key_ceremony_tests {
use super::*;

#[test]
fn generate_creates_private_file_once_and_inspect_redacts_material() {
let nonce = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.expect("clock after epoch")
.as_nanos();
let dir =
std::env::temp_dir().join(format!("fleet-cert-key-{}-{nonce}", std::process::id()));
std::fs::create_dir(&dir).expect("create isolated test directory");
let path = dir.join("p256.pk8");
let path_text = path.to_string_lossy().into_owned();
let generated = key_cmd(
&[
"generate".into(),
"--algorithm".into(),
"p256".into(),
"--out".into(),
path_text.clone(),
],
true,
);
assert!(generated.is_ok());
let bytes = std::fs::read(&path).expect("generated PKCS#8 key");
assert!(!bytes.is_empty());
assert!(engine::inspect_key(AlgorithmId::P256, &bytes).is_ok());
assert!(
key_cmd(
&[
"inspect".into(),
"--algorithm".into(),
"p256".into(),
"--in".into(),
path_text.clone(),
],
true,
)
.is_ok()
);
assert!(
key_cmd(
&[
"generate".into(),
"--algorithm".into(),
"p256".into(),
"--out".into(),
path_text,
],
true,
)
.is_err()
);
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
assert_eq!(
std::fs::metadata(&path).unwrap().permissions().mode() & 0o777,
0o600
);
}
std::fs::remove_dir_all(dir).expect("remove isolated test directory");
}
}

// ---------------------------------------------------------------- ocsp

fn ocsp_cmd(args: &[String], json_out: bool) -> Result<i32> {
Expand Down
31 changes: 31 additions & 0 deletions pkgs/fleet/crates/fleet-cert/src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,37 @@ impl MlDsa44Signer {
.to_vec();
Ok(MlDsa44Signer { key, public_key })
}

pub fn public_key(&self) -> &[u8] {
&self.public_key
}
}

/// Parse a PKCS#8 key using the explicitly named algorithm and return
/// only its public key bytes. Private material is never part of the
/// result, which is the metadata boundary used by `key inspect`.
pub fn inspect_key(algo: AlgorithmId, pkcs8: &[u8]) -> Result<Vec<u8>> {
match algo {
AlgorithmId::MlDsa44 => Ok(MlDsa44Signer::from_pkcs8(pkcs8)?.public_key().to_vec()),
AlgorithmId::Ed25519 => Ok(KeyPair::from_pkcs8_der_and_sign_algo(
&rustls_pki_types::PrivatePkcs8KeyDer::from(pkcs8.to_vec()),
&PKCS_ED25519,
)?
.public_key_raw()
.to_vec()),
AlgorithmId::P256 => Ok(KeyPair::from_pkcs8_der_and_sign_algo(
&rustls_pki_types::PrivatePkcs8KeyDer::from(pkcs8.to_vec()),
&PKCS_ECDSA_P256_SHA256,
)?
.public_key_raw()
.to_vec()),
AlgorithmId::Rsa4096 | AlgorithmId::Rsa2048 => Ok(KeyPair::from_pkcs8_der_and_sign_algo(
&rustls_pki_types::PrivatePkcs8KeyDer::from(pkcs8.to_vec()),
&PKCS_RSA_SHA256,
)?
.public_key_raw()
.to_vec()),
}
}

impl rcgen::PublicKeyData for MlDsa44Signer {
Expand Down