]> git.proxmox.com Git - proxmox-backup.git/blob - src/bin/proxmox_backup_client/key.rs
cleanup KeyConfig
[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::{
23 api2::types::{
24 PASSWORD_HINT_SCHEMA,
25 },
26 backup::{
27 rsa_decrypt_key_config,
28 CryptConfig,
29 Kdf,
30 KeyConfig,
31 KeyDerivationConfig,
32 },
33 tools,
34 };
35
36 #[api()]
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.
42 Text,
43 /// Format as Html. Includes QR codes as png images.
44 Html,
45 }
46
47 pub const DEFAULT_ENCRYPTION_KEY_FILE_NAME: &str = "encryption-key.json";
48 pub const MASTER_PUBKEY_FILE_NAME: &str = "master-public.pem";
49
50 pub fn find_master_pubkey() -> Result<Option<PathBuf>, Error> {
51 super::find_xdg_file(MASTER_PUBKEY_FILE_NAME, "main public key file")
52 }
53
54 pub fn place_master_pubkey() -> Result<PathBuf, Error> {
55 super::place_xdg_file(MASTER_PUBKEY_FILE_NAME, "main public key file")
56 }
57
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")
60 }
61
62 pub fn place_default_encryption_key() -> Result<PathBuf, Error> {
63 super::place_xdg_file(DEFAULT_ENCRYPTION_KEY_FILE_NAME, "default encryption key file")
64 }
65
66 pub fn read_optional_default_encryption_key() -> Result<Option<Vec<u8>>, Error> {
67 find_default_encryption_key()?
68 .map(file_get_contents)
69 .transpose()
70 }
71
72 pub fn get_encryption_key_password() -> Result<Vec<u8>, Error> {
73 // fixme: implement other input methods
74
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"),
79 Err(NotPresent) => {
80 // Try another method
81 }
82 }
83
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: ")?);
87 }
88
89 bail!("no password input mechanism available");
90 }
91
92 #[api(
93 input: {
94 properties: {
95 kdf: {
96 type: Kdf,
97 optional: true,
98 },
99 path: {
100 description:
101 "Output file. Without this the key will become the new default encryption key.",
102 optional: true,
103 },
104 hint: {
105 schema: PASSWORD_HINT_SCHEMA,
106 optional: true,
107 },
108 },
109 },
110 )]
111 /// Create a new encryption key.
112 fn create(
113 kdf: Option<Kdf>,
114 path: Option<String>,
115 hint: Option<String>
116 ) -> Result<(), Error> {
117 let path = match path {
118 Some(path) => PathBuf::from(path),
119 None => {
120 let path = place_default_encryption_key()?;
121 println!("creating default key at: {:?}", path);
122 path
123 }
124 };
125
126 let kdf = kdf.unwrap_or_default();
127
128 let mut key = [0u8; 32];
129 proxmox::sys::linux::fill_with_random_data(&mut key)?;
130 let crypt_config = CryptConfig::new(key.clone())?;
131
132 match kdf {
133 Kdf::None => {
134 if hint.is_some() {
135 bail!("password hint not allowed for Kdf::None");
136 }
137
138 let mut key_config = KeyConfig::without_password(key);
139 key_config.fingerprint = Some(crypt_config.fingerprint());
140
141 key_config.store(path, false)?;
142 }
143 Kdf::Scrypt | Kdf::PBKDF2 => {
144 // always read passphrase from tty
145 if !tty::stdin_isatty() {
146 bail!("unable to read passphrase - no tty");
147 }
148
149 let password = tty::read_and_verify_password("Encryption Key Password: ")?;
150
151 let mut key_config = KeyConfig::with_key(&key, &password, kdf)?;
152 key_config.fingerprint = Some(crypt_config.fingerprint());
153 key_config.hint = hint;
154
155 key_config.store(&path, false)?;
156 }
157 }
158
159 Ok(())
160 }
161
162 #[api(
163 input: {
164 properties: {
165 "master-keyfile": {
166 description: "(Private) master key to use.",
167 },
168 "encrypted-keyfile": {
169 description: "RSA-encrypted keyfile to import.",
170 },
171 kdf: {
172 type: Kdf,
173 optional: true,
174 },
175 "path": {
176 description:
177 "Output file. Without this the key will become the new default encryption key.",
178 optional: true,
179 },
180 hint: {
181 schema: PASSWORD_HINT_SCHEMA,
182 optional: true,
183 },
184 },
185 },
186 )]
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,
191 kdf: Option<Kdf>,
192 path: Option<String>,
193 hint: Option<String>,
194 ) -> Result<(), Error> {
195 let path = match path {
196 Some(path) => PathBuf::from(path),
197 None => {
198 let path = place_default_encryption_key()?;
199 if path.exists() {
200 bail!("Please remove default encryption key at {:?} before importing to default location (or choose a non-default one).", path);
201 }
202 println!("Importing key to default location at: {:?}", path);
203 path
204 }
205 };
206
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: ")?;
210
211 let master_key =
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))?
214 .rsa()
215 .map_err(|err| format_err!("not a valid private RSA key - {}", err))?;
216
217 let (key, created, fingerprint) =
218 rsa_decrypt_key_config(master_key, &encrypted_key, &get_encryption_key_password)?;
219
220 let kdf = kdf.unwrap_or_default();
221 match kdf {
222 Kdf::None => {
223 if hint.is_some() {
224 bail!("password hint not allowed for Kdf::None");
225 }
226
227 let mut key_config = KeyConfig::without_password(key);
228 key_config.created = created; // keep original value
229 key_config.fingerprint = Some(fingerprint);
230
231 key_config.store(path, true)?;
232
233 }
234 Kdf::Scrypt | Kdf::PBKDF2 => {
235 let password = tty::read_and_verify_password("New Password: ")?;
236
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;
241
242 new_key_config.store(path, true)?;
243 }
244 }
245
246 Ok(())
247 }
248
249 #[api(
250 input: {
251 properties: {
252 kdf: {
253 type: Kdf,
254 optional: true,
255 },
256 path: {
257 description: "Key file. Without this the default key's password will be changed.",
258 optional: true,
259 },
260 hint: {
261 schema: PASSWORD_HINT_SCHEMA,
262 optional: true,
263 },
264 },
265 },
266 )]
267 /// Change the encryption key's password.
268 fn change_passphrase(
269 kdf: Option<Kdf>,
270 path: Option<String>,
271 hint: Option<String>,
272 ) -> Result<(), Error> {
273 let path = match path {
274 Some(path) => PathBuf::from(path),
275 None => {
276 let path = find_default_encryption_key()?
277 .ok_or_else(|| {
278 format_err!("no encryption file provided and no default file found")
279 })?;
280 println!("updating default key at: {:?}", path);
281 path
282 }
283 };
284
285 let kdf = kdf.unwrap_or_default();
286
287 if !tty::stdin_isatty() {
288 bail!("unable to change passphrase - no tty");
289 }
290
291 let key_config = KeyConfig::load(&path)?;
292 let (key, created, fingerprint) = key_config.decrypt(&get_encryption_key_password)?;
293
294 match kdf {
295 Kdf::None => {
296 if hint.is_some() {
297 bail!("password hint not allowed for Kdf::None");
298 }
299
300 let mut key_config = KeyConfig::without_password(key);
301 key_config.created = created; // keep original value
302 key_config.fingerprint = Some(fingerprint);
303
304 key_config.store(&path, true)?;
305 }
306 Kdf::Scrypt | Kdf::PBKDF2 => {
307 let password = tty::read_and_verify_password("New Password: ")?;
308
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;
313
314 new_key_config.store(&path, true)?;
315 }
316 }
317
318 Ok(())
319 }
320
321 #[api(
322 properties: {
323 kdf: {
324 type: Kdf,
325 },
326 },
327 )]
328 #[derive(Deserialize, Serialize)]
329 /// Encryption Key Information
330 struct KeyInfo {
331 /// Path to key
332 path: String,
333 kdf: Kdf,
334 /// Key creation time
335 pub created: i64,
336 /// Key modification time
337 pub modified: i64,
338 /// Key fingerprint
339 #[serde(skip_serializing_if="Option::is_none")]
340 pub fingerprint: Option<String>,
341 /// Password hint
342 #[serde(skip_serializing_if="Option::is_none")]
343 pub hint: Option<String>,
344 }
345
346 #[api(
347 input: {
348 properties: {
349 path: {
350 description: "Key file. Without this the default key's metadata will be shown.",
351 optional: true,
352 },
353 "output-format": {
354 schema: OUTPUT_FORMAT,
355 optional: true,
356 },
357 },
358 },
359 )]
360 /// Print the encryption key's metadata.
361 fn show_key(
362 path: Option<String>,
363 param: Value,
364 ) -> Result<(), Error> {
365 let path = match path {
366 Some(path) => PathBuf::from(path),
367 None => {
368 let path = find_default_encryption_key()?
369 .ok_or_else(|| {
370 format_err!("no encryption file provided and no default file found")
371 })?;
372 path
373 }
374 };
375
376
377 let config: KeyConfig = serde_json::from_slice(&file_get_contents(path.clone())?)?;
378
379 let output_format = get_output_format(&param);
380
381 let info = KeyInfo {
382 path: format!("{:?}", path),
383 kdf: match config.kdf {
384 Some(KeyDerivationConfig::PBKDF2 { .. }) => Kdf::PBKDF2,
385 Some(KeyDerivationConfig::Scrypt { .. }) => Kdf::Scrypt,
386 None => Kdf::None,
387 },
388 created: config.created,
389 modified: config.modified,
390 fingerprint: match config.fingerprint {
391 Some(ref fp) => Some(format!("{}", fp)),
392 None => None,
393 },
394 hint: config.hint,
395 };
396
397 let options = proxmox::api::cli::default_table_format_options()
398 .column(ColumnConfig::new("path"))
399 .column(ColumnConfig::new("kdf"))
400 .column(ColumnConfig::new("created").renderer(tools::format::render_epoch))
401 .column(ColumnConfig::new("modified").renderer(tools::format::render_epoch))
402 .column(ColumnConfig::new("fingerprint"))
403 .column(ColumnConfig::new("hint"));
404
405 let return_type = ReturnType::new(false, &KeyInfo::API_SCHEMA);
406
407 format_and_print_result_full(
408 &mut serde_json::to_value(info)?,
409 &return_type,
410 &output_format,
411 &options,
412 );
413
414 Ok(())
415 }
416
417 #[api(
418 input: {
419 properties: {
420 path: {
421 description: "Path to the PEM formatted RSA public key.",
422 },
423 },
424 },
425 )]
426 /// Import an RSA public key used to put an encrypted version of the symmetric backup encryption
427 /// key onto the backup server along with each backup.
428 fn import_master_pubkey(path: String) -> Result<(), Error> {
429 let pem_data = file_get_contents(&path)?;
430
431 if let Err(err) = openssl::pkey::PKey::public_key_from_pem(&pem_data) {
432 bail!("Unable to decode PEM data - {}", err);
433 }
434
435 let target_path = place_master_pubkey()?;
436
437 replace_file(&target_path, &pem_data, CreateOptions::new())?;
438
439 println!("Imported public master key to {:?}", target_path);
440
441 Ok(())
442 }
443
444 #[api]
445 /// Create an RSA public/private key pair used to put an encrypted version of the symmetric backup
446 /// encryption key onto the backup server along with each backup.
447 fn create_master_key() -> Result<(), Error> {
448 // we need a TTY to query the new password
449 if !tty::stdin_isatty() {
450 bail!("unable to create master key - no tty");
451 }
452
453 let rsa = openssl::rsa::Rsa::generate(4096)?;
454 let pkey = openssl::pkey::PKey::from_rsa(rsa)?;
455
456 let password = String::from_utf8(tty::read_and_verify_password("Master Key Password: ")?)?;
457
458 let pub_key: Vec<u8> = pkey.public_key_to_pem()?;
459 let filename_pub = "master-public.pem";
460 println!("Writing public master key to {}", filename_pub);
461 replace_file(filename_pub, pub_key.as_slice(), CreateOptions::new())?;
462
463 let cipher = openssl::symm::Cipher::aes_256_cbc();
464 let priv_key: Vec<u8> = pkey.private_key_to_pem_pkcs8_passphrase(cipher, password.as_bytes())?;
465
466 let filename_priv = "master-private.pem";
467 println!("Writing private master key to {}", filename_priv);
468 replace_file(filename_priv, priv_key.as_slice(), CreateOptions::new())?;
469
470 Ok(())
471 }
472
473 #[api(
474 input: {
475 properties: {
476 path: {
477 description: "Key file. Without this the default key's will be used.",
478 optional: true,
479 },
480 subject: {
481 description: "Include the specified subject as titel text.",
482 optional: true,
483 },
484 "output-format": {
485 type: PaperkeyFormat,
486 optional: true,
487 },
488 },
489 },
490 )]
491 /// Generate a printable, human readable text file containing the encryption key.
492 ///
493 /// This also includes a scanable QR code for fast key restore.
494 fn paper_key(
495 path: Option<String>,
496 subject: Option<String>,
497 output_format: Option<PaperkeyFormat>,
498 ) -> Result<(), Error> {
499 let path = match path {
500 Some(path) => PathBuf::from(path),
501 None => {
502 let path = find_default_encryption_key()?
503 .ok_or_else(|| {
504 format_err!("no encryption file provided and no default file found")
505 })?;
506 path
507 }
508 };
509
510 let data = file_get_contents(&path)?;
511 let data = String::from_utf8(data)?;
512
513 let (data, is_private_key) = if data.starts_with("-----BEGIN ENCRYPTED PRIVATE KEY-----\n") {
514 let lines: Vec<String> = data
515 .lines()
516 .map(|s| s.trim_end())
517 .filter(|s| !s.is_empty())
518 .map(String::from)
519 .collect();
520
521 if !lines[lines.len()-1].starts_with("-----END ENCRYPTED PRIVATE KEY-----") {
522 bail!("unexpected key format");
523 }
524
525 if lines.len() < 20 {
526 bail!("unexpected key format");
527 }
528
529 (lines, true)
530 } else {
531 match serde_json::from_str::<KeyConfig>(&data) {
532 Ok(key_config) => {
533 let lines = serde_json::to_string_pretty(&key_config)?
534 .lines()
535 .map(String::from)
536 .collect();
537
538 (lines, false)
539 },
540 Err(err) => {
541 eprintln!("Couldn't parse '{:?}' as KeyConfig - {}", path, err);
542 bail!("Neither a PEM-formatted private key, nor a PBS key file.");
543 },
544 }
545 };
546
547 let format = output_format.unwrap_or(PaperkeyFormat::Html);
548
549 match format {
550 PaperkeyFormat::Html => paperkey_html(&data, subject, is_private_key),
551 PaperkeyFormat::Text => paperkey_text(&data, subject, is_private_key),
552 }
553 }
554
555 pub fn cli() -> CliCommandMap {
556 let key_create_cmd_def = CliCommand::new(&API_METHOD_CREATE)
557 .arg_param(&["path"])
558 .completion_cb("path", tools::complete_file_name);
559
560 let key_import_with_master_key_cmd_def = CliCommand::new(&API_METHOD_IMPORT_WITH_MASTER_KEY)
561 .arg_param(&["master-keyfile"])
562 .completion_cb("master-keyfile", tools::complete_file_name)
563 .arg_param(&["encrypted-keyfile"])
564 .completion_cb("encrypted-keyfile", tools::complete_file_name)
565 .arg_param(&["path"])
566 .completion_cb("path", tools::complete_file_name);
567
568 let key_change_passphrase_cmd_def = CliCommand::new(&API_METHOD_CHANGE_PASSPHRASE)
569 .arg_param(&["path"])
570 .completion_cb("path", tools::complete_file_name);
571
572 let key_create_master_key_cmd_def = CliCommand::new(&API_METHOD_CREATE_MASTER_KEY);
573 let key_import_master_pubkey_cmd_def = CliCommand::new(&API_METHOD_IMPORT_MASTER_PUBKEY)
574 .arg_param(&["path"])
575 .completion_cb("path", tools::complete_file_name);
576
577 let key_show_cmd_def = CliCommand::new(&API_METHOD_SHOW_KEY)
578 .arg_param(&["path"])
579 .completion_cb("path", tools::complete_file_name);
580
581 let paper_key_cmd_def = CliCommand::new(&API_METHOD_PAPER_KEY)
582 .arg_param(&["path"])
583 .completion_cb("path", tools::complete_file_name);
584
585 CliCommandMap::new()
586 .insert("create", key_create_cmd_def)
587 .insert("import-with-master-key", key_import_with_master_key_cmd_def)
588 .insert("create-master-key", key_create_master_key_cmd_def)
589 .insert("import-master-pubkey", key_import_master_pubkey_cmd_def)
590 .insert("change-passphrase", key_change_passphrase_cmd_def)
591 .insert("show", key_show_cmd_def)
592 .insert("paperkey", paper_key_cmd_def)
593 }
594
595 fn paperkey_html(lines: &[String], subject: Option<String>, is_private: bool) -> Result<(), Error> {
596
597 let img_size_pt = 500;
598
599 println!("<!DOCTYPE html>");
600 println!("<html lang=\"en\">");
601 println!("<head>");
602 println!("<meta charset=\"utf-8\">");
603 println!("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">");
604 println!("<title>Proxmox Backup Paperkey</title>");
605 println!("<style type=\"text/css\">");
606
607 println!(" p {{");
608 println!(" font-size: 12pt;");
609 println!(" font-family: monospace;");
610 println!(" white-space: pre-wrap;");
611 println!(" line-break: anywhere;");
612 println!(" }}");
613
614 println!("</style>");
615
616 println!("</head>");
617
618 println!("<body>");
619
620 if let Some(subject) = subject {
621 println!("<p>Subject: {}</p>", subject);
622 }
623
624 if is_private {
625 const BLOCK_SIZE: usize = 20;
626 let blocks = (lines.len() + BLOCK_SIZE -1)/BLOCK_SIZE;
627
628 for i in 0..blocks {
629 let start = i*BLOCK_SIZE;
630 let mut end = start + BLOCK_SIZE;
631 if end > lines.len() {
632 end = lines.len();
633 }
634 let data = &lines[start..end];
635
636 println!("<div style=\"page-break-inside: avoid;page-break-after: always\">");
637 println!("<p>");
638
639 for l in start..end {
640 println!("{:02}: {}", l, lines[l]);
641 }
642
643 println!("</p>");
644
645 let qr_code = generate_qr_code("svg", data)?;
646 let qr_code = base64::encode_config(&qr_code, base64::STANDARD_NO_PAD);
647
648 println!("<center>");
649 println!("<img");
650 println!("width=\"{}pt\" height=\"{}pt\"", img_size_pt, img_size_pt);
651 println!("src=\"data:image/svg+xml;base64,{}\"/>", qr_code);
652 println!("</center>");
653 println!("</div>");
654 }
655
656 println!("</body>");
657 println!("</html>");
658 return Ok(());
659 }
660
661 println!("<div style=\"page-break-inside: avoid\">");
662
663 println!("<p>");
664
665 println!("-----BEGIN PROXMOX BACKUP KEY-----");
666
667 for line in lines {
668 println!("{}", line);
669 }
670
671 println!("-----END PROXMOX BACKUP KEY-----");
672
673 println!("</p>");
674
675 let qr_code = generate_qr_code("svg", lines)?;
676 let qr_code = base64::encode_config(&qr_code, base64::STANDARD_NO_PAD);
677
678 println!("<center>");
679 println!("<img");
680 println!("width=\"{}pt\" height=\"{}pt\"", img_size_pt, img_size_pt);
681 println!("src=\"data:image/svg+xml;base64,{}\"/>", qr_code);
682 println!("</center>");
683
684 println!("</div>");
685
686 println!("</body>");
687 println!("</html>");
688
689 Ok(())
690 }
691
692 fn paperkey_text(lines: &[String], subject: Option<String>, is_private: bool) -> Result<(), Error> {
693
694 if let Some(subject) = subject {
695 println!("Subject: {}\n", subject);
696 }
697
698 if is_private {
699 const BLOCK_SIZE: usize = 5;
700 let blocks = (lines.len() + BLOCK_SIZE -1)/BLOCK_SIZE;
701
702 for i in 0..blocks {
703 let start = i*BLOCK_SIZE;
704 let mut end = start + BLOCK_SIZE;
705 if end > lines.len() {
706 end = lines.len();
707 }
708 let data = &lines[start..end];
709
710 for l in start..end {
711 println!("{:-2}: {}", l, lines[l]);
712 }
713 let qr_code = generate_qr_code("utf8i", data)?;
714 let qr_code = String::from_utf8(qr_code)
715 .map_err(|_| format_err!("Failed to read qr code (got non-utf8 data)"))?;
716 println!("{}", qr_code);
717 println!("{}", char::from(12u8)); // page break
718
719 }
720 return Ok(());
721 }
722
723 println!("-----BEGIN PROXMOX BACKUP KEY-----");
724 for line in lines {
725 println!("{}", line);
726 }
727 println!("-----END PROXMOX BACKUP KEY-----");
728
729 let qr_code = generate_qr_code("utf8i", &lines)?;
730 let qr_code = String::from_utf8(qr_code)
731 .map_err(|_| format_err!("Failed to read qr code (got non-utf8 data)"))?;
732
733 println!("{}", qr_code);
734
735 Ok(())
736 }
737
738 fn generate_qr_code(output_type: &str, lines: &[String]) -> Result<Vec<u8>, Error> {
739 let mut child = Command::new("qrencode")
740 .args(&["-t", output_type, "-m0", "-s1", "-lm", "--output", "-"])
741 .stdin(Stdio::piped())
742 .stdout(Stdio::piped())
743 .spawn()?;
744
745 {
746 let stdin = child.stdin.as_mut()
747 .ok_or_else(|| format_err!("Failed to open stdin"))?;
748 let data = lines.join("\n");
749 stdin.write_all(data.as_bytes())
750 .map_err(|_| format_err!("Failed to write to stdin"))?;
751 }
752
753 let output = child.wait_with_output()
754 .map_err(|_| format_err!("Failed to read stdout"))?;
755
756 let output = crate::tools::command_output(output, None)?;
757
758 Ok(output)
759 }