Skip to content

[PM-22845] Add account key rotation #313

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

Open
wants to merge 10 commits into
base: km/cose-content-format
Choose a base branch
from
Open
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
54 changes: 52 additions & 2 deletions crates/bitwarden-core/src/key_management/crypto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@ use std::collections::HashMap;
use base64::{engine::general_purpose::STANDARD, Engine};
use bitwarden_crypto::{
AsymmetricCryptoKey, CoseSerializable, CryptoError, EncString, Kdf, KeyDecryptable,
KeyEncryptable, MasterKey, Pkcs8PrivateKeyBytes, PrimitiveEncryptable, SignatureAlgorithm,
SignedPublicKey, SigningKey, SymmetricCryptoKey, UnsignedSharedKey, UserKey,
KeyEncryptable, MasterKey, Pkcs8PrivateKeyBytes, PrimitiveEncryptable, RotatedUserKeys,
SignatureAlgorithm, SignedPublicKey, SigningKey, SymmetricCryptoKey, UnsignedSharedKey,
UserKey,
};
use bitwarden_error::bitwarden_error;
use schemars::JsonSchema;
Expand Down Expand Up @@ -612,6 +613,55 @@ pub fn make_user_signing_keys_for_enrollment(
})
}

/// A rotated set of account keys for a user
#[derive(Serialize, Deserialize, Debug, JsonSchema)]
#[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 RotateUserKeysResponse {
/// The verifying key
pub verifying_key: String,
/// Signing key, encrypted with a symmetric key (user key, org key)
pub signing_key: EncString,
/// The user's public key, signed by the signing key
pub signed_public_key: String,
/// The user's public key, without signature
pub public_key: String,
/// The user's private key, encrypted with the user key
pub private_key: EncString,
}

impl From<RotatedUserKeys> for RotateUserKeysResponse {
fn from(rotated: RotatedUserKeys) -> Self {
RotateUserKeysResponse {
verifying_key: Base64String::from(rotated.verifying_key.to_vec()).into(),
signing_key: rotated.signing_key,
signed_public_key: Base64String::from(rotated.signed_public_key.to_vec()).into(),
public_key: Base64String::from(rotated.public_key.to_vec()).into(),
private_key: rotated.private_key,
}
}
}

/// Gets a set of new wrapped account keys for a user, given a new user key.
///
/// In the current implementation, it just re-encrypts any existing keys. This function expects a
/// user to be a v2 user; that is, they have a signing
pub fn get_v2_rotated_account_keys(
client: &Client,
user_key: String,
) -> Result<RotateUserKeysResponse, CryptoError> {
let key_store = client.internal.get_key_store();
let ctx = key_store.context();

ctx.dangerous_get_v2_rotated_account_keys(
&SymmetricCryptoKey::try_from(user_key)?,
AsymmetricKeyId::UserPrivateKey,
SigningKeyId::UserSigningKey,
)
.map(|rotated| rotated.into())
}

#[cfg(test)]
mod tests {
use std::num::NonZeroU32;
Expand Down
13 changes: 12 additions & 1 deletion crates/bitwarden-core/src/key_management/crypto_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,10 @@ use crate::key_management::crypto::{
};
use crate::{
client::encryption_settings::EncryptionSettingsError,
key_management::crypto::CryptoClientError, Client,
key_management::crypto::{
get_v2_rotated_account_keys, CryptoClientError, RotateUserKeysResponse,
},
Client,
};

/// A client for the crypto operations.
Expand Down Expand Up @@ -69,6 +72,14 @@ impl CryptoClient {
) -> Result<MakeUserSigningKeysResponse, CryptoError> {
make_user_signing_keys_for_enrollment(&self.client)
}

/// Creates a rotated set of account keys for the current state
pub fn get_v2_rotated_account_keys(
&self,
user_key: String,
) -> Result<RotateUserKeysResponse, CryptoError> {
get_v2_rotated_account_keys(&self.client, user_key)
}
}

impl CryptoClient {
Expand Down
6 changes: 6 additions & 0 deletions crates/bitwarden-core/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,12 @@ impl TryInto<Vec<u8>> for Base64String {
}
}

impl From<Base64String> for String {
fn from(val: Base64String) -> Self {
val.0
}
}

impl From<Vec<u8>> for Base64String {
fn from(val: Vec<u8>) -> Self {
Base64String(STANDARD.encode(val))
Expand Down
39 changes: 39 additions & 0 deletions crates/bitwarden-crypto/src/key_rotation/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
use crate::{
CoseKeyBytes, CoseSerializable, CoseSign1Bytes, CryptoError, EncString, KeyEncryptable,
KeyStoreContext, SpkiPublicKeyBytes, SymmetricCryptoKey,
};

/// Rotated set of account keys
pub struct RotatedUserKeys {
/// The verifying key
pub verifying_key: CoseKeyBytes,
/// Signing key, encrypted with a symmetric key (user key, org key)
pub signing_key: EncString,
/// The user's public key, signed by the signing key
pub signed_public_key: CoseSign1Bytes,
/// The user's public key, without signature
pub public_key: SpkiPublicKeyBytes,
/// The user's private key, encrypted with the user key
pub private_key: EncString,
}

/// Re-encrypts the user's keys with the provided symmetric key for a v2 user.
pub(crate) fn get_v2_rotated_account_keys<Ids: crate::KeyIds>(
new_user_key: &SymmetricCryptoKey,
current_user_private_key_id: Ids::Asymmetric,
current_user_signing_key_id: Ids::Signing,
ctx: &KeyStoreContext<Ids>,
) -> Result<RotatedUserKeys, CryptoError> {
let signing_key = ctx.get_signing_key(current_user_signing_key_id)?;
let private_key = ctx.get_asymmetric_key(current_user_private_key_id)?;
let signed_public_key =
ctx.make_signed_public_key(current_user_private_key_id, current_user_signing_key_id)?;

Ok(RotatedUserKeys {
verifying_key: signing_key.to_verifying_key().to_cose(),
signing_key: signing_key.to_cose().encrypt_with_key(new_user_key)?,
signed_public_key: signed_public_key.into(),
public_key: private_key.to_public_key().to_der()?,
private_key: private_key.to_der()?.encrypt_with_key(new_user_key)?,
})
}
4 changes: 2 additions & 2 deletions crates/bitwarden-crypto/src/keys/asymmetric_crypto_key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,14 @@ pub enum PublicKeyEncryptionAlgorithm {
RsaOaepSha1 = 0,
}

#[derive(Clone)]
#[derive(Clone, PartialEq, Debug)]
pub(crate) enum RawPublicKey {
RsaOaepSha1(RsaPublicKey),
}

/// Public key of a key pair used in a public key encryption scheme. It is used for
/// encrypting data.
#[derive(Clone)]
#[derive(Clone, PartialEq, Debug)]
pub struct AsymmetricPublicCryptoKey {
inner: RawPublicKey,
}
Expand Down
4 changes: 1 addition & 3 deletions crates/bitwarden-crypto/src/keys/signed_public_key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,9 +86,7 @@ impl From<SignedPublicKey> for CoseSign1Bytes {
impl TryFrom<CoseSign1Bytes> for SignedPublicKey {
type Error = EncodingError;
fn try_from(bytes: CoseSign1Bytes) -> Result<Self, EncodingError> {
Ok(SignedPublicKey(SignedObject::from_cose(
&CoseSign1Bytes::from(bytes),
)?))
Ok(SignedPublicKey(SignedObject::from_cose(&bytes)?))
}
}

Expand Down
2 changes: 2 additions & 0 deletions crates/bitwarden-crypto/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ pub use error::CryptoError;
pub(crate) use error::Result;
mod fingerprint;
pub use fingerprint::fingerprint;
mod key_rotation;
pub use key_rotation::*;
mod keys;
pub use keys::*;
mod rsa;
Expand Down
111 changes: 106 additions & 5 deletions crates/bitwarden-crypto/src/store/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use super::KeyStoreInner;
use crate::{
derive_shareable_key, error::UnsupportedOperation, signing, store::backend::StoreBackend,
AsymmetricCryptoKey, BitwardenLegacyKeyBytes, ContentFormat, CryptoError, EncString, KeyId,
KeyIds, Result, Signature, SignatureAlgorithm, SignedObject, SignedPublicKey,
KeyIds, Result, RotatedUserKeys, Signature, SignatureAlgorithm, SignedObject, SignedPublicKey,
SignedPublicKeyMessage, SigningKey, SymmetricCryptoKey, UnsignedSharedKey,
};

Expand Down Expand Up @@ -378,7 +378,10 @@ impl<Ids: KeyIds> KeyStoreContext<'_, Ids> {
.ok_or_else(|| crate::CryptoError::MissingKeyId(format!("{key_id:?}")))
}

fn get_asymmetric_key(&self, key_id: Ids::Asymmetric) -> Result<&AsymmetricCryptoKey> {
pub(crate) fn get_asymmetric_key(
&self,
key_id: Ids::Asymmetric,
) -> Result<&AsymmetricCryptoKey> {
if key_id.is_local() {
self.local_asymmetric_keys.get(key_id)
} else {
Expand All @@ -387,7 +390,7 @@ impl<Ids: KeyIds> KeyStoreContext<'_, Ids> {
.ok_or_else(|| crate::CryptoError::MissingKeyId(format!("{key_id:?}")))
}

fn get_signing_key(&self, key_id: Ids::Signing) -> Result<&SigningKey> {
pub(crate) fn get_signing_key(&self, key_id: Ids::Signing) -> Result<&SigningKey> {
if key_id.is_local() {
self.local_signing_keys.get(key_id)
} else {
Expand Down Expand Up @@ -512,6 +515,21 @@ impl<Ids: KeyIds> KeyStoreContext<'_, Ids> {
) -> Result<(Signature, signing::SerializedMessage)> {
self.get_signing_key(key)?.sign_detached(message, namespace)
}

/// Re-encrypts the user's keys with the provided symmetric key for a v2 user.
pub fn dangerous_get_v2_rotated_account_keys(
&self,
new_user_key: &SymmetricCryptoKey,
current_user_private_key_id: Ids::Asymmetric,
current_user_signing_key_id: Ids::Signing,
) -> Result<RotatedUserKeys> {
crate::get_v2_rotated_account_keys(
new_user_key,
current_user_private_key_id,
current_user_signing_key_id,
self,
)
}
}

#[cfg(test)]
Expand All @@ -524,8 +542,10 @@ mod tests {
tests::{Data, DataView},
KeyStore,
},
traits::tests::{TestIds, TestSigningKey, TestSymmKey},
CompositeEncryptable, CryptoError, Decryptable, SignatureAlgorithm, SigningKey,
traits::tests::{TestAsymmKey, TestIds, TestSigningKey, TestSymmKey},
AsymmetricCryptoKey, AsymmetricPublicCryptoKey, CompositeEncryptable, CoseKeyBytes,
CoseSerializable, CryptoError, Decryptable, KeyDecryptable, Pkcs8PrivateKeyBytes,
PublicKeyEncryptionAlgorithm, SignatureAlgorithm, SignedPublicKey, SigningKey,
SigningNamespace, SymmetricCryptoKey,
};

Expand Down Expand Up @@ -716,4 +736,85 @@ mod tests {
&SigningNamespace::ExampleNamespace
))
}

#[test]
fn test_account_key_rotation() {
let store: KeyStore<TestIds> = KeyStore::default();
let mut ctx = store.context_mut();

// Generate a new user key
let new_user_key = SymmetricCryptoKey::make_xchacha20_poly1305_key();
let current_user_private_key_id = TestAsymmKey::A(0);
let current_user_signing_key_id = TestSigningKey::A(0);

// Make the keys
ctx.generate_symmetric_key(TestSymmKey::A(0)).unwrap();
ctx.make_signing_key(current_user_signing_key_id).unwrap();
ctx.set_asymmetric_key(
current_user_private_key_id,
AsymmetricCryptoKey::make(PublicKeyEncryptionAlgorithm::RsaOaepSha1),
)
.unwrap();

// Get the rotated account keys
let rotated_keys = ctx
.dangerous_get_v2_rotated_account_keys(
&new_user_key,
current_user_private_key_id,
current_user_signing_key_id,
)
.unwrap();

// Public/Private key
assert_eq!(
AsymmetricPublicCryptoKey::from_der(&rotated_keys.public_key).unwrap(),
ctx.get_asymmetric_key(current_user_private_key_id)
.unwrap()
.to_public_key(),
);
let decrypted_private_key: Vec<u8> = rotated_keys
.private_key
.decrypt_with_key(&new_user_key)
.unwrap();
let private_key =
AsymmetricCryptoKey::from_der(&Pkcs8PrivateKeyBytes::from(decrypted_private_key))
.unwrap();
assert_eq!(
private_key.to_der().unwrap(),
ctx.get_asymmetric_key(current_user_private_key_id)
.unwrap()
.to_der()
.unwrap()
);

// Signing Key
let decrypted_signing_key: Vec<u8> = rotated_keys
.signing_key
.decrypt_with_key(&new_user_key)
.unwrap();
let signing_key =
SigningKey::from_cose(&CoseKeyBytes::from(decrypted_signing_key)).unwrap();
assert_eq!(
signing_key.to_cose(),
ctx.get_signing_key(current_user_signing_key_id)
.unwrap()
.to_cose(),
);

// Signed Public Key
let signed_public_key = SignedPublicKey::try_from(rotated_keys.signed_public_key).unwrap();
let unwrapped_key = signed_public_key
.verify_and_unwrap(
&ctx.get_signing_key(current_user_signing_key_id)
.unwrap()
.to_verifying_key(),
)
.unwrap();
assert_eq!(
unwrapped_key,
ctx.get_asymmetric_key(current_user_private_key_id)
.unwrap()
.to_public_key()
);
}
}