]> git.proxmox.com Git - proxmox-backup.git/blob - src/bin/proxmox_backup_client/key.rs
Merge branch 'master' of ssh://proxdev.maurer-it.com/rust/proxmox-backup
[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 KeyInfo,
26 Kdf,
27 },
28 backup::{
29 rsa_decrypt_key_config,
30 CryptConfig,
31 KeyConfig,
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 input: {
323 properties: {
324 path: {
325 description: "Key file. Without this the default key's metadata will be shown.",
326 optional: true,
327 },
328 "output-format": {
329 schema: OUTPUT_FORMAT,
330 optional: true,
331 },
332 },
333 },
334 )]
335 /// Print the encryption key's metadata.
336 fn show_key(
337 path: Option<String>,
338 param: Value,
339 ) -> Result<(), Error> {
340 let path = match path {
341 Some(path) => PathBuf::from(path),
342 None => {
343 let path = find_default_encryption_key()?
344 .ok_or_else(|| {
345 format_err!("no encryption file provided and no default file found")
346 })?;
347 path
348 }
349 };
350
351
352 let config: KeyConfig = serde_json::from_slice(&file_get_contents(path.clone())?)?;
353
354 let output_format = get_output_format(&param);
355
356 let mut info: KeyInfo = (&config).into();
357 info.path = Some(format!("{:?}", path));
358
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"));
366
367 let return_type = ReturnType::new(false, &KeyInfo::API_SCHEMA);
368
369 format_and_print_result_full(
370 &mut serde_json::to_value(info)?,
371 &return_type,
372 &output_format,
373 &options,
374 );
375
376 Ok(())
377 }
378
379 #[api(
380 input: {
381 properties: {
382 path: {
383 description: "Path to the PEM formatted RSA public key.",
384 },
385 },
386 },
387 )]
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)?;
392
393 if let Err(err) = openssl::pkey::PKey::public_key_from_pem(&pem_data) {
394 bail!("Unable to decode PEM data - {}", err);
395 }
396
397 let target_path = place_master_pubkey()?;
398
399 replace_file(&target_path, &pem_data, CreateOptions::new())?;
400
401 println!("Imported public master key to {:?}", target_path);
402
403 Ok(())
404 }
405
406 #[api]
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");
413 }
414
415 let rsa = openssl::rsa::Rsa::generate(4096)?;
416 let pkey = openssl::pkey::PKey::from_rsa(rsa)?;
417
418 let password = String::from_utf8(tty::read_and_verify_password("Master Key Password: ")?)?;
419
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())?;
424
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())?;
427
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())?;
431
432 Ok(())
433 }
434
435 #[api(
436 input: {
437 properties: {
438 path: {
439 description: "Key file. Without this the default key's will be used.",
440 optional: true,
441 },
442 subject: {
443 description: "Include the specified subject as titel text.",
444 optional: true,
445 },
446 "output-format": {
447 type: PaperkeyFormat,
448 optional: true,
449 },
450 },
451 },
452 )]
453 /// Generate a printable, human readable text file containing the encryption key.
454 ///
455 /// This also includes a scanable QR code for fast key restore.
456 fn paper_key(
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),
463 None => {
464 let path = find_default_encryption_key()?
465 .ok_or_else(|| {
466 format_err!("no encryption file provided and no default file found")
467 })?;
468 path
469 }
470 };
471
472 let data = file_get_contents(&path)?;
473 let data = String::from_utf8(data)?;
474
475 let (data, is_private_key) = if data.starts_with("-----BEGIN ENCRYPTED PRIVATE KEY-----\n") {
476 let lines: Vec<String> = data
477 .lines()
478 .map(|s| s.trim_end())
479 .filter(|s| !s.is_empty())
480 .map(String::from)
481 .collect();
482
483 if !lines[lines.len()-1].starts_with("-----END ENCRYPTED PRIVATE KEY-----") {
484 bail!("unexpected key format");
485 }
486
487 if lines.len() < 20 {
488 bail!("unexpected key format");
489 }
490
491 (lines, true)
492 } else {
493 match serde_json::from_str::<KeyConfig>(&data) {
494 Ok(key_config) => {
495 let lines = serde_json::to_string_pretty(&key_config)?
496 .lines()
497 .map(String::from)
498 .collect();
499
500 (lines, false)
501 },
502 Err(err) => {
503 eprintln!("Couldn't parse '{:?}' as KeyConfig - {}", path, err);
504 bail!("Neither a PEM-formatted private key, nor a PBS key file.");
505 },
506 }
507 };
508
509 let format = output_format.unwrap_or(PaperkeyFormat::Html);
510
511 match format {
512 PaperkeyFormat::Html => paperkey_html(&data, subject, is_private_key),
513 PaperkeyFormat::Text => paperkey_text(&data, subject, is_private_key),
514 }
515 }
516
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);
521
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);
529
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);
533
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);
538
539 let key_show_cmd_def = CliCommand::new(&API_METHOD_SHOW_KEY)
540 .arg_param(&["path"])
541 .completion_cb("path", tools::complete_file_name);
542
543 let paper_key_cmd_def = CliCommand::new(&API_METHOD_PAPER_KEY)
544 .arg_param(&["path"])
545 .completion_cb("path", tools::complete_file_name);
546
547 CliCommandMap::new()
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)
555 }
556
557 fn paperkey_html(lines: &[String], subject: Option<String>, is_private: bool) -> Result<(), Error> {
558
559 let img_size_pt = 500;
560
561 println!("<!DOCTYPE html>");
562 println!("<html lang=\"en\">");
563 println!("<head>");
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\">");
568
569 println!(" p {{");
570 println!(" font-size: 12pt;");
571 println!(" font-family: monospace;");
572 println!(" white-space: pre-wrap;");
573 println!(" line-break: anywhere;");
574 println!(" }}");
575
576 println!("</style>");
577
578 println!("</head>");
579
580 println!("<body>");
581
582 if let Some(subject) = subject {
583 println!("<p>Subject: {}</p>", subject);
584 }
585
586 if is_private {
587 const BLOCK_SIZE: usize = 20;
588 let blocks = (lines.len() + BLOCK_SIZE -1)/BLOCK_SIZE;
589
590 for i in 0..blocks {
591 let start = i*BLOCK_SIZE;
592 let mut end = start + BLOCK_SIZE;
593 if end > lines.len() {
594 end = lines.len();
595 }
596 let data = &lines[start..end];
597
598 println!("<div style=\"page-break-inside: avoid;page-break-after: always\">");
599 println!("<p>");
600
601 for l in start..end {
602 println!("{:02}: {}", l, lines[l]);
603 }
604
605 println!("</p>");
606
607 let qr_code = generate_qr_code("svg", data)?;
608 let qr_code = base64::encode_config(&qr_code, base64::STANDARD_NO_PAD);
609
610 println!("<center>");
611 println!("<img");
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>");
615 println!("</div>");
616 }
617
618 println!("</body>");
619 println!("</html>");
620 return Ok(());
621 }
622
623 println!("<div style=\"page-break-inside: avoid\">");
624
625 println!("<p>");
626
627 println!("-----BEGIN PROXMOX BACKUP KEY-----");
628
629 for line in lines {
630 println!("{}", line);
631 }
632
633 println!("-----END PROXMOX BACKUP KEY-----");
634
635 println!("</p>");
636
637 let qr_code = generate_qr_code("svg", lines)?;
638 let qr_code = base64::encode_config(&qr_code, base64::STANDARD_NO_PAD);
639
640 println!("<center>");
641 println!("<img");
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>");
645
646 println!("</div>");
647
648 println!("</body>");
649 println!("</html>");
650
651 Ok(())
652 }
653
654 fn paperkey_text(lines: &[String], subject: Option<String>, is_private: bool) -> Result<(), Error> {
655
656 if let Some(subject) = subject {
657 println!("Subject: {}\n", subject);
658 }
659
660 if is_private {
661 const BLOCK_SIZE: usize = 5;
662 let blocks = (lines.len() + BLOCK_SIZE -1)/BLOCK_SIZE;
663
664 for i in 0..blocks {
665 let start = i*BLOCK_SIZE;
666 let mut end = start + BLOCK_SIZE;
667 if end > lines.len() {
668 end = lines.len();
669 }
670 let data = &lines[start..end];
671
672 for l in start..end {
673 println!("{:-2}: {}", l, lines[l]);
674 }
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
680
681 }
682 return Ok(());
683 }
684
685 println!("-----BEGIN PROXMOX BACKUP KEY-----");
686 for line in lines {
687 println!("{}", line);
688 }
689 println!("-----END PROXMOX BACKUP KEY-----");
690
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)"))?;
694
695 println!("{}", qr_code);
696
697 Ok(())
698 }
699
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())
705 .spawn()?;
706
707 {
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"))?;
713 }
714
715 let output = child.wait_with_output()
716 .map_err(|_| format_err!("Failed to read stdout"))?;
717
718 let output = crate::tools::command_output(output, None)?;
719
720 Ok(output)
721 }