public inbox for pbs-devel@lists.proxmox.com
 help / color / mirror / Atom feed
From: Max Carrara <m.carrara@proxmox.com>
To: pbs-devel@lists.proxmox.com
Subject: Re: [pbs-devel] [PATCH proxmox v2 03/12] auth-api: add ability to use hmac singing in keyring
Date: Thu, 7 Mar 2024 11:11:21 +0100	[thread overview]
Message-ID: <a48c1342-37b2-4c49-a896-9b4d2f7a9b56@proxmox.com> (raw)
In-Reply-To: <20240306123609.164021-4-s.sterz@proxmox.com>

On 3/6/24 13:36, Stefan Sterz wrote:
> 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};

Should be:
pub use auth_key::{HMACKey, Keyring, PrivateKey, PublicKey};

IMHO super minor thing, can be done when applying the series.

>  
>  #[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
> +        });
> +    }
>  }





  reply	other threads:[~2024-03-07 10:11 UTC|newest]

Thread overview: 18+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2024-03-06 12:35 [pbs-devel] [PATCH proxmox{, -backup} v2 00/12] auth-api clean up and improvements Stefan Sterz
2024-03-06 12:35 ` [pbs-devel] [PATCH proxmox v2 01/12] auth-api: move signing into the private key Stefan Sterz
2024-03-06 12:35 ` [pbs-devel] [PATCH proxmox v2 02/12] auth-api: move to Ed25519 signatures Stefan Sterz
2024-03-06 12:36 ` [pbs-devel] [PATCH proxmox v2 03/12] auth-api: add ability to use hmac singing in keyring Stefan Sterz
2024-03-07 10:11   ` Max Carrara [this message]
2024-03-06 12:36 ` [pbs-devel] [PATCH proxmox v2 04/12] auth-api: use constant time comparison for csrf tokens Stefan Sterz
2024-03-07 10:17   ` Max Carrara
2024-03-06 12:36 ` [pbs-devel] [PATCH proxmox v2 05/12] auth-api: move to hmac signing " Stefan Sterz
2024-03-06 12:36 ` [pbs-devel] [PATCH proxmox v2 06/12] sys: crypt: move to yescrypt for password hashing Stefan Sterz
2024-03-06 12:36 ` [pbs-devel] [PATCH proxmox v2 07/12] sys: crypt: use constant time comparison for password verification Stefan Sterz
2024-03-06 12:36 ` [pbs-devel] [PATCH proxmox v2 08/12] auth-api: fix types `compilefail` test Stefan Sterz
2024-03-06 12:36 ` [pbs-devel] [PATCH proxmox-backup v2 09/12] auth: move to hmac keys for csrf tokens Stefan Sterz
2024-03-06 12:36 ` [pbs-devel] [PATCH proxmox-backup v2 10/12] auth: upgrade hashes on user log in Stefan Sterz
2024-03-06 12:36 ` [pbs-devel] [PATCH proxmox-backup v2 11/12] auth: move to auth-api's private and public keys when loading keys Stefan Sterz
2024-03-06 12:36 ` [pbs-devel] [PATCH proxmox-backup v2 12/12] auth: use auth-api when generating keys and generate ec keys Stefan Sterz
2024-03-07 10:12 ` [pbs-devel] [PATCH proxmox{, -backup} v2 00/12] auth-api clean up and improvements Max Carrara
2024-05-22 14:13 ` [pbs-devel] applied-series: " Wolfgang Bumiller
2024-05-24  8:45   ` Max Carrara

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=a48c1342-37b2-4c49-a896-9b4d2f7a9b56@proxmox.com \
    --to=m.carrara@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