1 use std
::convert
::TryFrom
;
2 use std
::path
::PathBuf
;
4 use anyhow
::{bail, format_err, Error}
;
8 use proxmox
::api
::cli
::{
9 format_and_print_result_full
, get_output_format
, CliCommand
, CliCommandMap
, ColumnConfig
,
12 use proxmox
::api
::router
::ReturnType
;
13 use proxmox
::sys
::linux
::tty
;
14 use proxmox
::tools
::fs
::{file_get_contents, replace_file, CreateOptions}
;
17 api2
::types
::{Kdf, KeyInfo, RsaPubKeyInfo, PASSWORD_HINT_SCHEMA}
,
18 backup
::{rsa_decrypt_key_config, KeyConfig}
,
20 tools
::paperkey
::{generate_paper_key, PaperkeyFormat}
,
23 pub const DEFAULT_ENCRYPTION_KEY_FILE_NAME
: &str = "encryption-key.json";
24 pub const DEFAULT_MASTER_PUBKEY_FILE_NAME
: &str = "master-public.pem";
26 pub fn find_default_master_pubkey() -> Result
<Option
<PathBuf
>, Error
> {
28 DEFAULT_MASTER_PUBKEY_FILE_NAME
,
29 "default master public key file",
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",
40 pub fn find_default_encryption_key() -> Result
<Option
<PathBuf
>, Error
> {
42 DEFAULT_ENCRYPTION_KEY_FILE_NAME
,
43 "default encryption key file",
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",
55 pub fn read_optional_default_encryption_key() -> Result
<Option
<Vec
<u8>>, Error
> {
56 find_default_encryption_key()?
57 .map(file_get_contents
)
62 pub fn read_optional_default_master_pubkey() -> Result
<Option
<Vec
<u8>>, Error
> {
63 find_default_master_pubkey()?
64 .map(file_get_contents
)
69 static mut TEST_DEFAULT_ENCRYPTION_KEY
: Result
<Option
<Vec
<u8>>, Error
> = Ok(None
);
72 pub fn read_optional_default_encryption_key() -> Result
<Option
<Vec
<u8>>, Error
> {
73 // not safe when multiple concurrent test cases end up here!
75 match &TEST_DEFAULT_ENCRYPTION_KEY
{
76 Ok(key
) => Ok(key
.clone()),
77 Err(_
) => bail
!("test error"),
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
;
89 static mut TEST_DEFAULT_MASTER_PUBKEY
: Result
<Option
<Vec
<u8>>, Error
> = Ok(None
);
92 pub fn read_optional_default_master_pubkey() -> Result
<Option
<Vec
<u8>>, Error
> {
93 // not safe when multiple concurrent test cases end up here!
95 match &TEST_DEFAULT_MASTER_PUBKEY
{
96 Ok(key
) => Ok(key
.clone()),
97 Err(_
) => bail
!("test error"),
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
;
108 pub fn get_encryption_key_password() -> Result
<Vec
<u8>, Error
> {
109 // fixme: implement other input methods
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"),
116 // Try another method
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: ")?
);
125 bail
!("no password input mechanism available");
137 "Output file. Without this the key will become the new default encryption key.",
141 schema
: PASSWORD_HINT_SCHEMA
,
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
),
152 let path
= place_default_encryption_key()?
;
153 println
!("creating default key at: {:?}", path
);
158 let kdf
= kdf
.unwrap_or_default();
160 let mut key
= [0u8; 32];
161 proxmox
::sys
::linux
::fill_with_random_data(&mut key
)?
;
166 bail
!("password hint not allowed for Kdf::None");
169 let key_config
= KeyConfig
::without_password(key
)?
;
171 key_config
.store(path
, false)?
;
173 Kdf
::Scrypt
| Kdf
::PBKDF2
=> {
174 // always read passphrase from tty
175 if !tty
::stdin_isatty() {
176 bail
!("unable to read passphrase - no tty");
179 let password
= tty
::read_and_verify_password("Encryption Key Password: ")?
;
181 let mut key_config
= KeyConfig
::with_key(&key
, &password
, kdf
)?
;
182 key_config
.hint
= hint
;
184 key_config
.store(&path
, false)?
;
195 description
: "(Private) master key to use.",
197 "encrypted-keyfile": {
198 description
: "RSA-encrypted keyfile to import.",
206 "Output file. Without this the key will become the new default encryption key.",
210 schema
: PASSWORD_HINT_SCHEMA
,
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
,
221 path
: Option
<String
>,
222 hint
: Option
<String
>,
223 ) -> Result
<(), Error
> {
224 let path
= match path
{
225 Some(path
) => PathBuf
::from(path
),
227 let path
= place_default_encryption_key()?
;
229 bail
!("Please remove default encryption key at {:?} before importing to default location (or choose a non-default one).", path
);
231 println
!("Importing key to default location at: {:?}", path
);
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: ")?
;
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
))?
243 .map_err(|err
| format_err
!("not a valid private RSA key - {}", err
))?
;
245 let (key
, created
, _fingerprint
) =
246 rsa_decrypt_key_config(master_key
, &encrypted_key
, &get_encryption_key_password
)?
;
248 let kdf
= kdf
.unwrap_or_default();
252 bail
!("password hint not allowed for Kdf::None");
255 let mut key_config
= KeyConfig
::without_password(key
)?
;
256 key_config
.created
= created
; // keep original value
258 key_config
.store(path
, true)?
;
260 Kdf
::Scrypt
| Kdf
::PBKDF2
=> {
261 let password
= tty
::read_and_verify_password("New Password: ")?
;
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
;
267 new_key_config
.store(path
, true)?
;
282 description
: "Key file. Without this the default key's password will be changed.",
286 schema
: PASSWORD_HINT_SCHEMA
,
292 /// Change the encryption key's password.
293 fn change_passphrase(
295 path
: Option
<String
>,
296 hint
: Option
<String
>,
297 ) -> Result
<(), Error
> {
298 let path
= match path
{
299 Some(path
) => PathBuf
::from(path
),
301 let path
= find_default_encryption_key()?
.ok_or_else(|| {
302 format_err
!("no encryption file provided and no default file found")
304 println
!("updating default key at: {:?}", path
);
309 let kdf
= kdf
.unwrap_or_default();
311 if !tty
::stdin_isatty() {
312 bail
!("unable to change passphrase - no tty");
315 let key_config
= KeyConfig
::load(&path
)?
;
316 let (key
, created
, _fingerprint
) = key_config
.decrypt(&get_encryption_key_password
)?
;
321 bail
!("password hint not allowed for Kdf::None");
324 let mut key_config
= KeyConfig
::without_password(key
)?
;
325 key_config
.created
= created
; // keep original value
327 key_config
.store(&path
, true)?
;
329 Kdf
::Scrypt
| Kdf
::PBKDF2
=> {
330 let password
= tty
::read_and_verify_password("New Password: ")?
;
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
;
336 new_key_config
.store(&path
, true)?
;
347 description
: "Key file. Without this the default key's metadata will be shown.",
351 schema
: OUTPUT_FORMAT
,
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"))?
,
365 let config
: KeyConfig
= serde_json
::from_slice(&file_get_contents(path
.clone())?
)?
;
367 let output_format
= get_output_format(¶m
);
369 let mut info
: KeyInfo
= (&config
).into();
370 info
.path
= Some(format
!("{:?}", path
));
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"));
380 let return_type
= ReturnType
::new(false, &KeyInfo
::API_SCHEMA
);
382 format_and_print_result_full(
383 &mut serde_json
::to_value(info
)?
,
396 description
: "Path to the PEM formatted RSA public key.",
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.
404 /// The imported key will be used as default master key for future invocations by the same local
406 fn import_master_pubkey(path
: String
) -> Result
<(), Error
> {
407 let pem_data
= file_get_contents(&path
)?
;
409 match openssl
::pkey
::PKey
::public_key_from_pem(&pem_data
) {
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
);
417 Err(err
) => bail
!("Unable to decode PEM data - {}", err
),
420 let target_path
= place_default_master_pubkey()?
;
422 replace_file(&target_path
, &pem_data
, CreateOptions
::new())?
;
424 println
!("Imported public master key to {:?}", target_path
);
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");
439 println
!("Generating {}-bit RSA key..", bits
);
440 let rsa
= openssl
::rsa
::Rsa
::generate(bits
)?
;
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
);
448 let pkey
= openssl
::pkey
::PKey
::from_rsa(rsa
)?
;
450 let password
= String
::from_utf8(tty
::read_and_verify_password("Master Key Password: ")?
)?
;
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())?
;
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())?
;
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())?
;
472 description
: "Path to the PEM formatted RSA public key. Default location will be used if not specified.",
476 schema
: OUTPUT_FORMAT
,
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."))?
,
490 let path
= path
.canonicalize()?
;
492 let output_format
= get_output_format(¶m
);
494 let pem_data
= file_get_contents(path
.clone())?
;
495 let rsa
= openssl
::rsa
::Rsa
::public_key_from_pem(&pem_data
)?
;
497 let mut info
= RsaPubKeyInfo
::try_from(rsa
)?
;
498 info
.path
= Some(path
.display().to_string());
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"));
506 let return_type
= ReturnType
::new(false, &RsaPubKeyInfo
::API_SCHEMA
);
508 format_and_print_result_full(
509 &mut serde_json
::to_value(info
)?
,
522 description
: "Key file. Without this the default key's will be used.",
526 description
: "Include the specified subject as titel text.",
530 type: PaperkeyFormat
,
536 /// Generate a printable, human readable text file containing the encryption key.
538 /// This also includes a scanable QR code for fast key restore.
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"))?
,
550 let data
= file_get_contents(&path
)?
;
551 let data
= String
::from_utf8(data
)?
;
553 generate_paper_key(std
::io
::stdout(), &data
, subject
, output_format
)
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
);
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
);
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
);
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
);
581 let key_show_cmd_def
= CliCommand
::new(&API_METHOD_SHOW_KEY
)
582 .arg_param(&["path"])
583 .completion_cb("path", tools
::complete_file_name
);
585 let paper_key_cmd_def
= CliCommand
::new(&API_METHOD_PAPER_KEY
)
586 .arg_param(&["path"])
587 .completion_cb("path", tools
::complete_file_name
);
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
)