]> git.proxmox.com Git - proxmox-backup.git/blob - src/bin/proxmox_backup_client/key.rs
client: allow passing specific master key
[proxmox-backup.git] / src / bin / proxmox_backup_client / key.rs
1 use std::convert::TryFrom;
2 use std::path::PathBuf;
3
4 use anyhow::{bail, format_err, Error};
5 use serde_json::Value;
6
7 use proxmox::api::api;
8 use proxmox::api::cli::{
9 format_and_print_result_full, get_output_format, CliCommand, CliCommandMap, ColumnConfig,
10 OUTPUT_FORMAT,
11 };
12 use proxmox::api::router::ReturnType;
13 use proxmox::sys::linux::tty;
14 use proxmox::tools::fs::{file_get_contents, replace_file, CreateOptions};
15
16 use proxmox_backup::{
17 api2::types::{Kdf, KeyInfo, RsaPubKeyInfo, PASSWORD_HINT_SCHEMA},
18 backup::{rsa_decrypt_key_config, KeyConfig},
19 tools,
20 tools::paperkey::{generate_paper_key, PaperkeyFormat},
21 };
22
23 pub const DEFAULT_ENCRYPTION_KEY_FILE_NAME: &str = "encryption-key.json";
24 pub const DEFAULT_MASTER_PUBKEY_FILE_NAME: &str = "master-public.pem";
25
26 pub fn find_default_master_pubkey() -> Result<Option<PathBuf>, Error> {
27 super::find_xdg_file(
28 DEFAULT_MASTER_PUBKEY_FILE_NAME,
29 "default master public key file",
30 )
31 }
32
33 pub fn place_default_master_pubkey() -> Result<PathBuf, Error> {
34 super::place_xdg_file(
35 DEFAULT_MASTER_PUBKEY_FILE_NAME,
36 "default master public key file",
37 )
38 }
39
40 pub fn find_default_encryption_key() -> Result<Option<PathBuf>, Error> {
41 super::find_xdg_file(
42 DEFAULT_ENCRYPTION_KEY_FILE_NAME,
43 "default encryption key file",
44 )
45 }
46
47 pub fn place_default_encryption_key() -> Result<PathBuf, Error> {
48 super::place_xdg_file(
49 DEFAULT_ENCRYPTION_KEY_FILE_NAME,
50 "default encryption key file",
51 )
52 }
53
54 #[cfg(not(test))]
55 pub fn read_optional_default_encryption_key() -> Result<Option<Vec<u8>>, Error> {
56 find_default_encryption_key()?
57 .map(file_get_contents)
58 .transpose()
59 }
60
61 #[cfg(not(test))]
62 pub fn read_optional_default_master_pubkey() -> Result<Option<Vec<u8>>, Error> {
63 find_default_master_pubkey()?
64 .map(file_get_contents)
65 .transpose()
66 }
67
68 #[cfg(test)]
69 static mut TEST_DEFAULT_ENCRYPTION_KEY: Result<Option<Vec<u8>>, Error> = Ok(None);
70
71 #[cfg(test)]
72 pub fn read_optional_default_encryption_key() -> Result<Option<Vec<u8>>, Error> {
73 // not safe when multiple concurrent test cases end up here!
74 unsafe {
75 match &TEST_DEFAULT_ENCRYPTION_KEY {
76 Ok(key) => Ok(key.clone()),
77 Err(_) => bail!("test error"),
78 }
79 }
80 }
81
82 #[cfg(test)]
83 // not safe when multiple concurrent test cases end up here!
84 pub unsafe fn set_test_encryption_key(value: Result<Option<Vec<u8>>, Error>) {
85 TEST_DEFAULT_ENCRYPTION_KEY = value;
86 }
87
88 #[cfg(test)]
89 static mut TEST_DEFAULT_MASTER_PUBKEY: Result<Option<Vec<u8>>, Error> = Ok(None);
90
91 #[cfg(test)]
92 pub fn read_optional_default_master_pubkey() -> Result<Option<Vec<u8>>, Error> {
93 // not safe when multiple concurrent test cases end up here!
94 unsafe {
95 match &TEST_DEFAULT_MASTER_PUBKEY {
96 Ok(key) => Ok(key.clone()),
97 Err(_) => bail!("test error"),
98 }
99 }
100 }
101
102 #[cfg(test)]
103 // not safe when multiple concurrent test cases end up here!
104 pub unsafe fn set_test_default_master_pubkey(value: Result<Option<Vec<u8>>, Error>) {
105 TEST_DEFAULT_MASTER_PUBKEY = value;
106 }
107
108 pub fn get_encryption_key_password() -> Result<Vec<u8>, Error> {
109 // fixme: implement other input methods
110
111 use std::env::VarError::*;
112 match std::env::var("PBS_ENCRYPTION_PASSWORD") {
113 Ok(p) => return Ok(p.as_bytes().to_vec()),
114 Err(NotUnicode(_)) => bail!("PBS_ENCRYPTION_PASSWORD contains bad characters"),
115 Err(NotPresent) => {
116 // Try another method
117 }
118 }
119
120 // If we're on a TTY, query the user for a password
121 if tty::stdin_isatty() {
122 return Ok(tty::read_password("Encryption Key Password: ")?);
123 }
124
125 bail!("no password input mechanism available");
126 }
127
128 #[api(
129 input: {
130 properties: {
131 kdf: {
132 type: Kdf,
133 optional: true,
134 },
135 path: {
136 description:
137 "Output file. Without this the key will become the new default encryption key.",
138 optional: true,
139 },
140 hint: {
141 schema: PASSWORD_HINT_SCHEMA,
142 optional: true,
143 },
144 },
145 },
146 )]
147 /// Create a new encryption key.
148 fn create(kdf: Option<Kdf>, path: Option<String>, hint: Option<String>) -> Result<(), Error> {
149 let path = match path {
150 Some(path) => PathBuf::from(path),
151 None => {
152 let path = place_default_encryption_key()?;
153 println!("creating default key at: {:?}", path);
154 path
155 }
156 };
157
158 let kdf = kdf.unwrap_or_default();
159
160 let mut key = [0u8; 32];
161 proxmox::sys::linux::fill_with_random_data(&mut key)?;
162
163 match kdf {
164 Kdf::None => {
165 if hint.is_some() {
166 bail!("password hint not allowed for Kdf::None");
167 }
168
169 let key_config = KeyConfig::without_password(key)?;
170
171 key_config.store(path, false)?;
172 }
173 Kdf::Scrypt | Kdf::PBKDF2 => {
174 // always read passphrase from tty
175 if !tty::stdin_isatty() {
176 bail!("unable to read passphrase - no tty");
177 }
178
179 let password = tty::read_and_verify_password("Encryption Key Password: ")?;
180
181 let mut key_config = KeyConfig::with_key(&key, &password, kdf)?;
182 key_config.hint = hint;
183
184 key_config.store(&path, false)?;
185 }
186 }
187
188 Ok(())
189 }
190
191 #[api(
192 input: {
193 properties: {
194 "master-keyfile": {
195 description: "(Private) master key to use.",
196 },
197 "encrypted-keyfile": {
198 description: "RSA-encrypted keyfile to import.",
199 },
200 kdf: {
201 type: Kdf,
202 optional: true,
203 },
204 "path": {
205 description:
206 "Output file. Without this the key will become the new default encryption key.",
207 optional: true,
208 },
209 hint: {
210 schema: PASSWORD_HINT_SCHEMA,
211 optional: true,
212 },
213 },
214 },
215 )]
216 /// Import an encrypted backup of an encryption key using a (private) master key.
217 async fn import_with_master_key(
218 master_keyfile: String,
219 encrypted_keyfile: String,
220 kdf: Option<Kdf>,
221 path: Option<String>,
222 hint: Option<String>,
223 ) -> Result<(), Error> {
224 let path = match path {
225 Some(path) => PathBuf::from(path),
226 None => {
227 let path = place_default_encryption_key()?;
228 if path.exists() {
229 bail!("Please remove default encryption key at {:?} before importing to default location (or choose a non-default one).", path);
230 }
231 println!("Importing key to default location at: {:?}", path);
232 path
233 }
234 };
235
236 let encrypted_key = file_get_contents(&encrypted_keyfile)?;
237 let master_key = file_get_contents(&master_keyfile)?;
238 let password = tty::read_password("Master Key Password: ")?;
239
240 let master_key = openssl::pkey::PKey::private_key_from_pem_passphrase(&master_key, &password)
241 .map_err(|err| format_err!("failed to read PEM-formatted private key - {}", err))?
242 .rsa()
243 .map_err(|err| format_err!("not a valid private RSA key - {}", err))?;
244
245 let (key, created, _fingerprint) =
246 rsa_decrypt_key_config(master_key, &encrypted_key, &get_encryption_key_password)?;
247
248 let kdf = kdf.unwrap_or_default();
249 match kdf {
250 Kdf::None => {
251 if hint.is_some() {
252 bail!("password hint not allowed for Kdf::None");
253 }
254
255 let mut key_config = KeyConfig::without_password(key)?;
256 key_config.created = created; // keep original value
257
258 key_config.store(path, true)?;
259 }
260 Kdf::Scrypt | Kdf::PBKDF2 => {
261 let password = tty::read_and_verify_password("New Password: ")?;
262
263 let mut new_key_config = KeyConfig::with_key(&key, &password, kdf)?;
264 new_key_config.created = created; // keep original value
265 new_key_config.hint = hint;
266
267 new_key_config.store(path, true)?;
268 }
269 }
270
271 Ok(())
272 }
273
274 #[api(
275 input: {
276 properties: {
277 kdf: {
278 type: Kdf,
279 optional: true,
280 },
281 path: {
282 description: "Key file. Without this the default key's password will be changed.",
283 optional: true,
284 },
285 hint: {
286 schema: PASSWORD_HINT_SCHEMA,
287 optional: true,
288 },
289 },
290 },
291 )]
292 /// Change the encryption key's password.
293 fn change_passphrase(
294 kdf: Option<Kdf>,
295 path: Option<String>,
296 hint: Option<String>,
297 ) -> Result<(), Error> {
298 let path = match path {
299 Some(path) => PathBuf::from(path),
300 None => {
301 let path = find_default_encryption_key()?.ok_or_else(|| {
302 format_err!("no encryption file provided and no default file found")
303 })?;
304 println!("updating default key at: {:?}", path);
305 path
306 }
307 };
308
309 let kdf = kdf.unwrap_or_default();
310
311 if !tty::stdin_isatty() {
312 bail!("unable to change passphrase - no tty");
313 }
314
315 let key_config = KeyConfig::load(&path)?;
316 let (key, created, _fingerprint) = key_config.decrypt(&get_encryption_key_password)?;
317
318 match kdf {
319 Kdf::None => {
320 if hint.is_some() {
321 bail!("password hint not allowed for Kdf::None");
322 }
323
324 let mut key_config = KeyConfig::without_password(key)?;
325 key_config.created = created; // keep original value
326
327 key_config.store(&path, true)?;
328 }
329 Kdf::Scrypt | Kdf::PBKDF2 => {
330 let password = tty::read_and_verify_password("New Password: ")?;
331
332 let mut new_key_config = KeyConfig::with_key(&key, &password, kdf)?;
333 new_key_config.created = created; // keep original value
334 new_key_config.hint = hint;
335
336 new_key_config.store(&path, true)?;
337 }
338 }
339
340 Ok(())
341 }
342
343 #[api(
344 input: {
345 properties: {
346 path: {
347 description: "Key file. Without this the default key's metadata will be shown.",
348 optional: true,
349 },
350 "output-format": {
351 schema: OUTPUT_FORMAT,
352 optional: true,
353 },
354 },
355 },
356 )]
357 /// Print the encryption key's metadata.
358 fn show_key(path: Option<String>, param: Value) -> Result<(), Error> {
359 let path = match path {
360 Some(path) => PathBuf::from(path),
361 None => find_default_encryption_key()?
362 .ok_or_else(|| format_err!("no encryption file provided and no default file found"))?,
363 };
364
365 let config: KeyConfig = serde_json::from_slice(&file_get_contents(path.clone())?)?;
366
367 let output_format = get_output_format(&param);
368
369 let mut info: KeyInfo = (&config).into();
370 info.path = Some(format!("{:?}", path));
371
372 let options = proxmox::api::cli::default_table_format_options()
373 .column(ColumnConfig::new("path"))
374 .column(ColumnConfig::new("kdf"))
375 .column(ColumnConfig::new("created").renderer(tools::format::render_epoch))
376 .column(ColumnConfig::new("modified").renderer(tools::format::render_epoch))
377 .column(ColumnConfig::new("fingerprint"))
378 .column(ColumnConfig::new("hint"));
379
380 let return_type = ReturnType::new(false, &KeyInfo::API_SCHEMA);
381
382 format_and_print_result_full(
383 &mut serde_json::to_value(info)?,
384 &return_type,
385 &output_format,
386 &options,
387 );
388
389 Ok(())
390 }
391
392 #[api(
393 input: {
394 properties: {
395 path: {
396 description: "Path to the PEM formatted RSA public key.",
397 },
398 },
399 },
400 )]
401 /// Import an RSA public key used to put an encrypted version of the symmetric backup encryption
402 /// key onto the backup server along with each backup.
403 ///
404 /// The imported key will be used as default master key for future invocations by the same local
405 /// user.
406 fn import_master_pubkey(path: String) -> Result<(), Error> {
407 let pem_data = file_get_contents(&path)?;
408
409 match openssl::pkey::PKey::public_key_from_pem(&pem_data) {
410 Ok(key) => {
411 let info = RsaPubKeyInfo::try_from(key.rsa()?)?;
412 println!("Found following key at {:?}", path);
413 println!("Modulus: {}", info.modulus);
414 println!("Exponent: {}", info.exponent);
415 println!("Length: {}", info.length);
416 }
417 Err(err) => bail!("Unable to decode PEM data - {}", err),
418 };
419
420 let target_path = place_default_master_pubkey()?;
421
422 replace_file(&target_path, &pem_data, CreateOptions::new())?;
423
424 println!("Imported public master key to {:?}", target_path);
425
426 Ok(())
427 }
428
429 #[api]
430 /// Create an RSA public/private key pair used to put an encrypted version of the symmetric backup
431 /// encryption key onto the backup server along with each backup.
432 fn create_master_key() -> Result<(), Error> {
433 // we need a TTY to query the new password
434 if !tty::stdin_isatty() {
435 bail!("unable to create master key - no tty");
436 }
437
438 let bits = 4096;
439 println!("Generating {}-bit RSA key..", bits);
440 let rsa = openssl::rsa::Rsa::generate(bits)?;
441 let public =
442 openssl::rsa::Rsa::from_public_components(rsa.n().to_owned()?, rsa.e().to_owned()?)?;
443 let info = RsaPubKeyInfo::try_from(public)?;
444 println!("Modulus: {}", info.modulus);
445 println!("Exponent: {}", info.exponent);
446 println!();
447
448 let pkey = openssl::pkey::PKey::from_rsa(rsa)?;
449
450 let password = String::from_utf8(tty::read_and_verify_password("Master Key Password: ")?)?;
451
452 let pub_key: Vec<u8> = pkey.public_key_to_pem()?;
453 let filename_pub = "master-public.pem";
454 println!("Writing public master key to {}", filename_pub);
455 replace_file(filename_pub, pub_key.as_slice(), CreateOptions::new())?;
456
457 let cipher = openssl::symm::Cipher::aes_256_cbc();
458 let priv_key: Vec<u8> =
459 pkey.private_key_to_pem_pkcs8_passphrase(cipher, password.as_bytes())?;
460
461 let filename_priv = "master-private.pem";
462 println!("Writing private master key to {}", filename_priv);
463 replace_file(filename_priv, priv_key.as_slice(), CreateOptions::new())?;
464
465 Ok(())
466 }
467
468 #[api(
469 input: {
470 properties: {
471 path: {
472 description: "Path to the PEM formatted RSA public key. Default location will be used if not specified.",
473 optional: true,
474 },
475 "output-format": {
476 schema: OUTPUT_FORMAT,
477 optional: true,
478 },
479 },
480 },
481 )]
482 /// List information about master key
483 fn show_master_pubkey(path: Option<String>, param: Value) -> Result<(), Error> {
484 let path = match path {
485 Some(path) => PathBuf::from(path),
486 None => find_default_master_pubkey()?
487 .ok_or_else(|| format_err!("No path specified and no default master key available."))?,
488 };
489
490 let path = path.canonicalize()?;
491
492 let output_format = get_output_format(&param);
493
494 let pem_data = file_get_contents(path.clone())?;
495 let rsa = openssl::rsa::Rsa::public_key_from_pem(&pem_data)?;
496
497 let mut info = RsaPubKeyInfo::try_from(rsa)?;
498 info.path = Some(path.display().to_string());
499
500 let options = proxmox::api::cli::default_table_format_options()
501 .column(ColumnConfig::new("path"))
502 .column(ColumnConfig::new("modulus"))
503 .column(ColumnConfig::new("exponent"))
504 .column(ColumnConfig::new("length"));
505
506 let return_type = ReturnType::new(false, &RsaPubKeyInfo::API_SCHEMA);
507
508 format_and_print_result_full(
509 &mut serde_json::to_value(info)?,
510 &return_type,
511 &output_format,
512 &options,
513 );
514
515 Ok(())
516 }
517
518 #[api(
519 input: {
520 properties: {
521 path: {
522 description: "Key file. Without this the default key's will be used.",
523 optional: true,
524 },
525 subject: {
526 description: "Include the specified subject as titel text.",
527 optional: true,
528 },
529 "output-format": {
530 type: PaperkeyFormat,
531 optional: true,
532 },
533 },
534 },
535 )]
536 /// Generate a printable, human readable text file containing the encryption key.
537 ///
538 /// This also includes a scanable QR code for fast key restore.
539 fn paper_key(
540 path: Option<String>,
541 subject: Option<String>,
542 output_format: Option<PaperkeyFormat>,
543 ) -> Result<(), Error> {
544 let path = match path {
545 Some(path) => PathBuf::from(path),
546 None => find_default_encryption_key()?
547 .ok_or_else(|| format_err!("no encryption file provided and no default file found"))?,
548 };
549
550 let data = file_get_contents(&path)?;
551 let data = String::from_utf8(data)?;
552
553 generate_paper_key(std::io::stdout(), &data, subject, output_format)
554 }
555
556 pub fn cli() -> CliCommandMap {
557 let key_create_cmd_def = CliCommand::new(&API_METHOD_CREATE)
558 .arg_param(&["path"])
559 .completion_cb("path", tools::complete_file_name);
560
561 let key_import_with_master_key_cmd_def = CliCommand::new(&API_METHOD_IMPORT_WITH_MASTER_KEY)
562 .arg_param(&["master-keyfile"])
563 .completion_cb("master-keyfile", tools::complete_file_name)
564 .arg_param(&["encrypted-keyfile"])
565 .completion_cb("encrypted-keyfile", tools::complete_file_name)
566 .arg_param(&["path"])
567 .completion_cb("path", tools::complete_file_name);
568
569 let key_change_passphrase_cmd_def = CliCommand::new(&API_METHOD_CHANGE_PASSPHRASE)
570 .arg_param(&["path"])
571 .completion_cb("path", tools::complete_file_name);
572
573 let key_create_master_key_cmd_def = CliCommand::new(&API_METHOD_CREATE_MASTER_KEY);
574 let key_import_master_pubkey_cmd_def = CliCommand::new(&API_METHOD_IMPORT_MASTER_PUBKEY)
575 .arg_param(&["path"])
576 .completion_cb("path", tools::complete_file_name);
577 let key_show_master_pubkey_cmd_def = CliCommand::new(&API_METHOD_SHOW_MASTER_PUBKEY)
578 .arg_param(&["path"])
579 .completion_cb("path", tools::complete_file_name);
580
581 let key_show_cmd_def = CliCommand::new(&API_METHOD_SHOW_KEY)
582 .arg_param(&["path"])
583 .completion_cb("path", tools::complete_file_name);
584
585 let paper_key_cmd_def = CliCommand::new(&API_METHOD_PAPER_KEY)
586 .arg_param(&["path"])
587 .completion_cb("path", tools::complete_file_name);
588
589 CliCommandMap::new()
590 .insert("create", key_create_cmd_def)
591 .insert("import-with-master-key", key_import_with_master_key_cmd_def)
592 .insert("create-master-key", key_create_master_key_cmd_def)
593 .insert("import-master-pubkey", key_import_master_pubkey_cmd_def)
594 .insert("change-passphrase", key_change_passphrase_cmd_def)
595 .insert("show", key_show_cmd_def)
596 .insert("show-master-pubkey", key_show_master_pubkey_cmd_def)
597 .insert("paperkey", paper_key_cmd_def)
598 }