1 use std
::path
::PathBuf
;
3 use std
::process
::{Stdio, Command}
;
5 use anyhow
::{bail, format_err, Error}
;
6 use serde
::{Deserialize, Serialize}
;
10 use proxmox
::api
::cli
::{
14 format_and_print_result_full
,
18 use proxmox
::api
::router
::ReturnType
;
19 use proxmox
::sys
::linux
::tty
;
20 use proxmox
::tools
::fs
::{file_get_contents, replace_file, CreateOptions}
;
22 use proxmox_backup
::backup
::{
23 encrypt_key_with_passphrase
,
25 rsa_decrypt_key_config
,
33 use proxmox_backup
::tools
;
36 #[derive(Debug, Serialize, Deserialize)]
37 #[serde(rename_all = "lowercase")]
38 /// Paperkey output format
39 pub enum PaperkeyFormat
{
40 /// Format as Utf8 text. Includes QR codes as ascii-art.
42 /// Format as Html. Includes QR codes as png images.
46 pub const DEFAULT_ENCRYPTION_KEY_FILE_NAME
: &str = "encryption-key.json";
47 pub const MASTER_PUBKEY_FILE_NAME
: &str = "master-public.pem";
49 pub fn find_master_pubkey() -> Result
<Option
<PathBuf
>, Error
> {
50 super::find_xdg_file(MASTER_PUBKEY_FILE_NAME
, "main public key file")
53 pub fn place_master_pubkey() -> Result
<PathBuf
, Error
> {
54 super::place_xdg_file(MASTER_PUBKEY_FILE_NAME
, "main public key file")
57 pub fn find_default_encryption_key() -> Result
<Option
<PathBuf
>, Error
> {
58 super::find_xdg_file(DEFAULT_ENCRYPTION_KEY_FILE_NAME
, "default encryption key file")
61 pub fn place_default_encryption_key() -> Result
<PathBuf
, Error
> {
62 super::place_xdg_file(DEFAULT_ENCRYPTION_KEY_FILE_NAME
, "default encryption key file")
65 pub fn read_optional_default_encryption_key() -> Result
<Option
<Vec
<u8>>, Error
> {
66 find_default_encryption_key()?
67 .map(file_get_contents
)
71 pub fn get_encryption_key_password() -> Result
<Vec
<u8>, Error
> {
72 // fixme: implement other input methods
74 use std
::env
::VarError
::*;
75 match std
::env
::var("PBS_ENCRYPTION_PASSWORD") {
76 Ok(p
) => return Ok(p
.as_bytes().to_vec()),
77 Err(NotUnicode(_
)) => bail
!("PBS_ENCRYPTION_PASSWORD contains bad characters"),
83 // If we're on a TTY, query the user for a password
84 if tty
::stdin_isatty() {
85 return Ok(tty
::read_password("Encryption Key Password: ")?
);
88 bail
!("no password input mechanism available");
100 "Output file. Without this the key will become the new default encryption key.",
106 /// Create a new encryption key.
107 fn create(kdf
: Option
<Kdf
>, path
: Option
<String
>) -> Result
<(), Error
> {
108 let path
= match path
{
109 Some(path
) => PathBuf
::from(path
),
111 let path
= place_default_encryption_key()?
;
112 println
!("creating default key at: {:?}", path
);
117 let kdf
= kdf
.unwrap_or_default();
119 let mut key_array
= [0u8; 32];
120 proxmox
::sys
::linux
::fill_with_random_data(&mut key_array
)?
;
121 let crypt_config
= CryptConfig
::new(key_array
)?
;
122 let key
= key_array
.to_vec();
126 let created
= proxmox
::tools
::time
::epoch_i64();
136 fingerprint
: Some(crypt_config
.fingerprint()),
140 Kdf
::Scrypt
| Kdf
::PBKDF2
=> {
141 // always read passphrase from tty
142 if !tty
::stdin_isatty() {
143 bail
!("unable to read passphrase - no tty");
146 let password
= tty
::read_and_verify_password("Encryption Key Password: ")?
;
148 let mut key_config
= encrypt_key_with_passphrase(&key
, &password
, kdf
)?
;
149 key_config
.fingerprint
= Some(crypt_config
.fingerprint());
151 store_key_config(&path
, false, key_config
)?
;
162 description
: "(Private) master key to use.",
164 "encrypted-keyfile": {
165 description
: "RSA-encrypted keyfile to import.",
173 "Output file. Without this the key will become the new default encryption key.",
179 /// Import an encrypted backup of an encryption key using a (private) master key.
180 async
fn import_with_master_key(
181 master_keyfile
: String
,
182 encrypted_keyfile
: String
,
184 path
: Option
<String
>,
185 ) -> Result
<(), Error
> {
186 let path
= match path
{
187 Some(path
) => PathBuf
::from(path
),
189 let path
= place_default_encryption_key()?
;
191 bail
!("Please remove default encryption key at {:?} before importing to default location (or choose a non-default one).", path
);
193 println
!("Importing key to default location at: {:?}", path
);
198 let encrypted_key
= file_get_contents(&encrypted_keyfile
)?
;
199 let master_key
= file_get_contents(&master_keyfile
)?
;
200 let password
= tty
::read_password("Master Key Password: ")?
;
203 openssl
::pkey
::PKey
::private_key_from_pem_passphrase(&master_key
, &password
)
204 .map_err(|err
| format_err
!("failed to read PEM-formatted private key - {}", err
))?
206 .map_err(|err
| format_err
!("not a valid private RSA key - {}", err
))?
;
208 let (key
, created
, fingerprint
) =
209 rsa_decrypt_key_config(master_key
, &encrypted_key
, &get_encryption_key_password
)?
;
211 let kdf
= kdf
.unwrap_or_default();
214 let modified
= proxmox
::tools
::time
::epoch_i64();
221 created
, // keep original value
224 fingerprint
: Some(fingerprint
),
228 Kdf
::Scrypt
| Kdf
::PBKDF2
=> {
229 let password
= tty
::read_and_verify_password("New Password: ")?
;
231 let mut new_key_config
= encrypt_key_with_passphrase(&key
, &password
, kdf
)?
;
232 new_key_config
.created
= created
; // keep original value
233 new_key_config
.fingerprint
= Some(fingerprint
);
235 store_key_config(&path
, true, new_key_config
)?
;
250 description
: "Key file. Without this the default key's password will be changed.",
256 /// Change the encryption key's password.
257 fn change_passphrase(kdf
: Option
<Kdf
>, path
: Option
<String
>) -> Result
<(), Error
> {
258 let path
= match path
{
259 Some(path
) => PathBuf
::from(path
),
261 let path
= find_default_encryption_key()?
263 format_err
!("no encryption file provided and no default file found")
265 println
!("updating default key at: {:?}", path
);
270 let kdf
= kdf
.unwrap_or_default();
272 if !tty
::stdin_isatty() {
273 bail
!("unable to change passphrase - no tty");
276 let (key
, created
, fingerprint
) = load_and_decrypt_key(&path
, &get_encryption_key_password
)?
;
280 let modified
= proxmox
::tools
::time
::epoch_i64();
287 created
, // keep original value
290 fingerprint
: Some(fingerprint
),
294 Kdf
::Scrypt
| Kdf
::PBKDF2
=> {
295 let password
= tty
::read_and_verify_password("New Password: ")?
;
297 let mut new_key_config
= encrypt_key_with_passphrase(&key
, &password
, kdf
)?
;
298 new_key_config
.created
= created
; // keep original value
299 new_key_config
.fingerprint
= Some(fingerprint
);
301 store_key_config(&path
, true, new_key_config
)?
;
315 #[derive(Deserialize, Serialize)]
316 /// Encryption Key Information
321 /// Key creation time
323 /// Key modification time
326 pub fingerprint
: Option
<String
>,
333 description
: "Key file. Without this the default key's metadata will be shown.",
337 schema
: OUTPUT_FORMAT
,
343 /// Print the encryption key's metadata.
345 path
: Option
<String
>,
347 ) -> Result
<(), Error
> {
348 let path
= match path
{
349 Some(path
) => PathBuf
::from(path
),
351 let path
= find_default_encryption_key()?
353 format_err
!("no encryption file provided and no default file found")
360 let config
: KeyConfig
= serde_json
::from_slice(&file_get_contents(path
.clone())?
)?
;
362 let output_format
= get_output_format(¶m
);
365 path
: format
!("{:?}", path
),
366 kdf
: match config
.kdf
{
367 Some(KeyDerivationConfig
::PBKDF2 { .. }
) => Kdf
::PBKDF2
,
368 Some(KeyDerivationConfig
::Scrypt { .. }
) => Kdf
::Scrypt
,
371 created
: config
.created
,
372 modified
: config
.modified
,
373 fingerprint
: match config
.fingerprint
{
374 Some(ref fp
) => Some(format
!("{}", fp
)),
379 let options
= proxmox
::api
::cli
::default_table_format_options()
380 .column(ColumnConfig
::new("path"))
381 .column(ColumnConfig
::new("kdf"))
382 .column(ColumnConfig
::new("created").renderer(tools
::format
::render_epoch
))
383 .column(ColumnConfig
::new("modified").renderer(tools
::format
::render_epoch
))
384 .column(ColumnConfig
::new("fingerprint"));
386 let return_type
= ReturnType
::new(false, &KeyInfo
::API_SCHEMA
);
388 format_and_print_result_full(
389 &mut serde_json
::to_value(info
)?
,
402 description
: "Path to the PEM formatted RSA public key.",
407 /// Import an RSA public key used to put an encrypted version of the symmetric backup encryption
408 /// key onto the backup server along with each backup.
409 fn import_master_pubkey(path
: String
) -> Result
<(), Error
> {
410 let pem_data
= file_get_contents(&path
)?
;
412 if let Err(err
) = openssl
::pkey
::PKey
::public_key_from_pem(&pem_data
) {
413 bail
!("Unable to decode PEM data - {}", err
);
416 let target_path
= place_master_pubkey()?
;
418 replace_file(&target_path
, &pem_data
, CreateOptions
::new())?
;
420 println
!("Imported public master key to {:?}", target_path
);
426 /// Create an RSA public/private key pair used to put an encrypted version of the symmetric backup
427 /// encryption key onto the backup server along with each backup.
428 fn create_master_key() -> Result
<(), Error
> {
429 // we need a TTY to query the new password
430 if !tty
::stdin_isatty() {
431 bail
!("unable to create master key - no tty");
434 let rsa
= openssl
::rsa
::Rsa
::generate(4096)?
;
435 let pkey
= openssl
::pkey
::PKey
::from_rsa(rsa
)?
;
437 let password
= String
::from_utf8(tty
::read_and_verify_password("Master Key Password: ")?
)?
;
439 let pub_key
: Vec
<u8> = pkey
.public_key_to_pem()?
;
440 let filename_pub
= "master-public.pem";
441 println
!("Writing public master key to {}", filename_pub
);
442 replace_file(filename_pub
, pub_key
.as_slice(), CreateOptions
::new())?
;
444 let cipher
= openssl
::symm
::Cipher
::aes_256_cbc();
445 let priv_key
: Vec
<u8> = pkey
.private_key_to_pem_pkcs8_passphrase(cipher
, password
.as_bytes())?
;
447 let filename_priv
= "master-private.pem";
448 println
!("Writing private master key to {}", filename_priv
);
449 replace_file(filename_priv
, priv_key
.as_slice(), CreateOptions
::new())?
;
458 description
: "Key file. Without this the default key's will be used.",
462 description
: "Include the specified subject as titel text.",
466 type: PaperkeyFormat
,
472 /// Generate a printable, human readable text file containing the encryption key.
474 /// This also includes a scanable QR code for fast key restore.
476 path
: Option
<String
>,
477 subject
: Option
<String
>,
478 output_format
: Option
<PaperkeyFormat
>,
479 ) -> Result
<(), Error
> {
480 let path
= match path
{
481 Some(path
) => PathBuf
::from(path
),
483 let path
= find_default_encryption_key()?
485 format_err
!("no encryption file provided and no default file found")
491 let data
= file_get_contents(&path
)?
;
492 let data
= String
::from_utf8(data
)?
;
494 let (data
, is_private_key
) = if data
.starts_with("-----BEGIN ENCRYPTED PRIVATE KEY-----\n") {
495 let lines
: Vec
<String
> = data
497 .map(|s
| s
.trim_end())
498 .filter(|s
| !s
.is_empty())
502 if !lines
[lines
.len()-1].starts_with("-----END ENCRYPTED PRIVATE KEY-----") {
503 bail
!("unexpected key format");
506 if lines
.len() < 20 {
507 bail
!("unexpected key format");
512 match serde_json
::from_str
::<KeyConfig
>(&data
) {
514 let lines
= serde_json
::to_string_pretty(&key_config
)?
522 eprintln
!("Couldn't parse '{:?}' as KeyConfig - {}", path
, err
);
523 bail
!("Neither a PEM-formatted private key, nor a PBS key file.");
528 let format
= output_format
.unwrap_or(PaperkeyFormat
::Html
);
531 PaperkeyFormat
::Html
=> paperkey_html(&data
, subject
, is_private_key
),
532 PaperkeyFormat
::Text
=> paperkey_text(&data
, subject
, is_private_key
),
536 pub fn cli() -> CliCommandMap
{
537 let key_create_cmd_def
= CliCommand
::new(&API_METHOD_CREATE
)
538 .arg_param(&["path"])
539 .completion_cb("path", tools
::complete_file_name
);
541 let key_import_with_master_key_cmd_def
= CliCommand
::new(&API_METHOD_IMPORT_WITH_MASTER_KEY
)
542 .arg_param(&["master-keyfile"])
543 .completion_cb("master-keyfile", tools
::complete_file_name
)
544 .arg_param(&["encrypted-keyfile"])
545 .completion_cb("encrypted-keyfile", tools
::complete_file_name
)
546 .arg_param(&["path"])
547 .completion_cb("path", tools
::complete_file_name
);
549 let key_change_passphrase_cmd_def
= CliCommand
::new(&API_METHOD_CHANGE_PASSPHRASE
)
550 .arg_param(&["path"])
551 .completion_cb("path", tools
::complete_file_name
);
553 let key_create_master_key_cmd_def
= CliCommand
::new(&API_METHOD_CREATE_MASTER_KEY
);
554 let key_import_master_pubkey_cmd_def
= CliCommand
::new(&API_METHOD_IMPORT_MASTER_PUBKEY
)
555 .arg_param(&["path"])
556 .completion_cb("path", tools
::complete_file_name
);
558 let key_show_cmd_def
= CliCommand
::new(&API_METHOD_SHOW_KEY
)
559 .arg_param(&["path"])
560 .completion_cb("path", tools
::complete_file_name
);
562 let paper_key_cmd_def
= CliCommand
::new(&API_METHOD_PAPER_KEY
)
563 .arg_param(&["path"])
564 .completion_cb("path", tools
::complete_file_name
);
567 .insert("create", key_create_cmd_def
)
568 .insert("import-with-master-key", key_import_with_master_key_cmd_def
)
569 .insert("create-master-key", key_create_master_key_cmd_def
)
570 .insert("import-master-pubkey", key_import_master_pubkey_cmd_def
)
571 .insert("change-passphrase", key_change_passphrase_cmd_def
)
572 .insert("show", key_show_cmd_def
)
573 .insert("paperkey", paper_key_cmd_def
)
576 fn paperkey_html(lines
: &[String
], subject
: Option
<String
>, is_private
: bool
) -> Result
<(), Error
> {
578 let img_size_pt
= 500;
580 println
!("<!DOCTYPE html>");
581 println
!("<html lang=\"en\">");
583 println
!("<meta charset=\"utf-8\">");
584 println
!("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">");
585 println
!("<title>Proxmox Backup Paperkey</title>");
586 println
!("<style type=\"text/css\">");
589 println
!(" font-size: 12pt;");
590 println
!(" font-family: monospace;");
591 println
!(" white-space: pre-wrap;");
592 println
!(" line-break: anywhere;");
595 println
!("</style>");
601 if let Some(subject
) = subject
{
602 println
!("<p>Subject: {}</p>", subject
);
606 const BLOCK_SIZE
: usize = 20;
607 let blocks
= (lines
.len() + BLOCK_SIZE
-1)/BLOCK_SIZE
;
610 let start
= i
*BLOCK_SIZE
;
611 let mut end
= start
+ BLOCK_SIZE
;
612 if end
> lines
.len() {
615 let data
= &lines
[start
..end
];
617 println
!("<div style=\"page-break-inside: avoid;page-break-after: always\">");
620 for l
in start
..end
{
621 println
!("{:02}: {}", l
, lines
[l
]);
626 let qr_code
= generate_qr_code("svg", data
)?
;
627 let qr_code
= base64
::encode_config(&qr_code
, base64
::STANDARD_NO_PAD
);
629 println
!("<center>");
631 println
!("width=\"{}pt\" height=\"{}pt\"", img_size_pt
, img_size_pt
);
632 println
!("src=\"data:image/svg+xml;base64,{}\"/>", qr_code
);
633 println
!("</center>");
642 println
!("<div style=\"page-break-inside: avoid\">");
646 println
!("-----BEGIN PROXMOX BACKUP KEY-----");
649 println
!("{}", line
);
652 println
!("-----END PROXMOX BACKUP KEY-----");
656 let qr_code
= generate_qr_code("svg", lines
)?
;
657 let qr_code
= base64
::encode_config(&qr_code
, base64
::STANDARD_NO_PAD
);
659 println
!("<center>");
661 println
!("width=\"{}pt\" height=\"{}pt\"", img_size_pt
, img_size_pt
);
662 println
!("src=\"data:image/svg+xml;base64,{}\"/>", qr_code
);
663 println
!("</center>");
673 fn paperkey_text(lines
: &[String
], subject
: Option
<String
>, is_private
: bool
) -> Result
<(), Error
> {
675 if let Some(subject
) = subject
{
676 println
!("Subject: {}\n", subject
);
680 const BLOCK_SIZE
: usize = 5;
681 let blocks
= (lines
.len() + BLOCK_SIZE
-1)/BLOCK_SIZE
;
684 let start
= i
*BLOCK_SIZE
;
685 let mut end
= start
+ BLOCK_SIZE
;
686 if end
> lines
.len() {
689 let data
= &lines
[start
..end
];
691 for l
in start
..end
{
692 println
!("{:-2}: {}", l
, lines
[l
]);
694 let qr_code
= generate_qr_code("utf8i", data
)?
;
695 let qr_code
= String
::from_utf8(qr_code
)
696 .map_err(|_
| format_err
!("Failed to read qr code (got non-utf8 data)"))?
;
697 println
!("{}", qr_code
);
698 println
!("{}", char::from(12u8)); // page break
704 println
!("-----BEGIN PROXMOX BACKUP KEY-----");
706 println
!("{}", line
);
708 println
!("-----END PROXMOX BACKUP KEY-----");
710 let qr_code
= generate_qr_code("utf8i", &lines
)?
;
711 let qr_code
= String
::from_utf8(qr_code
)
712 .map_err(|_
| format_err
!("Failed to read qr code (got non-utf8 data)"))?
;
714 println
!("{}", qr_code
);
719 fn generate_qr_code(output_type
: &str, lines
: &[String
]) -> Result
<Vec
<u8>, Error
> {
720 let mut child
= Command
::new("qrencode")
721 .args(&["-t", output_type
, "-m0", "-s1", "-lm", "--output", "-"])
722 .stdin(Stdio
::piped())
723 .stdout(Stdio
::piped())
727 let stdin
= child
.stdin
.as_mut()
728 .ok_or_else(|| format_err
!("Failed to open stdin"))?
;
729 let data
= lines
.join("\n");
730 stdin
.write_all(data
.as_bytes())
731 .map_err(|_
| format_err
!("Failed to write to stdin"))?
;
734 let output
= child
.wait_with_output()
735 .map_err(|_
| format_err
!("Failed to read stdout"))?
;
737 let output
= crate::tools
::command_output(output
, None
)?
;