auth.rs

  1use anyhow::{Context as _, Result};
  2use base64::prelude::*;
  3use rand::{Rng as _, thread_rng};
  4use rsa::pkcs1::{DecodeRsaPublicKey, EncodeRsaPublicKey};
  5use rsa::traits::PaddingScheme;
  6use rsa::{Oaep, Pkcs1v15Encrypt, RsaPrivateKey, RsaPublicKey};
  7use sha2::Sha256;
  8use std::convert::TryFrom;
  9
 10fn oaep_sha256_padding() -> impl PaddingScheme {
 11    Oaep::new::<Sha256>()
 12}
 13
 14#[derive(Debug, PartialEq, Eq, Clone, Copy)]
 15pub enum EncryptionFormat {
 16    /// The original encryption format.
 17    ///
 18    /// This is using [`Pkcs1v15Encrypt`], which is vulnerable to side-channel attacks.
 19    /// As such, we're in the process of phasing it out.
 20    ///
 21    /// See [here](https://people.redhat.com/~hkario/marvin/) for more details.
 22    V0,
 23
 24    /// The new encryption key format using Optimal Asymmetric Encryption Padding (OAEP) with a SHA-256 digest.
 25    V1,
 26}
 27
 28pub struct PublicKey(RsaPublicKey);
 29
 30pub struct PrivateKey(RsaPrivateKey);
 31
 32/// Generate a public and private key for asymmetric encryption.
 33pub fn keypair() -> Result<(PublicKey, PrivateKey)> {
 34    let mut rng = thread_rng();
 35    let bits = 2048;
 36    let private_key = RsaPrivateKey::new(&mut rng, bits)?;
 37    let public_key = RsaPublicKey::from(&private_key);
 38    Ok((PublicKey(public_key), PrivateKey(private_key)))
 39}
 40
 41/// Generate a random 64-character base64 string.
 42pub fn random_token() -> String {
 43    let mut rng = thread_rng();
 44    let mut token_bytes = [0; 48];
 45    for byte in token_bytes.iter_mut() {
 46        *byte = rng.r#gen();
 47    }
 48    BASE64_URL_SAFE.encode(token_bytes)
 49}
 50
 51impl PublicKey {
 52    /// Convert a string to a base64-encoded string that can only be decoded with the corresponding
 53    /// private key.
 54    pub fn encrypt_string(&self, string: &str, format: EncryptionFormat) -> Result<String> {
 55        let mut rng = thread_rng();
 56        let bytes = string.as_bytes();
 57        let encrypted_bytes = match format {
 58            EncryptionFormat::V0 => self.0.encrypt(&mut rng, Pkcs1v15Encrypt, bytes),
 59            EncryptionFormat::V1 => self.0.encrypt(&mut rng, oaep_sha256_padding(), bytes),
 60        }
 61        .context("failed to encrypt string with public key")?;
 62        let encrypted_string = BASE64_URL_SAFE.encode(&encrypted_bytes);
 63        Ok(encrypted_string)
 64    }
 65}
 66
 67impl PrivateKey {
 68    /// Decrypt a base64-encoded string that was encrypted by the corresponding public key.
 69    pub fn decrypt_string(&self, encrypted_string: &str) -> Result<String> {
 70        let encrypted_bytes = BASE64_URL_SAFE
 71            .decode(encrypted_string)
 72            .context("failed to base64-decode encrypted string")?;
 73        let bytes = self
 74            .0
 75            .decrypt(oaep_sha256_padding(), &encrypted_bytes)
 76            .or_else(|_err| {
 77                // If we failed to decrypt using the new format, try decrypting with the old
 78                // one to handle mismatches between the client and server.
 79                self.0.decrypt(Pkcs1v15Encrypt, &encrypted_bytes)
 80            })
 81            .context("failed to decrypt string with private key")?;
 82        let string = String::from_utf8(bytes).context("decrypted content was not valid utf8")?;
 83        Ok(string)
 84    }
 85}
 86
 87impl TryFrom<PublicKey> for String {
 88    type Error = anyhow::Error;
 89    fn try_from(key: PublicKey) -> Result<Self> {
 90        let bytes = key
 91            .0
 92            .to_pkcs1_der()
 93            .context("failed to serialize public key")?;
 94        let string = BASE64_URL_SAFE.encode(&bytes);
 95        Ok(string)
 96    }
 97}
 98
 99impl TryFrom<String> for PublicKey {
100    type Error = anyhow::Error;
101    fn try_from(value: String) -> Result<Self> {
102        let bytes = BASE64_URL_SAFE
103            .decode(&value)
104            .context("failed to base64-decode public key string")?;
105        let key = Self(RsaPublicKey::from_pkcs1_der(&bytes).context("failed to parse public key")?);
106        Ok(key)
107    }
108}
109
110#[cfg(test)]
111mod tests {
112    use super::*;
113
114    #[test]
115    fn test_generate_encrypt_and_decrypt_token() {
116        // CLIENT:
117        // * generate a keypair for asymmetric encryption
118        // * serialize the public key to send it to the server.
119        let (public, private) = keypair().unwrap();
120        let public_string = String::try_from(public).unwrap();
121        assert_printable(&public_string);
122
123        // SERVER:
124        // * parse the public key
125        // * generate a random token.
126        // * encrypt the token using the public key.
127        let public = PublicKey::try_from(public_string).unwrap();
128        let token = random_token();
129        let encrypted_token = public.encrypt_string(&token, EncryptionFormat::V1).unwrap();
130        assert_eq!(token.len(), 64);
131        assert_ne!(encrypted_token, token);
132        assert_printable(&token);
133        assert_printable(&encrypted_token);
134
135        // CLIENT:
136        // * decrypt the token using the private key.
137        let decrypted_token = private.decrypt_string(&encrypted_token).unwrap();
138        assert_eq!(decrypted_token, token);
139    }
140
141    #[test]
142    fn test_generate_encrypt_and_decrypt_token_with_v0_encryption_format() {
143        // CLIENT:
144        // * generate a keypair for asymmetric encryption
145        // * serialize the public key to send it to the server.
146        let (public, private) = keypair().unwrap();
147        let public_string = String::try_from(public).unwrap();
148        assert_printable(&public_string);
149
150        // SERVER:
151        // * parse the public key
152        // * generate a random token.
153        // * encrypt the token using the public key.
154        let public = PublicKey::try_from(public_string).unwrap();
155        let token = random_token();
156        let encrypted_token = public.encrypt_string(&token, EncryptionFormat::V0).unwrap();
157        assert_eq!(token.len(), 64);
158        assert_ne!(encrypted_token, token);
159        assert_printable(&token);
160        assert_printable(&encrypted_token);
161
162        // CLIENT:
163        // * decrypt the token using the private key.
164        let decrypted_token = private.decrypt_string(&encrypted_token).unwrap();
165        assert_eq!(decrypted_token, token);
166    }
167
168    #[test]
169    fn test_encode_and_decode_base64_public_key() {
170        // A base64-encoded public key.
171        //
172        // We're using a literal string to ensure that encoding and decoding works across differences in implementations.
173        let encoded_public_key = "MIGJAoGBAMPvufou8wOuUIF1Wlkbtn0ZMM9nC55QJ06nTZvgMfZv5esFVU9-cQO_JC1P9ZoEcMDJweFERnQuQLqzsrMDLFbkdgL128ZU43WOLiQraxaICFIZsPUeTtWMKp2D5bPWsNxs-lnCma7vCAry6fpXuj5AKQdk7cTZJNucgvZQ0uUfAgMBAAE=".to_string();
174
175        // Make sure we can parse the public key.
176        let public_key = PublicKey::try_from(encoded_public_key.clone()).unwrap();
177
178        // Make sure we re-encode to the same format.
179        assert_eq!(encoded_public_key, String::try_from(public_key).unwrap());
180    }
181
182    #[test]
183    fn test_tokens_are_always_url_safe() {
184        for _ in 0..5 {
185            let token = random_token();
186            let (public_key, _) = keypair().unwrap();
187            let encrypted_token = public_key
188                .encrypt_string(&token, EncryptionFormat::V1)
189                .unwrap();
190            let public_key_str = String::try_from(public_key).unwrap();
191
192            assert_printable(&token);
193            assert_printable(&public_key_str);
194            assert_printable(&encrypted_token);
195        }
196    }
197
198    fn assert_printable(token: &str) {
199        for c in token.chars() {
200            assert!(
201                c.is_ascii_graphic(),
202                "token {:?} has non-printable char {}",
203                token,
204                c
205            );
206            assert_ne!(c, '/', "token {:?} is not URL-safe", token);
207            assert_ne!(c, '&', "token {:?} is not URL-safe", token);
208        }
209    }
210}