feat(build): generate host keys automatically on build

This commit is contained in:
Erica Marigold 2025-01-31 12:56:34 +00:00
parent 36a62018e5
commit 262c75d36d
Signed by: DevComp
GPG key ID: 429EF1C337871656
5 changed files with 44 additions and 4 deletions

3
.gitignore vendored
View file

@ -1,3 +1,2 @@
/target
.data/*.log
*.pem*
.data/*.log

1
Cargo.lock generated
View file

@ -3443,6 +3443,7 @@ dependencies = [
"serde",
"serde_json",
"signal-hook",
"ssh-key",
"strip-ansi-escapes",
"strum",
"tokio",

View file

@ -45,4 +45,5 @@ tracing-subscriber = { version = "0.3.18", features = ["env-filter", "serde"] }
[build-dependencies]
anyhow = "1.0.90"
ssh-key = { version = "0.6.7", features = ["getrandom", "crypto"] }
vergen-gix = { version = "1.0.2", features = ["build", "cargo"] }

View file

@ -1,7 +1,44 @@
use std::{env, path::PathBuf};
use anyhow::Result;
use ssh_key::{rand_core, Algorithm, EcdsaCurve, LineEnding, PrivateKey};
use vergen_gix::{BuildBuilder, CargoBuilder, Emitter, GixBuilder};
const SSH_KEY_ALGOS: &[Algorithm] = &[
Algorithm::Rsa { hash: None },
Algorithm::Ed25519,
Algorithm::Ecdsa {
curve: EcdsaCurve::NistP256,
},
];
fn main() -> Result<()> {
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-changed=Cargo.toml");
// Generate openSSH host keys
let mut rng = rand_core::OsRng::default();
let keys = SSH_KEY_ALGOS
.iter()
.map(|algo| PrivateKey::random(&mut rng, algo.to_owned()).map_err(anyhow::Error::from))
.collect::<Vec<Result<PrivateKey>>>();
let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
for key_res in keys {
if let Ok(ref key) = key_res {
let path = out_dir.join(format!("{}.pem", key.algorithm().as_str()));
if path.exists() {
println!("cargo:warning=Skipping existing host key: {:?}", path);
continue;
}
key.write_openssh_file(&path, LineEnding::default())?;
} else {
println!("cargo:warning=Failed to generate host key: {:?}", key_res);
}
}
// Emit the build information
let build = BuildBuilder::all_build()?;
let gix = GixBuilder::all_git()?;
let cargo = CargoBuilder::all_cargo()?;

View file

@ -24,8 +24,9 @@ mod ssh;
mod tui;
const SSH_KEYS: &[&[u8]] = &[
include_bytes!("../rsa.pem"),
include_bytes!("../ed25519.pem"),
include_bytes!(concat!(env!("OUT_DIR"), "/ssh-rsa.pem")),
include_bytes!(concat!(env!("OUT_DIR"), "/ecdsa-sha2-nistp256.pem")),
include_bytes!(concat!(env!("OUT_DIR"), "/ssh-ed25519.pem")),
];
lazy_static! {
pub(crate) static ref OPTIONS: Cli = Cli::parse();
@ -36,6 +37,7 @@ lazy_static! {
async fn main() -> Result<()> {
crate::errors::init()?;
crate::logging::init()?;
let _ = *OPTIONS; // force clap to run by evaluating it
let config = ssh_config();
tracing::info!("Attempting to listen on {}", *SOCKET_ADDR);