public inbox for pbs-devel@lists.proxmox.com
 help / color / mirror / Atom feed
From: Stefan Sterz <s.sterz@proxmox.com>
To: pbs-devel@lists.proxmox.com
Subject: [pbs-devel] [PATCH proxmox 03/12] auth-api: add ability to use hmac singing in keyring
Date: Thu, 15 Feb 2024 16:19:52 +0100	[thread overview]
Message-ID: <20240215152001.269490-4-s.sterz@proxmox.com> (raw)
In-Reply-To: <20240215152001.269490-1-s.sterz@proxmox.com>

previously we only used asymmetric cryptographic schemes to
authenticate tickets. this is fairly costly and not necessary in every
instance. imagine a service that runs as a single daemon. this daemon
is then the only party that needs to sign and verify tickets. this
makes hmac perfectly suitable for such usecases. hmac has some
advantages over asymmetric schemes:

- much simpler and well reviewed construction
- much faster and better optimized crypto primitives (hash functions)

this commit first introduces a new hmac key wrapper that uses openssl's
hmac implementation and can easily be reused by other parts of the
code. it also refactors the keyring code to make it easier to rotate
new hmac keys into place so switching to hmac keys is easier.

hmac keys are symmetric, so the verification key is the same key as the
signing key. this breaks the previous assumption by the keyring that
these correspond to public and private keys. thus, this commit
introduces two wrapper enums to distinguish between hmac and asymmetric
signature schemes.

the verification of hmac keys is also done via `openssl::memcmp::eq()`
to avoid potential timing side-channel attacks.

below are some simple benchmarks done with criterion.rs to show how much
faster hmac is, no matter the actual hash function:

rsa 4096 + sha256        time:   [2.7825 ms 2.7907 ms 2.7995 ms]
ed25519                  time:   [94.411 µs 94.840 µs 95.324 µs]
hmac sha256              time:   [5.7202 µs 5.7412 µs 5.7645 µs]
hmac sha384              time:   [6.6577 µs 6.6780 µs 6.7006 µs]
hmac sha3_256            time:   [5.6930 µs 5.7114 µs 5.7322 µs]

rsa with 4096 bit keys and a sha256 digest is our current default. the
test itself consists of a single sign + verification cycle. criterion
repeats this test as it sees fit to arrive at the above numbers.

Signed-off-by: Stefan Sterz <s.sterz@proxmox.com>
---
 proxmox-auth-api/src/auth_key.rs | 131 ++++++++++++++++++++++++++++---
 proxmox-auth-api/src/lib.rs      |   2 +-
 proxmox-auth-api/src/ticket.rs   |  17 ++++
 3 files changed, 136 insertions(+), 14 deletions(-)

diff --git a/proxmox-auth-api/src/auth_key.rs b/proxmox-auth-api/src/auth_key.rs
index f7a83bb..b0847a1 100644
--- a/proxmox-auth-api/src/auth_key.rs
+++ b/proxmox-auth-api/src/auth_key.rs
@@ -140,13 +140,90 @@ impl From<PKey<Public>> for PublicKey {
     }
 }
 
+#[derive(Clone)]
+pub struct HMACKey {
+    key: PKey<Private>,
+}
+
+impl HMACKey {
+    fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
+        Ok(Self {
+            key: PKey::hmac(bytes)
+                .map_err(|err| format_err!("failed to create hmac key from bytes - {err}"))?,
+        })
+    }
+
+    pub fn from_base64(string: &str) -> Result<Self, Error> {
+        let bytes = base64::decode_config(string, base64::STANDARD_NO_PAD)
+            .map_err(|e| format_err!("could not decode base64 hmac key - {e}"))?;
+
+        Self::from_bytes(&bytes)
+    }
+
+    pub fn generate() -> Result<Self, Error> {
+        // 8*64 = 512 bit security
+        let mut bytes = [0u8; 64];
+        openssl::rand::rand_bytes(&mut bytes)
+            .map_err(|err| format_err!("failed to generate random bytes for hmac key - {err}"))?;
+
+        Self::from_bytes(&bytes)
+    }
+
+    pub fn sign(&self, digest: MessageDigest, data: &[u8]) -> Result<Vec<u8>, Error> {
+        let mut signer = Signer::new(digest, &self.key)
+            .map_err(|e| format_err!("failed to create hmac signer - {e}"))?;
+
+        signer
+            .sign_oneshot_to_vec(data)
+            .map_err(|e| format_err!("failed to sign to vec using hmac - {e}"))
+    }
+
+    pub fn verify(
+        &self,
+        digest: MessageDigest,
+        signature: &[u8],
+        data: &[u8],
+    ) -> Result<bool, Error> {
+        let digest = self.sign(digest, data).map_err(|e| {
+            format_err!("failed to verify, could not create comparison signature - {e}")
+        })?;
+
+        if signature.len() == digest.len() && openssl::memcmp::eq(signature, &digest) {
+            return Ok(true);
+        }
+
+        Ok(false)
+    }
+
+    /// This outputs the hmac key *without* any encryption just encoded as base64.
+    pub fn to_base64(&self) -> Result<String, Error> {
+        let bytes = self
+            .key
+            .raw_private_key()
+            .map_err(|e| format_err!("could not get key as raw bytes - {e}"))?;
+
+        Ok(base64::encode_config(bytes, base64::STANDARD_NO_PAD))
+    }
+}
+
+enum SigningKey {
+    Private(PrivateKey),
+    Hmac(HMACKey),
+}
+
+enum VerificationKey {
+    Public(PublicKey),
+    Hmac(HMACKey),
+}
+
 /// A key ring for authentication.
 ///
-/// This holds one active signing key for new tickets, and optionally multiple public keys for
-/// verifying them in order to support key rollover.
+/// This can hold one active signing key for new tickets (either an HMAC secret or an assymmetric
+/// key), and optionally multiple public keys and HMAC secrets for verifying them in order to
+/// support key rollover.
 pub struct Keyring {
-    signing_key: Option<PrivateKey>,
-    public_keys: Vec<PublicKey>,
+    signing_key: Option<SigningKey>,
+    public_keys: Vec<VerificationKey>,
 }
 
 impl Keyring {
@@ -158,6 +235,10 @@ impl Keyring {
         PrivateKey::generate_ec().map(Self::with_private_key)
     }
 
+    pub fn generate_new_hmac() -> Result<Self, Error> {
+        HMACKey::generate().map(Self::with_hmac_key)
+    }
+
     pub fn new() -> Self {
         Self {
             signing_key: None,
@@ -168,19 +249,30 @@ impl Keyring {
     pub fn with_public_key(key: PublicKey) -> Self {
         Self {
             signing_key: None,
-            public_keys: vec![key],
+            public_keys: vec![VerificationKey::Public(key)],
         }
     }
 
     pub fn with_private_key(key: PrivateKey) -> Self {
         Self {
-            signing_key: Some(key),
+            signing_key: Some(SigningKey::Private(key)),
+            public_keys: Vec::new(),
+        }
+    }
+
+    pub fn with_hmac_key(key: HMACKey) -> Self {
+        Self {
+            signing_key: Some(SigningKey::Hmac(key)),
             public_keys: Vec::new(),
         }
     }
 
     pub fn add_public_key(&mut self, key: PublicKey) {
-        self.public_keys.push(key);
+        self.public_keys.push(VerificationKey::Public(key));
+    }
+
+    pub fn add_hmac_key(&mut self, key: HMACKey) {
+        self.public_keys.push(VerificationKey::Hmac(key));
     }
 
     pub fn verify(
@@ -209,14 +301,24 @@ impl Keyring {
         }
 
         if let Some(key) = &self.signing_key {
-            if verify_with(&key.key, digest, signature, data)? {
-                return Ok(true);
+            match key {
+                SigningKey::Private(key) if verify_with(&key.key, digest, signature, data)? => {
+                    return Ok(true)
+                }
+                SigningKey::Hmac(key) if key.verify(digest, signature, data)? => return Ok(true),
+                _ => (),
             }
         }
 
         for key in &self.public_keys {
-            if verify_with(&key.key, digest, signature, data)? {
-                return Ok(true);
+            match key {
+                VerificationKey::Public(key) if verify_with(&key.key, digest, signature, data)? => {
+                    return Ok(true)
+                }
+                VerificationKey::Hmac(key) if key.verify(digest, signature, data)? => {
+                    return Ok(true)
+                }
+                _ => (),
             }
         }
 
@@ -224,11 +326,14 @@ impl Keyring {
     }
 
     pub(crate) fn sign(&self, digest: MessageDigest, data: &[u8]) -> Result<Vec<u8>, Error> {
-        let key = self
+        let signing_key = self
             .signing_key
             .as_ref()
             .ok_or_else(|| format_err!("no private key available for signing"))?;
 
-        key.sign(digest, data)
+        match signing_key {
+            SigningKey::Private(key) => key.sign(digest, data),
+            SigningKey::Hmac(key) => key.sign(digest, data),
+        }
     }
 }
diff --git a/proxmox-auth-api/src/lib.rs b/proxmox-auth-api/src/lib.rs
index d371b96..332dffc 100644
--- a/proxmox-auth-api/src/lib.rs
+++ b/proxmox-auth-api/src/lib.rs
@@ -22,7 +22,7 @@ pub use api::set_auth_context;
 mod auth_key;
 
 #[cfg(any(feature = "api", feature = "ticket"))]
-pub use auth_key::{Keyring, PrivateKey, PublicKey};
+pub use auth_key::{Keyring, PrivateKey, PublicKey, HMACKey};
 
 #[cfg(feature = "ticket")]
 pub mod ticket;
diff --git a/proxmox-auth-api/src/ticket.rs b/proxmox-auth-api/src/ticket.rs
index c8fc667..ff08815 100644
--- a/proxmox-auth-api/src/ticket.rs
+++ b/proxmox-auth-api/src/ticket.rs
@@ -314,4 +314,21 @@ mod test {
             false
         });
     }
+
+    #[test]
+    fn test_tickets_hmac() {
+        let keyring =
+            Keyring::generate_new_hmac().expect("failed to generate HMAC key for testing");
+
+        simple_test(&keyring, Some("secret aad data"), |_| true);
+        simple_test(&keyring, None, |_| true);
+        simple_test(&keyring, None, |t| {
+            t.change_time(0);
+            false
+        });
+        simple_test(&keyring, None, |t| {
+            t.change_time(crate::time::epoch_i64() + 0x1000_0000);
+            false
+        });
+    }
 }
-- 
2.39.2





  parent reply	other threads:[~2024-02-15 15:20 UTC|newest]

Thread overview: 35+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2024-02-15 15:19 [pbs-devel] [PATCH proxmox{, -backup} 00/12] authentication cleanup and Stefan Sterz
2024-02-15 15:19 ` [pbs-devel] [PATCH proxmox 01/12] auth-api: move signing into the private key Stefan Sterz
2024-02-26 20:22   ` Esi Y
2024-02-27  9:12     ` Stefan Sterz
2024-02-27 18:13       ` Esi Y
2024-02-29 16:07         ` Stefan Sterz
2024-02-15 15:19 ` [pbs-devel] [PATCH proxmox 02/12] auth-api: move to Ed25519 signatures Stefan Sterz
2024-02-15 15:19 ` Stefan Sterz [this message]
2024-02-15 15:19 ` [pbs-devel] [PATCH proxmox 04/12] auth-api: move to hmac signing for csrf tokens Stefan Sterz
2024-02-19 16:02   ` Max Carrara
2024-02-20 12:54     ` Max Carrara
2024-02-23  9:26       ` Stefan Sterz
2024-02-23 10:48         ` Thomas Lamprecht
2024-02-23 10:52           ` Stefan Sterz
2024-02-23 13:06         ` Wolfgang Bumiller
2024-02-15 15:19 ` [pbs-devel] [PATCH proxmox 05/12] sys: crypt: move to yescrypt for password hashing Stefan Sterz
2024-02-15 15:19 ` [pbs-devel] [PATCH proxmox 06/12] sys: crypt: use constant time comparison for password verification Stefan Sterz
2024-02-19 16:11   ` Max Carrara
2024-02-23  9:26     ` Stefan Sterz
2024-02-15 15:19 ` [pbs-devel] [PATCH proxmox 07/12] sys: crypt: add helper to allow upgrading hashes Stefan Sterz
2024-02-19 18:50   ` Max Carrara
2024-02-23  9:26     ` Stefan Sterz
2024-02-15 15:19 ` [pbs-devel] [PATCH proxmox 08/12] auth-api: fix types `compilefail` test Stefan Sterz
2024-02-15 15:19 ` [pbs-devel] [PATCH proxmox-backup 09/12] auth: move to hmac keys for csrf tokens Stefan Sterz
2024-02-19 18:55   ` Max Carrara
2024-02-23  9:26     ` Stefan Sterz
2024-02-15 15:19 ` [pbs-devel] [PATCH proxmox-backup 10/12] auth: upgrade hashes on user log in Stefan Sterz
2024-02-19 18:58   ` Max Carrara
2024-02-23  9:26     ` Stefan Sterz
2024-02-15 15:20 ` [pbs-devel] [PATCH proxmox-backup 11/12] auth/manager: add manager command to upgrade hashes Stefan Sterz
2024-02-19 19:06   ` Max Carrara
2024-02-23  9:26     ` Stefan Sterz
2024-02-15 15:20 ` [pbs-devel] [PATCH proxmox-backup 12/12] auth: us ec keys as auth keys Stefan Sterz
2024-02-19 19:10   ` Max Carrara
2024-02-23  9:26     ` Stefan Sterz

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=20240215152001.269490-4-s.sterz@proxmox.com \
    --to=s.sterz@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