From 8d76f060c57cc7193261628c219b947f9f4ff08c Mon Sep 17 00:00:00 2001 From: Alberto Faria Date: Wed, 14 Feb 2024 09:52:37 +0000 Subject: [PATCH] src/commands/create: Don't regen ssh keypair on container restart Signed-off-by: Alberto Faria --- src/commands/create/mod.rs | 55 ++++++++++++++++++++------------------ 1 file changed, 29 insertions(+), 26 deletions(-) diff --git a/src/commands/create/mod.rs b/src/commands/create/mod.rs index 93e5eea..e91a01a 100644 --- a/src/commands/create/mod.rs +++ b/src/commands/create/mod.rs @@ -513,38 +513,41 @@ fn set_up_first_boot_config( /// cloud-init but the user injected their public key into it themselves. fn get_container_ssh_key_pair(spec: &oci_spec::runtime::Spec, env: RuntimeEnv) -> Result { let ssh_path = spec.root_path()?.join("root/.ssh"); - fs::create_dir_all(&ssh_path)?; - let try_copy_user_key_pair = || -> Result { - if env != RuntimeEnv::Other { - // definitely not Podman, we're probably not running as the user that invoked the engine - return Ok(false); - } + if !ssh_path.join("id_rsa.pub").exists() { + fs::create_dir_all(&ssh_path)?; + + let try_copy_user_key_pair = || -> Result { + if env != RuntimeEnv::Other { + // definitely not Podman, we're probably not running as the user that invoked the engine + return Ok(false); + } - if let Some(user_home_path) = home::home_dir() { - let user_ssh = user_home_path.join(".ssh"); + if let Some(user_home_path) = home::home_dir() { + let user_ssh = user_home_path.join(".ssh"); - if user_ssh.join("id_rsa.pub").is_file() && user_ssh.join("id_rsa").is_file() { - fs::copy(user_ssh.join("id_rsa.pub"), ssh_path.join("id_rsa.pub"))?; - fs::copy(user_ssh.join("id_rsa"), ssh_path.join("id_rsa"))?; - return Ok(true); + if user_ssh.join("id_rsa.pub").is_file() && user_ssh.join("id_rsa").is_file() { + fs::copy(user_ssh.join("id_rsa.pub"), ssh_path.join("id_rsa.pub"))?; + fs::copy(user_ssh.join("id_rsa"), ssh_path.join("id_rsa"))?; + return Ok(true); + } } - } - Ok(false) - }; + Ok(false) + }; - if !try_copy_user_key_pair()? { - let status = Command::new("ssh-keygen") - .arg("-q") - .arg("-f") - .arg(ssh_path.join("id_rsa")) - .arg("-N") - .arg("") - .spawn()? - .wait()?; - - ensure!(status.success(), "ssh-keygen failed"); + if !try_copy_user_key_pair()? { + let status = Command::new("ssh-keygen") + .arg("-q") + .arg("-f") + .arg(ssh_path.join("id_rsa")) + .arg("-N") + .arg("") + .spawn()? + .wait()?; + + ensure!(status.success(), "ssh-keygen failed"); + } } Ok(fs::read_to_string(ssh_path.join("id_rsa.pub"))?)