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