bitwarden_crypto/enc_string/
asymmetric.rs

1use std::{fmt::Display, str::FromStr};
2
3use base64::{engine::general_purpose::STANDARD, Engine};
4pub use internal::UnsignedSharedKey;
5use rsa::Oaep;
6use serde::Deserialize;
7
8use super::{from_b64_vec, split_enc_string};
9use crate::{
10    error::{CryptoError, EncStringParseError, Result},
11    rsa::encrypt_rsa2048_oaep_sha1,
12    util::FromStrVisitor,
13    AsymmetricCryptoKey, AsymmetricPublicCryptoKey, RawPrivateKey, RawPublicKey,
14    SymmetricCryptoKey,
15};
16// This module is a workaround to avoid deprecated warnings that come from the ZeroizeOnDrop
17// macro expansion
18#[allow(deprecated)]
19mod internal {
20    #[cfg(feature = "wasm")]
21    #[wasm_bindgen::prelude::wasm_bindgen(typescript_custom_section)]
22    const TS_CUSTOM_TYPES: &'static str = r#"
23    export type UnsignedSharedKey = string;
24    "#;
25
26    /// # Encrypted string primitive
27    ///
28    /// [UnsignedSharedKey] is a Bitwarden specific primitive that represents an
29    /// asymmetrically encrypted symmetric key. Since the symmetric key is directly encrypted
30    /// with the public key, without any further signature, the receiver cannot guarantee the
31    /// senders identity.
32    ///
33    /// [UnsignedSharedKey] type allows for different encryption algorithms
34    /// to be used which is represented by the different variants of the enum.
35    ///
36    /// ## Note
37    ///
38    /// For backwards compatibility we will rarely if ever be able to remove support for decrypting
39    /// old variants, but we should be opinionated in which variants are used for encrypting.
40    ///
41    /// ## Variants
42    /// - [Rsa2048_OaepSha256_B64](UnsignedSharedKey::Rsa2048_OaepSha256_B64)
43    /// - [Rsa2048_OaepSha1_B64](UnsignedSharedKey::Rsa2048_OaepSha1_B64)
44    ///
45    /// ## Serialization
46    ///
47    /// [UnsignedSharedKey] implements [std::fmt::Display] and [std::str::FromStr] to allow
48    /// for easy serialization and uses a custom scheme to represent the different variants.
49    ///
50    /// The scheme is one of the following schemes:
51    /// - `[type].[data]`
52    ///
53    /// Where:
54    /// - `[type]`: is a digit number representing the variant.
55    /// - `[data]`: is the encrypted data.
56    #[allow(missing_docs)]
57    #[derive(Clone, zeroize::ZeroizeOnDrop)]
58    #[allow(unused, non_camel_case_types)]
59    pub enum UnsignedSharedKey {
60        /// 3
61        Rsa2048_OaepSha256_B64 { data: Vec<u8> },
62        /// 4
63        Rsa2048_OaepSha1_B64 { data: Vec<u8> },
64        /// 5
65        #[deprecated]
66        Rsa2048_OaepSha256_HmacSha256_B64 { data: Vec<u8>, mac: Vec<u8> },
67        /// 6
68        #[deprecated]
69        Rsa2048_OaepSha1_HmacSha256_B64 { data: Vec<u8>, mac: Vec<u8> },
70    }
71}
72
73/// To avoid printing sensitive information, [UnsignedSharedKey] debug prints to
74/// `UnsignedSharedKey`.
75impl std::fmt::Debug for UnsignedSharedKey {
76    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77        f.debug_struct("UnsignedSharedKey").finish()
78    }
79}
80
81/// Deserializes an [UnsignedSharedKey] from a string.
82impl FromStr for UnsignedSharedKey {
83    type Err = CryptoError;
84
85    fn from_str(s: &str) -> Result<Self, Self::Err> {
86        let (enc_type, parts) = split_enc_string(s);
87        match (enc_type, parts.len()) {
88            ("3", 1) => {
89                let data = from_b64_vec(parts[0])?;
90                Ok(UnsignedSharedKey::Rsa2048_OaepSha256_B64 { data })
91            }
92            ("4", 1) => {
93                let data = from_b64_vec(parts[0])?;
94                Ok(UnsignedSharedKey::Rsa2048_OaepSha1_B64 { data })
95            }
96            #[allow(deprecated)]
97            ("5", 2) => {
98                let data = from_b64_vec(parts[0])?;
99                let mac: Vec<u8> = from_b64_vec(parts[1])?;
100                Ok(UnsignedSharedKey::Rsa2048_OaepSha256_HmacSha256_B64 { data, mac })
101            }
102            #[allow(deprecated)]
103            ("6", 2) => {
104                let data = from_b64_vec(parts[0])?;
105                let mac: Vec<u8> = from_b64_vec(parts[1])?;
106                Ok(UnsignedSharedKey::Rsa2048_OaepSha1_HmacSha256_B64 { data, mac })
107            }
108
109            (enc_type, parts) => Err(EncStringParseError::InvalidTypeAsymm {
110                enc_type: enc_type.to_string(),
111                parts,
112            }
113            .into()),
114        }
115    }
116}
117
118impl Display for UnsignedSharedKey {
119    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
120        let parts: Vec<&[u8]> = match self {
121            UnsignedSharedKey::Rsa2048_OaepSha256_B64 { data } => vec![data],
122            UnsignedSharedKey::Rsa2048_OaepSha1_B64 { data } => vec![data],
123            #[allow(deprecated)]
124            UnsignedSharedKey::Rsa2048_OaepSha256_HmacSha256_B64 { data, mac } => {
125                vec![data, mac]
126            }
127            #[allow(deprecated)]
128            UnsignedSharedKey::Rsa2048_OaepSha1_HmacSha256_B64 { data, mac } => {
129                vec![data, mac]
130            }
131        };
132
133        let encoded_parts: Vec<String> = parts.iter().map(|part| STANDARD.encode(part)).collect();
134
135        write!(f, "{}.{}", self.enc_type(), encoded_parts.join("|"))?;
136
137        Ok(())
138    }
139}
140
141impl<'de> Deserialize<'de> for UnsignedSharedKey {
142    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
143    where
144        D: serde::Deserializer<'de>,
145    {
146        deserializer.deserialize_str(FromStrVisitor::new())
147    }
148}
149
150impl serde::Serialize for UnsignedSharedKey {
151    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
152    where
153        S: serde::Serializer,
154    {
155        serializer.serialize_str(&self.to_string())
156    }
157}
158
159impl UnsignedSharedKey {
160    /// Encapsulate a symmetric key, to be shared asymmetrically. Produces a
161    /// [UnsignedSharedKey::Rsa2048_OaepSha1_B64] variant. Note, this does not sign the data
162    /// and thus does not guarantee sender authenticity.
163    pub fn encapsulate_key_unsigned(
164        encapsulated_key: &SymmetricCryptoKey,
165        encapsulation_key: &AsymmetricPublicCryptoKey,
166    ) -> Result<UnsignedSharedKey> {
167        match encapsulation_key.inner() {
168            RawPublicKey::RsaOaepSha1(rsa_public_key) => {
169                Ok(UnsignedSharedKey::Rsa2048_OaepSha1_B64 {
170                    data: encrypt_rsa2048_oaep_sha1(
171                        rsa_public_key,
172                        &encapsulated_key.to_encoded(),
173                    )?,
174                })
175            }
176        }
177    }
178
179    /// The numerical representation of the encryption type of the [UnsignedSharedKey].
180    const fn enc_type(&self) -> u8 {
181        match self {
182            UnsignedSharedKey::Rsa2048_OaepSha256_B64 { .. } => 3,
183            UnsignedSharedKey::Rsa2048_OaepSha1_B64 { .. } => 4,
184            #[allow(deprecated)]
185            UnsignedSharedKey::Rsa2048_OaepSha256_HmacSha256_B64 { .. } => 5,
186            #[allow(deprecated)]
187            UnsignedSharedKey::Rsa2048_OaepSha1_HmacSha256_B64 { .. } => 6,
188        }
189    }
190}
191
192impl UnsignedSharedKey {
193    /// Decapsulate a symmetric key, shared asymmetrically.
194    /// Note: The shared key does not have a sender signature and sender authenticity is not
195    /// guaranteed.
196    pub fn decapsulate_key_unsigned(
197        &self,
198        decapsulation_key: &AsymmetricCryptoKey,
199    ) -> Result<SymmetricCryptoKey> {
200        match decapsulation_key.inner() {
201            RawPrivateKey::RsaOaepSha1(rsa_private_key) => {
202                use UnsignedSharedKey::*;
203                let mut key_data = match self {
204                    Rsa2048_OaepSha256_B64 { data } => {
205                        rsa_private_key.decrypt(Oaep::new::<sha2::Sha256>(), data)
206                    }
207                    Rsa2048_OaepSha1_B64 { data } => {
208                        rsa_private_key.decrypt(Oaep::new::<sha1::Sha1>(), data)
209                    }
210                    #[allow(deprecated)]
211                    Rsa2048_OaepSha256_HmacSha256_B64 { data, .. } => {
212                        rsa_private_key.decrypt(Oaep::new::<sha2::Sha256>(), data)
213                    }
214                    #[allow(deprecated)]
215                    Rsa2048_OaepSha1_HmacSha256_B64 { data, .. } => {
216                        rsa_private_key.decrypt(Oaep::new::<sha1::Sha1>(), data)
217                    }
218                }
219                .map_err(|_| CryptoError::KeyDecrypt)?;
220                SymmetricCryptoKey::try_from(key_data.as_mut_slice())
221            }
222        }
223    }
224}
225
226/// Usually we wouldn't want to expose UnsignedSharedKeys in the API or the schemas.
227/// But during the transition phase we will expose endpoints using the UnsignedSharedKey
228/// type.
229impl schemars::JsonSchema for UnsignedSharedKey {
230    fn schema_name() -> String {
231        "UnsignedSharedKey".to_string()
232    }
233
234    fn json_schema(generator: &mut schemars::r#gen::SchemaGenerator) -> schemars::schema::Schema {
235        generator.subschema_for::<String>()
236    }
237}
238
239#[cfg(test)]
240mod tests {
241    use schemars::schema_for;
242
243    use super::UnsignedSharedKey;
244    use crate::{AsymmetricCryptoKey, SymmetricCryptoKey};
245
246    const RSA_PRIVATE_KEY: &str = "-----BEGIN PRIVATE KEY-----
247MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCXRVrCX+2hfOQS
2488HzYUS2oc/jGVTZpv+/Ryuoh9d8ihYX9dd0cYh2tl6KWdFc88lPUH11Oxqy20Rk2
249e5r/RF6T9yM0Me3NPnaKt+hlhLtfoc0h86LnhD56A9FDUfuI0dVnPcrwNv0YJIo9
2504LwxtbqBULNvXl6wJ7WAbODrCQy5ZgMVg+iH+gGpwiqsZqHt+KuoHWcN53MSPDfa
251F4/YMB99U3TziJMOOJask1TEEnakMPln11PczNDazT17DXIxYrbPfutPdh6sLs6A
252QOajdZijfEvepgnOe7cQ7aeatiOJFrjTApKPGxOVRzEMX4XS4xbyhH0QxQeB6l16
253l8C0uxIBAgMBAAECggEASaWfeVDA3cVzOPFSpvJm20OTE+R6uGOU+7vh36TX/POq
25492qBuwbd0h0oMD32FxsXywd2IxtBDUSiFM9699qufTVuM0Q3tZw6lHDTOVG08+tP
255dr8qSbMtw7PGFxN79fHLBxejjO4IrM9lapjWpxEF+11x7r+wM+0xRZQ8sNFYG46a
256PfIaty4BGbL0I2DQ2y8I57iBCAy69eht59NLMm27fRWGJIWCuBIjlpfzET1j2HLX
257UIh5bTBNzqaN039WH49HczGE3mQKVEJZc/efk3HaVd0a1Sjzyn0QY+N1jtZN3jTR
258buDWA1AknkX1LX/0tUhuS3/7C3ejHxjw4Dk1ZLo5/QKBgQDIWvqFn0+IKRSu6Ua2
259hDsufIHHUNLelbfLUMmFthxabcUn4zlvIscJO00Tq/ezopSRRvbGiqnxjv/mYxuc
260vOUBeZtlus0Q9RTACBtw9TGoNTmQbEunJ2FOSlqbQxkBBAjgGEppRPt30iGj/VjA
261hCATq2MYOa/X4dVR51BqQAFIEwKBgQDBSIfTFKC/hDk6FKZlgwvupWYJyU9Rkyfs
262tPErZFmzoKhPkQ3YORo2oeAYmVUbS9I2iIYpYpYQJHX8jMuCbCz4ONxTCuSIXYQY
263UcUq4PglCKp31xBAE6TN8SvhfME9/MvuDssnQinAHuF0GDAhF646T3LLS1not6Vs
264zv7brwSoGwKBgQC88v/8cGfi80ssQZeMnVvq1UTXIeQcQnoY5lGHJl3K8mbS3TnX
265E6c9j417Fdz+rj8KWzBzwWXQB5pSPflWcdZO886Xu/mVGmy9RWgLuVFhXwCwsVEP
266jNX5ramRb0/vY0yzenUCninBsIxFSbIfrPtLUYCc4hpxr+sr2Mg/y6jpvQKBgBez
267MRRs3xkcuXepuI2R+BCXL1/b02IJTUf1F+1eLLGd7YV0H+J3fgNc7gGWK51hOrF9
268JBZHBGeOUPlaukmPwiPdtQZpu4QNE3l37VlIpKTF30E6mb+BqR+nht3rUjarnMXg
269AoEZ18y6/KIjpSMpqC92Nnk/EBM9EYe6Cf4eA9ApAoGAeqEUg46UTlJySkBKURGp
270Is3v1kkf5I0X8DnOhwb+HPxNaiEdmO7ckm8+tPVgppLcG0+tMdLjigFQiDUQk2y3
271WjyxP5ZvXu7U96jaJRI8PFMoE06WeVYcdIzrID2HvqH+w0UQJFrLJ/0Mn4stFAEz
272XKZBokBGnjFnTnKcs7nv/O8=
273-----END PRIVATE KEY-----";
274
275    #[test]
276    fn test_enc_string_rsa2048_oaep_sha256_b64() {
277        let key_pair = AsymmetricCryptoKey::from_pem(RSA_PRIVATE_KEY).unwrap();
278        let enc_str: &str = "3.SUx5gWrgmAKs/S1BoQrqOmx2Hl5fPVBVHokW17Flvm4TpBnJJRkfoitp7Jc4dfazPYjWGlckJz6X+qe+/AWilS1mxtzS0PmDy7tS5xP0GRlB39dstCd5jDw1wPmTbXiLcQ5VTvzpRAfRMEYVveTsEvVTByvEYAGSn4TnCsUDykyhRbD0YcJ4r1KHLs1b3BCBy2M1Gl5nmwckH08CAXaf8VfuBFStAGRKueovqp4euneQla+4G4fXdVvb8qKPnu0iVuALIE6nUNmeOiA3xN3d+akMxbbGxrQ1Ca4TYWjHVdj9C6abngQHkjKNYQwGUXrYo160hP4LIHn/huK6bZe5dQ==";
279        let enc_string: UnsignedSharedKey = enc_str.parse().unwrap();
280
281        let test_key = SymmetricCryptoKey::generate_seeded_for_unit_tests("test");
282        assert_eq!(enc_string.enc_type(), 3);
283
284        let res = enc_string.decapsulate_key_unsigned(&key_pair).unwrap();
285        assert_eq!(res, test_key);
286    }
287
288    #[test]
289    fn test_enc_string_rsa2048_oaep_sha1_b64() {
290        let private_key = AsymmetricCryptoKey::from_pem(RSA_PRIVATE_KEY).unwrap();
291        let enc_str: &str = "4.DMD1D5r6BsDDd7C/FE1eZbMCKrmryvAsCKj6+bO54gJNUxisOI7SDcpPLRXf+JdhqY15pT+wimQ5cD9C+6OQ6s71LFQHewXPU29l9Pa1JxGeiKqp37KLYf+1IS6UB2K3ANN35C52ZUHh2TlzIS5RuntxnpCw7APbcfpcnmIdLPJBtuj/xbFd6eBwnI3GSe5qdS6/Ixdd0dgsZcpz3gHJBKmIlSo0YN60SweDq3kTJwox9xSqdCueIDg5U4khc7RhjYx8b33HXaNJj3DwgIH8iLj+lqpDekogr630OhHG3XRpvl4QzYO45bmHb8wAh67Dj70nsZcVg6bAEFHdSFohww==";
292        let enc_string: UnsignedSharedKey = enc_str.parse().unwrap();
293
294        let test_key = SymmetricCryptoKey::generate_seeded_for_unit_tests("test");
295        assert_eq!(enc_string.enc_type(), 4);
296
297        let res = enc_string.decapsulate_key_unsigned(&private_key).unwrap();
298        assert_eq!(res, test_key);
299    }
300
301    #[test]
302    fn test_enc_string_rsa2048_oaep_sha1_hmac_sha256_b64() {
303        let private_key = AsymmetricCryptoKey::from_pem(RSA_PRIVATE_KEY).unwrap();
304        let enc_str: &str = "6.DMD1D5r6BsDDd7C/FE1eZbMCKrmryvAsCKj6+bO54gJNUxisOI7SDcpPLRXf+JdhqY15pT+wimQ5cD9C+6OQ6s71LFQHewXPU29l9Pa1JxGeiKqp37KLYf+1IS6UB2K3ANN35C52ZUHh2TlzIS5RuntxnpCw7APbcfpcnmIdLPJBtuj/xbFd6eBwnI3GSe5qdS6/Ixdd0dgsZcpz3gHJBKmIlSo0YN60SweDq3kTJwox9xSqdCueIDg5U4khc7RhjYx8b33HXaNJj3DwgIH8iLj+lqpDekogr630OhHG3XRpvl4QzYO45bmHb8wAh67Dj70nsZcVg6bAEFHdSFohww==|AA==";
305        let enc_string: UnsignedSharedKey = enc_str.parse().unwrap();
306
307        let test_key: SymmetricCryptoKey =
308            SymmetricCryptoKey::generate_seeded_for_unit_tests("test");
309        assert_eq!(enc_string.enc_type(), 6);
310
311        let res = enc_string.decapsulate_key_unsigned(&private_key).unwrap();
312        assert_eq!(res.to_base64(), test_key.to_base64());
313    }
314
315    #[test]
316    fn test_enc_string_serialization() {
317        #[derive(serde::Serialize, serde::Deserialize)]
318        struct Test {
319            key: UnsignedSharedKey,
320        }
321
322        let cipher = "6.ThnNc67nNr7GELyuhGGfsXNP2zJnNqhrIsjntEQ27r2qmn8vwdHbTbfO0cwt6YgSibDN0PjiCZ1O3Wb/IFq+vwvyRwFqF9145wBF8CQCbkhV+M0XvO99kh0daovtt120Nve/5ETI5PbPag9VdalKRQWZypJaqQHm5TAQVf4F5wtLlCLMBkzqTk+wkFe7BPMTGn07T+O3eJbTxXvyMZewQ7icJF0MZVA7VyWX9qElmZ89FCKowbf1BMr5pbcQ+0KdXcSVW3to43VkTp7k7COwsuH3M/i1AuVP5YN8ixjyRpvaeGqX/ap2nCHK2Wj5VxgCGT7XEls6ZknnAp9nB9qVjQ==|s3ntw5H/KKD/qsS0lUghTHl5Sm9j6m7YEdNHf0OeAFQ=";
323        let serialized = format!("{{\"key\":\"{cipher}\"}}");
324
325        let t = serde_json::from_str::<Test>(&serialized).unwrap();
326        assert_eq!(t.key.enc_type(), 6);
327        assert_eq!(t.key.to_string(), cipher);
328        assert_eq!(serde_json::to_string(&t).unwrap(), serialized);
329    }
330
331    #[test]
332    fn test_from_str_invalid() {
333        let enc_str = "7.ABC";
334        let enc_string: Result<UnsignedSharedKey, _> = enc_str.parse();
335
336        let err = enc_string.unwrap_err();
337        assert_eq!(
338            err.to_string(),
339            "EncString error, Invalid asymmetric type, got type 7 with 1 parts"
340        );
341    }
342
343    #[test]
344    fn test_debug_format() {
345        let enc_str: &str = "4.ZheRb3PCfAunyFdQYPfyrFqpuvmln9H9w5nDjt88i5A7ug1XE0LJdQHCIYJl0YOZ1gCOGkhFu/CRY2StiLmT3iRKrrVBbC1+qRMjNNyDvRcFi91LWsmRXhONVSPjywzrJJXglsztDqGkLO93dKXNhuKpcmtBLsvgkphk/aFvxbaOvJ/FHdK/iV0dMGNhc/9tbys8laTdwBlI5xIChpRcrfH+XpSFM88+Bu03uK67N9G6eU1UmET+pISJwJvMuIDMqH+qkT7OOzgL3t6I0H2LDj+CnsumnQmDsvQzDiNfTR0IgjpoE9YH2LvPXVP2wVUkiTwXD9cG/E7XeoiduHyHjw==";
346        let enc_string: UnsignedSharedKey = enc_str.parse().unwrap();
347
348        let debug_string = format!("{:?}", enc_string);
349        assert_eq!(debug_string, "UnsignedSharedKey");
350    }
351
352    #[test]
353    fn test_json_schema() {
354        let schema = schema_for!(UnsignedSharedKey);
355
356        assert_eq!(
357            serde_json::to_string(&schema).unwrap(),
358            r#"{"$schema":"http://json-schema.org/draft-07/schema#","title":"UnsignedSharedKey","type":"string"}"#
359        );
360    }
361}