]> git.proxmox.com Git - proxmox-backup.git/blob - src/bin/proxmox_backup_client/key.rs
clippy: remove unnecessary clones
[proxmox-backup.git] / src / bin / proxmox_backup_client / key.rs
1 use std::path::PathBuf;
2 use std::io::Write;
3 use std::process::{Stdio, Command};
4
5 use anyhow::{bail, format_err, Error};
6 use serde::{Deserialize, Serialize};
7 use serde_json::Value;
8
9 use proxmox::api::api;
10 use proxmox::api::cli::{
11 ColumnConfig,
12 CliCommand,
13 CliCommandMap,
14 format_and_print_result_full,
15 get_output_format,
16 OUTPUT_FORMAT,
17 };
18 use proxmox::api::router::ReturnType;
19 use proxmox::sys::linux::tty;
20 use proxmox::tools::fs::{file_get_contents, replace_file, CreateOptions};
21
22 use proxmox_backup::backup::{
23 encrypt_key_with_passphrase,
24 load_and_decrypt_key,
25 rsa_decrypt_key_config,
26 store_key_config,
27 CryptConfig,
28 Kdf,
29 KeyConfig,
30 KeyDerivationConfig,
31 };
32
33 use proxmox_backup::tools;
34
35 #[api()]
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.
41 Text,
42 /// Format as Html. Includes QR codes as png images.
43 Html,
44 }
45
46 pub const DEFAULT_ENCRYPTION_KEY_FILE_NAME: &str = "encryption-key.json";
47 pub const MASTER_PUBKEY_FILE_NAME: &str = "master-public.pem";
48
49 pub fn find_master_pubkey() -> Result<Option<PathBuf>, Error> {
50 super::find_xdg_file(MASTER_PUBKEY_FILE_NAME, "main public key file")
51 }
52
53 pub fn place_master_pubkey() -> Result<PathBuf, Error> {
54 super::place_xdg_file(MASTER_PUBKEY_FILE_NAME, "main public key file")
55 }
56
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")
59 }
60
61 pub fn place_default_encryption_key() -> Result<PathBuf, Error> {
62 super::place_xdg_file(DEFAULT_ENCRYPTION_KEY_FILE_NAME, "default encryption key file")
63 }
64
65 pub fn read_optional_default_encryption_key() -> Result<Option<Vec<u8>>, Error> {
66 find_default_encryption_key()?
67 .map(file_get_contents)
68 .transpose()
69 }
70
71 pub fn get_encryption_key_password() -> Result<Vec<u8>, Error> {
72 // fixme: implement other input methods
73
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"),
78 Err(NotPresent) => {
79 // Try another method
80 }
81 }
82
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: ")?);
86 }
87
88 bail!("no password input mechanism available");
89 }
90
91 #[api(
92 input: {
93 properties: {
94 kdf: {
95 type: Kdf,
96 optional: true,
97 },
98 path: {
99 description:
100 "Output file. Without this the key will become the new default encryption key.",
101 optional: true,
102 }
103 },
104 },
105 )]
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),
110 None => {
111 let path = place_default_encryption_key()?;
112 println!("creating default key at: {:?}", path);
113 path
114 }
115 };
116
117 let kdf = kdf.unwrap_or_default();
118
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();
123
124 match kdf {
125 Kdf::None => {
126 let created = proxmox::tools::time::epoch_i64();
127
128 store_key_config(
129 &path,
130 false,
131 KeyConfig {
132 kdf: None,
133 created,
134 modified: created,
135 data: key,
136 fingerprint: Some(crypt_config.fingerprint()),
137 },
138 )?;
139 }
140 Kdf::Scrypt | Kdf::PBKDF2 => {
141 // always read passphrase from tty
142 if !tty::stdin_isatty() {
143 bail!("unable to read passphrase - no tty");
144 }
145
146 let password = tty::read_and_verify_password("Encryption Key Password: ")?;
147
148 let mut key_config = encrypt_key_with_passphrase(&key, &password, kdf)?;
149 key_config.fingerprint = Some(crypt_config.fingerprint());
150
151 store_key_config(&path, false, key_config)?;
152 }
153 }
154
155 Ok(())
156 }
157
158 #[api(
159 input: {
160 properties: {
161 "master-keyfile": {
162 description: "(Private) master key to use.",
163 },
164 "encrypted-keyfile": {
165 description: "RSA-encrypted keyfile to import.",
166 },
167 kdf: {
168 type: Kdf,
169 optional: true,
170 },
171 "path": {
172 description:
173 "Output file. Without this the key will become the new default encryption key.",
174 optional: true,
175 }
176 },
177 },
178 )]
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,
183 kdf: Option<Kdf>,
184 path: Option<String>,
185 ) -> Result<(), Error> {
186 let path = match path {
187 Some(path) => PathBuf::from(path),
188 None => {
189 let path = place_default_encryption_key()?;
190 if path.exists() {
191 bail!("Please remove default encryption key at {:?} before importing to default location (or choose a non-default one).", path);
192 }
193 println!("Importing key to default location at: {:?}", path);
194 path
195 }
196 };
197
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: ")?;
201
202 let master_key =
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))?
205 .rsa()
206 .map_err(|err| format_err!("not a valid private RSA key - {}", err))?;
207
208 let (key, created, fingerprint) =
209 rsa_decrypt_key_config(master_key, &encrypted_key, &get_encryption_key_password)?;
210
211 let kdf = kdf.unwrap_or_default();
212 match kdf {
213 Kdf::None => {
214 let modified = proxmox::tools::time::epoch_i64();
215
216 store_key_config(
217 &path,
218 true,
219 KeyConfig {
220 kdf: None,
221 created, // keep original value
222 modified,
223 data: key.to_vec(),
224 fingerprint: Some(fingerprint),
225 },
226 )?;
227 }
228 Kdf::Scrypt | Kdf::PBKDF2 => {
229 let password = tty::read_and_verify_password("New Password: ")?;
230
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);
234
235 store_key_config(&path, true, new_key_config)?;
236 }
237 }
238
239 Ok(())
240 }
241
242 #[api(
243 input: {
244 properties: {
245 kdf: {
246 type: Kdf,
247 optional: true,
248 },
249 path: {
250 description: "Key file. Without this the default key's password will be changed.",
251 optional: true,
252 }
253 },
254 },
255 )]
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),
260 None => {
261 let path = find_default_encryption_key()?
262 .ok_or_else(|| {
263 format_err!("no encryption file provided and no default file found")
264 })?;
265 println!("updating default key at: {:?}", path);
266 path
267 }
268 };
269
270 let kdf = kdf.unwrap_or_default();
271
272 if !tty::stdin_isatty() {
273 bail!("unable to change passphrase - no tty");
274 }
275
276 let (key, created, fingerprint) = load_and_decrypt_key(&path, &get_encryption_key_password)?;
277
278 match kdf {
279 Kdf::None => {
280 let modified = proxmox::tools::time::epoch_i64();
281
282 store_key_config(
283 &path,
284 true,
285 KeyConfig {
286 kdf: None,
287 created, // keep original value
288 modified,
289 data: key.to_vec(),
290 fingerprint: Some(fingerprint),
291 },
292 )?;
293 }
294 Kdf::Scrypt | Kdf::PBKDF2 => {
295 let password = tty::read_and_verify_password("New Password: ")?;
296
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);
300
301 store_key_config(&path, true, new_key_config)?;
302 }
303 }
304
305 Ok(())
306 }
307
308 #[api(
309 properties: {
310 kdf: {
311 type: Kdf,
312 },
313 },
314 )]
315 #[derive(Deserialize, Serialize)]
316 /// Encryption Key Information
317 struct KeyInfo {
318 /// Path to key
319 path: String,
320 kdf: Kdf,
321 /// Key creation time
322 pub created: i64,
323 /// Key modification time
324 pub modified: i64,
325 /// Key fingerprint
326 pub fingerprint: Option<String>,
327 }
328
329 #[api(
330 input: {
331 properties: {
332 path: {
333 description: "Key file. Without this the default key's metadata will be shown.",
334 optional: true,
335 },
336 "output-format": {
337 schema: OUTPUT_FORMAT,
338 optional: true,
339 },
340 },
341 },
342 )]
343 /// Print the encryption key's metadata.
344 fn show_key(
345 path: Option<String>,
346 param: Value,
347 ) -> Result<(), Error> {
348 let path = match path {
349 Some(path) => PathBuf::from(path),
350 None => {
351 let path = find_default_encryption_key()?
352 .ok_or_else(|| {
353 format_err!("no encryption file provided and no default file found")
354 })?;
355 path
356 }
357 };
358
359
360 let config: KeyConfig = serde_json::from_slice(&file_get_contents(path.clone())?)?;
361
362 let output_format = get_output_format(&param);
363
364 let info = KeyInfo {
365 path: format!("{:?}", path),
366 kdf: match config.kdf {
367 Some(KeyDerivationConfig::PBKDF2 { .. }) => Kdf::PBKDF2,
368 Some(KeyDerivationConfig::Scrypt { .. }) => Kdf::Scrypt,
369 None => Kdf::None,
370 },
371 created: config.created,
372 modified: config.modified,
373 fingerprint: match config.fingerprint {
374 Some(ref fp) => Some(format!("{}", fp)),
375 None => None,
376 },
377 };
378
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"));
385
386 let return_type = ReturnType::new(false, &KeyInfo::API_SCHEMA);
387
388 format_and_print_result_full(
389 &mut serde_json::to_value(info)?,
390 &return_type,
391 &output_format,
392 &options,
393 );
394
395 Ok(())
396 }
397
398 #[api(
399 input: {
400 properties: {
401 path: {
402 description: "Path to the PEM formatted RSA public key.",
403 },
404 },
405 },
406 )]
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)?;
411
412 if let Err(err) = openssl::pkey::PKey::public_key_from_pem(&pem_data) {
413 bail!("Unable to decode PEM data - {}", err);
414 }
415
416 let target_path = place_master_pubkey()?;
417
418 replace_file(&target_path, &pem_data, CreateOptions::new())?;
419
420 println!("Imported public master key to {:?}", target_path);
421
422 Ok(())
423 }
424
425 #[api]
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");
432 }
433
434 let rsa = openssl::rsa::Rsa::generate(4096)?;
435 let pkey = openssl::pkey::PKey::from_rsa(rsa)?;
436
437 let password = String::from_utf8(tty::read_and_verify_password("Master Key Password: ")?)?;
438
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())?;
443
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())?;
446
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())?;
450
451 Ok(())
452 }
453
454 #[api(
455 input: {
456 properties: {
457 path: {
458 description: "Key file. Without this the default key's will be used.",
459 optional: true,
460 },
461 subject: {
462 description: "Include the specified subject as titel text.",
463 optional: true,
464 },
465 "output-format": {
466 type: PaperkeyFormat,
467 optional: true,
468 },
469 },
470 },
471 )]
472 /// Generate a printable, human readable text file containing the encryption key.
473 ///
474 /// This also includes a scanable QR code for fast key restore.
475 fn paper_key(
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),
482 None => {
483 let path = find_default_encryption_key()?
484 .ok_or_else(|| {
485 format_err!("no encryption file provided and no default file found")
486 })?;
487 path
488 }
489 };
490
491 let data = file_get_contents(&path)?;
492 let data = String::from_utf8(data)?;
493
494 let (data, is_private_key) = if data.starts_with("-----BEGIN ENCRYPTED PRIVATE KEY-----\n") {
495 let lines: Vec<String> = data
496 .lines()
497 .map(|s| s.trim_end())
498 .filter(|s| !s.is_empty())
499 .map(String::from)
500 .collect();
501
502 if !lines[lines.len()-1].starts_with("-----END ENCRYPTED PRIVATE KEY-----") {
503 bail!("unexpected key format");
504 }
505
506 if lines.len() < 20 {
507 bail!("unexpected key format");
508 }
509
510 (lines, true)
511 } else {
512 match serde_json::from_str::<KeyConfig>(&data) {
513 Ok(key_config) => {
514 let lines = serde_json::to_string_pretty(&key_config)?
515 .lines()
516 .map(String::from)
517 .collect();
518
519 (lines, false)
520 },
521 Err(err) => {
522 eprintln!("Couldn't parse '{:?}' as KeyConfig - {}", path, err);
523 bail!("Neither a PEM-formatted private key, nor a PBS key file.");
524 },
525 }
526 };
527
528 let format = output_format.unwrap_or(PaperkeyFormat::Html);
529
530 match format {
531 PaperkeyFormat::Html => paperkey_html(&data, subject, is_private_key),
532 PaperkeyFormat::Text => paperkey_text(&data, subject, is_private_key),
533 }
534 }
535
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);
540
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);
548
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);
552
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);
557
558 let key_show_cmd_def = CliCommand::new(&API_METHOD_SHOW_KEY)
559 .arg_param(&["path"])
560 .completion_cb("path", tools::complete_file_name);
561
562 let paper_key_cmd_def = CliCommand::new(&API_METHOD_PAPER_KEY)
563 .arg_param(&["path"])
564 .completion_cb("path", tools::complete_file_name);
565
566 CliCommandMap::new()
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)
574 }
575
576 fn paperkey_html(lines: &[String], subject: Option<String>, is_private: bool) -> Result<(), Error> {
577
578 let img_size_pt = 500;
579
580 println!("<!DOCTYPE html>");
581 println!("<html lang=\"en\">");
582 println!("<head>");
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\">");
587
588 println!(" p {{");
589 println!(" font-size: 12pt;");
590 println!(" font-family: monospace;");
591 println!(" white-space: pre-wrap;");
592 println!(" line-break: anywhere;");
593 println!(" }}");
594
595 println!("</style>");
596
597 println!("</head>");
598
599 println!("<body>");
600
601 if let Some(subject) = subject {
602 println!("<p>Subject: {}</p>", subject);
603 }
604
605 if is_private {
606 const BLOCK_SIZE: usize = 20;
607 let blocks = (lines.len() + BLOCK_SIZE -1)/BLOCK_SIZE;
608
609 for i in 0..blocks {
610 let start = i*BLOCK_SIZE;
611 let mut end = start + BLOCK_SIZE;
612 if end > lines.len() {
613 end = lines.len();
614 }
615 let data = &lines[start..end];
616
617 println!("<div style=\"page-break-inside: avoid;page-break-after: always\">");
618 println!("<p>");
619
620 for l in start..end {
621 println!("{:02}: {}", l, lines[l]);
622 }
623
624 println!("</p>");
625
626 let qr_code = generate_qr_code("svg", data)?;
627 let qr_code = base64::encode_config(&qr_code, base64::STANDARD_NO_PAD);
628
629 println!("<center>");
630 println!("<img");
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>");
634 println!("</div>");
635 }
636
637 println!("</body>");
638 println!("</html>");
639 return Ok(());
640 }
641
642 println!("<div style=\"page-break-inside: avoid\">");
643
644 println!("<p>");
645
646 println!("-----BEGIN PROXMOX BACKUP KEY-----");
647
648 for line in lines {
649 println!("{}", line);
650 }
651
652 println!("-----END PROXMOX BACKUP KEY-----");
653
654 println!("</p>");
655
656 let qr_code = generate_qr_code("svg", lines)?;
657 let qr_code = base64::encode_config(&qr_code, base64::STANDARD_NO_PAD);
658
659 println!("<center>");
660 println!("<img");
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>");
664
665 println!("</div>");
666
667 println!("</body>");
668 println!("</html>");
669
670 Ok(())
671 }
672
673 fn paperkey_text(lines: &[String], subject: Option<String>, is_private: bool) -> Result<(), Error> {
674
675 if let Some(subject) = subject {
676 println!("Subject: {}\n", subject);
677 }
678
679 if is_private {
680 const BLOCK_SIZE: usize = 5;
681 let blocks = (lines.len() + BLOCK_SIZE -1)/BLOCK_SIZE;
682
683 for i in 0..blocks {
684 let start = i*BLOCK_SIZE;
685 let mut end = start + BLOCK_SIZE;
686 if end > lines.len() {
687 end = lines.len();
688 }
689 let data = &lines[start..end];
690
691 for l in start..end {
692 println!("{:-2}: {}", l, lines[l]);
693 }
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
699
700 }
701 return Ok(());
702 }
703
704 println!("-----BEGIN PROXMOX BACKUP KEY-----");
705 for line in lines {
706 println!("{}", line);
707 }
708 println!("-----END PROXMOX BACKUP KEY-----");
709
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)"))?;
713
714 println!("{}", qr_code);
715
716 Ok(())
717 }
718
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())
724 .spawn()?;
725
726 {
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"))?;
732 }
733
734 let output = child.wait_with_output()
735 .map_err(|_| format_err!("Failed to read stdout"))?;
736
737 let output = crate::tools::command_output(output, None)?;
738
739 Ok(output)
740 }