]> git.proxmox.com Git - proxmox-backup.git/blobdiff - src/bin/proxmox_backup_client/key.rs
typo fixes all over the place
[proxmox-backup.git] / src / bin / proxmox_backup_client / key.rs
index ef3123bbbd4fa8dc1d8f574692e959d845fbcc1e..76b135a2d20910acc51cd7067198c9c13ac30cee 100644 (file)
@@ -1,3 +1,4 @@
+use std::convert::TryFrom;
 use std::path::PathBuf;
 
 use anyhow::{bail, format_err, Error};
@@ -5,11 +6,7 @@ use serde_json::Value;
 
 use proxmox::api::api;
 use proxmox::api::cli::{
-    ColumnConfig,
-    CliCommand,
-    CliCommandMap,
-    format_and_print_result_full,
-    get_output_format,
+    format_and_print_result_full, get_output_format, CliCommand, CliCommandMap, ColumnConfig,
     OUTPUT_FORMAT,
 };
 use proxmox::api::router::ReturnType;
@@ -17,47 +14,101 @@ use proxmox::sys::linux::tty;
 use proxmox::tools::fs::{file_get_contents, replace_file, CreateOptions};
 
 use proxmox_backup::{
-    tools::paperkey::{
-        PaperkeyFormat,
-        generate_paper_key,
-    },
-    api2::types::{
-        PASSWORD_HINT_SCHEMA,
-        KeyInfo,
-        Kdf,
-    },
-    backup::{
-        rsa_decrypt_key_config,
-        KeyConfig,
-    },
+    api2::types::{Kdf, KeyInfo, RsaPubKeyInfo, PASSWORD_HINT_SCHEMA},
+    backup::{rsa_decrypt_key_config, KeyConfig},
     tools,
+    tools::paperkey::{generate_paper_key, PaperkeyFormat},
 };
 
+use crate::KeyWithSource;
+
 pub const DEFAULT_ENCRYPTION_KEY_FILE_NAME: &str = "encryption-key.json";
-pub const MASTER_PUBKEY_FILE_NAME: &str = "master-public.pem";
+pub const DEFAULT_MASTER_PUBKEY_FILE_NAME: &str = "master-public.pem";
 
-pub fn find_master_pubkey() -> Result<Option<PathBuf>, Error> {
-    super::find_xdg_file(MASTER_PUBKEY_FILE_NAME, "main public key file")
+pub fn find_default_master_pubkey() -> Result<Option<PathBuf>, Error> {
+    super::find_xdg_file(
+        DEFAULT_MASTER_PUBKEY_FILE_NAME,
+        "default master public key file",
+    )
 }
 
-pub fn place_master_pubkey() -> Result<PathBuf, Error> {
-    super::place_xdg_file(MASTER_PUBKEY_FILE_NAME, "main public key file")
+pub fn place_default_master_pubkey() -> Result<PathBuf, Error> {
+    super::place_xdg_file(
+        DEFAULT_MASTER_PUBKEY_FILE_NAME,
+        "default master public key file",
+    )
 }
 
 pub fn find_default_encryption_key() -> Result<Option<PathBuf>, Error> {
-    super::find_xdg_file(DEFAULT_ENCRYPTION_KEY_FILE_NAME, "default encryption key file")
+    super::find_xdg_file(
+        DEFAULT_ENCRYPTION_KEY_FILE_NAME,
+        "default encryption key file",
+    )
 }
 
 pub fn place_default_encryption_key() -> Result<PathBuf, Error> {
-    super::place_xdg_file(DEFAULT_ENCRYPTION_KEY_FILE_NAME, "default encryption key file")
+    super::place_xdg_file(
+        DEFAULT_ENCRYPTION_KEY_FILE_NAME,
+        "default encryption key file",
+    )
 }
 
-pub fn read_optional_default_encryption_key() -> Result<Option<Vec<u8>>, Error> {
+#[cfg(not(test))]
+pub(crate) fn read_optional_default_encryption_key() -> Result<Option<KeyWithSource>, Error> {
     find_default_encryption_key()?
-        .map(file_get_contents)
+        .map(|path| file_get_contents(path).map(KeyWithSource::from_default))
+        .transpose()
+}
+
+#[cfg(not(test))]
+pub(crate) fn read_optional_default_master_pubkey() -> Result<Option<KeyWithSource>, Error> {
+    find_default_master_pubkey()?
+        .map(|path| file_get_contents(path).map(KeyWithSource::from_default))
         .transpose()
 }
 
+#[cfg(test)]
+static mut TEST_DEFAULT_ENCRYPTION_KEY: Result<Option<Vec<u8>>, Error> = Ok(None);
+
+#[cfg(test)]
+pub(crate) fn read_optional_default_encryption_key() -> Result<Option<KeyWithSource>, Error> {
+    // not safe when multiple concurrent test cases end up here!
+    unsafe {
+        match &TEST_DEFAULT_ENCRYPTION_KEY {
+            Ok(Some(key)) => Ok(Some(KeyWithSource::from_default(key.clone()))),
+            Ok(None) => Ok(None),
+            Err(_) => bail!("test error"),
+        }
+    }
+}
+
+#[cfg(test)]
+// not safe when multiple concurrent test cases end up here!
+pub(crate) unsafe fn set_test_encryption_key(value: Result<Option<Vec<u8>>, Error>) {
+    TEST_DEFAULT_ENCRYPTION_KEY = value;
+}
+
+#[cfg(test)]
+static mut TEST_DEFAULT_MASTER_PUBKEY: Result<Option<Vec<u8>>, Error> = Ok(None);
+
+#[cfg(test)]
+pub(crate) fn read_optional_default_master_pubkey() -> Result<Option<KeyWithSource>, Error> {
+    // not safe when multiple concurrent test cases end up here!
+    unsafe {
+        match &TEST_DEFAULT_MASTER_PUBKEY {
+            Ok(Some(key)) => Ok(Some(KeyWithSource::from_default(key.clone()))),
+            Ok(None) => Ok(None),
+            Err(_) => bail!("test error"),
+        }
+    }
+}
+
+#[cfg(test)]
+// not safe when multiple concurrent test cases end up here!
+pub(crate) unsafe fn set_test_default_master_pubkey(value: Result<Option<Vec<u8>>, Error>) {
+    TEST_DEFAULT_MASTER_PUBKEY = value;
+}
+
 pub fn get_encryption_key_password() -> Result<Vec<u8>, Error> {
     // fixme: implement other input methods
 
@@ -98,11 +149,7 @@ pub fn get_encryption_key_password() -> Result<Vec<u8>, Error> {
     },
 )]
 /// Create a new encryption key.
-fn create(
-    kdf: Option<Kdf>,
-    path: Option<String>,
-    hint: Option<String>
-) -> Result<(), Error> {
+fn create(kdf: Option<Kdf>, path: Option<String>, hint: Option<String>) -> Result<(), Error> {
     let path = match path {
         Some(path) => PathBuf::from(path),
         None => {
@@ -194,8 +241,7 @@ async fn import_with_master_key(
     let master_key = file_get_contents(&master_keyfile)?;
     let password = tty::read_password("Master Key Password: ")?;
 
-    let master_key =
-        openssl::pkey::PKey::private_key_from_pem_passphrase(&master_key, &password)
+    let master_key = openssl::pkey::PKey::private_key_from_pem_passphrase(&master_key, &password)
         .map_err(|err| format_err!("failed to read PEM-formatted private key - {}", err))?
         .rsa()
         .map_err(|err| format_err!("not a valid private RSA key - {}", err))?;
@@ -214,7 +260,6 @@ async fn import_with_master_key(
             key_config.created = created; // keep original value
 
             key_config.store(path, true)?;
-
         }
         Kdf::Scrypt | Kdf::PBKDF2 => {
             let password = tty::read_and_verify_password("New Password: ")?;
@@ -257,10 +302,9 @@ fn change_passphrase(
     let path = match path {
         Some(path) => PathBuf::from(path),
         None => {
-            let path = find_default_encryption_key()?
-                .ok_or_else(|| {
-                    format_err!("no encryption file provided and no default file found")
-                })?;
+            let path = find_default_encryption_key()?.ok_or_else(|| {
+                format_err!("no encryption file provided and no default file found")
+            })?;
             println!("updating default key at: {:?}", path);
             path
         }
@@ -282,7 +326,7 @@ fn change_passphrase(
             }
 
             let mut key_config = KeyConfig::without_password(key)?;
-            key_config.created =  created; // keep original value
+            key_config.created = created; // keep original value
 
             key_config.store(&path, true)?;
         }
@@ -315,22 +359,13 @@ fn change_passphrase(
     },
 )]
 /// Print the encryption key's metadata.
-fn show_key(
-    path: Option<String>,
-    param: Value,
-) -> Result<(), Error> {
+fn show_key(path: Option<String>, param: Value) -> Result<(), Error> {
     let path = match path {
         Some(path) => PathBuf::from(path),
-        None => {
-            let path = find_default_encryption_key()?
-                .ok_or_else(|| {
-                    format_err!("no encryption file provided and no default file found")
-                })?;
-            path
-        }
+        None => find_default_encryption_key()?
+            .ok_or_else(|| format_err!("no encryption file provided and no default file found"))?,
     };
 
-
     let config: KeyConfig = serde_json::from_slice(&file_get_contents(path.clone())?)?;
 
     let output_format = get_output_format(&param);
@@ -369,14 +404,24 @@ fn show_key(
 )]
 /// Import an RSA public key used to put an encrypted version of the symmetric backup encryption
 /// key onto the backup server along with each backup.
+///
+/// The imported key will be used as default master key for future invocations by the same local
+/// user.
 fn import_master_pubkey(path: String) -> Result<(), Error> {
     let pem_data = file_get_contents(&path)?;
 
-    if let Err(err) = openssl::pkey::PKey::public_key_from_pem(&pem_data) {
-        bail!("Unable to decode PEM data - {}", err);
-    }
+    match openssl::pkey::PKey::public_key_from_pem(&pem_data) {
+        Ok(key) => {
+            let info = RsaPubKeyInfo::try_from(key.rsa()?)?;
+            println!("Found following key at {:?}", path);
+            println!("Modulus: {}", info.modulus);
+            println!("Exponent: {}", info.exponent);
+            println!("Length: {}", info.length);
+        }
+        Err(err) => bail!("Unable to decode PEM data - {}", err),
+    };
 
-    let target_path = place_master_pubkey()?;
+    let target_path = place_default_master_pubkey()?;
 
     replace_file(&target_path, &pem_data, CreateOptions::new())?;
 
@@ -394,7 +439,16 @@ fn create_master_key() -> Result<(), Error> {
         bail!("unable to create master key - no tty");
     }
 
-    let rsa = openssl::rsa::Rsa::generate(4096)?;
+    let bits = 4096;
+    println!("Generating {}-bit RSA key..", bits);
+    let rsa = openssl::rsa::Rsa::generate(bits)?;
+    let public =
+        openssl::rsa::Rsa::from_public_components(rsa.n().to_owned()?, rsa.e().to_owned()?)?;
+    let info = RsaPubKeyInfo::try_from(public)?;
+    println!("Modulus: {}", info.modulus);
+    println!("Exponent: {}", info.exponent);
+    println!();
+
     let pkey = openssl::pkey::PKey::from_rsa(rsa)?;
 
     let password = String::from_utf8(tty::read_and_verify_password("Master Key Password: ")?)?;
@@ -405,7 +459,8 @@ fn create_master_key() -> Result<(), Error> {
     replace_file(filename_pub, pub_key.as_slice(), CreateOptions::new())?;
 
     let cipher = openssl::symm::Cipher::aes_256_cbc();
-    let priv_key: Vec<u8> = pkey.private_key_to_pem_pkcs8_passphrase(cipher, password.as_bytes())?;
+    let priv_key: Vec<u8> =
+        pkey.private_key_to_pem_pkcs8_passphrase(cipher, password.as_bytes())?;
 
     let filename_priv = "master-private.pem";
     println!("Writing private master key to {}", filename_priv);
@@ -414,6 +469,56 @@ fn create_master_key() -> Result<(), Error> {
     Ok(())
 }
 
+#[api(
+    input: {
+        properties: {
+            path: {
+                description: "Path to the PEM formatted RSA public key. Default location will be used if not specified.",
+                optional: true,
+            },
+            "output-format": {
+                schema: OUTPUT_FORMAT,
+                optional: true,
+            },
+        },
+    },
+)]
+/// List information about master key
+fn show_master_pubkey(path: Option<String>, param: Value) -> Result<(), Error> {
+    let path = match path {
+        Some(path) => PathBuf::from(path),
+        None => find_default_master_pubkey()?
+            .ok_or_else(|| format_err!("No path specified and no default master key available."))?,
+    };
+
+    let path = path.canonicalize()?;
+
+    let output_format = get_output_format(&param);
+
+    let pem_data = file_get_contents(path.clone())?;
+    let rsa = openssl::rsa::Rsa::public_key_from_pem(&pem_data)?;
+
+    let mut info = RsaPubKeyInfo::try_from(rsa)?;
+    info.path = Some(path.display().to_string());
+
+    let options = proxmox::api::cli::default_table_format_options()
+        .column(ColumnConfig::new("path"))
+        .column(ColumnConfig::new("modulus"))
+        .column(ColumnConfig::new("exponent"))
+        .column(ColumnConfig::new("length"));
+
+    let return_type = ReturnType::new(false, &RsaPubKeyInfo::API_SCHEMA);
+
+    format_and_print_result_full(
+        &mut serde_json::to_value(info)?,
+        &return_type,
+        &output_format,
+        &options,
+    );
+
+    Ok(())
+}
+
 #[api(
     input: {
         properties: {
@@ -422,7 +527,7 @@ fn create_master_key() -> Result<(), Error> {
                 optional: true,
             },
             subject: {
-                description: "Include the specified subject as titel text.",
+                description: "Include the specified subject as title text.",
                 optional: true,
             },
             "output-format": {
@@ -442,13 +547,8 @@ fn paper_key(
 ) -> Result<(), Error> {
     let path = match path {
         Some(path) => PathBuf::from(path),
-        None => {
-            let path = find_default_encryption_key()?
-                .ok_or_else(|| {
-                    format_err!("no encryption file provided and no default file found")
-                })?;
-            path
-        }
+        None => find_default_encryption_key()?
+            .ok_or_else(|| format_err!("no encryption file provided and no default file found"))?,
     };
 
     let data = file_get_contents(&path)?;
@@ -478,6 +578,9 @@ pub fn cli() -> CliCommandMap {
     let key_import_master_pubkey_cmd_def = CliCommand::new(&API_METHOD_IMPORT_MASTER_PUBKEY)
         .arg_param(&["path"])
         .completion_cb("path", tools::complete_file_name);
+    let key_show_master_pubkey_cmd_def = CliCommand::new(&API_METHOD_SHOW_MASTER_PUBKEY)
+        .arg_param(&["path"])
+        .completion_cb("path", tools::complete_file_name);
 
     let key_show_cmd_def = CliCommand::new(&API_METHOD_SHOW_KEY)
         .arg_param(&["path"])
@@ -494,5 +597,6 @@ pub fn cli() -> CliCommandMap {
         .insert("import-master-pubkey", key_import_master_pubkey_cmd_def)
         .insert("change-passphrase", key_change_passphrase_cmd_def)
         .insert("show", key_show_cmd_def)
+        .insert("show-master-pubkey", key_show_master_pubkey_cmd_def)
         .insert("paperkey", paper_key_cmd_def)
 }