public inbox for pbs-devel@lists.proxmox.com
 help / color / mirror / Atom feed
From: "Fabian Grünbichler" <f.gruenbichler@proxmox.com>
To: pbs-devel@lists.proxmox.com
Subject: [pbs-devel] [PATCH proxmox-backup 2/7] key: add fingerprint to key config
Date: Tue, 17 Nov 2020 18:57:20 +0100	[thread overview]
Message-ID: <20201117175725.3634238-3-f.gruenbichler@proxmox.com> (raw)
In-Reply-To: <20201117175725.3634238-1-f.gruenbichler@proxmox.com>

and set/generate it on
- key creation
- key passphrase change
- key decryption if not already set (not persisted, but returned)
- key encryption with master key

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
---

Notes:
    an existing passwordless key can be 'updated' non-interactively with
    
    proxmox-backup-client key change-passphrase $path --kdf none
    
    something like this could go into the/some postinst to retro-actively give all
    the PVE generated storage keys a fingerprint field. this only affects the 'key
    show' subcommand (introduced later in this series) or manual checks of the key
    file, any operations actually using the key have access to its CryptConfig and
    thus the fingerprint() function anyway..

 src/backup/crypt_config.rs                 |  8 ++-
 src/backup/key_derivation.rs               | 23 +++++++--
 src/bin/proxmox-backup-client.rs           |  6 +--
 src/bin/proxmox_backup_client/benchmark.rs |  2 +-
 src/bin/proxmox_backup_client/catalog.rs   |  4 +-
 src/bin/proxmox_backup_client/key.rs       | 17 +++++--
 src/bin/proxmox_backup_client/mount.rs     |  2 +-
 src/tools/format.rs                        | 58 ++++++++++++++++++++++
 8 files changed, 105 insertions(+), 15 deletions(-)

diff --git a/src/backup/crypt_config.rs b/src/backup/crypt_config.rs
index 01ab0942..177923b3 100644
--- a/src/backup/crypt_config.rs
+++ b/src/backup/crypt_config.rs
@@ -228,7 +228,13 @@ impl CryptConfig {
     ) -> Result<Vec<u8>, Error> {
 
         let modified = proxmox::tools::time::epoch_i64();
-        let key_config = super::KeyConfig { kdf: None, created, modified, data: self.enc_key.to_vec() };
+        let key_config = super::KeyConfig {
+            kdf: None,
+            created,
+            modified,
+            data: self.enc_key.to_vec(),
+            fingerprint: Some(self.fingerprint()),
+        };
         let data = serde_json::to_string(&key_config)?.as_bytes().to_vec();
 
         let mut buffer = vec![0u8; rsa.size() as usize];
diff --git a/src/backup/key_derivation.rs b/src/backup/key_derivation.rs
index 2c807723..dcf18cfa 100644
--- a/src/backup/key_derivation.rs
+++ b/src/backup/key_derivation.rs
@@ -2,6 +2,8 @@ use anyhow::{bail, format_err, Context, Error};
 
 use serde::{Deserialize, Serialize};
 
+use crate::backup::CryptConfig;
+
 use proxmox::tools::fs::{file_get_contents, replace_file, CreateOptions};
 use proxmox::try_block;
 
@@ -66,6 +68,10 @@ pub struct KeyConfig {
     pub modified: i64,
     #[serde(with = "proxmox::tools::serde::bytes_as_base64")]
     pub data: Vec<u8>,
+    #[serde(skip_serializing_if = "Option::is_none")]
+    #[serde(default)]
+    #[serde(with = "crate::tools::format::opt_sha256_as_fingerprint")]
+    pub fingerprint: Option<[u8; 32]>,
  }
 
 pub fn store_key_config(
@@ -142,13 +148,14 @@ pub fn encrypt_key_with_passphrase(
         created,
         modified: created,
         data: enc_data,
+        fingerprint: None,
     })
 }
 
 pub fn load_and_decrypt_key(
     path: &std::path::Path,
     passphrase: &dyn Fn() -> Result<Vec<u8>, Error>,
-) -> Result<([u8;32], i64), Error> {
+) -> Result<([u8;32], i64, [u8;32]), Error> {
     do_load_and_decrypt_key(path, passphrase)
         .with_context(|| format!("failed to load decryption key from {:?}", path))
 }
@@ -156,14 +163,14 @@ pub fn load_and_decrypt_key(
 fn do_load_and_decrypt_key(
     path: &std::path::Path,
     passphrase: &dyn Fn() -> Result<Vec<u8>, Error>,
-) -> Result<([u8;32], i64), Error> {
+) -> Result<([u8;32], i64, [u8;32]), Error> {
     decrypt_key(&file_get_contents(&path)?, passphrase)
 }
 
 pub fn decrypt_key(
     mut keydata: &[u8],
     passphrase: &dyn Fn() -> Result<Vec<u8>, Error>,
-) -> Result<([u8;32], i64), Error> {
+) -> Result<([u8;32], i64, [u8;32]), Error> {
     let key_config: KeyConfig = serde_json::from_reader(&mut keydata)?;
 
     let raw_data = key_config.data;
@@ -203,5 +210,13 @@ pub fn decrypt_key(
     let mut result = [0u8; 32];
     result.copy_from_slice(&key);
 
-    Ok((result, created))
+    let fingerprint = match key_config.fingerprint {
+        Some(fingerprint) => fingerprint,
+        None => {
+            let crypt_config = CryptConfig::new(result.clone())?;
+            crypt_config.fingerprint()
+        },
+    };
+
+    Ok((result, created, fingerprint))
 }
diff --git a/src/bin/proxmox-backup-client.rs b/src/bin/proxmox-backup-client.rs
index 70aba77f..c63c7eb6 100644
--- a/src/bin/proxmox-backup-client.rs
+++ b/src/bin/proxmox-backup-client.rs
@@ -1069,7 +1069,7 @@ async fn create_backup(
     let (crypt_config, rsa_encrypted_key) = match keydata {
         None => (None, None),
         Some(key) => {
-            let (key, created) = decrypt_key(&key, &key::get_encryption_key_password)?;
+            let (key, created, _fingerprint) = decrypt_key(&key, &key::get_encryption_key_password)?;
 
             let crypt_config = CryptConfig::new(key)?;
 
@@ -1380,7 +1380,7 @@ async fn restore(param: Value) -> Result<Value, Error> {
     let crypt_config = match keydata {
         None => None,
         Some(key) => {
-            let (key, _) = decrypt_key(&key, &key::get_encryption_key_password)?;
+            let (key, _, _) = decrypt_key(&key, &key::get_encryption_key_password)?;
             Some(Arc::new(CryptConfig::new(key)?))
         }
     };
@@ -1538,7 +1538,7 @@ async fn upload_log(param: Value) -> Result<Value, Error> {
     let crypt_config = match keydata {
         None => None,
         Some(key) => {
-            let (key, _created) = decrypt_key(&key, &key::get_encryption_key_password)?;
+            let (key, _created, _) = decrypt_key(&key, &key::get_encryption_key_password)?;
             let crypt_config = CryptConfig::new(key)?;
             Some(Arc::new(crypt_config))
         }
diff --git a/src/bin/proxmox_backup_client/benchmark.rs b/src/bin/proxmox_backup_client/benchmark.rs
index b0d769e8..e53e43ce 100644
--- a/src/bin/proxmox_backup_client/benchmark.rs
+++ b/src/bin/proxmox_backup_client/benchmark.rs
@@ -151,7 +151,7 @@ pub async fn benchmark(
     let crypt_config = match keyfile {
         None => None,
         Some(path) => {
-            let (key, _) = load_and_decrypt_key(&path, &crate::key::get_encryption_key_password)?;
+            let (key, _, _) = load_and_decrypt_key(&path, &crate::key::get_encryption_key_password)?;
             let crypt_config = CryptConfig::new(key)?;
             Some(Arc::new(crypt_config))
         }
diff --git a/src/bin/proxmox_backup_client/catalog.rs b/src/bin/proxmox_backup_client/catalog.rs
index e4931e10..37ad842f 100644
--- a/src/bin/proxmox_backup_client/catalog.rs
+++ b/src/bin/proxmox_backup_client/catalog.rs
@@ -73,7 +73,7 @@ async fn dump_catalog(param: Value) -> Result<Value, Error> {
     let crypt_config = match keydata {
         None => None,
         Some(key) => {
-            let (key, _created) = decrypt_key(&key, &get_encryption_key_password)?;
+            let (key, _created, _fingerprint) = decrypt_key(&key, &get_encryption_key_password)?;
             let crypt_config = CryptConfig::new(key)?;
             Some(Arc::new(crypt_config))
         }
@@ -170,7 +170,7 @@ async fn catalog_shell(param: Value) -> Result<(), Error> {
     let crypt_config = match keydata {
         None => None,
         Some(key) => {
-            let (key, _created) = decrypt_key(&key, &get_encryption_key_password)?;
+            let (key, _created, _fingerprint) = decrypt_key(&key, &get_encryption_key_password)?;
             let crypt_config = CryptConfig::new(key)?;
             Some(Arc::new(crypt_config))
         }
diff --git a/src/bin/proxmox_backup_client/key.rs b/src/bin/proxmox_backup_client/key.rs
index 8b802b3e..915ee970 100644
--- a/src/bin/proxmox_backup_client/key.rs
+++ b/src/bin/proxmox_backup_client/key.rs
@@ -11,7 +11,11 @@ use proxmox::sys::linux::tty;
 use proxmox::tools::fs::{file_get_contents, replace_file, CreateOptions};
 
 use proxmox_backup::backup::{
-    encrypt_key_with_passphrase, load_and_decrypt_key, store_key_config, KeyConfig,
+    encrypt_key_with_passphrase,
+    load_and_decrypt_key,
+    store_key_config,
+    CryptConfig,
+    KeyConfig,
 };
 use proxmox_backup::tools;
 
@@ -121,6 +125,9 @@ fn create(kdf: Option<Kdf>, path: Option<String>) -> Result<(), Error> {
     let kdf = kdf.unwrap_or_default();
 
     let key = proxmox::sys::linux::random_data(32)?;
+    use std::convert::TryInto;
+    let key_array: [u8; 32] = key.clone()[0..32].try_into().unwrap();
+    let crypt_config = CryptConfig::new(key_array)?;
 
     match kdf {
         Kdf::None => {
@@ -134,6 +141,7 @@ fn create(kdf: Option<Kdf>, path: Option<String>) -> Result<(), Error> {
                     created,
                     modified: created,
                     data: key,
+                    fingerprint: Some(crypt_config.fingerprint()),
                 },
             )?;
         }
@@ -145,7 +153,8 @@ fn create(kdf: Option<Kdf>, path: Option<String>) -> Result<(), Error> {
 
             let password = tty::read_and_verify_password("Encryption Key Password: ")?;
 
-            let key_config = encrypt_key_with_passphrase(&key, &password)?;
+            let mut key_config = encrypt_key_with_passphrase(&key, &password)?;
+            key_config.fingerprint = Some(crypt_config.fingerprint());
 
             store_key_config(&path, false, key_config)?;
         }
@@ -188,7 +197,7 @@ fn change_passphrase(kdf: Option<Kdf>, path: Option<String>) -> Result<(), Error
         bail!("unable to change passphrase - no tty");
     }
 
-    let (key, created) = load_and_decrypt_key(&path, &get_encryption_key_password)?;
+    let (key, created, fingerprint) = load_and_decrypt_key(&path, &get_encryption_key_password)?;
 
     match kdf {
         Kdf::None => {
@@ -202,6 +211,7 @@ fn change_passphrase(kdf: Option<Kdf>, path: Option<String>) -> Result<(), Error
                     created, // keep original value
                     modified,
                     data: key.to_vec(),
+                    fingerprint: Some(fingerprint),
                 },
             )?;
         }
@@ -210,6 +220,7 @@ fn change_passphrase(kdf: Option<Kdf>, path: Option<String>) -> Result<(), Error
 
             let mut new_key_config = encrypt_key_with_passphrase(&key, &password)?;
             new_key_config.created = created; // keep original value
+            new_key_config.fingerprint = Some(fingerprint);
 
             store_key_config(&path, true, new_key_config)?;
         }
diff --git a/src/bin/proxmox_backup_client/mount.rs b/src/bin/proxmox_backup_client/mount.rs
index 415fbf9d..6283961e 100644
--- a/src/bin/proxmox_backup_client/mount.rs
+++ b/src/bin/proxmox_backup_client/mount.rs
@@ -182,7 +182,7 @@ async fn mount_do(param: Value, pipe: Option<RawFd>) -> Result<Value, Error> {
     let crypt_config = match keyfile {
         None => None,
         Some(path) => {
-            let (key, _) = load_and_decrypt_key(&path, &crate::key::get_encryption_key_password)?;
+            let (key, _, _) = load_and_decrypt_key(&path, &crate::key::get_encryption_key_password)?;
             Some(Arc::new(CryptConfig::new(key)?))
         }
     };
diff --git a/src/tools/format.rs b/src/tools/format.rs
index 8fe6aa82..c16559a7 100644
--- a/src/tools/format.rs
+++ b/src/tools/format.rs
@@ -102,6 +102,64 @@ impl From<u64> for HumanByte {
     }
 }
 
+pub fn as_fingerprint(bytes: &[u8]) -> String {
+    proxmox::tools::digest_to_hex(bytes)
+        .as_bytes()
+        .chunks(2)
+        .map(|v| std::str::from_utf8(v).unwrap())
+        .collect::<Vec<&str>>().join(":")
+}
+
+pub mod opt_sha256_as_fingerprint {
+    use serde::{self, Serializer, Deserializer};
+
+    pub fn serialize<S>(
+        csum: &Option<[u8; 32]>,
+        serializer: S,
+    ) -> Result<S::Ok, S::Error>
+    where
+        S: Serializer,
+    {
+        crate::tools::format::sha256_as_fingerprint::serialize(&csum.unwrap(), serializer)
+    }
+
+    pub fn deserialize<'de, D>(
+        deserializer: D,
+    ) -> Result<Option<[u8; 32]>, D::Error>
+    where
+        D: Deserializer<'de>,
+    {
+        crate::tools::format::sha256_as_fingerprint::deserialize(deserializer)
+            .map(|digest| Some(digest))
+    }
+}
+
+pub mod sha256_as_fingerprint {
+    use serde::{self, Deserialize, Serializer, Deserializer};
+
+    pub fn serialize<S>(
+        csum: &[u8; 32],
+        serializer: S,
+    ) -> Result<S::Ok, S::Error>
+    where
+        S: Serializer,
+    {
+        let s = crate::tools::format::as_fingerprint(csum);
+        serializer.serialize_str(&s)
+    }
+
+    pub fn deserialize<'de, D>(
+        deserializer: D,
+    ) -> Result<[u8; 32], D::Error>
+    where
+        D: Deserializer<'de>,
+    {
+        let mut s = String::deserialize(deserializer)?;
+        s.retain(|c| c != ':');
+        proxmox::tools::hex_to_digest(&s).map_err(serde::de::Error::custom)
+    }
+}
+
 #[test]
 fn correct_byte_convert() {
     fn convert(b: usize) -> String {
-- 
2.20.1





  parent reply	other threads:[~2020-11-17 17:57 UTC|newest]

Thread overview: 17+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2020-11-17 17:57 [pbs-devel] [PATCH proxmox-backup 0/7] add, persist and check key fingerprint Fabian Grünbichler
2020-11-17 17:57 ` [pbs-devel] [PATCH proxmox-backup 1/7] crypt config: add fingerprint mechanism Fabian Grünbichler
2020-11-17 17:57 ` Fabian Grünbichler [this message]
2020-11-18  8:48   ` [pbs-devel] [PATCH proxmox-backup 2/7] key: add fingerprint to key config Wolfgang Bumiller
2020-11-17 17:57 ` [pbs-devel] [PATCH proxmox-backup 3/7] client: print key fingerprint and master key Fabian Grünbichler
2020-11-17 18:38   ` Thomas Lamprecht
2020-11-17 17:57 ` [pbs-devel] [PATCH proxmox-backup 4/7] client: add 'key show' command Fabian Grünbichler
2020-11-17 17:57 ` [pbs-devel] [PATCH proxmox-backup 5/7] add key fingerprint to manifest Fabian Grünbichler
2020-11-17 17:57 ` [pbs-devel] [PATCH proxmox-backup 6/7] fix #3139: manifest: check fingerprint when loading with key Fabian Grünbichler
2020-11-17 17:57 ` [pbs-devel] [PATCH proxmox-backup 7/7] client: check fingerprint after downloading manifest Fabian Grünbichler
2020-11-18  5:27 ` [pbs-devel] [PATCH proxmox-backup 0/7] add, persist and check key fingerprint Dietmar Maurer
2020-11-18  5:47   ` Dietmar Maurer
2020-11-18  6:47     ` Thomas Lamprecht
2020-11-18  8:27       ` Fabian Grünbichler
2020-11-18  8:54         ` Dietmar Maurer
2020-11-23  7:55         ` Dietmar Maurer
2020-11-23  8:16           ` Fabian Grünbichler

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20201117175725.3634238-3-f.gruenbichler@proxmox.com \
    --to=f.gruenbichler@proxmox.com \
    --cc=pbs-devel@lists.proxmox.com \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox
Service provided by Proxmox Server Solutions GmbH | Privacy | Legal