bitwarden_core/auth/
tde.rs

1use bitwarden_crypto::{
2    AsymmetricPublicCryptoKey, DeviceKey, EncString, Kdf, SpkiPublicKeyBytes, SymmetricCryptoKey,
3    TrustDeviceResponse, UnsignedSharedKey, UserKey,
4};
5use bitwarden_encoding::B64;
6
7use crate::{
8    client::{encryption_settings::EncryptionSettingsError, internal::UserKeyState},
9    Client,
10};
11
12/// This function generates a new user key and key pair, initializes the client's crypto with the
13/// generated user key, and encrypts the user key with the organization public key for admin
14/// password reset. If remember_device is true, it also generates a device key.
15pub(super) fn make_register_tde_keys(
16    client: &Client,
17    email: String,
18    org_public_key: B64,
19    remember_device: bool,
20) -> Result<RegisterTdeKeyResponse, EncryptionSettingsError> {
21    let public_key =
22        AsymmetricPublicCryptoKey::from_der(&SpkiPublicKeyBytes::from(&org_public_key))?;
23
24    let user_key = UserKey::new(SymmetricCryptoKey::make_aes256_cbc_hmac_key());
25    let key_pair = user_key.make_key_pair()?;
26
27    let admin_reset = UnsignedSharedKey::encapsulate_key_unsigned(&user_key.0, &public_key)?;
28
29    let device_key = if remember_device {
30        Some(DeviceKey::trust_device(&user_key.0)?)
31    } else {
32        None
33    };
34
35    client
36        .internal
37        .set_login_method(crate::client::LoginMethod::User(
38            crate::client::UserLoginMethod::Username {
39                client_id: "".to_owned(),
40                email,
41                kdf: Kdf::default(),
42            },
43        ));
44    client.internal.initialize_user_crypto_decrypted_key(
45        user_key.0,
46        UserKeyState {
47            private_key: key_pair.private.clone(),
48            // TODO (https://bitwarden.atlassian.net/browse/PM-21771) Signing keys are not supported on registration yet. This needs to be changed as
49            // soon as registration is supported.
50            signing_key: None,
51            security_state: None,
52        },
53    )?;
54
55    Ok(RegisterTdeKeyResponse {
56        private_key: key_pair.private,
57        public_key: key_pair.public,
58
59        admin_reset,
60        device_key,
61    })
62}
63
64#[allow(missing_docs)]
65#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
66pub struct RegisterTdeKeyResponse {
67    pub private_key: EncString,
68    pub public_key: B64,
69
70    pub admin_reset: UnsignedSharedKey,
71    pub device_key: Option<TrustDeviceResponse>,
72}