Compare commits

..
22 changed files with 196 additions and 660 deletions

No files matched your search

-1
View File
@@ -18,7 +18,6 @@ extend-ignore-re = [
"COSE",
"COSEKey",
"COSEAlgorithm",
"CoseEncrypt0",
# Ignore this specific string as it's valid
"Ensure they are valid OTPs",
# This word is misspelled upstream
@@ -3,5 +3,3 @@ DROP TABLE IF EXISTS user_signature_key_pairs;
ALTER TABLE users DROP COLUMN signed_public_key;
ALTER TABLE users DROP COLUMN security_state;
ALTER TABLE users DROP COLUMN security_version;
ALTER TABLE users DROP COLUMN v2_upgrade_token;
ALTER TABLE users_organizations DROP COLUMN v2_upgrade_token;
@@ -1,8 +1,6 @@
ALTER TABLE users ADD COLUMN signed_public_key TEXT;
ALTER TABLE users ADD COLUMN security_state TEXT;
ALTER TABLE users ADD COLUMN security_version INTEGER;
ALTER TABLE users ADD COLUMN v2_upgrade_token TEXT;
ALTER TABLE users_organizations ADD COLUMN v2_upgrade_token TEXT;
CREATE TABLE user_signature_key_pairs (
uuid CHAR(36) NOT NULL PRIMARY KEY,
@@ -3,5 +3,3 @@ DROP TABLE IF EXISTS user_signature_key_pairs;
ALTER TABLE users DROP COLUMN signed_public_key;
ALTER TABLE users DROP COLUMN security_state;
ALTER TABLE users DROP COLUMN security_version;
ALTER TABLE users DROP COLUMN v2_upgrade_token;
ALTER TABLE users_organizations DROP COLUMN v2_upgrade_token;
@@ -1,8 +1,6 @@
ALTER TABLE users ADD COLUMN signed_public_key TEXT;
ALTER TABLE users ADD COLUMN security_state TEXT;
ALTER TABLE users ADD COLUMN security_version INTEGER;
ALTER TABLE users ADD COLUMN v2_upgrade_token TEXT;
ALTER TABLE users_organizations ADD COLUMN v2_upgrade_token TEXT;
CREATE TABLE user_signature_key_pairs (
uuid CHAR(36) NOT NULL PRIMARY KEY,
@@ -3,5 +3,3 @@ DROP TABLE IF EXISTS user_signature_key_pairs;
ALTER TABLE users DROP COLUMN signed_public_key;
ALTER TABLE users DROP COLUMN security_state;
ALTER TABLE users DROP COLUMN security_version;
ALTER TABLE users DROP COLUMN v2_upgrade_token;
ALTER TABLE users_organizations DROP COLUMN v2_upgrade_token;
@@ -1,8 +1,6 @@
ALTER TABLE users ADD COLUMN signed_public_key TEXT;
ALTER TABLE users ADD COLUMN security_state TEXT;
ALTER TABLE users ADD COLUMN security_version INTEGER;
ALTER TABLE users ADD COLUMN v2_upgrade_token TEXT;
ALTER TABLE users_organizations ADD COLUMN v2_upgrade_token TEXT;
CREATE TABLE user_signature_key_pairs (
uuid TEXT NOT NULL PRIMARY KEY,
+83 -440
View File
@@ -1,7 +1,6 @@
use std::collections::HashSet;
use chrono::Utc;
use num_traits::FromPrimitive;
use rocket::{
http::Status,
request::{FromRequest, Outcome, Request},
@@ -12,7 +11,7 @@ use serde_json::Value;
use crate::{
CONFIG,
api::{
AnonymousNotify, ApiResult, EmptyResult, JsonResult, LogOutReason, Notify, PasswordOrOtpData, UpdateType,
AnonymousNotify, ApiResult, EmptyResult, JsonResult, Notify, PasswordOrOtpData, UpdateType,
core::{accept_org_invite, log_user_event, two_factor::email},
master_password_policy, register_push_device, unregister_push_device,
},
@@ -49,10 +48,8 @@ pub fn routes() -> Vec<rocket::Route> {
post_password,
post_set_password,
post_kdf,
get_key_rotation_data,
post_rotatekey,
post_user_key,
post_rotate_user_keys,
post_sstamp,
post_email_token,
post_email,
@@ -313,23 +310,6 @@ impl AccountKeysData {
}
}
impl WrappedAccountCryptographicState {
/// This shape is v2-only: the key pairs and security state were already required by the
/// deserializer, so a missing signed public key fails the all-or-nothing check in
/// [`AccountKeysData::validate`] rather than falling back to v1, which would silently turn a
/// rotation into a downgrade.
fn validate(self) -> ApiResult<ValidatedAccountKeys> {
AccountKeysData {
user_key_encrypted_account_private_key: None,
account_public_key: None,
public_key_encryption_key_pair: Some(self.public_key_encryption_key_pair),
signature_key_pair: Some(self.signature_key_pair),
security_state: Some(self.security_state),
}
.validate()
}
}
impl From<KeysData> for ValidatedAccountKeys {
fn from(keys: KeysData) -> Self {
Self {
@@ -1086,62 +1066,43 @@ struct UpdateEmergencyAccessData {
#[serde(rename_all = "camelCase")]
struct UpdateResetPasswordData {
organization_id: OrganizationId,
// Absent in a v1 -> v2 upgrade, which keeps the key the organization already holds
reset_password_key: Option<String>,
reset_password_key: String,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct KeyData {
account_unlock_data: RotateAccountUnlockData,
account_keys: AccountKeysData,
account_keys: RotateAccountKeys,
account_data: RotateAccountData,
old_master_key_authentication_hash: String,
new_user_key_id: Option<KeyId>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct RotateAccountUnlockData {
emergency_access_unlock_data: Vec<UpdateEmergencyAccessData>,
master_password_unlock_data: MasterPasswordUnlockData,
#[serde(flatten)]
common: CommonUnlockData,
organization_account_recovery_unlock_data: Vec<UpdateResetPasswordData>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct MasterPasswordUnlockData {
#[serde(flatten)]
kdf: KDFData,
kdf_type: i32,
kdf_iterations: i32,
kdf_parallelism: Option<i32>,
kdf_memory: Option<i32>,
email: String,
master_key_authentication_hash: String,
master_key_encrypted_user_key: String,
contained_key_id: Option<KeyId>,
}
/// The unlock data both rotation endpoints share. Vaultwarden has neither trusted device encryption
/// nor passkey login, so `key-rotation-data` reports none of either and these must arrive empty.
///
/// Ref: <https://github.com/bitwarden/server/blob/main/src/Api/KeyManagement/Models/Requests/CommonUnlockDataRequestModel.cs>
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct CommonUnlockData {
emergency_access_unlock_data: Vec<UpdateEmergencyAccessData>,
organization_account_recovery_unlock_data: Vec<UpdateResetPasswordData>,
#[serde(default)]
passkey_unlock_data: Vec<Value>,
#[serde(default)]
device_key_unlock_data: Vec<Value>,
v2_upgrade_token: Option<V2UpgradeTokenData>,
}
/// Lets clients that still hold the v1 user key derive the v2 one after another client upgraded the
/// account, so a v1 -> v2 upgrade doesn't have to log every other session out. Opaque to us.
#[derive(Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
struct V2UpgradeTokenData {
wrapped_user_key1: String,
wrapped_user_key2: String,
struct RotateAccountKeys {
user_key_encrypted_account_private_key: String,
account_public_key: String,
}
#[derive(Deserialize)]
@@ -1152,148 +1113,31 @@ struct RotateAccountData {
sends: Vec<SendData>,
}
/// Body of `rotate-user-keys`, which rotates the keys without touching the master password.
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct RotateUserKeysData {
wrapped_account_cryptographic_state: WrappedAccountCryptographicState,
unlock_data: CommonUnlockData,
account_data: RotateAccountData,
unlock_method_data: UnlockMethodData,
new_user_key_id: Option<KeyId>,
}
/// The v2-only account cryptographic state, where all three parts are mandatory.
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct WrappedAccountCryptographicState {
public_key_encryption_key_pair: PublicKeyEncryptionKeyPairData,
signature_key_pair: SignatureKeyPairData,
security_state: SecurityStateData,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct UnlockMethodData {
unlock_method: i32,
master_password_unlock_data: Option<RotateMasterPasswordUnlockData>,
// `keyConnectorKeyWrappedUserKey` is deliberately not read: that unlock method is rejected.
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct RotateMasterPasswordUnlockData {
kdf: KDFData,
salt: String,
master_key_wrapped_user_key: String,
contained_key_id: Option<KeyId>,
}
/// The user key wrapped in the master password unlock data has to be the new one.
///
/// Ref: <https://github.com/bitwarden/server/blob/main/src/Core/KeyManagement/Models/Data/MasterPasswordUnlockData.cs>
fn validate_contained_key_id(contained_key_id: Option<&KeyId>, new_user_key_id: Option<&KeyId>) -> EmptyResult {
match (contained_key_id, new_user_key_id) {
// Neither is sent by clients that predate key ids
(None, None) => Ok(()),
(Some(contained), Some(new)) if contained == new => Ok(()),
_ => err!("Invalid user key sent in master-password unlock data."),
}
}
/// Ref: <https://github.com/bitwarden/server/blob/main/src/Api/KeyManagement/Enums/UnlockMethod.cs>
#[derive(num_derive::FromPrimitive)]
enum UnlockMethod {
Tde = 0,
MasterPassword = 1,
KeyConnector = 2,
}
/// The rotation-specific checks on the new account keys.
///
/// A rotation re-wraps the existing keys under a new user key; it must not swap the identity the
/// account presents to others. So the public key never changes, and for an account that is already
/// v2 the verifying key doesn't either — only the *wrapped* signing key does. A v1 account may gain
/// a signature key pair, which is the v1 -> v2 upgrade.
///
/// Ref: <https://github.com/bitwarden/server/blob/main/src/Core/KeyManagement/UserKey/Implementations/RotateUserAccountKeysCommand.cs>
async fn validate_rotation_account_keys(keys: &ValidatedAccountKeys, user: &User, conn: &DbConn) -> EmptyResult {
if user.public_key.as_ref() != Some(&keys.public_key) {
err!("Changing the asymmetric keypair is not possible during key rotation")
}
let Some(v2) = &keys.v2 else {
if user.is_v2() {
err!("Cannot downgrade an account from v2 to v1 encryption during key rotation")
}
// A v1 rotation: the private key stays wrapped by an AES-CBC-HMAC user key
if enc_string_type(&keys.private_key) != Some(ENC_TYPE_AES_CBC_256_HMAC_SHA256) {
err!("The provided account private key was not wrapped with AES-256-CBC-HMAC")
}
return Ok(());
};
// Both a v2 rotation and the v1 -> v2 upgrade end up with a COSE user key wrapping the private keys
if enc_string_type(&v2.signing_key) != Some(ENC_TYPE_COSE_ENCRYPT0) {
err!("The provided signing key data is not wrapped with XChaCha20-Poly1305.")
}
if enc_string_type(&keys.private_key) != Some(ENC_TYPE_COSE_ENCRYPT0) {
err!("The provided private key encryption key is not wrapped with XChaCha20-Poly1305.")
}
if v2.verifying_key.is_empty() || v2.signed_public_key.is_empty() || v2.security_state.is_empty() {
err!("The v2 account keys are missing the verifying key, signed public key or security state")
}
if !user.is_v2() {
// The v1 -> v2 upgrade, which is where the signature key pair comes from
return Ok(());
}
let Some(key_pair) = UserSignatureKeyPair::find_by_user(&user.uuid, conn).await else {
err!("The account is missing its signature key pair")
};
if key_pair.verifying_key != v2.verifying_key {
err!("Changing the verifying key is not possible during key rotation")
}
Ok(())
}
/// `AesCbc256_HmacSha256_B64`, the v1 user key
const ENC_TYPE_AES_CBC_256_HMAC_SHA256: &str = "2";
/// `CoseEncrypt0B64`, the v2 user key
const ENC_TYPE_COSE_ENCRYPT0: &str = "7";
/// The encryption type of an EncString, the number before the first `.`.
fn enc_string_type(enc_string: &str) -> Option<&str> {
enc_string.split_once('.').map(|(enc_type, _)| enc_type)
}
impl KDFData {
/// Whether these are the settings the user already has, which a key rotation can't change.
fn is_unchanged_for(&self, user: &User) -> bool {
user.client_kdf_type == self.kdf
&& user.client_kdf_iter == self.kdf_iterations
&& user.client_kdf_memory == self.kdf_memory
&& user.client_kdf_parallelism == self.kdf_parallelism
}
}
/// A rotation re-encrypts everything under the new user key, so anything left out would be
/// unreadable afterwards. Both rotation endpoints require the client to send the complete set.
fn validate_rotation_data(
data: &RotateData,
fn validate_keydata(
data: &KeyData,
existing_ciphers: &[Cipher],
existing_folders: &[Folder],
existing_emergency_access: &[EmergencyAccess],
existing_memberships: &[Membership],
existing_sends: &[Send],
user: &User,
) -> EmptyResult {
let account_data = &data.account_data;
if user.client_kdf_type != data.account_unlock_data.master_password_unlock_data.kdf_type
|| user.client_kdf_iter != data.account_unlock_data.master_password_unlock_data.kdf_iterations
|| user.client_kdf_memory != data.account_unlock_data.master_password_unlock_data.kdf_memory
|| user.client_kdf_parallelism != data.account_unlock_data.master_password_unlock_data.kdf_parallelism
|| user.email != data.account_unlock_data.master_password_unlock_data.email
{
err!("Changing the kdf variant or email is not supported during key rotation");
}
if user.public_key.as_ref() != Some(&data.account_keys.account_public_key) {
err!("Changing the asymmetric keypair is not possible during key rotation")
}
// Check that we're correctly rotating all the user's ciphers
let existing_cipher_ids = existing_ciphers.iter().map(|c| &c.uuid).collect::<HashSet<&CipherId>>();
let provided_cipher_ids = account_data
let provided_cipher_ids = data
.account_data
.ciphers
.iter()
.filter(|c| c.organization_id.is_none())
@@ -1305,7 +1149,8 @@ fn validate_rotation_data(
// Check that we're correctly rotating all the user's folders
let existing_folder_ids = existing_folders.iter().map(|f| &f.uuid).collect::<HashSet<&FolderId>>();
let provided_folder_ids = account_data.folders.iter().filter_map(|f| f.id.as_ref()).collect::<HashSet<&FolderId>>();
let provided_folder_ids =
data.account_data.folders.iter().filter_map(|f| f.id.as_ref()).collect::<HashSet<&FolderId>>();
if !provided_folder_ids.is_superset(&existing_folder_ids) {
err!("All existing folders must be included in the rotation")
}
@@ -1313,8 +1158,12 @@ fn validate_rotation_data(
// Check that we're correctly rotating all the user's emergency access keys
let existing_emergency_access_ids =
existing_emergency_access.iter().map(|ea| &ea.uuid).collect::<HashSet<&EmergencyAccessId>>();
let provided_emergency_access_ids =
data.unlock_data.emergency_access_unlock_data.iter().map(|ea| &ea.id).collect::<HashSet<&EmergencyAccessId>>();
let provided_emergency_access_ids = data
.account_unlock_data
.emergency_access_unlock_data
.iter()
.map(|ea| &ea.id)
.collect::<HashSet<&EmergencyAccessId>>();
if !provided_emergency_access_ids.is_superset(&existing_emergency_access_ids) {
err!("All existing emergency access keys must be included in the rotation")
}
@@ -1323,7 +1172,7 @@ fn validate_rotation_data(
let existing_reset_password_ids =
existing_memberships.iter().map(|m| &m.org_uuid).collect::<HashSet<&OrganizationId>>();
let provided_reset_password_ids = data
.unlock_data
.account_unlock_data
.organization_account_recovery_unlock_data
.iter()
.map(|rp| &rp.organization_id)
@@ -1334,7 +1183,7 @@ fn validate_rotation_data(
// Check that we're correctly rotating all the user's sends
let existing_send_ids = existing_sends.iter().map(|s| &s.uuid).collect::<HashSet<&SendId>>();
let provided_send_ids = account_data.sends.iter().filter_map(|s| s.id.as_ref()).collect::<HashSet<&SendId>>();
let provided_send_ids = data.account_data.sends.iter().filter_map(|s| s.id.as_ref()).collect::<HashSet<&SendId>>();
if !provided_send_ids.is_superset(&existing_send_ids) {
err!("All existing sends must be included in the rotation")
}
@@ -1342,184 +1191,23 @@ fn validate_rotation_data(
Ok(())
}
/// The public keys and encrypted keysets that participate in a key rotation, so the client can
/// re-share the new user key without having to piece this together from several endpoints.
///
/// The four collections must always be present, even when empty: the SDK errors out if any of them
/// is missing. `trustedDeviceKeyData` and `passkeyKeyData` are always empty here, since vaultwarden
/// supports neither trusted device encryption nor passkey (PRF) login.
///
/// Ref: <https://github.com/bitwarden/server/blob/main/src/Core/KeyManagement/UserKey/Queries/KeyRotationDataQuery.cs>
#[get("/accounts/key-management/key-rotation-data")]
async fn get_key_rotation_data(headers: Headers, conn: DbConn) -> JsonResult {
let user_id = &headers.user.uuid;
let mut organization_data = Vec::new();
for membership in Membership::find_by_user(user_id, &conn).await {
// Only memberships actually enrolled in account recovery take part in the rotation.
if membership.reset_password_key.is_none() {
continue;
}
let Some(org) = Organization::find_by_uuid(&membership.org_uuid, &conn).await else {
continue;
};
let Some(public_key) = org.public_key else {
continue;
};
organization_data.push(json!({
"organizationId": org.uuid,
"organizationName": org.name,
"organizationPublicKey": public_key,
"object": "organizationPasswordResetKeyData",
}));
}
let mut emergency_access_data = Vec::new();
for emergency_access in EmergencyAccess::find_all_confirmed_by_grantor_uuid(user_id, &conn).await {
// Without a stored key there is nothing to re-share.
if emergency_access.key_encrypted.is_none() {
continue;
}
let Some(grantee_id) = emergency_access.grantee_uuid.clone() else {
continue;
};
let Some(grantee) = User::find_by_uuid(&grantee_id, &conn).await else {
continue;
};
let Some(public_key) = grantee.public_key.clone() else {
continue;
};
emergency_access_data.push(json!({
"id": emergency_access.uuid,
"granteeId": grantee_id,
"granteeName": grantee.name,
"granteeEmail": grantee.email,
"publicKey": public_key,
"object": "emergencyAccessKeyData",
}));
}
Ok(Json(json!({
"organizationPasswordResetKeyData": organization_data,
"emergencyAccessKeyData": emergency_access_data,
"trustedDeviceKeyData": [],
"passkeyKeyData": [],
"object": "keyRotationData",
})))
}
/// Everything a rotation replaces, once each endpoint's wrapper has been peeled off.
struct RotateData {
account_keys: ValidatedAccountKeys,
account_data: RotateAccountData,
unlock_data: CommonUnlockData,
/// Only v2 (COSE) user keys have an id, so this is `None` for a v1 -> v1 rotation.
new_user_key_id: Option<KeyId>,
/// The new user key, wrapped by the master key.
wrapped_user_key: String,
/// Only for `rotate-user-account-keys`, where the master password changes along with the keys.
new_password_hash: Option<String>,
}
impl CommonUnlockData {
/// We advertise no trusted devices or passkeys in `key-rotation-data`, so a client sending
/// either has produced keys for something that doesn't exist here. Silently dropping them would
/// leave the client believing an unlock method was rotated when it wasn't.
fn validate(&self) -> EmptyResult {
if !self.passkey_unlock_data.is_empty() {
err!("Passkey unlock is not supported")
}
if !self.device_key_unlock_data.is_empty() {
err!("Trusted device unlock is not supported")
}
Ok(())
}
}
#[post("/accounts/key-management/rotate-user-account-keys", data = "<data>")]
async fn post_rotatekey(data: Json<KeyData>, headers: Headers, conn: DbConn, nt: Notify<'_>) -> EmptyResult {
// TODO: See if we can wrap everything within a SQL Transaction. If something fails it should revert everything.
let data: KeyData = data.into_inner();
if !headers.user.check_valid_password(&data.old_master_key_authentication_hash) {
err!("Invalid password")
}
let unlock_data = data.account_unlock_data.master_password_unlock_data;
if !unlock_data.kdf.is_unchanged_for(&headers.user) || unlock_data.email != headers.user.email {
err!("Changing the kdf variant or email is not supported during key rotation");
// This only rotates the keys of a v1 account. A v2 account's signing key would stay wrapped by the
// old user key, and a v1 account can't be upgraded here, since the signature key pair isn't read.
// Either would leave an account that can't be unlocked.
if headers.user.is_v2() {
err!("Key rotation is not supported for v2 accounts")
}
validate_contained_key_id(unlock_data.contained_key_id.as_ref(), data.new_user_key_id.as_ref())?;
let mut common = data.account_unlock_data.common;
// This endpoint always logs every session out, so an upgrade token is never kept here. That
// also clears one left over from an earlier upgrade. Ref: upstream's AccountsKeyManagementController
common.v2_upgrade_token = None;
rotate_account(
RotateData {
account_keys: data.account_keys.validate()?,
account_data: data.account_data,
unlock_data: common,
new_user_key_id: data.new_user_key_id,
wrapped_user_key: unlock_data.master_key_encrypted_user_key,
new_password_hash: Some(unlock_data.master_key_authentication_hash),
},
headers,
conn,
nt,
)
.await
}
/// The body shared by both rotation endpoints: check that the client re-encrypted everything, re-save
/// it, then swap the account keys and the wrapped user key.
async fn rotate_account(data: RotateData, headers: Headers, conn: DbConn, nt: Notify<'_>) -> EmptyResult {
// TODO: See if we can wrap everything within a SQL Transaction. If something fails it should revert everything.
data.unlock_data.validate()?;
let user_id = &headers.user.uuid;
let mut existing_ciphers = Cipher::find_owned_by_user(user_id, &conn).await;
let mut existing_folders = Folder::find_by_user(user_id, &conn).await;
let mut existing_emergency_access = EmergencyAccess::find_all_confirmed_by_grantor_uuid(user_id, &conn).await;
let mut existing_memberships = Membership::find_by_user(user_id, &conn).await;
// We only rotate the reset password key if it is set.
existing_memberships.retain(|m| m.reset_password_key.is_some());
let mut existing_sends = Send::find_by_user(user_id, &conn).await;
validate_rotation_data(
&data,
&existing_ciphers,
&existing_folders,
&existing_emergency_access,
&existing_memberships,
&existing_sends,
)?;
validate_rotation_account_keys(&data.account_keys, &headers.user, &conn).await?;
// The upgrade token only means anything for a v1 account moving to v2: it lets sessions still
// holding the v1 user key pick up the v2 one instead of being forced to re-authenticate. For an
// account that is already v2 it is meaningless, so it gets discarded and the security stamp is
// reset, as a rotation otherwise would. That ends the refresh tokens, while the access tokens in
// use run out on their own, as upstream.
let is_upgrade = data.unlock_data.v2_upgrade_token.is_some() && !headers.user.is_v2();
let upgrade_token = match &data.unlock_data.v2_upgrade_token {
Some(token) if is_upgrade => Some(serde_json::to_string(token)?),
_ => None,
};
// An upgrade can't re-wrap the account recovery keys: that needs the organization's public key
// to be trusted, and an upgrade shows the user no prompt. So the stored keys are kept, and each
// organization gets the upgrade token instead, to unwrap the v2 user key with.
// Ref: upstream's OrganizationUserRotationValidator
for reset_password_data in &data.unlock_data.organization_account_recovery_unlock_data {
let has_key = reset_password_data.reset_password_key.as_deref().is_some_and(|k| !k.is_empty());
if is_upgrade && has_key {
err!("Account recovery keys cannot be rotated during a V1 to V2 upgrade rotation.")
}
if !is_upgrade && !has_key {
err!("Account recovery keys cannot be null or empty during rotation.")
}
if !data.account_keys.user_key_encrypted_account_private_key.starts_with("2.") {
err!("The provided account private key was not wrapped with AES-256-CBC-HMAC")
}
// Validate the import before continuing
@@ -1528,8 +1216,28 @@ async fn rotate_account(data: RotateData, headers: Headers, conn: DbConn, nt: No
// TODO: See if we can optimize the whole cipher adding/importing and prevent duplicate code and checks.
Cipher::validate_cipher_data(&data.account_data.ciphers)?;
let user_id = &headers.user.uuid;
// TODO: Ideally we'd do everything after this point in a single transaction.
let mut existing_ciphers = Cipher::find_owned_by_user(user_id, &conn).await;
let mut existing_folders = Folder::find_by_user(user_id, &conn).await;
let mut existing_emergency_access = EmergencyAccess::find_all_confirmed_by_grantor_uuid(user_id, &conn).await;
let mut existing_memberships = Membership::find_by_user(user_id, &conn).await;
// We only rotate the reset password key if it is set.
existing_memberships.retain(|m| m.reset_password_key.is_some());
let mut existing_sends = Send::find_by_user(user_id, &conn).await;
validate_keydata(
&data,
&existing_ciphers,
&existing_folders,
&existing_emergency_access,
&existing_memberships,
&existing_sends,
&headers.user,
)?;
// Update folder data
for folder_data in data.account_data.folders {
// Skip `null` folder id entries.
@@ -1545,7 +1253,7 @@ async fn rotate_account(data: RotateData, headers: Headers, conn: DbConn, nt: No
}
// Update emergency access data
for emergency_access_data in data.unlock_data.emergency_access_unlock_data {
for emergency_access_data in data.account_unlock_data.emergency_access_unlock_data {
let Some(saved_emergency_access) =
existing_emergency_access.iter_mut().find(|ea| ea.uuid == emergency_access_data.id)
else {
@@ -1557,17 +1265,14 @@ async fn rotate_account(data: RotateData, headers: Headers, conn: DbConn, nt: No
}
// Update reset password data
for reset_password_data in data.unlock_data.organization_account_recovery_unlock_data {
for reset_password_data in data.account_unlock_data.organization_account_recovery_unlock_data {
let Some(membership) =
existing_memberships.iter_mut().find(|m| m.org_uuid == reset_password_data.organization_id)
else {
err!("Reset password doesn't exist")
};
if !is_upgrade {
membership.reset_password_key = reset_password_data.reset_password_key;
}
membership.v2_upgrade_token.clone_from(&upgrade_token);
membership.reset_password_key = Some(reset_password_data.reset_password_key);
membership.save(&conn).await?;
}
@@ -1589,95 +1294,33 @@ async fn rotate_account(data: RotateData, headers: Headers, conn: DbConn, nt: No
};
// Prevent triggering cipher updates via WebSockets by settings UpdateType::None
// Other sessions still hold the old user key, so an update to a re-encrypted cipher could cause issues.
// After the user is saved they are logged out, or on an upgrade, told to sync the new key.
// The user sessions are invalidated because all the ciphers were re-encrypted and thus triggering an update could cause issues.
// We force the users to logout after the user has been saved to try and prevent these issues.
update_cipher_from_data(saved_cipher, cipher_data, &headers, None, &conn, &nt, UpdateType::None).await?;
}
}
// Update user data
let mut user = headers.user;
user.v2_upgrade_token = upgrade_token;
data.account_keys.apply(&mut user)?;
// The old id names a key that no longer exists, so it is replaced even when the new key has none.
user.key_id = data.new_user_key_id;
user.private_key = Some(data.account_keys.user_key_encrypted_account_private_key);
user.set_password(
&data.account_unlock_data.master_password_unlock_data.master_key_authentication_hash,
Some(data.account_unlock_data.master_password_unlock_data.master_key_encrypted_user_key),
true,
None,
&conn,
)
.await?;
user.akey = data.wrapped_user_key;
if let Some(new_password_hash) = data.new_password_hash {
user.set_password(&new_password_hash, None, false, None, &conn).await?;
}
// An upgrade keeps the sessions alive, see `is_upgrade` above
if !is_upgrade {
user.reset_security_stamp_after_key_rotation(&conn).await?;
}
// The key pair goes first: if saving the user then fails during an upgrade, the account is still
// v1 and the key pair unused, instead of a v2 account without one, which no client could unlock.
// A failure between the two writes of a v2 rotation still needs a transaction to undo.
data.account_keys.save_signature_key_pair(&user.uuid, &conn).await?;
user.save(&conn).await?;
let save_result = user.save(&conn).await;
// Prevent logging out the client where the user requested this endpoint from.
// If you do logout the user it will causes issues at the client side.
// Adding the device uuid will prevent this.
// When the sessions were kept alive, the reason lets the other clients sync the new keys (through
// the upgrade token) instead of logging out, if they have `pm-31050-no-logout-key-upgrade-rotation`.
let reason = is_upgrade.then_some(LogOutReason::KeyRotation);
nt.send_logout_with_reason(&user, Some(&headers.device), reason, &conn).await;
nt.send_logout(&user, Some(&headers.device), &conn).await;
Ok(())
}
/// Rotates the account keys without changing the master password.
///
/// Unlike `rotate-user-account-keys` this carries no proof of the master password: the request is
/// authorized by the session alone, which is how upstream defines it, and the client has to be
/// unlocked to produce the payload in the first place.
///
/// Ref: <https://github.com/bitwarden/server/blob/main/src/Api/KeyManagement/Controllers/AccountsKeyManagementController.cs>
#[post("/accounts/key-management/rotate-user-keys", data = "<data>")]
async fn post_rotate_user_keys(
data: Json<RotateUserKeysData>,
headers: Headers,
conn: DbConn,
nt: Notify<'_>,
) -> EmptyResult {
let data: RotateUserKeysData = data.into_inner();
let wrapped_user_key = match UnlockMethod::from_i32(data.unlock_method_data.unlock_method) {
Some(UnlockMethod::MasterPassword) => {
let Some(unlock_data) = data.unlock_method_data.master_password_unlock_data else {
err!("Missing master password unlock data")
};
if !unlock_data.kdf.is_unchanged_for(&headers.user) {
err!("Changing the kdf variant is not supported during key rotation")
}
if unlock_data.salt != headers.user.email {
err!("Invalid master password salt")
}
validate_contained_key_id(unlock_data.contained_key_id.as_ref(), data.new_user_key_id.as_ref())?;
unlock_data.master_key_wrapped_user_key
}
Some(UnlockMethod::Tde) => err!("Trusted device encryption is not supported"),
Some(UnlockMethod::KeyConnector) => err!("Key connector is not supported"),
None => err!("Unrecognized unlock method"),
};
rotate_account(
RotateData {
account_keys: data.wrapped_account_cryptographic_state.validate()?,
account_data: data.account_data,
unlock_data: data.unlock_data,
new_user_key_id: data.new_user_key_id,
wrapped_user_key,
new_password_hash: None,
},
headers,
conn,
nt,
)
.await
save_result
}
#[derive(Deserialize)]
+9 -12
View File
@@ -197,14 +197,11 @@ async fn sync(data: SyncData, headers: Headers, client_version: Option<ClientVer
Value::Null
};
// Upstream omits these two when unset rather than sending null.
// Upstream omits this when unset rather than sending null.
let mut user_decryption = json!({ "masterPasswordUnlock": master_password_unlock });
if let Some(key_id) = &headers.user.key_id {
user_decryption["userKeyId"] = json!(key_id);
}
if let Some(v2_upgrade_token) = headers.user.v2_upgrade_token_json() {
user_decryption["v2UpgradeToken"] = v2_upgrade_token;
}
Ok(Json(json!({
"profile": user_json,
@@ -2268,8 +2265,15 @@ impl CipherSyncData {
}
}
// Generate a HashMap with the Organization UUID as key and the Membership record
let members: HashMap<OrganizationId, Membership> = Membership::find_confirmed_by_user(user_id, conn)
.await
.into_iter()
.map(|m| (m.org_uuid.clone(), m))
.collect();
// Generate a list of Cipher UUID's containing a Vec with one or more Attachment records
let orgs = Membership::get_orgs_by_user(user_id, conn).await;
let orgs: Vec<OrganizationId> = members.keys().cloned().collect();
let attachments = Attachment::find_all_by_user_and_orgs(user_id, &orgs, conn).await;
let mut cipher_attachments: HashMap<CipherId, Vec<Attachment>> = HashMap::with_capacity(attachments.len());
for attachment in attachments {
@@ -2284,13 +2288,6 @@ impl CipherSyncData {
cipher_collections.entry(cipher).or_default().push(collection);
}
// Generate a HashMap with the Organization UUID as key and the Membership record
let members: HashMap<OrganizationId, Membership> = Membership::find_confirmed_by_user(user_id, conn)
.await
.into_iter()
.map(|m| (m.org_uuid.clone(), m))
.collect();
// Generate a HashMap with the User_Collections UUID as key and the CollectionUser record
let user_collections: HashMap<CollectionId, CollectionUser> = CollectionUser::find_by_user(user_id, conn)
.await
+14 -8
View File
@@ -415,8 +415,9 @@ async fn get_org_collections_details(org_id: OrganizationId, headers: ManagerHea
let col_users = CollectionUser::find_by_organization_swap_user_uuid_with_member_uuid(&org_id, &conn).await;
// Generate a HashMap to get the correct MembershipType per user to determine the manage permission
// We use the uuid instead of the user_uuid here, since that is what is used in CollectionUser
// This lists other members for admins, so it must not depend on the membership status
let membership_type: HashMap<MembershipId, i32> =
Membership::find_confirmed_by_org(&org_id, &conn).await.into_iter().map(|m| (m.uuid, m.atype)).collect();
Membership::find_by_org(&org_id, &conn).await.into_iter().map(|m| (m.uuid, m.atype)).collect();
// check if current user has full access to the organization (either directly or via any group)
let has_full_access_to_org = member.has_full_access()
@@ -818,11 +819,9 @@ async fn get_org_collection_detail(
// Generate a HashMap to get the correct MembershipType per user to determine the manage permission
// We use the uuid instead of the user_uuid here, since that is what is used in CollectionUser
let membership_type: HashMap<MembershipId, i32> = Membership::find_confirmed_by_org(&org_id, &conn)
.await
.into_iter()
.map(|m| (m.uuid, m.atype))
.collect();
// This lists other members for admins, so it must not depend on the membership status
let membership_type: HashMap<MembershipId, i32> =
Membership::find_by_org(&org_id, &conn).await.into_iter().map(|m| (m.uuid, m.atype)).collect();
let users: Vec<Value> =
CollectionUser::find_by_org_and_coll_swap_user_uuid_with_member_uuid(&org_id, &collection.uuid, &conn)
@@ -960,8 +959,9 @@ async fn get_members(
let mut users_json = Vec::new();
for u in Membership::find_by_org(&org_id, &conn).await {
// The user can be a manager instead of an admin, but we've checked above that they have full access
users_json.push(
u.to_json_user_details(
u.to_json_details_for_admin(
data.include_collections.unwrap_or(false),
data.include_groups.unwrap_or(false),
&conn,
@@ -1516,7 +1516,9 @@ async fn get_user(
// In this case, when groups are requested we also need to include collections.
// Else these will not be shown in the interface, and could lead to missing collections when saved.
let include_groups = data.include_groups.unwrap_or(false);
Ok(Json(user.to_json_user_details(data.include_collections.unwrap_or(include_groups), include_groups, &conn).await))
Ok(Json(
user.to_json_details_for_admin(data.include_collections.unwrap_or(include_groups), include_groups, &conn).await,
))
}
#[derive(Deserialize)]
@@ -1835,6 +1837,10 @@ async fn post_org_import(
if org_id != headers.membership.org_uuid {
err!("Organization not found", "Organization id's do not match");
}
// OrgMemberHeaders also allows invited and accepted members, which are not allowed to import
if headers.membership.status != MembershipStatus::Confirmed as i32 {
err!("You need to be a Member of the Organization to call this endpoint")
}
let data: ImportData = data.into_inner();
// Validate the import before continuing
+1 -1
View File
@@ -23,7 +23,7 @@ pub use crate::api::{
icons::routes as icons_routes,
identity::routes as identity_routes,
notifications::routes as notifications_routes,
notifications::{AnonymousNotify, LogOutReason, Notify, UpdateType, WS_ANONYMOUS_SUBSCRIPTIONS, WS_USERS},
notifications::{AnonymousNotify, Notify, UpdateType, WS_ANONYMOUS_SUBSCRIPTIONS, WS_USERS},
push::{
push_cipher_update, push_folder_update, push_logout, push_send_update, push_user_update, register_push_device,
unregister_push_device,
+6 -28
View File
@@ -383,36 +383,23 @@ impl WebSocketUsers {
}
pub async fn send_logout(&self, user: &User, acting_device: Option<&Device>, conn: &DbConn) {
self.send_logout_with_reason(user, acting_device, None, conn).await;
}
/// A logout that clients may handle differently depending on `reason`, e.g. syncing instead of
/// logging out after a key rotation that kept the sessions alive.
pub async fn send_logout_with_reason(
&self,
user: &User,
acting_device: Option<&Device>,
reason: Option<LogOutReason>,
conn: &DbConn,
) {
// Skip any processing if both WebSockets and Push are not active
if *NOTIFICATIONS_DISABLED {
return;
}
let acting_device_id = acting_device.map(|d| d.uuid.clone());
let mut payload =
vec![("UserId".into(), user.uuid.to_string().into()), ("Date".into(), serialize_date(user.updated_at))];
if let Some(reason) = reason {
payload.push(("Reason".into(), (reason as i32).into()));
}
let data = create_update(payload, UpdateType::LogOut, acting_device_id);
let data = create_update(
vec![("UserId".into(), user.uuid.to_string().into()), ("Date".into(), serialize_date(user.updated_at))],
UpdateType::LogOut,
acting_device_id,
);
if CONFIG.enable_websocket() {
self.send_update(&user.uuid, &data).await;
}
if CONFIG.push_enabled() {
push_logout(user, acting_device, reason, conn).await;
push_logout(user, acting_device, conn).await;
}
}
@@ -680,15 +667,6 @@ fn create_ping() -> Vec<u8> {
serialize(&Value::Array(vec![6.into()]))
}
/// Why a logout was pushed. Absent for a plain logout.
///
/// Ref: <https://github.com/bitwarden/server/blob/main/src/Core/Enums/PushNotificationLogOutReason.cs>
/// (`KdfChange = 0` is not sent by vaultwarden yet.)
#[derive(Copy, Clone, Eq, PartialEq)]
pub enum LogOutReason {
KeyRotation = 1,
}
// https://github.com/bitwarden/server/blob/375af7c43b10d9da03525d41452f95de3f921541/src/Core/Enums/PushType.cs
#[derive(Copy, Clone, Eq, PartialEq)]
pub enum UpdateType {
+3 -4
View File
@@ -12,7 +12,7 @@ use tokio::sync::RwLock;
use crate::{
CONFIG,
api::{ApiResult, EmptyResult, LogOutReason, UpdateType},
api::{ApiResult, EmptyResult, UpdateType},
db::{
DbConn,
models::{AuthRequestId, Cipher, Device, Folder, PushId, Send, User, UserId},
@@ -188,7 +188,7 @@ pub async fn push_cipher_update(ut: UpdateType, cipher: &Cipher, device: &Device
}
}
pub async fn push_logout(user: &User, acting_device: Option<&Device>, reason: Option<LogOutReason>, conn: &DbConn) {
pub async fn push_logout(user: &User, acting_device: Option<&Device>, conn: &DbConn) {
if Device::check_user_has_push_device(&user.uuid, conn).await {
tokio::task::spawn(send_to_push_relay(json!({
"userId": user.uuid,
@@ -198,8 +198,7 @@ pub async fn push_logout(user: &User, acting_device: Option<&Device>, reason: Op
"type": UpdateType::LogOut as i32,
"payload": {
"userId": user.uuid,
"date": format_date(&user.updated_at),
"reason": reason.map(|r| r as i32),
"date": format_date(&user.updated_at)
},
"clientType": null,
"installationId": null
+25 -7
View File
@@ -30,7 +30,7 @@ use crate::{
models::{
AttachmentId, CipherId, Collection, CollectionId, Device, DeviceId, DeviceType, EmergencyAccessId,
EventType, Membership, MembershipId, MembershipStatus, MembershipType, OrgApiKeyId, OrganizationId,
SendFileId, SendId, User, UserId,
SendFileId, SendId, User, UserId, UserStampException,
},
},
error::Error,
@@ -667,13 +667,31 @@ impl<'r> FromRequest<'r> for Headers {
};
if user.security_stamp != claims.sstamp {
let Some(current_route) = request.route().and_then(|r| r.name.as_deref()) else {
err_handler!("Error getting current route for stamp exception")
};
if let Some(stamp_exception) =
user.stamp_exception.as_deref().and_then(|s| serde_json::from_str::<UserStampException>(s).ok())
{
let Some(current_route) = request.route().and_then(|r| r.name.as_deref()) else {
err_handler!("Error getting current route for stamp exception")
};
// Expired exceptions are dropped the next time the stamp is reset, not here: writing them
// back from this request could undo a reset made since the user was read.
if !user.stamp_exceptions().iter().any(|e| e.allows(&claims.sstamp, current_route)) {
// Check if the stamp exception has expired first.
// Then, check if the current route matches any of the allowed routes.
// After that check the stamp in exception matches the one in the claims.
if Utc::now().timestamp() > stamp_exception.expire {
// If the stamp exception has been expired remove it from the database.
// This prevents checking this stamp exception for new requests.
let mut user = user;
user.reset_stamp_exception();
if let Err(e) = user.save(&conn).await {
error!("Error updating user: {e:#?}");
}
err_handler!("Stamp exception is expired")
} else if !stamp_exception.routes.contains(&current_route.to_owned()) {
err_handler!("Invalid security stamp: Current route and exception route do not match")
} else if stamp_exception.security_stamp != claims.sstamp {
err_handler!("Invalid security stamp for matched stamp exception")
}
} else {
err_handler!("Invalid security stamp")
}
}
-3
View File
@@ -1434,11 +1434,8 @@ pub const SUPPORTED_FEATURE_FLAGS: &[&str] = &[
"ssh-key-vault-item",
"pm-25373-windows-biometrics-v2",
"pm-26340-linux-biometrics-v2",
"pm-31050-no-logout-key-upgrade-rotation",
"pm-27278-v2-password-registration",
"enable-account-encryption-v2-jit-password-registration",
"pm-30144-sdk-key-rotation",
"force-upgrade-v2-encryption",
// Mobile Team
"anon-addy-self-host-alias",
"simple-login-self-host-alias",
+5
View File
@@ -1040,6 +1040,7 @@ impl Cipher {
.eq(ciphers_collections::collection_uuid)
.and(collections_groups::groups_uuid.eq(groups::uuid))),
)
.filter(users_organizations::status.eq(MembershipStatus::Confirmed as i32))
.filter(
users_organizations::access_all
.eq(true) // User has access all
@@ -1071,6 +1072,7 @@ impl Cipher {
.eq(ciphers_collections::collection_uuid)
.and(users_collections::user_uuid.eq(user_uuid.clone()))),
)
.filter(users_organizations::status.eq(MembershipStatus::Confirmed as i32))
.filter(
users_organizations::access_all
.eq(true) // User has access all
@@ -1115,6 +1117,7 @@ impl Cipher {
.eq(ciphers_collections::collection_uuid)
.and(collections_groups::groups_uuid.eq(groups::uuid))),
)
.filter(users_organizations::status.eq(MembershipStatus::Confirmed as i32))
.filter(
users_organizations::access_all
.eq(true) // User has access all
@@ -1147,6 +1150,7 @@ impl Cipher {
.eq(ciphers_collections::collection_uuid)
.and(users_collections::user_uuid.eq(user_uuid.clone()))),
)
.filter(users_organizations::status.eq(MembershipStatus::Confirmed as i32))
.filter(
users_organizations::access_all
.eq(true) // User has access all
@@ -1198,6 +1202,7 @@ impl Cipher {
.or_filter(users_organizations::atype.le(MembershipType::Admin as i32)) // User is admin or owner
.or_filter(groups::access_all.eq(true)) //Access via group
.or_filter(collections_groups::collections_uuid.is_not_null()) //Access via group
.filter(users_organizations::status.eq(MembershipStatus::Confirmed as i32))
.select(ciphers_collections::all_columns)
.distinct()
.load::<(CipherId, CollectionId)>(conn)
+17 -2
View File
@@ -367,6 +367,7 @@ impl Collection {
.and(collections_groups::collections_uuid.eq(collections::uuid))),
)
.filter(collections::uuid.eq(uuid))
.filter(users_organizations::status.eq(MembershipStatus::Confirmed as i32))
.filter(
users_collections::collection_uuid
.eq(uuid)
@@ -406,6 +407,7 @@ impl Collection {
.and(users_organizations::user_uuid.eq(user_uuid))),
)
.filter(collections::uuid.eq(uuid))
.filter(users_organizations::status.eq(MembershipStatus::Confirmed as i32))
.filter(users_collections::collection_uuid.eq(uuid).or(
// Directly accessed collection
users_organizations::access_all.eq(true).or(
@@ -430,7 +432,8 @@ impl Collection {
.inner_join(
users_organizations::table.on(collections::org_uuid
.eq(users_organizations::org_uuid)
.and(users_organizations::user_uuid.eq(user_uuid.clone()))),
.and(users_organizations::user_uuid.eq(user_uuid.clone()))
.and(users_organizations::status.eq(MembershipStatus::Confirmed as i32))),
)
.left_join(
users_collections::table.on(users_collections::collection_uuid
@@ -476,7 +479,8 @@ impl Collection {
.inner_join(
users_organizations::table.on(collections::org_uuid
.eq(users_organizations::org_uuid)
.and(users_organizations::user_uuid.eq(user_uuid.clone()))),
.and(users_organizations::user_uuid.eq(user_uuid.clone()))
.and(users_organizations::status.eq(MembershipStatus::Confirmed as i32))),
)
.left_join(
users_collections::table.on(users_collections::collection_uuid
@@ -527,6 +531,7 @@ impl Collection {
.and(collections_groups::collections_uuid.eq(collections::uuid))),
)
.filter(collections::uuid.eq(&self.uuid))
.filter(users_organizations::status.eq(MembershipStatus::Confirmed as i32))
.filter(
users_collections::collection_uuid
.eq(&self.uuid)
@@ -586,6 +591,7 @@ impl Collection {
.and(collections_groups::collections_uuid.eq(collections::uuid))),
)
.filter(collections::uuid.eq(&uuid))
.filter(users_organizations::status.eq(MembershipStatus::Confirmed as i32))
.filter(
users_collections::collection_uuid
.eq(&uuid)
@@ -650,6 +656,7 @@ impl Collection {
.and(collections_groups::collections_uuid.eq(collections::uuid))),
)
.filter(collections::org_uuid.eq(&org_uuid))
.filter(users_organizations::status.eq(MembershipStatus::Confirmed as i32))
.filter(
// Manage permission on a collection assigned directly or via a group.
users_collections::manage.eq(true).or(collections_groups::manage.eq(true)),
@@ -819,10 +826,18 @@ impl CollectionUser {
.await
}
// Only returns the collections of organizations the user is a confirmed member of
pub async fn find_by_user(user_uuid: &UserId, conn: &DbConn) -> Vec<Self> {
conn.run(move |conn| {
users_collections::table
.inner_join(collections::table.on(collections::uuid.eq(users_collections::collection_uuid)))
.inner_join(
users_organizations::table.on(users_organizations::org_uuid
.eq(collections::org_uuid)
.and(users_organizations::user_uuid.eq(users_collections::user_uuid))),
)
.filter(users_collections::user_uuid.eq(user_uuid))
.filter(users_organizations::status.eq(MembershipStatus::Confirmed as i32))
.select(users_collections::all_columns)
.load::<Self>(conn)
.expect("Error loading users_collections")
+2
View File
@@ -249,6 +249,7 @@ impl Group {
.and(groups::organizations_uuid.eq(users_organizations::org_uuid))),
)
.filter(users_organizations::user_uuid.eq(user_uuid))
.filter(users_organizations::status.eq(MembershipStatus::Confirmed as i32))
.filter(groups::access_all.eq(true))
.select(groups::organizations_uuid)
.distinct()
@@ -387,6 +388,7 @@ impl CollectionGroup {
.and(collections::org_uuid.eq(groups::organizations_uuid))),
)
.filter(users_organizations::user_uuid.eq(user_uuid))
.filter(users_organizations::status.eq(MembershipStatus::Confirmed as i32))
.select(collections_groups::all_columns)
.load::<Self>(conn)
.expect("Error loading user collection groups")
+1 -1
View File
@@ -40,5 +40,5 @@ pub use self::sso_auth::{OIDCAuthenticatedUser, OIDCCodeResponseError, SsoAuth};
pub use self::two_factor::{TwoFactor, TwoFactorType};
pub use self::two_factor_duo_context::TwoFactorDuoContext;
pub use self::two_factor_incomplete::TwoFactorIncomplete;
pub use self::user::{Invitation, KeyId, SsoUser, User, UserId, UserKdfType};
pub use self::user::{Invitation, KeyId, SsoUser, User, UserId, UserKdfType, UserStampException};
pub use self::user_signature_key_pair::{SignatureAlgorithm, UserSignatureKeyPair};
+22 -63
View File
@@ -1,7 +1,4 @@
use std::{
cmp::Ordering,
collections::{HashMap, HashSet},
};
use std::cmp::Ordering;
use chrono::{NaiveDateTime, Utc};
use derive_more::{AsRef, Deref, Display, From};
@@ -24,8 +21,8 @@ use crate::{
use macros::UuidFromParam;
use super::{
Cipher, CipherId, Collection, CollectionGroup, CollectionId, CollectionUser, Group, GroupId, GroupUser, OrgPolicy,
OrgPolicyType, TwoFactor, User, UserId,
Cipher, CipherId, Collection, CollectionId, CollectionUser, Group, GroupId, GroupUser, OrgPolicy, OrgPolicyType,
TwoFactor, User, UserId,
};
#[derive(Identifiable, Queryable, Insertable, AsChangeset)]
@@ -57,10 +54,6 @@ pub struct Membership {
pub atype: i32,
pub reset_password_key: Option<String>,
pub external_id: Option<String>,
/// A copy of the user's v2 upgrade token, kept when a v1 -> v2 upgrade leaves the account
/// recovery key (`reset_password_key`) wrapped by the v1 user key. It lets the organization
/// unwrap the v2 user key from it. Opaque to us, like `User::v2_upgrade_token`.
pub v2_upgrade_token: Option<String>,
}
#[derive(Identifiable, Queryable, Insertable, AsChangeset)]
@@ -278,7 +271,6 @@ impl Membership {
atype: MembershipType::User as i32,
reset_password_key: None,
external_id: None,
v2_upgrade_token: None,
}
}
@@ -541,7 +533,13 @@ impl Membership {
})
}
pub async fn to_json_user_details(&self, include_collections: bool, include_groups: bool, conn: &DbConn) -> Value {
// Used by admins to view other members, so nothing here may depend on this member's status
pub async fn to_json_details_for_admin(
&self,
include_collections: bool,
include_groups: bool,
conn: &DbConn,
) -> Value {
let user = User::find_by_uuid(&self.user_uuid, conn).await.unwrap();
// Because BitWarden want the status to be -1 for revoked users we need to catch that here.
@@ -564,52 +562,23 @@ impl Membership {
// Check if a user is in a group which has access to all collections
// If that is the case, we should not return individual collections!
// This is used by admins to view other members, so it must not depend on the membership status
let full_access_group =
CONFIG.org_groups_enabled() && Group::is_in_full_access_group(&self.user_uuid, &self.org_uuid, conn).await;
CONFIG.org_groups_enabled() && GroupUser::has_full_access_by_member(&self.org_uuid, &self.uuid, conn).await;
// If collections are to be included, only include them if the user does not have full access via a group or defined to the user it self
// Only the collections assigned directly are returned, the ones assigned via a group are returned via a special group endpoint
let collections: Vec<Value> = if include_collections && !(full_access_group || self.access_all) {
// Get all collections for the user here already to prevent more queries
let cu: HashMap<CollectionId, CollectionUser> =
CollectionUser::find_by_organization_and_user_uuid(&self.org_uuid, &self.user_uuid, conn)
.await
.into_iter()
.map(|cu| (cu.collection_uuid.clone(), cu))
.collect();
// Get all collection groups for this user to prevent there inclusion
let cg: HashSet<CollectionId> = CollectionGroup::find_by_user(&self.user_uuid, conn)
CollectionUser::find_by_organization_and_user_uuid(&self.org_uuid, &self.user_uuid, conn)
.await
.into_iter()
.map(|cg| cg.collections_uuid)
.collect();
Collection::find_by_organization_and_user_uuid(&self.org_uuid, &self.user_uuid, conn)
.await
.into_iter()
.filter_map(|c| {
let (read_only, hide_passwords, manage) = if self.has_full_access() {
(false, false, self.atype >= MembershipType::Manager)
} else if let Some(cu) = cu.get(&c.uuid) {
(
cu.read_only,
cu.hide_passwords,
cu.manage || (self.atype == MembershipType::Manager && !cu.read_only && !cu.hide_passwords),
)
// If previous checks failed it might be that this user has access via a group, but we should not return those elements here
// Those are returned via a special group endpoint
} else if cg.contains(&c.uuid) {
return None;
} else {
(true, true, false)
};
Some(json!({
"id": c.uuid,
"readOnly": read_only,
"hidePasswords": hide_passwords,
"manage": manage,
}))
.map(|cu| {
json!({
"id": cu.collection_uuid,
"readOnly": cu.read_only,
"hidePasswords": cu.hide_passwords,
"manage": cu.manage || (self.atype == MembershipType::Manager && !cu.read_only && !cu.hide_passwords),
})
})
.collect()
} else {
@@ -1037,17 +1006,6 @@ impl Membership {
.await
}
pub async fn get_orgs_by_user(user_uuid: &UserId, conn: &DbConn) -> Vec<OrganizationId> {
conn.run(move |conn| {
users_organizations::table
.filter(users_organizations::user_uuid.eq(user_uuid))
.select(users_organizations::org_uuid)
.load::<OrganizationId>(conn)
.unwrap_or_default()
})
.await
}
pub async fn find_by_user_and_policy(user_uuid: &UserId, policy_type: OrgPolicyType, conn: &DbConn) -> Vec<Self> {
conn.run(move |conn| {
users_organizations::table
@@ -1131,6 +1089,7 @@ impl Membership {
.and(ciphers::organization_uuid.eq(users_organizations::org_uuid.nullable()))),
)
.filter(users_organizations::user_uuid.eq(user_uuid))
.filter(users_organizations::status.eq(MembershipStatus::Confirmed as i32))
.filter(
users_organizations::atype.eq_any(vec![MembershipType::Owner as i32, MembershipType::Admin as i32]),
)
+8 -76
View File
@@ -6,7 +6,6 @@ use serde_json::Value;
use crate::{
CONFIG,
api::EmptyResult,
auth::DEFAULT_ACCESS_VALIDITY,
crypto,
db::{
DbConn,
@@ -79,9 +78,6 @@ pub struct User {
pub signed_public_key: Option<String>,
pub security_state: Option<String>,
pub security_version: Option<i32>,
/// JSON `{"wrappedUserKey1": ..., "wrappedUserKey2": ...}`, letting clients that still hold the
/// v1 user key obtain the v2 one after another client performed the upgrade. Opaque to us.
pub v2_upgrade_token: Option<String>,
}
#[derive(Identifiable, Queryable, Insertable)]
@@ -110,28 +106,13 @@ enum UserStatus {
_Disabled = 2,
}
/// A previous security stamp that is still accepted, until `expire`.
#[derive(Serialize, Deserialize)]
pub struct UserStampException {
/// The routes the stamp is still accepted on, or `None` for any route.
pub routes: Option<Vec<String>>,
pub routes: Vec<String>,
pub security_stamp: String,
pub expire: i64,
}
impl UserStampException {
pub fn is_expired(&self) -> bool {
Utc::now().timestamp() > self.expire
}
/// Whether this exception lets a token carrying `security_stamp` through on `route`.
pub fn allows(&self, security_stamp: &str, route: &str) -> bool {
!self.is_expired()
&& self.security_stamp == security_stamp
&& self.routes.as_ref().is_none_or(|routes| routes.iter().any(|r| r == route))
}
}
/// Local methods
impl User {
pub const CLIENT_KDF_TYPE_DEFAULT: i32 = UserKdfType::Pbkdf2 as i32;
@@ -188,7 +169,6 @@ impl User {
signed_public_key: None,
security_state: None,
security_version: None,
v2_upgrade_token: None,
}
}
@@ -255,41 +235,10 @@ impl User {
pub async fn reset_security_stamp(&mut self, conn: &DbConn) -> EmptyResult {
self.security_stamp = get_uuid();
// A reset is meant to end the other sessions, which a key rotation's grace would undo. The
// route exceptions stay, since they are set right before a reset, for the stamp it replaces.
// This is also where expired exceptions get dropped.
let mut exceptions = self.stamp_exceptions();
exceptions.retain(|e| e.routes.is_some() && !e.is_expired());
self.set_stamp_exceptions(&exceptions);
Device::rotate_refresh_tokens_by_user(&self.uuid, conn).await?;
Ok(())
}
/// Resets the security stamp after a key rotation, while letting the access tokens already
/// issued keep working until they expire.
///
/// This is what upstream does: there the stamp is only checked when a token is refreshed, so a
/// rotation invalidates refresh tokens but not the access tokens in use. Clients rely on it to
/// keep a session going across a rotation. Chained rotations keep every earlier stamp that is
/// still within its window.
pub async fn reset_security_stamp_after_key_rotation(&mut self, conn: &DbConn) -> EmptyResult {
let previous_stamp = self.security_stamp.clone();
let mut grace: Vec<UserStampException> =
self.stamp_exceptions().into_iter().filter(|e| e.routes.is_none() && !e.is_expired()).collect();
self.reset_security_stamp(conn).await?;
grace.push(UserStampException {
routes: None,
security_stamp: previous_stamp,
expire: (Utc::now() + *DEFAULT_ACCESS_VALIDITY).timestamp(),
});
let mut exceptions = self.stamp_exceptions();
exceptions.extend(grace);
self.set_stamp_exceptions(&exceptions);
Ok(())
}
/// Set the stamp_exception to only allow a subsequent request matching a specific route using the current security-stamp.
///
/// # Arguments
@@ -298,30 +247,17 @@ impl User {
/// After these 2 minutes this stamp will expire.
///
pub fn set_stamp_exception(&mut self, route_exception: Vec<String>) {
self.set_stamp_exceptions(&[UserStampException {
routes: Some(route_exception),
let stamp_exception = UserStampException {
routes: route_exception,
security_stamp: self.security_stamp.clone(),
expire: (Utc::now() + TimeDelta::try_minutes(2).unwrap()).timestamp(),
}]);
};
self.stamp_exception = Some(serde_json::to_string(&stamp_exception).unwrap_or_default());
}
/// The previous security stamps that are still accepted, expired ones included.
pub fn stamp_exceptions(&self) -> Vec<UserStampException> {
let Some(stored) = self.stamp_exception.as_deref() else {
return Vec::new();
};
// Before key rotations kept sessions alive, only a single route exception was stored.
serde_json::from_str::<Vec<UserStampException>>(stored)
.or_else(|_| serde_json::from_str::<UserStampException>(stored).map(|e| vec![e]))
.unwrap_or_default()
}
fn set_stamp_exceptions(&mut self, exceptions: &[UserStampException]) {
self.stamp_exception = if exceptions.is_empty() {
None
} else {
Some(serde_json::to_string(&exceptions).unwrap_or_default())
};
/// Resets the stamp_exception to prevent re-use of the previous security-stamp
pub fn reset_stamp_exception(&mut self) {
self.stamp_exception = None;
}
pub fn display_name(&self) -> &str {
@@ -387,10 +323,6 @@ impl User {
})
}
pub fn v2_upgrade_token_json(&self) -> Option<Value> {
self.v2_upgrade_token.as_ref().and_then(|token| serde_json::from_str(token).ok())
}
pub async fn to_json(&self, conn: &DbConn) -> Value {
let mut orgs_json = Vec::new();
for c in Membership::find_confirmed_by_user(&self.uuid, conn).await {
-2
View File
@@ -221,7 +221,6 @@ table! {
signed_public_key -> Nullable<Text>,
security_state -> Nullable<Text>,
security_version -> Nullable<Integer>,
v2_upgrade_token -> Nullable<Text>,
}
}
@@ -259,7 +258,6 @@ table! {
atype -> Integer,
reset_password_key -> Nullable<Text>,
external_id -> Nullable<Text>,
v2_upgrade_token -> Nullable<Text>,
}
}