Skip to content

[PM-24683] Add updateKdf function #383

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weโ€™ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 18 commits into
base: km/pm-24051-add-master-password-unlock-decryption-options-to-identity-sync-response
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/bitwarden-core/src/auth/login/password.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ pub(crate) async fn login_password(

let master_key = MasterKey::derive(&input.password, &input.email, &input.kdf)?;
let password_hash = master_key
.derive_master_key_hash(input.password.as_bytes(), HashPurpose::ServerAuthorization)?;
.derive_master_key_hash(input.password.as_bytes(), HashPurpose::ServerAuthorization);

let response = request_identity_tokens(client, input, &password_hash).await?;

Expand Down
2 changes: 1 addition & 1 deletion crates/bitwarden-core/src/auth/password/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ pub(crate) fn determine_password_hash(
purpose: HashPurpose,
) -> Result<String, CryptoError> {
let master_key = MasterKey::derive(password, email, kdf)?;
master_key.derive_master_key_hash(password.as_bytes(), purpose)
Ok(master_key.derive_master_key_hash(password.as_bytes(), purpose))
}

#[cfg(test)]
Expand Down
2 changes: 1 addition & 1 deletion crates/bitwarden-core/src/auth/password/validate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ pub(crate) fn validate_password_user_key(
}

Ok(master_key
.derive_master_key_hash(password.as_bytes(), HashPurpose::LocalAuthorization)?)
.derive_master_key_hash(password.as_bytes(), HashPurpose::LocalAuthorization))
}
}
} else {
Expand Down
2 changes: 1 addition & 1 deletion crates/bitwarden-core/src/auth/register.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ pub(super) fn make_register_keys(
) -> Result<RegisterKeyResponse, CryptoError> {
let master_key = MasterKey::derive(&password, &email, &kdf)?;
let master_password_hash =
master_key.derive_master_key_hash(password.as_bytes(), HashPurpose::ServerAuthorization)?;
master_key.derive_master_key_hash(password.as_bytes(), HashPurpose::ServerAuthorization);
let (user_key, encrypted_user_key) = master_key.make_user_key()?;
let keys = user_key.make_key_pair()?;

Expand Down
158 changes: 157 additions & 1 deletion crates/bitwarden-core/src/key_management/crypto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ use crate::{
client::{encryption_settings::EncryptionSettingsError, LoginMethod, UserLoginMethod},
error::StatefulCryptoError,
key_management::{
master_password::{
MasterPasswordAuthenticationData, MasterPasswordError, MasterPasswordUnlockData,
},
AsymmetricKeyId, SecurityState, SignedSecurityState, SigningKeyId, SymmetricKeyId,
},
Client, NotAuthenticatedError, VaultLockedError, WrongPasswordError,
Expand All @@ -39,6 +42,8 @@ pub enum CryptoClientError {
VaultLocked(#[from] VaultLockedError),
#[error(transparent)]
Crypto(#[from] bitwarden_crypto::CryptoError),
#[error(transparent)]
MasterPassword(#[from] MasterPasswordError),
}

/// State used for initializing the user cryptographic state.
Expand Down Expand Up @@ -265,6 +270,63 @@ pub(super) async fn get_user_encryption_key(client: &Client) -> Result<String, C
Ok(user_key.to_base64())
}

/// Response from the `update_kdf` function
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
#[cfg_attr(feature = "wasm", derive(Tsify), tsify(into_wasm_abi, from_wasm_abi))]
pub struct UpdateKdfResponse {
/// The authentication data for the new KDF setting
master_password_authentication_data: MasterPasswordAuthenticationData,
/// The unlock data for the new KDF setting
master_password_unlock_data: MasterPasswordUnlockData,
/// The authentication data for the prior to the KDF change
old_master_password_authentication_data: MasterPasswordAuthenticationData,
}

pub(super) fn update_kdf(
client: &Client,
password: &str,
new_kdf: &Kdf,
) -> Result<UpdateKdfResponse, CryptoClientError> {
let key_store = client.internal.get_key_store();
let ctx = key_store.context();
// FIXME: [PM-18099] Once MasterKey deals with KeyIds, this should be updated
#[allow(deprecated)]
let user_key = ctx.dangerous_get_symmetric_key(SymmetricKeyId::User)?;

let login_method = client
.internal
.get_login_method()
.ok_or(NotAuthenticatedError)?;
let email = match login_method.as_ref() {
LoginMethod::User(UserLoginMethod::Username { email, .. })
| LoginMethod::User(UserLoginMethod::ApiKey { email, .. }) => email,
#[cfg(feature = "secrets")]
LoginMethod::ServiceAccount(_) => return Err(NotAuthenticatedError)?,
};

let authentication_data = MasterPasswordAuthenticationData::derive(password, new_kdf, email)
.map_err(CryptoClientError::MasterPassword)?;
let unlock_data = MasterPasswordUnlockData::derive(password, new_kdf, email, user_key)
.map_err(CryptoClientError::MasterPassword)?;
let old_authentication_data = MasterPasswordAuthenticationData::derive(
password,
&client
.internal
.get_kdf()
.map_err(|_| NotAuthenticatedError)?,
email,
)
.map_err(CryptoClientError::MasterPassword)?;

Ok(UpdateKdfResponse {
master_password_authentication_data: authentication_data,
master_password_unlock_data: unlock_data,
old_master_password_authentication_data: old_authentication_data,
})
}

/// Response from the `update_password` function
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
Expand Down Expand Up @@ -307,7 +369,7 @@ pub(super) fn update_password(
let password_hash = new_master_key.derive_master_key_hash(
new_password.as_bytes(),
bitwarden_crypto::HashPurpose::ServerAuthorization,
)?;
);

Ok(UpdatePasswordResponse {
password_hash,
Expand Down Expand Up @@ -737,6 +799,100 @@ mod tests {
"pgEBAlAmkP0QgfdMVbIujX55W/yNAycEgQIgBiFYIEM6JxBmjWQTruAm3s6BTaJy1q6BzQetMBacNeRJ0kxR";
const TEST_VECTOR_SECURITY_STATE_V2: &str = "hFgepAEnAxg8BFAmkP0QgfdMVbIujX55W/yNOgABOH8CoFgkomhlbnRpdHlJZFBHOOw2BI9OQoNq+Vl1xZZKZ3ZlcnNpb24CWEAlchbJR0vmRfShG8On7Q2gknjkw4Dd6MYBLiH4u+/CmfQdmjNZdf6kozgW/6NXyKVNu8dAsKsin+xxXkDyVZoG";

#[tokio::test]
async fn test_update_kdf() {
let client = Client::new(None);

let priv_key: EncString = "2.kmLY8NJVuiKBFJtNd/ZFpA==|qOodlRXER+9ogCe3yOibRHmUcSNvjSKhdDuztLlucs10jLiNoVVVAc+9KfNErLSpx5wmUF1hBOJM8zwVPjgQTrmnNf/wuDpwiaCxNYb/0v4FygPy7ccAHK94xP1lfqq7U9+tv+/yiZSwgcT+xF0wFpoxQeNdNRFzPTuD9o4134n8bzacD9DV/WjcrXfRjbBCzzuUGj1e78+A7BWN7/5IWLz87KWk8G7O/W4+8PtEzlwkru6Wd1xO19GYU18oArCWCNoegSmcGn7w7NDEXlwD403oY8Oa7ylnbqGE28PVJx+HLPNIdSC6YKXeIOMnVs7Mctd/wXC93zGxAWD6ooTCzHSPVV50zKJmWIG2cVVUS7j35H3rGDtUHLI+ASXMEux9REZB8CdVOZMzp2wYeiOpggebJy6MKOZqPT1R3X0fqF2dHtRFPXrNsVr1Qt6bS9qTyO4ag1/BCvXF3P1uJEsI812BFAne3cYHy5bIOxuozPfipJrTb5WH35bxhElqwT3y/o/6JWOGg3HLDun31YmiZ2HScAsUAcEkA4hhoTNnqy4O2s3yVbCcR7jF7NLsbQc0MDTbnjxTdI4VnqUIn8s2c9hIJy/j80pmO9Bjxp+LQ9a2hUkfHgFhgHxZUVaeGVth8zG2kkgGdrp5VHhxMVFfvB26Ka6q6qE/UcS2lONSv+4T8niVRJz57qwctj8MNOkA3PTEfe/DP/LKMefke31YfT0xogHsLhDkx+mS8FCc01HReTjKLktk/Jh9mXwC5oKwueWWwlxI935ecn+3I2kAuOfMsgPLkoEBlwgiREC1pM7VVX1x8WmzIQVQTHd4iwnX96QewYckGRfNYWz/zwvWnjWlfcg8kRSe+68EHOGeRtC5r27fWLqRc0HNcjwpgHkI/b6czerCe8+07TWql4keJxJxhBYj3iOH7r9ZS8ck51XnOb8tGL1isimAJXodYGzakwktqHAD7MZhS+P02O+6jrg7d+yPC2ZCuS/3TOplYOCHQIhnZtR87PXTUwr83zfOwAwCyv6KP84JUQ45+DItrXLap7nOVZKQ5QxYIlbThAO6eima6Zu5XHfqGPMNWv0bLf5+vAjIa5np5DJrSwz9no/hj6CUh0iyI+SJq4RGI60lKtypMvF6MR3nHLEHOycRUQbZIyTHWl4QQLdHzuwN9lv10ouTEvNr6sFflAX2yb6w3hlCo7oBytH3rJekjb3IIOzBpeTPIejxzVlh0N9OT5MZdh4sNKYHUoWJ8mnfjdM+L4j5Q2Kgk/XiGDgEebkUxiEOQUdVpePF5uSCE+TPav/9FIRGXGiFn6NJMaU7aBsDTFBLloffFLYDpd8/bTwoSvifkj7buwLYM+h/qcnfdy5FWau1cKav+Blq/ZC0qBpo658RTC8ZtseAFDgXoQZuksM10hpP9bzD04Bx30xTGX81QbaSTNwSEEVrOtIhbDrj9OI43KH4O6zLzK+t30QxAv5zjk10RZ4+5SAdYndIlld9Y62opCfPDzRy3ubdve4ZEchpIKWTQvIxq3T5ogOhGaWBVYnkMtM2GVqvWV//46gET5SH/MdcwhACUcZ9kCpMnWH9CyyUwYvTT3UlNyV+DlS27LMPvaw7tx7qa+GfNCoCBd8S4esZpQYK/WReiS8=|pc7qpD42wxyXemdNPuwxbh8iIaryrBPu8f/DGwYdHTw=".parse().unwrap();

let kdf = Kdf::PBKDF2 {
iterations: 100_000.try_into().unwrap(),
};

initialize_user_crypto(
& client,
InitUserCryptoRequest {
user_id: Some(uuid::Uuid::new_v4()),
kdf_params: kdf.clone(),
email: "[email protected]".into(),
private_key: priv_key.to_owned(),
signing_key: None,
security_state: None,
method: InitUserCryptoMethod::Password {
password: "asdfasdfasdf".into(),
user_key: "2.u2HDQ/nH2J7f5tYHctZx6Q==|NnUKODz8TPycWJA5svexe1wJIz2VexvLbZh2RDfhj5VI3wP8ZkR0Vicvdv7oJRyLI1GyaZDBCf9CTBunRTYUk39DbZl42Rb+Xmzds02EQhc=|rwuo5wgqvTJf3rgwOUfabUyzqhguMYb3sGBjOYqjevc=".parse().unwrap(),
},
},
)
.await
.unwrap();

let new_kdf = Kdf::PBKDF2 {
iterations: 600_000.try_into().unwrap(),
};
let new_kdf_response = update_kdf(&client, "123412341234", &new_kdf).unwrap();

let client2 = Client::new(None);

initialize_user_crypto(
&client2,
InitUserCryptoRequest {
user_id: Some(uuid::Uuid::new_v4()),
kdf_params: new_kdf.clone(),
email: "[email protected]".into(),
private_key: priv_key.to_owned(),
signing_key: None,
security_state: None,
method: InitUserCryptoMethod::Password {
password: "123412341234".into(),
user_key: new_kdf_response
.master_password_unlock_data
.master_key_wrapped_user_key,
},
},
)
.await
.unwrap();

let new_hash = client2
.kdf()
.hash_password(
"[email protected]".into(),
"123412341234".into(),
new_kdf.clone(),
bitwarden_crypto::HashPurpose::ServerAuthorization,
)
.await
.unwrap();

assert_eq!(
new_hash,
new_kdf_response
.master_password_authentication_data
.master_password_authentication_hash
);

let client_key = {
let key_store = client.internal.get_key_store();
let ctx = key_store.context();
#[allow(deprecated)]
ctx.dangerous_get_symmetric_key(SymmetricKeyId::User)
.unwrap()
.to_base64()
};

let client2_key = {
let key_store = client2.internal.get_key_store();
let ctx = key_store.context();
#[allow(deprecated)]
ctx.dangerous_get_symmetric_key(SymmetricKeyId::User)
.unwrap()
.to_base64()
};

assert_eq!(client_key, client2_key);
}

#[tokio::test]
async fn test_update_password() {
let client = Client::new(None);
Expand Down
16 changes: 13 additions & 3 deletions crates/bitwarden-core/src/key_management/crypto_client.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use bitwarden_crypto::CryptoError;
use bitwarden_crypto::{CryptoError, Kdf};
#[cfg(feature = "internal")]
use bitwarden_crypto::{EncString, UnsignedSharedKey};
#[cfg(feature = "wasm")]
Expand All @@ -19,8 +19,8 @@ use crate::{
client::encryption_settings::EncryptionSettingsError,
error::StatefulCryptoError,
key_management::crypto::{
get_v2_rotated_account_keys, make_v2_keys_for_v1_user, CryptoClientError,
UserCryptoV2KeysResponse,
get_v2_rotated_account_keys, make_v2_keys_for_v1_user, update_kdf, CryptoClientError,
UpdateKdfResponse, UserCryptoV2KeysResponse,
},
Client,
};
Expand Down Expand Up @@ -80,6 +80,16 @@ impl CryptoClient {
) -> Result<UserCryptoV2KeysResponse, StatefulCryptoError> {
get_v2_rotated_account_keys(&self.client)
}

/// Update the user's kdf settings, which will re-encrypt the user's encryption key with the new
/// kdf settings. This returns the new encrypted user key and the new password hash.
pub fn update_kdf(
&self,
password: String,
kdf: Kdf,
) -> Result<UpdateKdfResponse, CryptoClientError> {
update_kdf(&self.client, &password, &kdf)
}
}

impl CryptoClient {
Expand Down
Loading