Compare commits

...
18 changed files with 910 additions and 255 deletions

No files matched your search

+1
View File
@@ -15,6 +15,7 @@ extend-ignore-re = [
"(?i)helo_name", "(?i)helo_name",
"Server name sent during.+HELO", "Server name sent during.+HELO",
# COSE Is short for CBOR Object Signing and Encryption, ignore these specific items # COSE Is short for CBOR Object Signing and Encryption, ignore these specific items
"COSE",
"COSEKey", "COSEKey",
"COSEAlgorithm", "COSEAlgorithm",
# Ignore this specific string as it's valid # Ignore this specific string as it's valid
+1 -1
View File
@@ -107,7 +107,7 @@ serde = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.151" serde_json = "1.0.151"
# A safe, extensible ORM and Query builder # A safe, extensible ORM and Query builder
diesel = { version = "2.3.13", features = ["chrono", "r2d2", "numeric"] } diesel = { version = "2.3.13", features = ["chrono", "r2d2", "numeric", "64-column-tables"] }
diesel_migrations = "2.3.2" diesel_migrations = "2.3.2"
derive_more = { version = "2.1.1", features = [ derive_more = { version = "2.1.1", features = [
@@ -0,0 +1,5 @@
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;
@@ -0,0 +1,14 @@
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;
CREATE TABLE user_signature_key_pairs (
uuid CHAR(36) NOT NULL PRIMARY KEY,
user_uuid CHAR(36) NOT NULL UNIQUE,
signature_algorithm INTEGER NOT NULL, -- 0 = ed25519, 1 = mldsa44
signing_key TEXT NOT NULL,
verifying_key TEXT NOT NULL,
created_at DATETIME NOT NULL,
updated_at DATETIME NOT NULL,
FOREIGN KEY (user_uuid) REFERENCES users (uuid) ON DELETE CASCADE
);
@@ -0,0 +1,5 @@
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;
@@ -0,0 +1,13 @@
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;
CREATE TABLE user_signature_key_pairs (
uuid CHAR(36) NOT NULL PRIMARY KEY,
user_uuid CHAR(36) NOT NULL UNIQUE REFERENCES users (uuid) ON DELETE CASCADE,
signature_algorithm INTEGER NOT NULL, -- 0 = ed25519, 1 = mldsa44
signing_key TEXT NOT NULL,
verifying_key TEXT NOT NULL,
created_at TIMESTAMP NOT NULL,
updated_at TIMESTAMP NOT NULL
);
@@ -0,0 +1,5 @@
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;
@@ -0,0 +1,13 @@
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;
CREATE TABLE user_signature_key_pairs (
uuid TEXT NOT NULL PRIMARY KEY,
user_uuid TEXT NOT NULL UNIQUE REFERENCES users (uuid) ON DELETE CASCADE,
signature_algorithm INTEGER NOT NULL, -- 0 = ed25519, 1 = mldsa44
signing_key TEXT NOT NULL,
verifying_key TEXT NOT NULL,
created_at DATETIME NOT NULL,
updated_at DATETIME NOT NULL
);
+346 -64
View File
@@ -22,8 +22,8 @@ use crate::{
models::{ models::{
AuthRequest, AuthRequestId, Cipher, CipherId, Device, DeviceId, DeviceType, DeviceWithAuthRequest, AuthRequest, AuthRequestId, Cipher, CipherId, Device, DeviceId, DeviceType, DeviceWithAuthRequest,
EmergencyAccess, EmergencyAccessId, EventType, Folder, FolderId, Invitation, KeyId, Membership, EmergencyAccess, EmergencyAccessId, EventType, Folder, FolderId, Invitation, KeyId, Membership,
MembershipId, OrgPolicy, OrgPolicyType, Organization, OrganizationId, Send, SendId, User, UserId, MembershipId, OrgPolicy, OrgPolicyType, Organization, OrganizationId, Send, SendId, SignatureAlgorithm,
UserKdfType, User, UserId, UserKdfType, UserSignatureKeyPair,
}, },
}, },
mail, mail,
@@ -42,6 +42,7 @@ pub fn routes() -> Vec<rocket::Route> {
post_profile, post_profile,
put_avatar, put_avatar,
get_public_keys, get_public_keys,
get_account_public_keys,
get_keys, get_keys,
post_keys, post_keys,
post_password, post_password,
@@ -104,6 +105,9 @@ pub struct RegisterData {
#[serde(alias = "userAsymmetricKeys")] #[serde(alias = "userAsymmetricKeys")]
keys: Option<KeysData>, keys: Option<KeysData>,
// Supersedes `keys`, and the only way a v2 account can be registered.
account_keys: Option<AccountKeysData>,
master_password_hint: Option<String>, master_password_hint: Option<String>,
organization_user_id: Option<MembershipId>, organization_user_id: Option<MembershipId>,
@@ -115,36 +119,6 @@ pub struct RegisterData {
org_invite_token: Option<String>, org_invite_token: Option<String>,
} }
impl RegisterData {
fn hash(&self) -> String {
self.compat.fold(|rdc| &rdc.master_password_hash, |rdcu| &rdcu.master_password_authentication.hash).to_owned()
}
fn kdf(&self) -> &KDFData {
self.compat.fold(|rdc| &rdc.kdf, |rdcu| &rdcu.master_password_authentication.kdf)
}
fn key(&self) -> String {
self.compat.fold(|rdc| &rdc.key, |rdcu| &rdcu.master_password_unlock.key).to_owned()
}
// When comparing with salt, email need to be normalized:
// - https://github.com/bitwarden/clients/blob/web-v2026.5.0/libs/common/src/key-management/master-password/services/master-password.service.ts#L171
fn unprocessable(&self) -> bool {
let mut unprocessable = false;
*self.compat.fold(
|_| &false,
|rdcu| {
let email = self.email.trim().to_lowercase();
unprocessable = rdcu.master_password_authentication.kdf != rdcu.master_password_unlock.kdf
|| rdcu.master_password_authentication.salt != email
|| rdcu.master_password_unlock.salt != email;
&unprocessable
},
)
}
}
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
struct RegisterDataOld { struct RegisterDataOld {
#[serde(flatten)] #[serde(flatten)]
@@ -184,6 +158,42 @@ impl RegisterDataCompat {
RegisterDataCompat::RegisterDataCur(rdcu) => fcu(rdcu), RegisterDataCompat::RegisterDataCur(rdcu) => fcu(rdcu),
} }
} }
fn hash(&self) -> String {
self.fold(|rdc| &rdc.master_password_hash, |rdcu| &rdcu.master_password_authentication.hash).to_owned()
}
fn kdf(&self) -> &KDFData {
self.fold(|rdc| &rdc.kdf, |rdcu| &rdcu.master_password_authentication.kdf)
}
fn key(&self) -> String {
self.fold(|rdc| &rdc.key, |rdcu| &rdcu.master_password_unlock.key).to_owned()
}
/// The id of the user key, which only the current format carries.
fn key_id(&self) -> Option<KeyId> {
match self {
RegisterDataCompat::RegisterDataOld(_) => None,
RegisterDataCompat::RegisterDataCur(rdcu) => rdcu.master_password_unlock.contained_key_id.clone(),
}
}
// When comparing with salt, email need to be normalized:
// - https://github.com/bitwarden/clients/blob/web-v2026.5.0/libs/common/src/key-management/master-password/services/master-password.service.ts#L171
fn unprocessable(&self, email: &str) -> bool {
let mut unprocessable = false;
*self.fold(
|_| &false,
|rdcu| {
let email = email.trim().to_lowercase();
unprocessable = rdcu.master_password_authentication.kdf != rdcu.master_password_unlock.kdf
|| rdcu.master_password_authentication.salt != email
|| rdcu.master_password_unlock.salt != email;
&unprocessable
},
)
}
} }
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
@@ -193,6 +203,183 @@ struct KeysData {
public_key: String, public_key: String,
} }
/// The `accountKeys` payload, which replaces the flat `keys`/`userAsymmetricKeys` object.
///
/// It carries either a "v1" state (just the encryption key pair) or a "v2" one, which adds a
/// signature key pair, a signed public key, and a signed security state. The two deprecated
/// top-level fields are still sent by the SDK alongside the nested ones and are only used as a
/// fallback for clients that don't send `publicKeyEncryptionKeyPair` yet.
///
/// Ref: <https://github.com/bitwarden/server/blob/main/src/Core/KeyManagement/Models/Api/Request/AccountKeysRequestModel.cs>
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AccountKeysData {
user_key_encrypted_account_private_key: Option<String>,
account_public_key: Option<String>,
public_key_encryption_key_pair: Option<PublicKeyEncryptionKeyPairData>,
signature_key_pair: Option<SignatureKeyPairData>,
security_state: Option<SecurityStateData>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct PublicKeyEncryptionKeyPairData {
wrapped_private_key: String,
public_key: String,
signed_public_key: Option<String>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct SignatureKeyPairData {
signature_algorithm: String,
wrapped_signing_key: String,
verifying_key: String,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct SecurityStateData {
security_state: String,
security_version: i32,
}
pub struct ValidatedAccountKeys {
private_key: String,
public_key: String,
v2: Option<ValidatedV2AccountKeys>,
}
struct ValidatedV2AccountKeys {
signed_public_key: String,
signing_key: String,
verifying_key: String,
signature_algorithm: SignatureAlgorithm,
security_state: String,
security_version: i32,
}
impl AccountKeysData {
/// Checks that the payload describes a complete account cryptographic state.
///
/// The v2 fields have to be all present or all absent: a client that receives a COSE-wrapped
/// private key without the matching signature key pair and security state refuses to unlock the
/// vault, so storing half a state would produce an account nobody can log into.
pub fn validate(self) -> ApiResult<ValidatedAccountKeys> {
let (private_key, public_key, signed_public_key) = if let Some(key_pair) = self.public_key_encryption_key_pair {
(key_pair.wrapped_private_key, key_pair.public_key, key_pair.signed_public_key)
// Older clients only send the deprecated top-level fields, which are always v1.
} else if let (Some(private_key), Some(public_key)) =
(self.user_key_encrypted_account_private_key, self.account_public_key)
{
(private_key, public_key, None)
} else {
err!("The account keys are missing an encryption key pair")
};
let v2 = match (signed_public_key, self.signature_key_pair, self.security_state) {
(Some(signed_public_key), Some(signature_key_pair), Some(security_state)) => {
let Some(signature_algorithm) = SignatureAlgorithm::parse(&signature_key_pair.signature_algorithm)
else {
err!(format!(
"Unsupported signature algorithm: {}",
signature_key_pair.signature_algorithm.escape_debug()
))
};
Some(ValidatedV2AccountKeys {
signed_public_key,
signing_key: signature_key_pair.wrapped_signing_key,
verifying_key: signature_key_pair.verifying_key,
signature_algorithm,
security_state: security_state.security_state,
security_version: security_state.security_version,
})
}
(None, None, None) => None,
_ => err!(
"Invalid account keys: the signed public key, signature key pair and security state must either all be present or all be absent"
),
};
Ok(ValidatedAccountKeys {
private_key,
public_key,
v2,
})
}
}
impl From<KeysData> for ValidatedAccountKeys {
fn from(keys: KeysData) -> Self {
Self {
private_key: keys.encrypted_private_key,
public_key: keys.public_key,
v2: None,
}
}
}
impl ValidatedAccountKeys {
/// The keys of a request that may carry either shape. `accountKeys` supersedes the flat `keys`
/// object when both are sent.
fn from_request(account_keys: Option<AccountKeysData>, keys: Option<KeysData>) -> ApiResult<Option<Self>> {
match (account_keys, keys) {
(Some(account_keys), _) => account_keys.validate().map(Some),
(None, keys) => Ok(keys.map(Self::from)),
}
}
fn is_v2(&self) -> bool {
self.v2.is_some()
}
/// Writes the parts of the state that live on the user itself. The user still needs saving, and
/// [`Self::save_signature_key_pair`] still needs calling once it has been.
///
/// Rejects downgrading an account from v2 back to v1.
pub fn apply(&self, user: &mut User) -> EmptyResult {
if user.is_v2() && self.v2.is_none() {
err!("Cannot downgrade an account from v2 to v1 encryption")
}
user.private_key = Some(self.private_key.clone());
user.public_key = Some(self.public_key.clone());
user.signed_public_key = self.v2.as_ref().map(|v2| v2.signed_public_key.clone());
user.security_state = self.v2.as_ref().map(|v2| v2.security_state.clone());
user.security_version = self.v2.as_ref().map(|v2| v2.security_version);
Ok(())
}
/// Persists the signature key pair. Separate from [`Self::apply`] because the row has a foreign
/// key to the user, so it can only be written once the user exists.
pub async fn save_signature_key_pair(&self, user_id: &UserId, conn: &DbConn) -> EmptyResult {
// Skip if the account is v1, since v1 accounts don't have a signature key pair.
let Some(v2) = &self.v2 else {
return Ok(());
};
let mut key_pair = match UserSignatureKeyPair::find_by_user(user_id, conn).await {
Some(mut key_pair) => {
key_pair.signature_algorithm = v2.signature_algorithm as i32;
key_pair.signing_key.clone_from(&v2.signing_key);
key_pair.verifying_key.clone_from(&v2.verifying_key);
key_pair
}
None => UserSignatureKeyPair::new(
user_id.clone(),
v2.signature_algorithm,
v2.signing_key.clone(),
v2.verifying_key.clone(),
),
};
key_pair.save(conn).await
}
}
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct MasterPasswordAuthentication { pub struct MasterPasswordAuthentication {
@@ -213,17 +400,19 @@ pub struct MasterPasswordUnlock {
#[serde(alias = "masterKeyWrappedUserKey")] #[serde(alias = "masterKeyWrappedUserKey")]
key: String, key: String,
contained_key_id: Option<KeyId>,
} }
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct SetPasswordData { pub struct SetPasswordData {
#[serde(flatten)] #[serde(flatten)]
kdf: KDFData, compat: RegisterDataCompat,
key: String,
keys: Option<KeysData>, keys: Option<KeysData>,
master_password_hash: String, // Supersedes `keys`, and the only way a v2 account can be initialized here.
account_keys: Option<AccountKeysData>,
master_password_hint: Option<String>, master_password_hint: Option<String>,
org_identifier: Option<String>, org_identifier: Option<String>,
} }
@@ -265,7 +454,7 @@ pub async fn register(data: Json<RegisterData>, conn: DbConn) -> JsonResult {
let mut name = None; let mut name = None;
let mut pending_emergency_access = None; let mut pending_emergency_access = None;
if data.unprocessable() { if data.compat.unprocessable(&data.email) {
err_code!("Unexpected RegisterData format", Status::UnprocessableEntity.code); err_code!("Unexpected RegisterData format", Status::UnprocessableEntity.code);
} }
@@ -334,10 +523,11 @@ pub async fn register(data: Json<RegisterData>, conn: DbConn) -> JsonResult {
err!("The field Name must be a string with a maximum length of 50."); err!("The field Name must be a string with a maximum length of 50.");
} }
// Check against the password hint setting here so if it fails, the user // Check against the password hint setting and the keys here so if they fail,
// can retry without losing their invitation below. // the user can retry without losing their invitation below.
let password_hint = clean_password_hint(data.master_password_hint.as_ref()); let password_hint = clean_password_hint(data.master_password_hint.as_ref());
enforce_password_hint_setting(password_hint.as_ref())?; enforce_password_hint_setting(password_hint.as_ref())?;
let account_keys = ValidatedAccountKeys::from_request(data.account_keys, data.keys)?;
let mut user = match User::find_by_mail(&email, &conn).await { let mut user = match User::find_by_mail(&email, &conn).await {
Some(user) => { Some(user) => {
@@ -384,9 +574,9 @@ pub async fn register(data: Json<RegisterData>, conn: DbConn) -> JsonResult {
// Make sure we don't leave a lingering invitation. // Make sure we don't leave a lingering invitation.
Invitation::take(&email, &conn).await; Invitation::take(&email, &conn).await;
set_kdf_data(&mut user, data.kdf())?; set_kdf_data(&mut user, data.compat.kdf())?;
user.set_password(&data.hash(), Some(data.key()), true, None, &conn).await?; user.set_password(&data.compat.hash(), Some(data.compat.key()), true, None, &conn).await?;
user.password_hint = password_hint; user.password_hint = password_hint;
// Add extra fields if present // Add extra fields if present
@@ -394,9 +584,13 @@ pub async fn register(data: Json<RegisterData>, conn: DbConn) -> JsonResult {
user.name = name; user.name = name;
} }
if let Some(keys) = data.keys { if let Some(ref account_keys) = account_keys {
user.private_key = Some(keys.encrypted_private_key); account_keys.apply(&mut user)?;
user.public_key = Some(keys.public_key); // Like upstream, only a v2 registration records the user key id. A v1 account reports it
// later, through `user-key-id`.
if account_keys.is_v2() {
user.key_id = data.compat.key_id();
}
} }
if email_verified { if email_verified {
@@ -420,6 +614,10 @@ pub async fn register(data: Json<RegisterData>, conn: DbConn) -> JsonResult {
user.save(&conn).await?; user.save(&conn).await?;
if let Some(account_keys) = account_keys {
account_keys.save_signature_key_pair(&user.uuid, &conn).await?;
}
// accept any open emergency access invitations // accept any open emergency access invitations
if !CONFIG.mail_enabled() && CONFIG.emergency_access_allowed() { if !CONFIG.mail_enabled() && CONFIG.emergency_access_allowed() {
for mut emergency_invite in EmergencyAccess::find_all_invited_by_grantee_email(&user.email, &conn).await { for mut emergency_invite in EmergencyAccess::find_all_invited_by_grantee_email(&user.email, &conn).await {
@@ -441,16 +639,22 @@ async fn post_set_password(data: Json<SetPasswordData>, headers: Headers, conn:
err!("Account already initialized, cannot set password") err!("Account already initialized, cannot set password")
} }
if data.compat.unprocessable(&user.email) {
err_code!("Unexpected SetPasswordData format", Status::UnprocessableEntity.code);
}
// Check against the password hint setting here so if it fails, // Check against the password hint setting here so if it fails,
// the user can retry without losing their invitation below. // the user can retry without losing their invitation below.
let password_hint = clean_password_hint(data.master_password_hint.as_ref()); let password_hint = clean_password_hint(data.master_password_hint.as_ref());
enforce_password_hint_setting(password_hint.as_ref())?; enforce_password_hint_setting(password_hint.as_ref())?;
set_kdf_data(&mut user, &data.kdf)?; let account_keys = ValidatedAccountKeys::from_request(data.account_keys, data.keys)?;
set_kdf_data(&mut user, data.compat.kdf())?;
user.set_password( user.set_password(
&data.master_password_hash, &data.compat.hash(),
Some(data.key), Some(data.compat.key()),
false, false,
Some(vec![String::from("revision_date")]), // We need to allow revision-date to use the old security_timestamp Some(vec![String::from("revision_date")]), // We need to allow revision-date to use the old security_timestamp
&conn, &conn,
@@ -458,9 +662,12 @@ async fn post_set_password(data: Json<SetPasswordData>, headers: Headers, conn:
.await?; .await?;
user.password_hint = password_hint; user.password_hint = password_hint;
if let Some(keys) = data.keys { if let Some(ref account_keys) = account_keys {
user.private_key = Some(keys.encrypted_private_key); account_keys.apply(&mut user)?;
user.public_key = Some(keys.public_key); // As in `register`, only a v2 account records the user key id here
if account_keys.is_v2() {
user.key_id = data.compat.key_id();
}
} }
if let Some(identifier) = data.org_identifier if let Some(identifier) = data.org_identifier
@@ -489,6 +696,10 @@ async fn post_set_password(data: Json<SetPasswordData>, headers: Headers, conn:
user.save(&conn).await?; user.save(&conn).await?;
if let Some(account_keys) = account_keys {
account_keys.save_signature_key_pair(&user.uuid, &conn).await?;
}
Ok(Json(json!({ Ok(Json(json!({
"object": "set-password", "object": "set-password",
}))) })))
@@ -569,8 +780,19 @@ async fn get_public_keys(user_id: UserId, _headers: Headers, conn: DbConn) -> Js
}))) })))
} }
#[get("/users/<user_id>/keys")]
async fn get_account_public_keys(user_id: UserId, _headers: Headers, conn: DbConn) -> JsonResult {
let user = match User::find_by_uuid(&user_id, &conn).await {
Some(user) if user.public_key.is_some() => user,
Some(_) => err_code!("User has no public_key", Status::NotFound.code),
None => err_code!("User doesn't exist", Status::NotFound.code),
};
Ok(Json(user.public_keys_json(&conn).await))
}
#[get("/accounts/keys")] #[get("/accounts/keys")]
fn get_keys(headers: Headers) -> JsonResult { async fn get_keys(headers: Headers, conn: DbConn) -> JsonResult {
let user = headers.user; let user = headers.user;
// The SDK reads a 404 as the user having no key pair yet // The SDK reads a 404 as the user having no key pair yet
@@ -582,29 +804,59 @@ fn get_keys(headers: Headers) -> JsonResult {
"key": (!user.akey.is_empty()).then_some(&user.akey), "key": (!user.akey.is_empty()).then_some(&user.akey),
"publicKey": user.public_key, "publicKey": user.public_key,
"privateKey": user.private_key, "privateKey": user.private_key,
"accountKeys": user.account_keys_json(), "accountKeys": user.account_keys_json(&conn).await,
"object": "keys", "object": "keys",
}))) })))
} }
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct PostKeysData {
#[serde(flatten)]
keys: Option<KeysData>,
account_keys: Option<AccountKeysData>,
// The id of the user key these account keys belong to, only honored for v2 `accountKeys`
user_key_id: Option<KeyId>,
}
#[post("/accounts/keys", data = "<data>")] #[post("/accounts/keys", data = "<data>")]
async fn post_keys(data: Json<KeysData>, headers: Headers, conn: DbConn) -> JsonResult { async fn post_keys(data: Json<PostKeysData>, headers: Headers, conn: DbConn) -> JsonResult {
let data: KeysData = data.into_inner(); let data: PostKeysData = data.into_inner();
let mut user = headers.user; let mut user = headers.user;
// This only sets the keys of an account that has none yet. Replacing existing ones is what a key
// rotation does, with the checks that go with it.
if user.private_key.is_some() || user.public_key.is_some() { if user.private_key.is_some() || user.public_key.is_some() {
err!("User has existing keypair") err!("User has existing keypair")
} }
user.private_key = Some(data.encrypted_private_key); // `accountKeys` supersedes the flat `keys` object when both are sent.
user.public_key = Some(data.public_key); let account_keys = match (data.account_keys, data.keys) {
(Some(account_keys), _) => {
let account_keys = account_keys.validate()?;
if !account_keys.is_v2() {
err!("AccountKeys are only supported for V2 encryption.")
}
// A client that predates key ids sends none, and reports it later through `user-key-id`
if data.user_key_id.is_some() {
user.key_id = data.user_key_id;
}
account_keys
}
(None, Some(keys)) => keys.into(),
(None, None) => err!("No account keys provided"),
};
account_keys.apply(&mut user)?;
user.save(&conn).await?; user.save(&conn).await?;
account_keys.save_signature_key_pair(&user.uuid, &conn).await?;
Ok(Json(json!({ Ok(Json(json!({
"key": (!user.akey.is_empty()).then_some(&user.akey),
"privateKey": user.private_key, "privateKey": user.private_key,
"publicKey": user.public_key, "publicKey": user.public_key,
"accountKeys": user.account_keys_json(&conn).await,
"object":"keys" "object":"keys"
}))) })))
} }
@@ -644,6 +896,8 @@ async fn post_password(data: Json<ChangePassData>, headers: Headers, conn: DbCon
err!("Invalid master password salt") err!("Invalid master password salt")
} }
validate_key_id_unchanged(&user, &unlock_data)?;
(authentication_data.master_password_authentication_hash, unlock_data.master_key_wrapped_user_key) (authentication_data.master_password_authentication_hash, unlock_data.master_key_wrapped_user_key)
} else if let (Some(new_master_password_hash), Some(new_key)) = (data.new_master_password_hash, data.key) { } else if let (Some(new_master_password_hash), Some(new_key)) = (data.new_master_password_hash, data.key) {
(new_master_password_hash, new_key) (new_master_password_hash, new_key)
@@ -732,6 +986,21 @@ struct UnlockData {
salt: String, salt: String,
kdf: KDFData, kdf: KDFData,
master_key_wrapped_user_key: String, master_key_wrapped_user_key: String,
contained_key_id: Option<KeyId>,
}
/// A password or KDF change re-wraps the same user key, so a key id sent with it has to be the
/// current one. Either may be missing: from a client that predates key ids, or a user whose key id
/// isn't known yet. There is nothing to compare in those cases.
///
/// Ref: <https://github.com/bitwarden/server/blob/main/src/Core/KeyManagement/Models/Data/MasterPasswordUnlockData.cs>
fn validate_key_id_unchanged(user: &User, unlock_data: &UnlockData) -> EmptyResult {
if let (Some(current), Some(contained)) = (&user.key_id, &unlock_data.contained_key_id)
&& current != contained
{
err!("Invalid user key sent in master-password unlock data.")
}
Ok(())
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@@ -758,6 +1027,8 @@ async fn post_kdf(data: Json<ChangeKdfData>, headers: Headers, conn: DbConn, nt:
err!("Invalid master password salt") err!("Invalid master password salt")
} }
validate_key_id_unchanged(&headers.user, &data.unlock_data)?;
let mut user = headers.user; let mut user = headers.user;
set_kdf_data(&mut user, &data.unlock_data.kdf)?; set_kdf_data(&mut user, &data.unlock_data.kdf)?;
@@ -933,6 +1204,16 @@ async fn post_rotatekey(data: Json<KeyData>, headers: Headers, conn: DbConn, nt:
err!("Invalid password") err!("Invalid password")
} }
// 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")
}
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 // Validate the import before continuing
// Bitwarden does not process the import if there is one item invalid. // Bitwarden does not process the import if there is one item invalid.
// Since we check for the size of the encrypted note length, we need to do that here to pre-validate it. // Since we check for the size of the encrypted note length, we need to do that here to pre-validate it.
@@ -1058,8 +1339,9 @@ struct KeyIdData {
#[post("/accounts/key-management/user-key-id", data = "<data>")] #[post("/accounts/key-management/user-key-id", data = "<data>")]
async fn post_user_key(data: Json<KeyIdData>, headers: Headers, conn: DbConn) -> EmptyResult { async fn post_user_key(data: Json<KeyIdData>, headers: Headers, conn: DbConn) -> EmptyResult {
let mut user = headers.user; let mut user = headers.user;
// Only a backfill for accounts that have none. Afterwards the id changes with the key, in a rotation.
if user.key_id.is_some() { if user.key_id.is_some() {
err_code!("Unexpected data", Status::UnprocessableEntity.code); err!("User key id is already set.")
} }
user.key_id = Some(data.into_inner().user_key_id); user.key_id = Some(data.into_inner().user_key_id);
@@ -1917,10 +2199,10 @@ mod tests {
) )
.unwrap(); .unwrap();
assert!(!data.unprocessable()); assert!(!data.compat.unprocessable(&data.email));
assert_eq!(data.hash(), "hash"); assert_eq!(data.compat.hash(), "hash");
assert_eq!(data.key(), "key"); assert_eq!(data.compat.key(), "key");
assert_eq!(data.kdf().kdf_iterations, 600_000); assert_eq!(data.compat.kdf().kdf_iterations, 600_000);
assert!(data.keys.is_some()); assert!(data.keys.is_some());
assert_eq!(data.email_verification_token.as_deref(), Some("token")); assert_eq!(data.email_verification_token.as_deref(), Some("token"));
} }
@@ -1942,10 +2224,10 @@ mod tests {
) )
.unwrap(); .unwrap();
assert!(!data.unprocessable()); assert!(!data.compat.unprocessable(&data.email));
assert_eq!(data.hash(), "hash"); assert_eq!(data.compat.hash(), "hash");
assert_eq!(data.key(), "key"); assert_eq!(data.compat.key(), "key");
assert_eq!(data.kdf().kdf_iterations, 600_000); assert_eq!(data.compat.kdf().kdf_iterations, 600_000);
assert!(data.keys.is_some()); assert!(data.keys.is_some());
} }
} }
+114 -29
View File
@@ -23,7 +23,8 @@ use crate::{
models::{ models::{
Archive, Attachment, AttachmentId, Cipher, CipherId, Collection, CollectionCipher, CollectionGroup, Archive, Attachment, AttachmentId, Cipher, CipherId, Collection, CollectionCipher, CollectionGroup,
CollectionId, CollectionUser, EventType, Favorite, Folder, FolderCipher, FolderId, Group, KeyId, CollectionId, CollectionUser, EventType, Favorite, Folder, FolderCipher, FolderId, Group, KeyId,
Membership, MembershipType, OrgPolicy, OrgPolicyType, OrganizationId, RepromptType, Send, UserId, Membership, MembershipType, OrgPolicy, OrgPolicyType, OrganizationId, RepromptType, Send, User, UserId,
is_data_blob_encrypted,
}, },
}, },
util::{NumberOrString, deser_opt_nonempty_str, save_temp_file}, util::{NumberOrString, deser_opt_nonempty_str, save_temp_file},
@@ -189,12 +190,19 @@ async fn sync(data: SyncData, headers: Headers, client_version: Option<ClientVer
// https://github.com/bitwarden/android/blob/release/2025.12-rc41/network/src/main/kotlin/com/bitwarden/network/model/MasterPasswordUnlockDataJson.kt#L22-L26 // https://github.com/bitwarden/android/blob/release/2025.12-rc41/network/src/main/kotlin/com/bitwarden/network/model/MasterPasswordUnlockDataJson.kt#L22-L26
"masterKeyEncryptedUserKey": headers.user.akey, "masterKeyEncryptedUserKey": headers.user.akey,
"masterKeyWrappedUserKey": headers.user.akey, "masterKeyWrappedUserKey": headers.user.akey,
"salt": headers.user.email "salt": headers.user.email,
"containedKeyId": headers.user.key_id,
}) })
} else { } else {
Value::Null Value::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);
}
Ok(Json(json!({ Ok(Json(json!({
"profile": user_json, "profile": user_json,
"folders": folders_json, "folders": folders_json,
@@ -204,10 +212,7 @@ async fn sync(data: SyncData, headers: Headers, client_version: Option<ClientVer
"ciphers": ciphers_json, "ciphers": ciphers_json,
"domains": domains_json, "domains": domains_json,
"sends": sends_json, "sends": sends_json,
"userDecryption": { "userDecryption": user_decryption,
"masterPasswordUnlock": master_password_unlock,
"userKeyId": headers.user.key_id,
},
"object": "sync" "object": "sync"
}))) })))
} }
@@ -284,7 +289,8 @@ pub struct CipherData {
Passport = 8 Passport = 8
*/ */
pub r#type: i32, pub r#type: i32,
pub name: String, // Absent on a blob-encrypted cipher, whose name is sealed inside `data`
pub name: Option<String>,
pub notes: Option<String>, pub notes: Option<String>,
fields: Option<Value>, fields: Option<Value>,
@@ -298,6 +304,9 @@ pub struct CipherData {
drivers_license: Option<Value>, drivers_license: Option<Value>,
passport: Option<Value>, passport: Option<Value>,
// The sealed blob of a v2 account's cipher, which replaces all of the fields above
data: Option<String>,
favorite: Option<bool>, favorite: Option<bool>,
reprompt: Option<i32>, reprompt: Option<i32>,
@@ -319,6 +328,70 @@ pub struct CipherData {
archived_date: Option<String>, archived_date: Option<String>,
} }
/// A field of a [`CipherData`] that fails upstream's model validation.
#[derive(Debug)]
pub struct CipherValidationError {
pub field: &'static str,
pub message: String,
}
impl From<CipherValidationError> for crate::Error {
fn from(e: CipherValidationError) -> Self {
Self::new_msg(e.message)
}
}
/// A user-owned cipher must be encrypted with the user's current key. Organization ciphers use the
/// organization key, which has no id yet, and either id may be missing: from a client that predates
/// the field, or a user whose key id isn't known yet. There is nothing to compare in those cases.
///
/// Ref: upstream's `CiphersController.ValidateCipherEncryptedByUser`
fn validate_encrypted_by_user_key(data: &CipherData, user: &User, is_org_cipher: bool) -> EmptyResult {
if !is_org_cipher
&& let (Some(cipher_key_id), Some(user_key_id)) = (&data.encrypted_by_key_id, &user.key_id)
&& cipher_key_id != user_key_id
{
err!("Cipher was not encrypted with the current user key. Please try again.")
}
Ok(())
}
/// Upstream's `[StringLength(500000)]` on `CipherRequestModel.Data`
const MAX_CIPHER_DATA_LENGTH: usize = 500_000;
impl CipherData {
/// Whether the content is a single blob rather than the per-type fields. This parses `data`, so
/// callers that need the answer more than once should keep it.
pub fn is_blob(&self) -> bool {
self.data.as_deref().is_some_and(is_data_blob_encrypted)
}
/// Checks the content the way upstream's model validation does, before anything is saved.
/// `is_blob` is [`Self::is_blob`].
///
/// Ref: <https://github.com/bitwarden/server/blob/main/src/Api/Vault/Models/Request/CipherRequestModel.cs>
pub fn validate_content(&self, is_blob: bool) -> Result<(), CipherValidationError> {
if let Some(data) = &self.data
&& data.len() > MAX_CIPHER_DATA_LENGTH
{
return Err(CipherValidationError {
field: "Data",
message: format!("The field Data must be a string with a maximum length of {MAX_CIPHER_DATA_LENGTH}."),
});
}
// A blob carries the name inside it, so only the other formats need one
if !is_blob && self.name.as_deref().is_none_or(|n| n.trim().is_empty()) {
return Err(CipherValidationError {
field: "Name",
message: String::from("The Name field is required."),
});
}
Ok(())
}
}
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct PartialCipherData { pub struct PartialCipherData {
@@ -355,13 +428,14 @@ async fn post_ciphers_create(
if data.cipher.encrypted_for != headers.user.uuid { if data.cipher.encrypted_for != headers.user.uuid {
err_code!("Invalid user cipher", Status::UnprocessableEntity.code); err_code!("Invalid user cipher", Status::UnprocessableEntity.code);
} }
validate_encrypted_by_user_key(&data.cipher, &headers.user, data.cipher.organization_id.is_some())?;
// This check is usually only needed in update_cipher_from_data(), but we // This check is usually only needed in update_cipher_from_data(), but we
// need it here as well to avoid creating an empty cipher in the call to // need it here as well to avoid creating an empty cipher in the call to
// cipher.save() below. // cipher.save() below.
enforce_personal_ownership_policy(Some(&data.cipher), &headers, &conn).await?; enforce_personal_ownership_policy(Some(&data.cipher), &headers, &conn).await?;
let mut cipher = Cipher::new(data.cipher.r#type, data.cipher.name.clone()); let mut cipher = Cipher::new(data.cipher.r#type, String::new());
cipher.user_uuid = Some(headers.user.uuid.clone()); cipher.user_uuid = Some(headers.user.uuid.clone());
cipher.save(&conn).await?; cipher.save(&conn).await?;
@@ -389,12 +463,7 @@ async fn post_ciphers(data: Json<CipherData>, headers: Headers, conn: DbConn, nt
err_code!("Invalid user cipher", Status::UnprocessableEntity.code); err_code!("Invalid user cipher", Status::UnprocessableEntity.code);
} }
if let Some(cipher_key_id) = &data.encrypted_by_key_id validate_encrypted_by_user_key(&data, &headers.user, data.organization_id.is_some())?;
&& let Some(user_key_id) = &headers.user.key_id
&& cipher_key_id != user_key_id
{
err_code!("Invalid key cipher", Status::UnprocessableEntity.code);
}
// The web/browser clients set this field to null as expected, but the // The web/browser clients set this field to null as expected, but the
// mobile clients seem to set the invalid value `0001-01-01T00:00:00`, // mobile clients seem to set the invalid value `0001-01-01T00:00:00`,
@@ -402,7 +471,7 @@ async fn post_ciphers(data: Json<CipherData>, headers: Headers, conn: DbConn, nt
// needed when creating a new cipher, so just ignore it unconditionally. // needed when creating a new cipher, so just ignore it unconditionally.
data.last_known_revision_date = None; data.last_known_revision_date = None;
let mut cipher = Cipher::new(data.r#type, data.name.clone()); let mut cipher = Cipher::new(data.r#type, String::new());
update_cipher_from_data(&mut cipher, data, &headers, None, &conn, &nt, UpdateType::SyncCipherCreate).await?; update_cipher_from_data(&mut cipher, data, &headers, None, &conn, &nt, UpdateType::SyncCipherCreate).await?;
Ok(Json(cipher.to_json(&headers.host, &headers.user.uuid, None, CipherSyncType::User, &conn).await?)) Ok(Json(cipher.to_json(&headers.host, &headers.user.uuid, None, CipherSyncType::User, &conn).await?))
@@ -451,6 +520,9 @@ pub async fn update_cipher_from_data(
enforce_personal_ownership_policy(Some(&data), headers, conn).await?; enforce_personal_ownership_policy(Some(&data), headers, conn).await?;
let is_blob = data.is_blob();
data.validate_content(is_blob)?;
// Check that the client isn't updating an existing cipher with stale data. // Check that the client isn't updating an existing cipher with stale data.
// And only perform this check when not importing ciphers, else the date/time check will fail. // And only perform this check when not importing ciphers, else the date/time check will fail.
if ut != UpdateType::None if ut != UpdateType::None
@@ -551,26 +623,37 @@ pub async fn update_cipher_from_data(
_ => err!("Invalid type"), _ => err!("Invalid type"),
}; };
let type_data = if let Some(mut data) = type_data_opt { if let Some(blob) = data.data.filter(|_| is_blob) {
// A blob holds all of the content, the name included, so nothing is kept outside it. The name
// column can't be null, so it's left empty; `to_json` reports it as null, as upstream does.
// TODO: Make `ciphers.name` nullable and store `None` here instead.
cipher.name = String::new();
cipher.notes = None;
cipher.fields = None;
cipher.password_history = None;
cipher.data = blob;
} else {
let Some(mut type_data) = type_data_opt else {
err!("Data missing")
};
// Remove the 'Response' key from the base object. // Remove the 'Response' key from the base object.
if let Some(data_obj) = data.as_object_mut() { if let Some(data_obj) = type_data.as_object_mut() {
data_obj.remove("response"); data_obj.remove("response");
} }
// Remove the 'Response' key from every Uri. // Remove the 'Response' key from every Uri.
if data["uris"].is_array() { if type_data["uris"].is_array() {
data["uris"] = clean_cipher_data(data["uris"].clone()); type_data["uris"] = clean_cipher_data(type_data["uris"].clone());
} }
data
} else { // `validate_content` made sure there is a name
err!("Data missing") cipher.name = data.name.unwrap_or_default();
}; cipher.notes = data.notes;
cipher.fields = data.fields.map(|f| clean_cipher_data(f).to_string());
cipher.password_history = data.password_history.map(|f| f.to_string());
cipher.data = type_data.to_string();
}
cipher.key = data.key; cipher.key = data.key;
cipher.name = data.name;
cipher.notes = data.notes;
cipher.fields = data.fields.map(|f| clean_cipher_data(f).to_string());
cipher.data = type_data.to_string();
cipher.password_history = data.password_history.map(|f| f.to_string());
cipher.reprompt = data.reprompt.filter(|r| *r == RepromptType::None as i32 || *r == RepromptType::Password as i32); cipher.reprompt = data.reprompt.filter(|r| *r == RepromptType::None as i32 || *r == RepromptType::Password as i32);
cipher.save(conn).await?; cipher.save(conn).await?;
@@ -667,7 +750,7 @@ async fn post_ciphers_import(data: Json<ImportData>, headers: Headers, conn: DbC
let folder_id = relations_map.get(&index).and_then(|i| folders.get(*i).cloned()); let folder_id = relations_map.get(&index).and_then(|i| folders.get(*i).cloned());
cipher_data.folder_id = folder_id; cipher_data.folder_id = folder_id;
let mut cipher = Cipher::new(cipher_data.r#type, cipher_data.name.clone()); let mut cipher = Cipher::new(cipher_data.r#type, String::new());
update_cipher_from_data(&mut cipher, cipher_data, &headers, None, &conn, &nt, UpdateType::None).await?; update_cipher_from_data(&mut cipher, cipher_data, &headers, None, &conn, &nt, UpdateType::None).await?;
} }
@@ -735,6 +818,8 @@ async fn put_cipher(
err!("Cipher is not write accessible") err!("Cipher is not write accessible")
} }
validate_encrypted_by_user_key(&data, &headers.user, cipher.organization_uuid.is_some())?;
update_cipher_from_data(&mut cipher, data, &headers, None, &conn, &nt, UpdateType::SyncCipherUpdate).await?; update_cipher_from_data(&mut cipher, data, &headers, None, &conn, &nt, UpdateType::SyncCipherUpdate).await?;
Ok(Json(cipher.to_json(&headers.host, &headers.user.uuid, None, CipherSyncType::User, &conn).await?)) Ok(Json(cipher.to_json(&headers.host, &headers.user.uuid, None, CipherSyncType::User, &conn).await?))
+1 -1
View File
@@ -1829,7 +1829,7 @@ async fn post_org_import(
cipher_data.folder_id = None; cipher_data.folder_id = None;
// Replace the client-provided, unvalidated organizationId with the real target org // Replace the client-provided, unvalidated organizationId with the real target org
cipher_data.organization_id = Some(org_id.clone()); cipher_data.organization_id = Some(org_id.clone());
let mut cipher = Cipher::new(cipher_data.r#type, cipher_data.name.clone()); let mut cipher = Cipher::new(cipher_data.r#type, String::new());
update_cipher_from_data( update_cipher_from_data(
&mut cipher, &mut cipher,
cipher_data, cipher_data,
+2 -24
View File
@@ -552,18 +552,7 @@ async fn authenticated_response(
Value::Null Value::Null
}; };
let account_keys = if user.private_key.is_some() { let account_keys = user.account_keys_json(conn).await;
json!({
"publicKeyEncryptionKeyPair": {
"wrappedPrivateKey": user.private_key,
"publicKey": user.public_key,
"Object": "publicKeyEncryptionKeyPair"
},
"Object": "privateKeys"
})
} else {
Value::Null
};
let mut result = json!({ let mut result = json!({
"access_token": auth_tokens.access_token(), "access_token": auth_tokens.access_token(),
@@ -709,18 +698,7 @@ async fn user_api_key_login(
Value::Null Value::Null
}; };
let account_keys = if user.private_key.is_some() { let account_keys = user.account_keys_json(conn).await;
json!({
"publicKeyEncryptionKeyPair": {
"wrappedPrivateKey": user.private_key,
"publicKey": user.public_key,
"Object": "publicKeyEncryptionKeyPair"
},
"Object": "privateKeys"
})
} else {
Value::Null
};
// Note: No refresh_token is returned. The CLI just repeats the // Note: No refresh_token is returned. The CLI just repeats the
// client_credentials login flow when the existing token expires. // client_credentials login flow when the existing token expires.
+2
View File
@@ -1424,6 +1424,8 @@ pub const SUPPORTED_FEATURE_FLAGS: &[&str] = &[
"ssh-agent-v2", "ssh-agent-v2",
// Key Management Team // Key Management Team
"windows-native-credential-sync", "windows-native-credential-sync",
"pm-27278-v2-password-registration",
"enable-account-encryption-v2-jit-password-registration",
// Mobile Team // Mobile Team
"pm-34171-card-scanner", "pm-34171-card-scanner",
// Platform Team // Platform Team
+154 -117
View File
@@ -63,6 +63,22 @@ pub struct Cipher {
pub reprompt: Option<i32>, pub reprompt: Option<i32>,
} }
/// Whether `data` is a sealed cipher blob rather than the legacy per-type JSON.
///
/// Ciphers of v2 accounts are encrypted as a single blob that carries everything, name included,
/// and is opaque to us. It is recognized the same way upstream does, by a top-level
/// `format_version` key that the legacy JSON never has.
///
/// Ref: <https://github.com/bitwarden/server/blob/main/src/Core/Vault/Entities/Cipher.cs>
pub fn is_data_blob_encrypted(data: &str) -> bool {
serde_json::from_str::<Value>(data).is_ok_and(|d| is_blob_value(&d))
}
/// [`is_data_blob_encrypted`] for `data` that was already parsed.
fn is_blob_value(data: &Value) -> bool {
data.get("format_version").is_some()
}
pub enum RepromptType { pub enum RepromptType {
None = 0, None = 0,
Password = 1, Password = 1,
@@ -110,6 +126,11 @@ impl Cipher {
.insert(format!("Ciphers[{index}].Notes"), serde_json::to_value([&max_note_size_msg]).unwrap()); .insert(format!("Ciphers[{index}].Notes"), serde_json::to_value([&max_note_size_msg]).unwrap());
} }
if let Err(e) = cipher.validate_content(cipher.is_blob()) {
validation_errors
.insert(format!("Ciphers[{index}].{}", e.field), serde_json::to_value([e.message]).unwrap());
}
// Validate the password history if it contains `null` values and if so, return a warning // Validate the password history if it contains `null` values and if so, return a warning
if let Some(Value::Array(password_history)) = &cipher.password_history { if let Some(Value::Array(password_history)) = &cipher.password_history {
for pwh in password_history { for pwh in password_history {
@@ -154,6 +175,11 @@ impl Cipher {
) -> Result<Value, crate::Error> { ) -> Result<Value, crate::Error> {
use crate::util::{format_date, validate_and_format_date}; use crate::util::{format_date, validate_and_format_date};
// Parsed once here, since `data` can be large and this runs for every cipher in a sync.
// `LowerCase` only lowercases the first letter of each key, so it keeps `format_version`.
let type_data = serde_json::from_str::<LowerCase<Value>>(&self.data).map(|d| d.data);
let is_blob_encrypted = type_data.as_ref().is_ok_and(is_blob_value);
let mut attachments_json: Value = Value::Null; let mut attachments_json: Value = Value::Null;
if let Some(cipher_sync_data) = cipher_sync_data { if let Some(cipher_sync_data) = cipher_sync_data {
if let Some(attachments) = cipher_sync_data.cipher_attachments.get(&self.uuid) if let Some(attachments) = cipher_sync_data.cipher_attachments.get(&self.uuid)
@@ -189,124 +215,62 @@ impl Cipher {
(false, false, false) (false, false, false)
}; };
let fields_json: Vec<_> = self // Like upstream, a cipher that was stored without fields or password history reports them as
.fields // null rather than as an empty list; clients keep the two apart.
.as_ref() let fields_json: Option<Vec<_>> = self.fields.as_ref().map(|s| {
.and_then(|s| { serde_json::from_str::<Vec<LowerCase<Value>>>(s)
serde_json::from_str::<Vec<LowerCase<Value>>>(s) .inspect_err(|e| warn!("Error parsing fields {e:?} for {}", self.uuid))
.inspect_err(|e| warn!("Error parsing fields {e:?} for {}", self.uuid)) .ok()
.ok() .map(|d| {
}) d.into_iter()
.map(|d| { .map(|mut f| {
d.into_iter() // Check if the `type` key is a number, strings break some clients
.map(|mut f| { // The fallback type is the hidden type `1`. this should prevent accidental data disclosure
// Check if the `type` key is a number, strings break some clients // If not try to convert the string value to a number and fallback to `1`
// The fallback type is the hidden type `1`. this should prevent accidental data disclosure // If it is both not a number and not a string, fallback to `1`
// If not try to convert the string value to a number and fallback to `1` match f.data.get("type") {
// If it is both not a number and not a string, fallback to `1` Some(t) if t.is_number() => {}
match f.data.get("type") { Some(t) if t.is_string() => {
Some(t) if t.is_number() => {} let type_num = &t.as_str().unwrap_or("1").parse::<u8>().unwrap_or(1);
Some(t) if t.is_string() => { f.data["type"] = json!(type_num);
let type_num = &t.as_str().unwrap_or("1").parse::<u8>().unwrap_or(1); }
f.data["type"] = json!(type_num); _ => {
f.data["type"] = json!(1);
}
} }
_ => { f.data
f.data["type"] = json!(1); })
} .collect()
} })
f.data .unwrap_or_default()
}) });
.collect()
})
.unwrap_or_default();
let password_history_json: Vec<_> = self let password_history_json: Option<Vec<_>> = self.password_history.as_ref().map(|s| {
.password_history serde_json::from_str::<Vec<LowerCase<Value>>>(s)
.as_ref() .inspect_err(|e| warn!("Error parsing password history {e:?} for {}", self.uuid))
.and_then(|s| { .ok()
serde_json::from_str::<Vec<LowerCase<Value>>>(s) .map(|d| {
.inspect_err(|e| warn!("Error parsing password history {e:?} for {}", self.uuid)) // Check every password history item if they are valid and return it.
.ok() // If a password field has the type `null` skip it, it breaks newer Bitwarden clients
}) // A second check is done to verify the lastUsedDate exists and is a valid DateTime string, if not the epoch start time will be used
.map(|d| { d.into_iter()
// Check every password history item if they are valid and return it. .filter_map(|d| match d.data.get("password") {
// If a password field has the type `null` skip it, it breaks newer Bitwarden clients Some(p) if p.is_string() => Some(d.data),
// A second check is done to verify the lastUsedDate exists and is a valid DateTime string, if not the epoch start time will be used _ => None,
d.into_iter() })
.filter_map(|d| match d.data.get("password") { .map(|mut d| {
Some(p) if p.is_string() => Some(d.data), let lud = if let Some(l) = d.get("lastUsedDate").and_then(|l| l.as_str()) {
_ => None, validate_and_format_date(l)
}) } else {
.map(|mut d| { "1970-01-01T00:00:00.000000Z".to_owned()
let lud = if let Some(l) = d.get("lastUsedDate").and_then(|l| l.as_str()) { };
validate_and_format_date(l) d["lastUsedDate"] = json!(lud);
} else { d
"1970-01-01T00:00:00.000000Z".to_owned() })
}; .collect()
d["lastUsedDate"] = json!(lud); })
d .unwrap_or_default()
}) });
.collect()
})
.unwrap_or_default();
// Get the type_data or a default to an empty json object '{}'.
// If not passing an empty object, mobile clients will crash.
let mut type_data_json = serde_json::from_str::<LowerCase<Value>>(&self.data)
.inspect_err(|_| warn!("Error parsing data field for {}", self.uuid))
.map_or_else(|_| Value::Object(serde_json::Map::new()), |d| d.data);
// NOTE: This was marked as *Backwards Compatibility Code*, but as of January 2021 this is still being used by upstream
// Set the first element of the Uris array as Uri, this is needed several (mobile) clients.
if self.atype == 1 {
// Upstream always has an `uri` key/value
type_data_json["uri"] = Value::Null;
if let Some(uris) = type_data_json["uris"].as_array_mut()
&& !uris.is_empty()
{
// Fix uri match values first, they are only allowed to be a number or null
// If it is a string, convert it to an int or null if that fails
for uri in &mut *uris {
if uri["match"].is_string() {
let match_value = match uri["match"].as_str().unwrap_or_default().parse::<u8>() {
Ok(n) => json!(n),
_ => Value::Null,
};
uri["match"] = match_value;
}
}
type_data_json["uri"] = uris[0]["uri"].clone();
}
// Check if `passwordRevisionDate` is a valid date, else convert it
if let Some(pw_revision) = type_data_json["passwordRevisionDate"].as_str() {
type_data_json["passwordRevisionDate"] = json!(validate_and_format_date(pw_revision));
}
}
// Fix secure note issues when data is invalid
// This breaks at least the native mobile clients
if self.atype == 2 {
match type_data_json {
Value::Object(ref t) if t.get("type").is_some_and(Value::is_number) => {}
_ => {
type_data_json = json!({"type": 0});
}
}
}
// Fix invalid SSH Entries
// This breaks at least the native mobile client if invalid
// The only way to fix this is by setting type_data_json to `null`
// Opening this ssh-key in the mobile client will probably crash the client, but you can edit, save and afterwards delete it
if self.atype == 5
&& (type_data_json["keyFingerprint"].as_str().is_none_or(str::is_empty)
|| type_data_json["privateKey"].as_str().is_none_or(str::is_empty)
|| type_data_json["publicKey"].as_str().is_none_or(str::is_empty))
{
warn!("Error parsing ssh-key, mandatory fields are invalid for {}", self.uuid);
type_data_json = Value::Null;
}
let collection_ids = if let Some(cipher_sync_data) = cipher_sync_data { let collection_ids = if let Some(cipher_sync_data) = cipher_sync_data {
if let Some(cipher_collections) = cipher_sync_data.cipher_collections.get(&self.uuid) { if let Some(cipher_collections) = cipher_sync_data.cipher_collections.get(&self.uuid) {
@@ -403,10 +367,83 @@ impl Cipher {
_ => err!(format!("Cipher {} has an invalid type {}", self.uuid, self.atype)), _ => err!(format!("Cipher {} has an invalid type {}", self.uuid, self.atype)),
}; };
json_object[key] = type_data_json; if is_blob_encrypted {
// The blob holds all of the content, so it is sent back as-is and the structured fields
// stay null, as upstream does. Only the name needs clearing, the others are never stored.
json_object["data"] = json!(self.data);
json_object["name"] = Value::Null;
} else {
json_object[key] = self.legacy_type_data_json(type_data);
}
Ok(json_object) Ok(json_object)
} }
/// The per-type data (`login`, `card`, …) of a legacy cipher, from `type_data` as parsed from
/// `self.data`, with fixups for values that are known to break clients.
fn legacy_type_data_json(&self, type_data: Result<Value, serde_json::Error>) -> Value {
use crate::util::validate_and_format_date;
// Get the type_data or a default to an empty json object '{}'.
// If not passing an empty object, mobile clients will crash.
let mut type_data_json = type_data
.inspect_err(|_| warn!("Error parsing data field for {}", self.uuid))
.unwrap_or_else(|_| Value::Object(serde_json::Map::new()));
// NOTE: This was marked as *Backwards Compatibility Code*, but as of January 2021 this is still being used by upstream
// Set the first element of the Uris array as Uri, this is needed several (mobile) clients.
if self.atype == 1 {
// Upstream always has an `uri` key/value
type_data_json["uri"] = Value::Null;
if let Some(uris) = type_data_json["uris"].as_array_mut()
&& !uris.is_empty()
{
// Fix uri match values first, they are only allowed to be a number or null
// If it is a string, convert it to an int or null if that fails
for uri in &mut *uris {
if uri["match"].is_string() {
let match_value = match uri["match"].as_str().unwrap_or_default().parse::<u8>() {
Ok(n) => json!(n),
_ => Value::Null,
};
uri["match"] = match_value;
}
}
type_data_json["uri"] = uris[0]["uri"].clone();
}
// Check if `passwordRevisionDate` is a valid date, else convert it
if let Some(pw_revision) = type_data_json["passwordRevisionDate"].as_str() {
type_data_json["passwordRevisionDate"] = json!(validate_and_format_date(pw_revision));
}
}
// Fix secure note issues when data is invalid
// This breaks at least the native mobile clients
if self.atype == 2 {
match type_data_json {
Value::Object(ref t) if t.get("type").is_some_and(Value::is_number) => {}
_ => {
type_data_json = json!({"type": 0});
}
}
}
// Fix invalid SSH Entries
// This breaks at least the native mobile client if invalid
// The only way to fix this is by setting type_data_json to `null`
// Opening this ssh-key in the mobile client will probably crash the client, but you can edit, save and afterwards delete it
if self.atype == 5
&& (type_data_json["keyFingerprint"].as_str().is_none_or(str::is_empty)
|| type_data_json["privateKey"].as_str().is_none_or(str::is_empty)
|| type_data_json["publicKey"].as_str().is_none_or(str::is_empty))
{
warn!("Error parsing ssh-key, mandatory fields are invalid for {}", self.uuid);
type_data_json = Value::Null;
}
type_data_json
}
pub async fn update_users_revision(&self, conn: &DbConn) -> Vec<UserId> { pub async fn update_users_revision(&self, conn: &DbConn) -> Vec<UserId> {
let mut user_uuids = Vec::new(); let mut user_uuids = Vec::new();
match self.user_uuid { match self.user_uuid {
+3 -1
View File
@@ -17,11 +17,12 @@ mod two_factor;
mod two_factor_duo_context; mod two_factor_duo_context;
mod two_factor_incomplete; mod two_factor_incomplete;
mod user; mod user;
mod user_signature_key_pair;
pub use self::archive::Archive; pub use self::archive::Archive;
pub use self::attachment::{Attachment, AttachmentId}; pub use self::attachment::{Attachment, AttachmentId};
pub use self::auth_request::{AuthRequest, AuthRequestId}; pub use self::auth_request::{AuthRequest, AuthRequestId};
pub use self::cipher::{Cipher, CipherId, RepromptType}; pub use self::cipher::{Cipher, CipherId, RepromptType, is_data_blob_encrypted};
pub use self::collection::{Collection, CollectionCipher, CollectionId, CollectionUser}; pub use self::collection::{Collection, CollectionCipher, CollectionId, CollectionUser};
pub use self::device::{Device, DeviceId, DeviceType, DeviceWithAuthRequest, PushId}; pub use self::device::{Device, DeviceId, DeviceType, DeviceWithAuthRequest, PushId};
pub use self::emergency_access::{EmergencyAccess, EmergencyAccessId, EmergencyAccessStatus, EmergencyAccessType}; pub use self::emergency_access::{EmergencyAccess, EmergencyAccessId, EmergencyAccessStatus, EmergencyAccessType};
@@ -40,3 +41,4 @@ pub use self::two_factor::{TwoFactor, TwoFactorType};
pub use self::two_factor_duo_context::TwoFactorDuoContext; pub use self::two_factor_duo_context::TwoFactorDuoContext;
pub use self::two_factor_incomplete::TwoFactorIncomplete; pub use self::two_factor_incomplete::TwoFactorIncomplete;
pub use self::user::{Invitation, KeyId, SsoUser, User, UserId, UserKdfType, UserStampException}; pub use self::user::{Invitation, KeyId, SsoUser, User, UserId, UserKdfType, UserStampException};
pub use self::user_signature_key_pair::{SignatureAlgorithm, UserSignatureKeyPair};
+77 -18
View File
@@ -20,6 +20,7 @@ use macros::UuidFromParam;
use super::{ use super::{
Cipher, Device, EmergencyAccess, Favorite, Folder, Membership, MembershipType, TwoFactor, TwoFactorIncomplete, Cipher, Device, EmergencyAccess, Favorite, Folder, Membership, MembershipType, TwoFactor, TwoFactorIncomplete,
UserSignatureKeyPair,
}; };
#[derive(Identifiable, Queryable, Insertable, AsChangeset, Selectable)] #[derive(Identifiable, Queryable, Insertable, AsChangeset, Selectable)]
@@ -71,6 +72,12 @@ pub struct User {
pub external_id: Option<String>, // Todo: Needs to be removed in the future, this is not used anymore. pub external_id: Option<String>, // Todo: Needs to be removed in the future, this is not used anymore.
pub key_id: Option<KeyId>, pub key_id: Option<KeyId>,
// "v2" account cryptographic state. Either all of these are set (together with a row in
// `user_signature_key_pairs`) or none of them are; see `User::is_v2`.
pub signed_public_key: Option<String>,
pub security_state: Option<String>,
pub security_version: Option<i32>,
} }
#[derive(Identifiable, Queryable, Insertable)] #[derive(Identifiable, Queryable, Insertable)]
@@ -158,9 +165,17 @@ impl User {
external_id: None, // Todo: Needs to be removed in the future, this is not used anymore. external_id: None, // Todo: Needs to be removed in the future, this is not used anymore.
key_id: None, key_id: None,
signed_public_key: None,
security_state: None,
security_version: None,
} }
} }
pub fn is_v2(&self) -> bool {
self.signed_public_key.is_some() && self.security_state.is_some() && self.security_version.is_some()
}
pub fn check_valid_password(&self, password: &str) -> bool { pub fn check_valid_password(&self, password: &str) -> bool {
crypto::verify_password_hash( crypto::verify_password_hash(
password.as_bytes(), password.as_bytes(),
@@ -261,23 +276,55 @@ impl User {
!CONFIG.mail_enabled() || self.verified_at.is_some() !CONFIG.mail_enabled() || self.verified_at.is_some()
} }
/// The `accountKeys` object (upstream's `PrivateKeysResponseModel`), null without a key pair async fn v2_signature_key_pair(&self, conn: &DbConn) -> Option<UserSignatureKeyPair> {
pub fn account_keys_json(&self) -> Value { if !self.is_v2() {
if self.private_key.is_some() { return None;
json!({
"publicKeyEncryptionKeyPair": {
"wrappedPrivateKey": self.private_key,
"publicKey": self.public_key,
"signedPublicKey": null,
"object": "publicKeyEncryptionKeyPair",
},
"securityState": null,
"signatureKeyPair": null,
"object": "privateKeys"
})
} else {
Value::Null
} }
UserSignatureKeyPair::find_by_user(&self.uuid, conn).await
}
pub async fn account_keys_json(&self, conn: &DbConn) -> Value {
if self.private_key.is_none() {
return Value::Null;
}
let (signed_public_key, signature_key_pair, security_state) = match self.v2_signature_key_pair(conn).await {
Some(key_pair) => (
json!(self.signed_public_key),
key_pair.to_json(),
json!({
"securityState": self.security_state,
"securityVersion": self.security_version,
}),
),
None => (Value::Null, Value::Null, Value::Null),
};
json!({
"publicKeyEncryptionKeyPair": {
"wrappedPrivateKey": self.private_key,
"publicKey": self.public_key,
"signedPublicKey": signed_public_key,
"object": "publicKeyEncryptionKeyPair",
},
"signatureKeyPair": signature_key_pair,
"securityState": security_state,
"object": "privateKeys"
})
}
pub async fn public_keys_json(&self, conn: &DbConn) -> Value {
let (signed_public_key, verifying_key) = match self.v2_signature_key_pair(conn).await {
Some(key_pair) => (json!(self.signed_public_key), json!(key_pair.verifying_key)),
None => (Value::Null, Value::Null),
};
json!({
"publicKey": self.public_key,
"signedPublicKey": signed_public_key,
"verifyingKey": verifying_key,
"object": "publicKeys"
})
} }
pub async fn to_json(&self, conn: &DbConn) -> Value { pub async fn to_json(&self, conn: &DbConn) -> Value {
@@ -300,7 +347,7 @@ impl User {
UserStatus::Enabled UserStatus::Enabled
}; };
let account_keys = self.account_keys_json(); let account_keys = self.account_keys_json(conn).await;
json!({ json!({
"_status": status as i32, "_status": status as i32,
@@ -376,6 +423,7 @@ impl User {
Device::delete_all_by_user(&self.uuid, conn).await?; Device::delete_all_by_user(&self.uuid, conn).await?;
TwoFactor::delete_all_by_user(&self.uuid, conn).await?; TwoFactor::delete_all_by_user(&self.uuid, conn).await?;
TwoFactorIncomplete::delete_all_by_user(&self.uuid, conn).await?; TwoFactorIncomplete::delete_all_by_user(&self.uuid, conn).await?;
UserSignatureKeyPair::delete_all_by_user(&self.uuid, conn).await?;
Invitation::take(&self.email, conn).await; // Delete invitation if any Invitation::take(&self.email, conn).await; // Delete invitation if any
conn.run(move |conn| { conn.run(move |conn| {
@@ -564,7 +612,18 @@ pub struct UserId(String);
)] )]
#[deref(forward)] #[deref(forward)]
#[from(forward)] #[from(forward)]
pub struct KeyId(String); pub struct KeyId(#[serde(deserialize_with = "deserialize_key_id")] String);
/// Rejects a key id from a request that isn't 16 bytes as lowercase hex, as upstream's `[KeyId]` does.
///
/// Ref: <https://github.com/bitwarden/server/blob/main/src/Core/KeyManagement/Models/Data/KeyId.cs>
fn deserialize_key_id<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<String, D::Error> {
let key_id = <String as serde::Deserialize>::deserialize(deserializer)?;
if key_id.len() != 32 || !key_id.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) {
return Err(serde::de::Error::custom("Key id must be a 32 character lowercase hex-encoded string."));
}
Ok(key_id)
}
impl SsoUser { impl SsoUser {
pub async fn save(&self, conn: &DbConn) -> EmptyResult { pub async fn save(&self, conn: &DbConn) -> EmptyResult {
+137
View File
@@ -0,0 +1,137 @@
use chrono::{NaiveDateTime, Utc};
use derive_more::{AsRef, Deref, Display, From};
use diesel::prelude::*;
use serde_json::Value;
use crate::{
api::EmptyResult,
db::{DbConn, schema::user_signature_key_pairs},
error::MapResult,
util::get_uuid,
};
use super::UserId;
/// A user's signature key pair, part of the "v2" account cryptographic state.
///
/// Upstream keeps this in its own table rather than as columns on the user, with a unique index on
/// the user id. The stated intent is to eventually keep superseded key pairs around (an `active`
/// flag was sketched but not shipped), which is why this is modelled as a row with its own identity
/// instead of a set of user attributes.
///
/// Ref: <https://github.com/bitwarden/server/blob/main/src/Sql/dbo/KeyManagement/Tables/UserSignatureKeyPair.sql>
#[derive(Identifiable, Queryable, Insertable, AsChangeset, Selectable)]
#[diesel(table_name = user_signature_key_pairs)]
#[diesel(treat_none_as_null = true)]
#[diesel(primary_key(uuid))]
pub struct UserSignatureKeyPair {
pub uuid: UserSignatureKeyPairId,
pub user_uuid: UserId,
pub signature_algorithm: i32,
/// The signing (private) key, wrapped by the user key.
pub signing_key: String,
/// The COSE-encoded public verifying key.
pub verifying_key: String,
pub created_at: NaiveDateTime,
pub updated_at: NaiveDateTime,
}
/// https://github.com/bitwarden/server/blob/main/src/Core/KeyManagement/Enums/SignatureAlgorithm.cs
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SignatureAlgorithm {
Ed25519 = 0,
MlDsa44 = 1,
}
impl SignatureAlgorithm {
pub fn parse(algorithm: &str) -> Option<Self> {
match algorithm {
"ed25519" => Some(Self::Ed25519),
"mldsa44" => Some(Self::MlDsa44),
_ => None,
}
}
}
/// Local methods
impl UserSignatureKeyPair {
pub fn new(
user_uuid: UserId,
signature_algorithm: SignatureAlgorithm,
signing_key: String,
verifying_key: String,
) -> Self {
let now = Utc::now().naive_utc();
Self {
uuid: UserSignatureKeyPairId(get_uuid()),
user_uuid,
signature_algorithm: signature_algorithm as i32,
signing_key,
verifying_key,
created_at: now,
updated_at: now,
}
}
pub fn to_json(&self) -> Value {
json!({
"wrappedSigningKey": self.signing_key,
"verifyingKey": self.verifying_key,
"object": "signatureKeyPair",
})
}
}
/// Database methods
impl UserSignatureKeyPair {
pub async fn save(&mut self, conn: &DbConn) -> EmptyResult {
self.updated_at = Utc::now().naive_utc();
db_run! { conn:
mysql {
diesel::insert_into(user_signature_key_pairs::table)
.values(&*self)
.on_conflict(diesel::dsl::DuplicatedKeys)
.do_update()
.set(&*self)
.execute(conn)
.map_res("Error saving user signature key pair")
}
postgresql, sqlite {
diesel::insert_into(user_signature_key_pairs::table)
.values(&*self)
.on_conflict(user_signature_key_pairs::user_uuid)
.do_update()
.set(&*self)
.execute(conn)
.map_res("Error saving user signature key pair")
}
}
}
/// The user's key pair. There is at most one, enforced by a unique index on `user_uuid`.
pub async fn find_by_user(user_uuid: &UserId, conn: &DbConn) -> Option<Self> {
conn.run(move |conn| {
user_signature_key_pairs::table
.filter(user_signature_key_pairs::user_uuid.eq(user_uuid))
.first::<Self>(conn)
.ok()
})
.await
}
pub async fn delete_all_by_user(user_uuid: &UserId, conn: &DbConn) -> EmptyResult {
conn.run(move |conn| {
diesel::delete(user_signature_key_pairs::table.filter(user_signature_key_pairs::user_uuid.eq(user_uuid)))
.execute(conn)
.map_res("Error deleting user signature key pairs")
})
.await
}
}
#[derive(Clone, Debug, AsRef, Deref, DieselNewType, Display, From, Hash, PartialEq, Eq, Serialize, Deserialize)]
pub struct UserSignatureKeyPairId(String);
+17
View File
@@ -218,6 +218,21 @@ table! {
avatar_color -> Nullable<Text>, avatar_color -> Nullable<Text>,
external_id -> Nullable<Text>, external_id -> Nullable<Text>,
key_id -> Nullable<Text>, key_id -> Nullable<Text>,
signed_public_key -> Nullable<Text>,
security_state -> Nullable<Text>,
security_version -> Nullable<Integer>,
}
}
table! {
user_signature_key_pairs (uuid) {
uuid -> Text,
user_uuid -> Text,
signature_algorithm -> Integer,
signing_key -> Text,
verifying_key -> Text,
created_at -> Timestamp,
updated_at -> Timestamp,
} }
} }
@@ -383,6 +398,7 @@ joinable!(collections_groups -> groups (groups_uuid));
joinable!(event -> users_organizations (uuid)); joinable!(event -> users_organizations (uuid));
joinable!(auth_requests -> users (user_uuid)); joinable!(auth_requests -> users (user_uuid));
joinable!(sso_users -> users (user_uuid)); joinable!(sso_users -> users (user_uuid));
joinable!(user_signature_key_pairs -> users (user_uuid));
allow_tables_to_appear_in_same_query!( allow_tables_to_appear_in_same_query!(
archives, archives,
@@ -409,4 +425,5 @@ allow_tables_to_appear_in_same_query!(
collections_groups, collections_groups,
event, event,
auth_requests, auth_requests,
user_signature_key_pairs,
); );