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}
;
29 rsa_decrypt_key_config
,
37 #[derive(Debug, Serialize, Deserialize)]
38 #[serde(rename_all = "lowercase")]
39 /// Paperkey output format
40 pub enum PaperkeyFormat
{
41 /// Format as Utf8 text. Includes QR codes as ascii-art.
43 /// Format as Html. Includes QR codes as png images.
47 pub const DEFAULT_ENCRYPTION_KEY_FILE_NAME
: &str = "encryption-key.json";
48 pub const MASTER_PUBKEY_FILE_NAME
: &str = "master-public.pem";
50 pub fn find_master_pubkey() -> Result
<Option
<PathBuf
>, Error
> {
51 super::find_xdg_file(MASTER_PUBKEY_FILE_NAME
, "main public key file")
54 pub fn place_master_pubkey() -> Result
<PathBuf
, Error
> {
55 super::place_xdg_file(MASTER_PUBKEY_FILE_NAME
, "main public key file")
58 pub fn find_default_encryption_key() -> Result
<Option
<PathBuf
>, Error
> {
59 super::find_xdg_file(DEFAULT_ENCRYPTION_KEY_FILE_NAME
, "default encryption key file")
62 pub fn place_default_encryption_key() -> Result
<PathBuf
, Error
> {
63 super::place_xdg_file(DEFAULT_ENCRYPTION_KEY_FILE_NAME
, "default encryption key file")
66 pub fn read_optional_default_encryption_key() -> Result
<Option
<Vec
<u8>>, Error
> {
67 find_default_encryption_key()?
68 .map(file_get_contents
)
72 pub fn get_encryption_key_password() -> Result
<Vec
<u8>, Error
> {
73 // fixme: implement other input methods
75 use std
::env
::VarError
::*;
76 match std
::env
::var("PBS_ENCRYPTION_PASSWORD") {
77 Ok(p
) => return Ok(p
.as_bytes().to_vec()),
78 Err(NotUnicode(_
)) => bail
!("PBS_ENCRYPTION_PASSWORD contains bad characters"),
84 // If we're on a TTY, query the user for a password
85 if tty
::stdin_isatty() {
86 return Ok(tty
::read_password("Encryption Key Password: ")?
);
89 bail
!("no password input mechanism available");
101 "Output file. Without this the key will become the new default encryption key.",
105 schema
: PASSWORD_HINT_SCHEMA
,
111 /// Create a new encryption key.
114 path
: Option
<String
>,
116 ) -> Result
<(), Error
> {
117 let path
= match path
{
118 Some(path
) => PathBuf
::from(path
),
120 let path
= place_default_encryption_key()?
;
121 println
!("creating default key at: {:?}", path
);
126 let kdf
= kdf
.unwrap_or_default();
128 let mut key
= [0u8; 32];
129 proxmox
::sys
::linux
::fill_with_random_data(&mut key
)?
;
130 let crypt_config
= CryptConfig
::new(key
.clone())?
;
135 bail
!("password hint not allowed for Kdf::None");
138 let mut key_config
= KeyConfig
::without_password(key
);
139 key_config
.fingerprint
= Some(crypt_config
.fingerprint());
141 key_config
.store(path
, false)?
;
143 Kdf
::Scrypt
| Kdf
::PBKDF2
=> {
144 // always read passphrase from tty
145 if !tty
::stdin_isatty() {
146 bail
!("unable to read passphrase - no tty");
149 let password
= tty
::read_and_verify_password("Encryption Key Password: ")?
;
151 let mut key_config
= KeyConfig
::with_key(&key
, &password
, kdf
)?
;
152 key_config
.fingerprint
= Some(crypt_config
.fingerprint());
153 key_config
.hint
= hint
;
155 key_config
.store(&path
, false)?
;
166 description
: "(Private) master key to use.",
168 "encrypted-keyfile": {
169 description
: "RSA-encrypted keyfile to import.",
177 "Output file. Without this the key will become the new default encryption key.",
181 schema
: PASSWORD_HINT_SCHEMA
,
187 /// Import an encrypted backup of an encryption key using a (private) master key.
188 async
fn import_with_master_key(
189 master_keyfile
: String
,
190 encrypted_keyfile
: String
,
192 path
: Option
<String
>,
193 hint
: Option
<String
>,
194 ) -> Result
<(), Error
> {
195 let path
= match path
{
196 Some(path
) => PathBuf
::from(path
),
198 let path
= place_default_encryption_key()?
;
200 bail
!("Please remove default encryption key at {:?} before importing to default location (or choose a non-default one).", path
);
202 println
!("Importing key to default location at: {:?}", path
);
207 let encrypted_key
= file_get_contents(&encrypted_keyfile
)?
;
208 let master_key
= file_get_contents(&master_keyfile
)?
;
209 let password
= tty
::read_password("Master Key Password: ")?
;
212 openssl
::pkey
::PKey
::private_key_from_pem_passphrase(&master_key
, &password
)
213 .map_err(|err
| format_err
!("failed to read PEM-formatted private key - {}", err
))?
215 .map_err(|err
| format_err
!("not a valid private RSA key - {}", err
))?
;
217 let (key
, created
, fingerprint
) =
218 rsa_decrypt_key_config(master_key
, &encrypted_key
, &get_encryption_key_password
)?
;
220 let kdf
= kdf
.unwrap_or_default();
224 bail
!("password hint not allowed for Kdf::None");
227 let mut key_config
= KeyConfig
::without_password(key
);
228 key_config
.created
= created
; // keep original value
229 key_config
.fingerprint
= Some(fingerprint
);
231 key_config
.store(path
, true)?
;
234 Kdf
::Scrypt
| Kdf
::PBKDF2
=> {
235 let password
= tty
::read_and_verify_password("New Password: ")?
;
237 let mut new_key_config
= KeyConfig
::with_key(&key
, &password
, kdf
)?
;
238 new_key_config
.created
= created
; // keep original value
239 new_key_config
.fingerprint
= Some(fingerprint
);
240 new_key_config
.hint
= hint
;
242 new_key_config
.store(path
, true)?
;
257 description
: "Key file. Without this the default key's password will be changed.",
261 schema
: PASSWORD_HINT_SCHEMA
,
267 /// Change the encryption key's password.
268 fn change_passphrase(
270 path
: Option
<String
>,
271 hint
: Option
<String
>,
272 ) -> Result
<(), Error
> {
273 let path
= match path
{
274 Some(path
) => PathBuf
::from(path
),
276 let path
= find_default_encryption_key()?
278 format_err
!("no encryption file provided and no default file found")
280 println
!("updating default key at: {:?}", path
);
285 let kdf
= kdf
.unwrap_or_default();
287 if !tty
::stdin_isatty() {
288 bail
!("unable to change passphrase - no tty");
291 let key_config
= KeyConfig
::load(&path
)?
;
292 let (key
, created
, fingerprint
) = key_config
.decrypt(&get_encryption_key_password
)?
;
297 bail
!("password hint not allowed for Kdf::None");
300 let mut key_config
= KeyConfig
::without_password(key
);
301 key_config
.created
= created
; // keep original value
302 key_config
.fingerprint
= Some(fingerprint
);
304 key_config
.store(&path
, true)?
;
306 Kdf
::Scrypt
| Kdf
::PBKDF2
=> {
307 let password
= tty
::read_and_verify_password("New Password: ")?
;
309 let mut new_key_config
= KeyConfig
::with_key(&key
, &password
, kdf
)?
;
310 new_key_config
.created
= created
; // keep original value
311 new_key_config
.fingerprint
= Some(fingerprint
);
312 new_key_config
.hint
= hint
;
314 new_key_config
.store(&path
, true)?
;
325 description
: "Key file. Without this the default key's metadata will be shown.",
329 schema
: OUTPUT_FORMAT
,
335 /// Print the encryption key's metadata.
337 path
: Option
<String
>,
339 ) -> Result
<(), Error
> {
340 let path
= match path
{
341 Some(path
) => PathBuf
::from(path
),
343 let path
= find_default_encryption_key()?
345 format_err
!("no encryption file provided and no default file found")
352 let config
: KeyConfig
= serde_json
::from_slice(&file_get_contents(path
.clone())?
)?
;
354 let output_format
= get_output_format(¶m
);
356 let mut info
: KeyInfo
= (&config
).into();
357 info
.path
= Some(format
!("{:?}", path
));
359 let options
= proxmox
::api
::cli
::default_table_format_options()
360 .column(ColumnConfig
::new("path"))
361 .column(ColumnConfig
::new("kdf"))
362 .column(ColumnConfig
::new("created").renderer(tools
::format
::render_epoch
))
363 .column(ColumnConfig
::new("modified").renderer(tools
::format
::render_epoch
))
364 .column(ColumnConfig
::new("fingerprint"))
365 .column(ColumnConfig
::new("hint"));
367 let return_type
= ReturnType
::new(false, &KeyInfo
::API_SCHEMA
);
369 format_and_print_result_full(
370 &mut serde_json
::to_value(info
)?
,
383 description
: "Path to the PEM formatted RSA public key.",
388 /// Import an RSA public key used to put an encrypted version of the symmetric backup encryption
389 /// key onto the backup server along with each backup.
390 fn import_master_pubkey(path
: String
) -> Result
<(), Error
> {
391 let pem_data
= file_get_contents(&path
)?
;
393 if let Err(err
) = openssl
::pkey
::PKey
::public_key_from_pem(&pem_data
) {
394 bail
!("Unable to decode PEM data - {}", err
);
397 let target_path
= place_master_pubkey()?
;
399 replace_file(&target_path
, &pem_data
, CreateOptions
::new())?
;
401 println
!("Imported public master key to {:?}", target_path
);
407 /// Create an RSA public/private key pair used to put an encrypted version of the symmetric backup
408 /// encryption key onto the backup server along with each backup.
409 fn create_master_key() -> Result
<(), Error
> {
410 // we need a TTY to query the new password
411 if !tty
::stdin_isatty() {
412 bail
!("unable to create master key - no tty");
415 let rsa
= openssl
::rsa
::Rsa
::generate(4096)?
;
416 let pkey
= openssl
::pkey
::PKey
::from_rsa(rsa
)?
;
418 let password
= String
::from_utf8(tty
::read_and_verify_password("Master Key Password: ")?
)?
;
420 let pub_key
: Vec
<u8> = pkey
.public_key_to_pem()?
;
421 let filename_pub
= "master-public.pem";
422 println
!("Writing public master key to {}", filename_pub
);
423 replace_file(filename_pub
, pub_key
.as_slice(), CreateOptions
::new())?
;
425 let cipher
= openssl
::symm
::Cipher
::aes_256_cbc();
426 let priv_key
: Vec
<u8> = pkey
.private_key_to_pem_pkcs8_passphrase(cipher
, password
.as_bytes())?
;
428 let filename_priv
= "master-private.pem";
429 println
!("Writing private master key to {}", filename_priv
);
430 replace_file(filename_priv
, priv_key
.as_slice(), CreateOptions
::new())?
;
439 description
: "Key file. Without this the default key's will be used.",
443 description
: "Include the specified subject as titel text.",
447 type: PaperkeyFormat
,
453 /// Generate a printable, human readable text file containing the encryption key.
455 /// This also includes a scanable QR code for fast key restore.
457 path
: Option
<String
>,
458 subject
: Option
<String
>,
459 output_format
: Option
<PaperkeyFormat
>,
460 ) -> Result
<(), Error
> {
461 let path
= match path
{
462 Some(path
) => PathBuf
::from(path
),
464 let path
= find_default_encryption_key()?
466 format_err
!("no encryption file provided and no default file found")
472 let data
= file_get_contents(&path
)?
;
473 let data
= String
::from_utf8(data
)?
;
475 let (data
, is_private_key
) = if data
.starts_with("-----BEGIN ENCRYPTED PRIVATE KEY-----\n") {
476 let lines
: Vec
<String
> = data
478 .map(|s
| s
.trim_end())
479 .filter(|s
| !s
.is_empty())
483 if !lines
[lines
.len()-1].starts_with("-----END ENCRYPTED PRIVATE KEY-----") {
484 bail
!("unexpected key format");
487 if lines
.len() < 20 {
488 bail
!("unexpected key format");
493 match serde_json
::from_str
::<KeyConfig
>(&data
) {
495 let lines
= serde_json
::to_string_pretty(&key_config
)?
503 eprintln
!("Couldn't parse '{:?}' as KeyConfig - {}", path
, err
);
504 bail
!("Neither a PEM-formatted private key, nor a PBS key file.");
509 let format
= output_format
.unwrap_or(PaperkeyFormat
::Html
);
512 PaperkeyFormat
::Html
=> paperkey_html(&data
, subject
, is_private_key
),
513 PaperkeyFormat
::Text
=> paperkey_text(&data
, subject
, is_private_key
),
517 pub fn cli() -> CliCommandMap
{
518 let key_create_cmd_def
= CliCommand
::new(&API_METHOD_CREATE
)
519 .arg_param(&["path"])
520 .completion_cb("path", tools
::complete_file_name
);
522 let key_import_with_master_key_cmd_def
= CliCommand
::new(&API_METHOD_IMPORT_WITH_MASTER_KEY
)
523 .arg_param(&["master-keyfile"])
524 .completion_cb("master-keyfile", tools
::complete_file_name
)
525 .arg_param(&["encrypted-keyfile"])
526 .completion_cb("encrypted-keyfile", tools
::complete_file_name
)
527 .arg_param(&["path"])
528 .completion_cb("path", tools
::complete_file_name
);
530 let key_change_passphrase_cmd_def
= CliCommand
::new(&API_METHOD_CHANGE_PASSPHRASE
)
531 .arg_param(&["path"])
532 .completion_cb("path", tools
::complete_file_name
);
534 let key_create_master_key_cmd_def
= CliCommand
::new(&API_METHOD_CREATE_MASTER_KEY
);
535 let key_import_master_pubkey_cmd_def
= CliCommand
::new(&API_METHOD_IMPORT_MASTER_PUBKEY
)
536 .arg_param(&["path"])
537 .completion_cb("path", tools
::complete_file_name
);
539 let key_show_cmd_def
= CliCommand
::new(&API_METHOD_SHOW_KEY
)
540 .arg_param(&["path"])
541 .completion_cb("path", tools
::complete_file_name
);
543 let paper_key_cmd_def
= CliCommand
::new(&API_METHOD_PAPER_KEY
)
544 .arg_param(&["path"])
545 .completion_cb("path", tools
::complete_file_name
);
548 .insert("create", key_create_cmd_def
)
549 .insert("import-with-master-key", key_import_with_master_key_cmd_def
)
550 .insert("create-master-key", key_create_master_key_cmd_def
)
551 .insert("import-master-pubkey", key_import_master_pubkey_cmd_def
)
552 .insert("change-passphrase", key_change_passphrase_cmd_def
)
553 .insert("show", key_show_cmd_def
)
554 .insert("paperkey", paper_key_cmd_def
)
557 fn paperkey_html(lines
: &[String
], subject
: Option
<String
>, is_private
: bool
) -> Result
<(), Error
> {
559 let img_size_pt
= 500;
561 println
!("<!DOCTYPE html>");
562 println
!("<html lang=\"en\">");
564 println
!("<meta charset=\"utf-8\">");
565 println
!("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">");
566 println
!("<title>Proxmox Backup Paperkey</title>");
567 println
!("<style type=\"text/css\">");
570 println
!(" font-size: 12pt;");
571 println
!(" font-family: monospace;");
572 println
!(" white-space: pre-wrap;");
573 println
!(" line-break: anywhere;");
576 println
!("</style>");
582 if let Some(subject
) = subject
{
583 println
!("<p>Subject: {}</p>", subject
);
587 const BLOCK_SIZE
: usize = 20;
588 let blocks
= (lines
.len() + BLOCK_SIZE
-1)/BLOCK_SIZE
;
591 let start
= i
*BLOCK_SIZE
;
592 let mut end
= start
+ BLOCK_SIZE
;
593 if end
> lines
.len() {
596 let data
= &lines
[start
..end
];
598 println
!("<div style=\"page-break-inside: avoid;page-break-after: always\">");
601 for l
in start
..end
{
602 println
!("{:02}: {}", l
, lines
[l
]);
607 let qr_code
= generate_qr_code("svg", data
)?
;
608 let qr_code
= base64
::encode_config(&qr_code
, base64
::STANDARD_NO_PAD
);
610 println
!("<center>");
612 println
!("width=\"{}pt\" height=\"{}pt\"", img_size_pt
, img_size_pt
);
613 println
!("src=\"data:image/svg+xml;base64,{}\"/>", qr_code
);
614 println
!("</center>");
623 println
!("<div style=\"page-break-inside: avoid\">");
627 println
!("-----BEGIN PROXMOX BACKUP KEY-----");
630 println
!("{}", line
);
633 println
!("-----END PROXMOX BACKUP KEY-----");
637 let qr_code
= generate_qr_code("svg", lines
)?
;
638 let qr_code
= base64
::encode_config(&qr_code
, base64
::STANDARD_NO_PAD
);
640 println
!("<center>");
642 println
!("width=\"{}pt\" height=\"{}pt\"", img_size_pt
, img_size_pt
);
643 println
!("src=\"data:image/svg+xml;base64,{}\"/>", qr_code
);
644 println
!("</center>");
654 fn paperkey_text(lines
: &[String
], subject
: Option
<String
>, is_private
: bool
) -> Result
<(), Error
> {
656 if let Some(subject
) = subject
{
657 println
!("Subject: {}\n", subject
);
661 const BLOCK_SIZE
: usize = 5;
662 let blocks
= (lines
.len() + BLOCK_SIZE
-1)/BLOCK_SIZE
;
665 let start
= i
*BLOCK_SIZE
;
666 let mut end
= start
+ BLOCK_SIZE
;
667 if end
> lines
.len() {
670 let data
= &lines
[start
..end
];
672 for l
in start
..end
{
673 println
!("{:-2}: {}", l
, lines
[l
]);
675 let qr_code
= generate_qr_code("utf8i", data
)?
;
676 let qr_code
= String
::from_utf8(qr_code
)
677 .map_err(|_
| format_err
!("Failed to read qr code (got non-utf8 data)"))?
;
678 println
!("{}", qr_code
);
679 println
!("{}", char::from(12u8)); // page break
685 println
!("-----BEGIN PROXMOX BACKUP KEY-----");
687 println
!("{}", line
);
689 println
!("-----END PROXMOX BACKUP KEY-----");
691 let qr_code
= generate_qr_code("utf8i", &lines
)?
;
692 let qr_code
= String
::from_utf8(qr_code
)
693 .map_err(|_
| format_err
!("Failed to read qr code (got non-utf8 data)"))?
;
695 println
!("{}", qr_code
);
700 fn generate_qr_code(output_type
: &str, lines
: &[String
]) -> Result
<Vec
<u8>, Error
> {
701 let mut child
= Command
::new("qrencode")
702 .args(&["-t", output_type
, "-m0", "-s1", "-lm", "--output", "-"])
703 .stdin(Stdio
::piped())
704 .stdout(Stdio
::piped())
708 let stdin
= child
.stdin
.as_mut()
709 .ok_or_else(|| format_err
!("Failed to open stdin"))?
;
710 let data
= lines
.join("\n");
711 stdin
.write_all(data
.as_bytes())
712 .map_err(|_
| format_err
!("Failed to write to stdin"))?
;
715 let output
= child
.wait_with_output()
716 .map_err(|_
| format_err
!("Failed to read stdout"))?
;
718 let output
= crate::tools
::command_output(output
, None
)?
;