]> 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 193367e3829b4dde06d1ef2ed42d996698d666ee..76b135a2d20910acc51cd7067198c9c13ac30cee 100644 (file)
+use std::convert::TryFrom;
 use std::path::PathBuf;
-use std::io::Write;
-use std::process::{Stdio, Command};
 
 use anyhow::{bail, format_err, Error};
-use serde::{Deserialize, Serialize};
+use serde_json::Value;
 
 use proxmox::api::api;
-use proxmox::api::cli::{CliCommand, CliCommandMap};
+use proxmox::api::cli::{
+    format_and_print_result_full, get_output_format, CliCommand, CliCommandMap, ColumnConfig,
+    OUTPUT_FORMAT,
+};
+use proxmox::api::router::ReturnType;
 use proxmox::sys::linux::tty;
 use proxmox::tools::fs::{file_get_contents, replace_file, CreateOptions};
 
-use proxmox_backup::backup::{
-    encrypt_key_with_passphrase,
-    load_and_decrypt_key,
-    store_key_config,
-    CryptConfig,
-    KeyConfig,
+use proxmox_backup::{
+    api2::types::{Kdf, KeyInfo, RsaPubKeyInfo, PASSWORD_HINT_SCHEMA},
+    backup::{rsa_decrypt_key_config, KeyConfig},
+    tools,
+    tools::paperkey::{generate_paper_key, PaperkeyFormat},
 };
-use proxmox_backup::tools;
-
-#[api()]
-#[derive(Debug, Serialize, Deserialize)]
-#[serde(rename_all = "lowercase")]
-/// Paperkey output format
-pub enum PaperkeyFormat {
-    /// Format as Utf8 text. Includes QR codes as ascii-art.
-    Text,
-    /// Format as Html. Includes QR codes as png images.
-    Html,
-}
+
+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
 
@@ -75,27 +129,6 @@ pub fn get_encryption_key_password() -> Result<Vec<u8>, Error> {
     bail!("no password input mechanism available");
 }
 
-#[api(
-    default: "scrypt",
-)]
-#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
-#[serde(rename_all = "kebab-case")]
-/// Key derivation function for password protected encryption keys.
-pub enum Kdf {
-    /// Do not encrypt the key.
-    None,
-
-    /// Encrypt they key with a password using SCrypt.
-    Scrypt,
-}
-
-impl Default for Kdf {
-    #[inline]
-    fn default() -> Self {
-        Kdf::Scrypt
-    }
-}
-
 #[api(
     input: {
         properties: {
@@ -107,12 +140,16 @@ impl Default for Kdf {
                 description:
                     "Output file. Without this the key will become the new default encryption key.",
                 optional: true,
-            }
+            },
+            hint: {
+                schema: PASSWORD_HINT_SCHEMA,
+                optional: true,
+            },
         },
     },
 )]
 /// Create a new encryption key.
-fn create(kdf: Option<Kdf>, path: 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 => {
@@ -124,28 +161,20 @@ fn create(kdf: Option<Kdf>, path: Option<String>) -> Result<(), Error> {
 
     let kdf = kdf.unwrap_or_default();
 
-    let mut key_array = [0u8; 32];
-    proxmox::sys::linux::fill_with_random_data(&mut key_array)?;
-    let crypt_config = CryptConfig::new(key_array.clone())?;
-    let key = key_array.to_vec();
+    let mut key = [0u8; 32];
+    proxmox::sys::linux::fill_with_random_data(&mut key)?;
 
     match kdf {
         Kdf::None => {
-            let created = proxmox::tools::time::epoch_i64();
-
-            store_key_config(
-                &path,
-                false,
-                KeyConfig {
-                    kdf: None,
-                    created,
-                    modified: created,
-                    data: key,
-                    fingerprint: Some(crypt_config.fingerprint()),
-                },
-            )?;
+            if hint.is_some() {
+                bail!("password hint not allowed for Kdf::None");
+            }
+
+            let key_config = KeyConfig::without_password(key)?;
+
+            key_config.store(path, false)?;
         }
-        Kdf::Scrypt => {
+        Kdf::Scrypt | Kdf::PBKDF2 => {
             // always read passphrase from tty
             if !tty::stdin_isatty() {
                 bail!("unable to read passphrase - no tty");
@@ -153,10 +182,93 @@ fn create(kdf: Option<Kdf>, path: Option<String>) -> Result<(), Error> {
 
             let password = tty::read_and_verify_password("Encryption Key Password: ")?;
 
-            let mut key_config = encrypt_key_with_passphrase(&key, &password)?;
-            key_config.fingerprint = Some(crypt_config.fingerprint());
+            let mut key_config = KeyConfig::with_key(&key, &password, kdf)?;
+            key_config.hint = hint;
 
-            store_key_config(&path, false, key_config)?;
+            key_config.store(&path, false)?;
+        }
+    }
+
+    Ok(())
+}
+
+#[api(
+    input: {
+        properties: {
+            "master-keyfile": {
+                description: "(Private) master key to use.",
+            },
+            "encrypted-keyfile": {
+                description: "RSA-encrypted keyfile to import.",
+            },
+            kdf: {
+                type: Kdf,
+                optional: true,
+            },
+            "path": {
+                description:
+                    "Output file. Without this the key will become the new default encryption key.",
+                optional: true,
+            },
+            hint: {
+                schema: PASSWORD_HINT_SCHEMA,
+                optional: true,
+            },
+        },
+    },
+)]
+/// Import an encrypted backup of an encryption key using a (private) master key.
+async fn import_with_master_key(
+    master_keyfile: String,
+    encrypted_keyfile: String,
+    kdf: Option<Kdf>,
+    path: Option<String>,
+    hint: Option<String>,
+) -> Result<(), Error> {
+    let path = match path {
+        Some(path) => PathBuf::from(path),
+        None => {
+            let path = place_default_encryption_key()?;
+            if path.exists() {
+                bail!("Please remove default encryption key at {:?} before importing to default location (or choose a non-default one).", path);
+            }
+            println!("Importing key to default location at: {:?}", path);
+            path
+        }
+    };
+
+    let encrypted_key = file_get_contents(&encrypted_keyfile)?;
+    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)
+        .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))?;
+
+    let (key, created, _fingerprint) =
+        rsa_decrypt_key_config(master_key, &encrypted_key, &get_encryption_key_password)?;
+
+    let kdf = kdf.unwrap_or_default();
+    match kdf {
+        Kdf::None => {
+            if hint.is_some() {
+                bail!("password hint not allowed for Kdf::None");
+            }
+
+            let mut key_config = KeyConfig::without_password(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: ")?;
+
+            let mut new_key_config = KeyConfig::with_key(&key, &password, kdf)?;
+            new_key_config.created = created; // keep original value
+            new_key_config.hint = hint;
+
+            new_key_config.store(path, true)?;
         }
     }
 
@@ -173,19 +285,26 @@ fn create(kdf: Option<Kdf>, path: Option<String>) -> Result<(), Error> {
             path: {
                 description: "Key file. Without this the default key's password will be changed.",
                 optional: true,
-            }
+            },
+            hint: {
+                schema: PASSWORD_HINT_SCHEMA,
+                optional: true,
+            },
         },
     },
 )]
 /// Change the encryption key's password.
-fn change_passphrase(kdf: Option<Kdf>, path: Option<String>) -> Result<(), Error> {
+fn change_passphrase(
+    kdf: Option<Kdf>,
+    path: Option<String>,
+    hint: Option<String>,
+) -> 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")
-                })?;
+            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
         }
@@ -197,38 +316,83 @@ fn change_passphrase(kdf: Option<Kdf>, path: Option<String>) -> Result<(), Error
         bail!("unable to change passphrase - no tty");
     }
 
-    let (key, created, fingerprint) = load_and_decrypt_key(&path, &get_encryption_key_password)?;
+    let key_config = KeyConfig::load(&path)?;
+    let (key, created, _fingerprint) = key_config.decrypt(&get_encryption_key_password)?;
 
     match kdf {
         Kdf::None => {
-            let modified = proxmox::tools::time::epoch_i64();
-
-            store_key_config(
-                &path,
-                true,
-                KeyConfig {
-                    kdf: None,
-                    created, // keep original value
-                    modified,
-                    data: key.to_vec(),
-                    fingerprint: Some(fingerprint),
-                },
-            )?;
+            if hint.is_some() {
+                bail!("password hint not allowed for Kdf::None");
+            }
+
+            let mut key_config = KeyConfig::without_password(key)?;
+            key_config.created = created; // keep original value
+
+            key_config.store(&path, true)?;
         }
-        Kdf::Scrypt => {
+        Kdf::Scrypt | Kdf::PBKDF2 => {
             let password = tty::read_and_verify_password("New Password: ")?;
 
-            let mut new_key_config = encrypt_key_with_passphrase(&key, &password)?;
+            let mut new_key_config = KeyConfig::with_key(&key, &password, kdf)?;
             new_key_config.created = created; // keep original value
-            new_key_config.fingerprint = Some(fingerprint);
+            new_key_config.hint = hint;
 
-            store_key_config(&path, true, new_key_config)?;
+            new_key_config.store(&path, true)?;
         }
     }
 
     Ok(())
 }
 
+#[api(
+    input: {
+        properties: {
+            path: {
+                description: "Key file. Without this the default key's metadata will be shown.",
+                optional: true,
+            },
+            "output-format": {
+                schema: OUTPUT_FORMAT,
+                optional: true,
+            },
+        },
+    },
+)]
+/// Print the encryption key's metadata.
+fn show_key(path: Option<String>, param: Value) -> Result<(), Error> {
+    let path = match path {
+        Some(path) => PathBuf::from(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);
+
+    let mut info: KeyInfo = (&config).into();
+    info.path = Some(format!("{:?}", path));
+
+    let options = proxmox::api::cli::default_table_format_options()
+        .column(ColumnConfig::new("path"))
+        .column(ColumnConfig::new("kdf"))
+        .column(ColumnConfig::new("created").renderer(tools::format::render_epoch))
+        .column(ColumnConfig::new("modified").renderer(tools::format::render_epoch))
+        .column(ColumnConfig::new("fingerprint"))
+        .column(ColumnConfig::new("hint"));
+
+    let return_type = ReturnType::new(false, &KeyInfo::API_SCHEMA);
+
+    format_and_print_result_full(
+        &mut serde_json::to_value(info)?,
+        &return_type,
+        &output_format,
+        &options,
+    );
+
+    Ok(())
+}
+
 #[api(
     input: {
         properties: {
@@ -240,14 +404,24 @@ fn change_passphrase(kdf: Option<Kdf>, path: Option<String>) -> Result<(), Error
 )]
 /// 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())?;
 
@@ -265,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: ")?)?;
@@ -276,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);
@@ -285,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: {
@@ -293,12 +527,11 @@ 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": {
                 type: PaperkeyFormat,
-                description: "Output format. Text or Html.",
                 optional: true,
             },
         },
@@ -314,24 +547,14 @@ 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)?;
-    let data = std::str::from_utf8(&data)?;
-
-    let format = output_format.unwrap_or(PaperkeyFormat::Html);
+    let data = String::from_utf8(data)?;
 
-    match format {
-        PaperkeyFormat::Html => paperkey_html(data, subject),
-        PaperkeyFormat::Text => paperkey_text(data, subject),
-    }
+    generate_paper_key(std::io::stdout(), &data, subject, output_format)
 }
 
 pub fn cli() -> CliCommandMap {
@@ -339,6 +562,14 @@ pub fn cli() -> CliCommandMap {
         .arg_param(&["path"])
         .completion_cb("path", tools::complete_file_name);
 
+    let key_import_with_master_key_cmd_def = CliCommand::new(&API_METHOD_IMPORT_WITH_MASTER_KEY)
+        .arg_param(&["master-keyfile"])
+        .completion_cb("master-keyfile", tools::complete_file_name)
+        .arg_param(&["encrypted-keyfile"])
+        .completion_cb("encrypted-keyfile", tools::complete_file_name)
+        .arg_param(&["path"])
+        .completion_cb("path", tools::complete_file_name);
+
     let key_change_passphrase_cmd_def = CliCommand::new(&API_METHOD_CHANGE_PASSPHRASE)
         .arg_param(&["path"])
         .completion_cb("path", tools::complete_file_name);
@@ -347,6 +578,13 @@ 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"])
+        .completion_cb("path", tools::complete_file_name);
 
     let paper_key_cmd_def = CliCommand::new(&API_METHOD_PAPER_KEY)
         .arg_param(&["path"])
@@ -354,208 +592,11 @@ pub fn cli() -> CliCommandMap {
 
     CliCommandMap::new()
         .insert("create", key_create_cmd_def)
+        .insert("import-with-master-key", key_import_with_master_key_cmd_def)
         .insert("create-master-key", key_create_master_key_cmd_def)
         .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)
 }
-
-fn paperkey_html(data: &str, subject: Option<String>) -> Result<(), Error> {
-
-    let img_size_pt = 500;
-
-    println!("<!DOCTYPE html>");
-    println!("<html lang=\"en\">");
-    println!("<head>");
-    println!("<meta charset=\"utf-8\">");
-    println!("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">");
-    println!("<title>Proxmox Backup Paperkey</title>");
-    println!("<style type=\"text/css\">");
-
-    println!("  p {{");
-    println!("    font-size: 12pt;");
-    println!("    font-family: monospace;");
-    println!("    white-space: pre-wrap;");
-    println!("    line-break: anywhere;");
-    println!("  }}");
-
-    println!("</style>");
-
-    println!("</head>");
-
-    println!("<body>");
-
-    if let Some(subject) = subject {
-        println!("<p>Subject: {}</p>", subject);
-    }
-
-    if data.starts_with("-----BEGIN ENCRYPTED PRIVATE KEY-----\n") {
-        let lines: Vec<String> = data.lines()
-            .map(|s| s.trim_end())
-            .filter(|s| !s.is_empty())
-            .map(String::from)
-            .collect();
-
-        if !lines[lines.len()-1].starts_with("-----END ENCRYPTED PRIVATE KEY-----") {
-            bail!("unexpected key format");
-        }
-
-        if lines.len() < 20 {
-            bail!("unexpected key format");
-        }
-
-        const BLOCK_SIZE: usize = 20;
-        let blocks = (lines.len() + BLOCK_SIZE -1)/BLOCK_SIZE;
-
-        for i in 0..blocks {
-            let start = i*BLOCK_SIZE;
-            let mut end = start + BLOCK_SIZE;
-            if end > lines.len() {
-                end = lines.len();
-            }
-            let data = &lines[start..end];
-
-            println!("<div style=\"page-break-inside: avoid;page-break-after: always\">");
-            println!("<p>");
-
-            for l in start..end {
-                println!("{:02}: {}", l, lines[l]);
-            }
-
-            println!("</p>");
-
-            let data = data.join("\n");
-            let qr_code = generate_qr_code("svg", data.as_bytes())?;
-            let qr_code = base64::encode_config(&qr_code, base64::STANDARD_NO_PAD);
-
-            println!("<center>");
-            println!("<img");
-            println!("width=\"{}pt\" height=\"{}pt\"", img_size_pt, img_size_pt);
-            println!("src=\"data:image/svg+xml;base64,{}\"/>", qr_code);
-            println!("</center>");
-            println!("</div>");
-       }
-
-        println!("</body>");
-        println!("</html>");
-        return Ok(());
-    }
-
-    let key_config: KeyConfig = serde_json::from_str(&data)?;
-    let key_text = serde_json::to_string_pretty(&key_config)?;
-
-    println!("<div style=\"page-break-inside: avoid\">");
-
-    println!("<p>");
-
-    println!("-----BEGIN PROXMOX BACKUP KEY-----");
-
-    for line in key_text.lines() {
-        println!("{}", line);
-    }
-
-    println!("-----END PROXMOX BACKUP KEY-----");
-
-    println!("</p>");
-
-    let qr_code = generate_qr_code("svg", key_text.as_bytes())?;
-    let qr_code = base64::encode_config(&qr_code, base64::STANDARD_NO_PAD);
-
-    println!("<center>");
-    println!("<img");
-    println!("width=\"{}pt\" height=\"{}pt\"", img_size_pt, img_size_pt);
-    println!("src=\"data:image/svg+xml;base64,{}\"/>", qr_code);
-    println!("</center>");
-
-    println!("</div>");
-
-    println!("</body>");
-    println!("</html>");
-
-    Ok(())
-}
-
-fn paperkey_text(data: &str, subject: Option<String>) -> Result<(), Error> {
-
-    if let Some(subject) = subject {
-        println!("Subject: {}\n", subject);
-    }
-
-    if data.starts_with("-----BEGIN ENCRYPTED PRIVATE KEY-----\n") {
-        let lines: Vec<String> = data.lines()
-            .map(|s| s.trim_end())
-            .filter(|s| !s.is_empty())
-            .map(String::from)
-            .collect();
-
-        if !lines[lines.len()-1].starts_with("-----END ENCRYPTED PRIVATE KEY-----") {
-            bail!("unexpected key format");
-        }
-
-        if lines.len() < 20 {
-            bail!("unexpected key format");
-        }
-
-        const BLOCK_SIZE: usize = 5;
-        let blocks = (lines.len() + BLOCK_SIZE -1)/BLOCK_SIZE;
-
-        for i in 0..blocks {
-            let start = i*BLOCK_SIZE;
-            let mut end = start + BLOCK_SIZE;
-            if end > lines.len() {
-                end = lines.len();
-            }
-            let data = &lines[start..end];
-
-            for l in start..end {
-                println!("{:-2}: {}", l, lines[l]);
-            }
-            let data = data.join("\n");
-            let qr_code = generate_qr_code("utf8i", data.as_bytes())?;
-            let qr_code = String::from_utf8(qr_code)
-                .map_err(|_| format_err!("Failed to read qr code (got non-utf8 data)"))?;
-            println!("{}", qr_code);
-            println!("{}", char::from(12u8)); // page break
-
-        }
-        return Ok(());
-    }
-
-    let key_config: KeyConfig = serde_json::from_str(&data)?;
-    let key_text = serde_json::to_string_pretty(&key_config)?;
-
-    println!("-----BEGIN PROXMOX BACKUP KEY-----");
-    println!("{}", key_text);
-    println!("-----END PROXMOX BACKUP KEY-----");
-
-    let qr_code = generate_qr_code("utf8i", key_text.as_bytes())?;
-    let qr_code = String::from_utf8(qr_code)
-        .map_err(|_| format_err!("Failed to read qr code (got non-utf8 data)"))?;
-
-    println!("{}", qr_code);
-
-    Ok(())
-}
-
-fn generate_qr_code(output_type: &str, data: &[u8]) -> Result<Vec<u8>, Error> {
-
-    let mut child = Command::new("qrencode")
-        .args(&["-t", output_type, "-m0", "-s1", "-lm", "--output", "-"])
-        .stdin(Stdio::piped())
-        .stdout(Stdio::piped())
-        .spawn()?;
-
-    {
-        let stdin = child.stdin.as_mut()
-            .ok_or_else(|| format_err!("Failed to open stdin"))?;
-        stdin.write_all(data)
-            .map_err(|_| format_err!("Failed to write to stdin"))?;
-    }
-
-    let output = child.wait_with_output()
-        .map_err(|_| format_err!("Failed to read stdout"))?;
-
-    let output = crate::tools::command_output(output, None)?;
-
-    Ok(output)
-}