Browse Source

Align several API responses and request checks with upstream (#8001)

pull/7728/merge
Daniel García 4 days ago
committed by GitHub
parent
commit
b12874bd83
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 5
      .env.template
  2. 1
      THREAT_MODEL.md
  3. 10
      playwright/tests/organization.smtp.spec.ts
  4. 94
      src/api/core/accounts.rs
  5. 41
      src/api/core/ciphers.rs
  6. 37
      src/api/core/organizations.rs
  7. 6
      src/config.rs
  8. 21
      src/db/models/auth_request.rs
  9. 6
      src/db/models/collection.rs
  10. 6
      src/db/models/organization.rs
  11. 5
      src/sso_client.rs
  12. 8
      src/util.rs

5
.env.template

@ -338,6 +338,8 @@
## "local" accepts it from any non global address, which covers a reverse proxy running on the same ## "local" accepts it from any non global address, which covers a reverse proxy running on the same
## host or container network. Use "all" to accept it from anywhere, or list the addresses of your ## host or container network. Use "all" to accept it from anywhere, or list the addresses of your
## proxy as IPs and CIDR ranges if it connects from a public address. ## proxy as IPs and CIDR ranges if it connects from a public address.
## Non global addresses include the 6to4, Teredo and local-use NAT64 ranges, which can carry clients from anywhere:
## if those can reach Vaultwarden, list your proxy instead of using "local", or those clients can set the header.
## For a list header like X-Forwarded-For, the client IP is the rightmost address that isn't one of ## For a list header like X-Forwarded-For, the client IP is the rightmost address that isn't one of
## these proxies, so with several proxies in a row (a CDN in front of nginx, for example) list all of them. ## these proxies, so with several proxies in a row (a CDN in front of nginx, for example) list all of them.
# IP_HEADER_TRUSTED_PROXIES=local # IP_HEADER_TRUSTED_PROXIES=local
@ -383,6 +385,7 @@
## Enabling this will cause the internal HTTP client to refuse to connect to any non-global IP address. ## Enabling this will cause the internal HTTP client to refuse to connect to any non-global IP address.
## Useful to secure your internal environment: See https://en.wikipedia.org/wiki/Reserved_IP_addresses for a list of IPs which it will block ## Useful to secure your internal environment: See https://en.wikipedia.org/wiki/Reserved_IP_addresses for a list of IPs which it will block
## Requests through an outbound proxy (HTTP_PROXY, HTTPS_PROXY or ALL_PROXY) aren't checked, because the proxy resolves the names.
# HTTP_REQUEST_BLOCK_NON_GLOBAL_IPS=true # HTTP_REQUEST_BLOCK_NON_GLOBAL_IPS=true
## Client Settings ## Client Settings
@ -524,7 +527,7 @@
## Enforce that the Single Org policy is enabled before setting the Reset Password policy ## Enforce that the Single Org policy is enabled before setting the Reset Password policy
## Bitwarden enforces this by default. In Vaultwarden we encouraged to use multiple organizations because groups were not available. ## Bitwarden enforces this by default. In Vaultwarden we encouraged to use multiple organizations because groups were not available.
## Setting this to true will enforce the Single Org Policy to be enabled before you can enable the Reset Password policy. ## Setting this to true will enforce the Single Org Policy to be enabled before you can enable the Reset Password policy.
# ENFORCE_SINGLE_ORG_WITH_RESET_PW_POLICY=false # ENFORCE_SINGLE_ORG_WITH_RESET_PW_POLICY=true
## Prefer IPv6 (AAAA) resolving ## Prefer IPv6 (AAAA) resolving
## This settings configures the DNS resolver to resolve IPv6 first, and if not available try IPv4 ## This settings configures the DNS resolver to resolve IPv6 first, and if not available try IPv4

1
THREAT_MODEL.md

@ -81,6 +81,7 @@ These are intended behavior or outside this model. Several match upstream Bitwar
- Attacks that need a missing or misconfigured reverse proxy, such as one not sending `X-Forwarded-Proto` (it decides the admin cookie's `Secure` flag). - Attacks that need a missing or misconfigured reverse proxy, such as one not sending `X-Forwarded-Proto` (it decides the admin cookie's `Secure` flag).
- Attacks that need another component to break its own specification, such as a NAT64 translator that forwards the `64:ff9b::/96` prefix to private addresses, against RFC 6052. - Attacks that need another component to break its own specification, such as a NAT64 translator that forwards the `64:ff9b::/96` prefix to private addresses, against RFC 6052.
- Outbound requests to the SSO provider, Yubico server or S3 endpoint the operator configures, which skip the outbound filter and can be on the internal network. - Outbound requests to the SSO provider, Yubico server or S3 endpoint the operator configures, which skip the outbound filter and can be on the internal network.
- Requests sent through an outbound proxy (`HTTP_PROXY`, `HTTPS_PROXY` or `ALL_PROXY`). The proxy resolves names itself, so `HTTP_REQUEST_BLOCK_NON_GLOBAL_IPS` can't check where they go. Configure the proxy so it can't reach anything sensitive, or so it blocks internal addresses.
- File permissions in the data folder. Host security belongs to the operator. - File permissions in the data folder. Host security belongs to the operator.
- Attacks that need physical access to a user's device. - Attacks that need physical access to a user's device.
- Self-exploitation, where someone can only affect their own account, such as self-XSS or weak KDF settings they choose. - Self-exploitation, where someone can only affect their own account, such as self-XSS or weak KDF settings they choose.

10
playwright/tests/organization.smtp.spec.ts

@ -42,9 +42,17 @@ test('Invite users', async ({ page }) => {
await createAccount(test, page, users.user1, mail1Buffer); await createAccount(test, page, users.user1, mail1Buffer);
await orgs.create(test, page, 'Test'); await orgs.create(test, page, 'Test');
await orgs.policies(test, page, 'Test');
// Account recovery requires the Single organisation policy (ENFORCE_SINGLE_ORG_WITH_RESET_PW_POLICY)
await test.step(`Set single organisation`, async () => {
await page.getByRole('button', { name: 'Single organisation' }).click();
await page.getByRole('checkbox', { name: 'Turn on' }).or(page.getByRole('switch', { name: 'Enable policy' })).check({ force: true });
await page.getByRole('button', { name: 'Save' }).click();
await utils.checkNotification(page, 'Edited policy Single organisation');
});
await test.step(`Set account recovery`, async () => { await test.step(`Set account recovery`, async () => {
await orgs.policies(test, page, 'Test');
await page.getByRole('button', { name: 'Account recovery' }).click(); await page.getByRole('button', { name: 'Account recovery' }).click();
await page.getByRole('checkbox', { name: 'Turn on' }).check(); await page.getByRole('checkbox', { name: 'Turn on' }).check();
await page.getByRole('checkbox', { name: 'Automatically enroll new' }).check(); await page.getByRole('checkbox', { name: 'Automatically enroll new' }).check();

94
src/api/core/accounts.rs

@ -21,10 +21,10 @@ use crate::{
db::{ db::{
DbConn, DbPool, DbConn, DbPool,
models::{ models::{
AuthRequest, AuthRequestId, Cipher, CipherId, Device, DeviceId, DeviceType, DeviceWithAuthRequest, AuthRequest, AuthRequestId, Cipher, CipherId, Device, DeviceId, DeviceWithAuthRequest, EmergencyAccess,
EmergencyAccess, EmergencyAccessId, EventType, Folder, FolderId, Invitation, KeyId, Membership, EmergencyAccessId, EventType, Folder, FolderId, Invitation, KeyId, Membership, MembershipId, OrgPolicy,
MembershipId, OrgPolicy, OrgPolicyType, Organization, OrganizationId, Send, SendId, SignatureAlgorithm, OrgPolicyType, Organization, OrganizationId, Send, SendId, SignatureAlgorithm, User, UserId, UserKdfType,
User, UserId, UserKdfType, UserSignatureKeyPair, UserSignatureKeyPair,
}, },
}, },
mail, mail,
@ -909,7 +909,9 @@ async fn get_keys(headers: Headers, conn: DbConn) -> JsonResult {
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
struct PostKeysData { struct PostKeysData {
// Required like upstream, even next to `accountKeys` // Required like upstream, even next to `accountKeys`
#[serde(alias = "PublicKey")]
public_key: Option<String>, public_key: Option<String>,
#[serde(alias = "EncryptedPrivateKey")]
encrypted_private_key: Option<String>, encrypted_private_key: Option<String>,
account_keys: Option<AccountKeysData>, account_keys: Option<AccountKeysData>,
// The id of the user key these account keys belong to, only honored for v2 `accountKeys` // The id of the user key these account keys belong to, only honored for v2 `accountKeys`
@ -2507,19 +2509,7 @@ async fn post_auth_request(
) )
.await; .await;
Ok(Json(json!({ Ok(Json(auth_request.to_json()))
"id": auth_request.uuid,
"publicKey": auth_request.public_key,
"requestDeviceType": DeviceType::from_i32(auth_request.device_type).to_string(),
"requestIpAddress": auth_request.request_ip,
"key": null,
"masterPasswordHash": null,
"creationDate": format_date(&auth_request.creation_date),
"responseDate": null,
"requestApproved": false,
"origin": CONFIG.domain_origin(),
"object": "auth-request"
})))
} }
#[get("/auth-requests/<auth_request_id>")] #[get("/auth-requests/<auth_request_id>")]
@ -2529,21 +2519,7 @@ async fn get_auth_request(auth_request_id: AuthRequestId, headers: Headers, conn
err!("AuthRequest doesn't exist", "Record not found or user uuid does not match") err!("AuthRequest doesn't exist", "Record not found or user uuid does not match")
}; };
let response_date_utc = auth_request.response_date.map(|response_date| format_date(&response_date)); Ok(Json(auth_request.to_json()))
Ok(Json(json!({
"id": &auth_request_id,
"publicKey": auth_request.public_key,
"requestDeviceType": DeviceType::from_i32(auth_request.device_type).to_string(),
"requestIpAddress": auth_request.request_ip,
"key": auth_request.enc_key,
"masterPasswordHash": auth_request.master_password_hash,
"creationDate": format_date(&auth_request.creation_date),
"responseDate": response_date_utc,
"requestApproved": auth_request.approved,
"origin": CONFIG.domain_origin(),
"object":"auth-request"
})))
} }
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
@ -2578,15 +2554,14 @@ async fn put_auth_request(
err!("An authentication request with the same device already exists") err!("An authentication request with the same device already exists")
} }
let response_date = Utc::now().naive_utc(); // Set the date now so that the response returns it
let response_date_utc = format_date(&response_date); auth_request.response_date = Some(Utc::now().naive_utc());
if data.request_approved { if data.request_approved {
auth_request.approved = Some(data.request_approved); auth_request.approved = Some(data.request_approved);
auth_request.enc_key = Some(data.key); auth_request.enc_key = Some(data.key);
auth_request.master_password_hash = data.master_password_hash; auth_request.master_password_hash = data.master_password_hash;
auth_request.response_device_id = Some(data.device_identifier.clone()); auth_request.response_device_id = Some(data.device_identifier.clone());
auth_request.response_date = Some(response_date);
auth_request.save(&conn).await?; auth_request.save(&conn).await?;
ant.send_auth_response(&auth_request.user_uuid, &auth_request.uuid).await; ant.send_auth_response(&auth_request.user_uuid, &auth_request.uuid).await;
@ -2613,19 +2588,7 @@ async fn put_auth_request(
.await; .await;
} }
Ok(Json(json!({ Ok(Json(auth_request.to_json()))
"id": &auth_request_id,
"publicKey": auth_request.public_key,
"requestDeviceType": DeviceType::from_i32(auth_request.device_type).to_string(),
"requestIpAddress": auth_request.request_ip,
"key": auth_request.enc_key,
"masterPasswordHash": auth_request.master_password_hash,
"creationDate": format_date(&auth_request.creation_date),
"responseDate": response_date_utc,
"requestApproved": auth_request.approved,
"origin": CONFIG.domain_origin(),
"object":"auth-request"
})))
} }
#[get("/auth-requests/<auth_request_id>/response?<code>")] #[get("/auth-requests/<auth_request_id>/response?<code>")]
@ -2648,21 +2611,7 @@ async fn get_auth_request_response(
err!("AuthRequest doesn't exist", "Invalid device, IP or code") err!("AuthRequest doesn't exist", "Invalid device, IP or code")
} }
let response_date_utc = auth_request.response_date.map(|response_date| format_date(&response_date)); Ok(Json(auth_request.to_json()))
Ok(Json(json!({
"id": &auth_request_id,
"publicKey": auth_request.public_key,
"requestDeviceType": DeviceType::from_i32(auth_request.device_type).to_string(),
"requestIpAddress": auth_request.request_ip,
"key": auth_request.enc_key,
"masterPasswordHash": auth_request.master_password_hash,
"creationDate": format_date(&auth_request.creation_date),
"responseDate": response_date_utc,
"requestApproved": auth_request.approved,
"origin": CONFIG.domain_origin(),
"object":"auth-request"
})))
} }
// Now unused but not yet removed // Now unused but not yet removed
@ -2680,23 +2629,8 @@ async fn get_auth_requests_pending(headers: Headers, conn: DbConn) -> JsonResult
"data": auth_requests "data": auth_requests
.iter() .iter()
.filter(|request| request.approved.is_none()) .filter(|request| request.approved.is_none())
.map(|request| { .map(AuthRequest::to_json)
let response_date_utc = request.response_date.map(|response_date| format_date(&response_date)); .collect::<Vec<Value>>(),
json!({
"id": request.uuid,
"publicKey": request.public_key,
"requestDeviceType": DeviceType::from_i32(request.device_type).to_string(),
"requestIpAddress": request.request_ip,
"key": request.enc_key,
"masterPasswordHash": request.master_password_hash,
"creationDate": format_date(&request.creation_date),
"responseDate": response_date_utc,
"requestApproved": request.approved,
"origin": CONFIG.domain_origin(),
"object":"auth-request"
})
}).collect::<Vec<Value>>(),
"continuationToken": null, "continuationToken": null,
"object": "list" "object": "list"
}))) })))

41
src/api/core/ciphers.rs

@ -1,6 +1,7 @@
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};
use chrono::{NaiveDateTime, Utc}; use chrono::{NaiveDateTime, Utc};
use rocket::{ use rocket::{
Route, Route,
form::{Form, FromForm}, form::{Form, FromForm},
@ -12,7 +13,7 @@ use serde_json::Value;
use crate::{ use crate::{
CONFIG, CONFIG,
api::{self, ApiResult, EmptyResult, JsonResult, Notify, PasswordOrOtpData, UpdateType, core::log_event}, api::{self, EmptyResult, JsonResult, Notify, PasswordOrOtpData, UpdateType, core::log_event},
auth::ClientVersion, auth::ClientVersion,
auth::{Headers, OrgIdGuard, OwnerHeaders}, auth::{Headers, OrgIdGuard, OwnerHeaders},
config::PathType, config::PathType,
@ -842,7 +843,7 @@ pub async fn seed_cipher(
user_id: &UserId, user_id: &UserId,
folder_ids: &HashMap<FolderId, FolderId>, folder_ids: &HashMap<FolderId, FolderId>,
conn: &DbConn, conn: &DbConn,
) -> ApiResult<CipherId> { ) -> api::ApiResult<CipherId> {
// Not in the request model, but a trashed cipher has to stay trashed // Not in the request model, but a trashed cipher has to stay trashed
let deleted_at = encrypted.get("deletedDate").and_then(Value::as_str).map(parse_seed_date).transpose()?; let deleted_at = encrypted.get("deletedDate").and_then(Value::as_str).map(parse_seed_date).transpose()?;
let mut data: CipherData = serde_json::from_value(encrypted)?; let mut data: CipherData = serde_json::from_value(encrypted)?;
@ -889,7 +890,7 @@ pub async fn seed_cipher(
} }
#[cfg(feature = "unsafe_test_mode")] #[cfg(feature = "unsafe_test_mode")]
fn parse_seed_date(date: &str) -> ApiResult<NaiveDateTime> { fn parse_seed_date(date: &str) -> api::ApiResult<NaiveDateTime> {
match chrono::DateTime::parse_from_rfc3339(date) { match chrono::DateTime::parse_from_rfc3339(date) {
Ok(date) => Ok(date.naive_utc()), Ok(date) => Ok(date.naive_utc()),
Err(e) => err!(format!("Invalid date {}: {e}", date.escape_debug())), Err(e) => err!(format!("Invalid date {}: {e}", date.escape_debug())),
@ -1518,6 +1519,13 @@ async fn share_cipher_by_uuid(
false, false,
) )
.await?; .await?;
// The moved attachments now count against the organization's limit
if transfer_cipher {
let moved: i64 = Attachment::find_by_cipher(&cipher.uuid, conn).await.iter().map(|a| a.file_size).sum();
if moved > 0 {
check_attachment_space(&cipher, moved, moved, conn).await?;
}
}
for col_id in &shared_to_collections { for col_id in &shared_to_collections {
CollectionCipher::save(&cipher.uuid, col_id, conn).await?; CollectionCipher::save(&cipher.uuid, col_id, conn).await?;
} }
@ -1619,17 +1627,17 @@ enum FileUploadType {
// Azure = 1, // only used upstream // Azure = 1, // only used upstream
} }
/// Remaining attachment storage in bytes for the cipher's owner, `None` when unlimited. /// Fails when `size` more bytes don't fit in the attachment storage of the cipher's owner.
/// `size_adjust` credits a v2 attachment whose record already counts as used. /// `size_adjust` credits bytes already counted as used, such as a v2 attachment's reserved record.
async fn attachment_size_limit(cipher: &Cipher, size_adjust: i64, conn: &DbConn) -> ApiResult<Option<i64>> { async fn check_attachment_space(cipher: &Cipher, size: i64, size_adjust: i64, conn: &DbConn) -> EmptyResult {
let (limit_kb, already_used) = if let Some(ref user_id) = cipher.user_uuid { let (limit_kb, already_used) = if let Some(ref user_id) = cipher.user_uuid {
let Some(limit_kb) = CONFIG.user_attachment_limit() else { let Some(limit_kb) = CONFIG.user_attachment_limit() else {
return Ok(None); return Ok(());
}; };
(limit_kb, Attachment::size_by_user(user_id, conn).await) (limit_kb, Attachment::size_by_user(user_id, conn).await)
} else if let Some(ref org_id) = cipher.organization_uuid { } else if let Some(ref org_id) = cipher.organization_uuid {
let Some(limit_kb) = CONFIG.org_attachment_limit() else { let Some(limit_kb) = CONFIG.org_attachment_limit() else {
return Ok(None); return Ok(());
}; };
(limit_kb, Attachment::size_by_org(org_id, conn).await) (limit_kb, Attachment::size_by_org(org_id, conn).await)
} else { } else {
@ -1649,8 +1657,11 @@ async fn attachment_size_limit(cipher: &Cipher, size_adjust: i64, conn: &DbConn)
if left <= 0 { if left <= 0 {
err!("Attachment storage limit reached! Delete some attachments to free up space") err!("Attachment storage limit reached! Delete some attachments to free up space")
} }
if size > left {
err!("Attachment storage limit exceeded with this file");
}
Ok(Some(left)) Ok(())
} }
/// v2 API for creating an attachment associated with a cipher. /// v2 API for creating an attachment associated with a cipher.
@ -1688,11 +1699,7 @@ async fn post_attachment_v2(
err!("Max file size is 525 MB.") err!("Max file size is 525 MB.")
} }
if let Some(size_limit) = attachment_size_limit(&cipher, 0, &conn).await? check_attachment_space(&cipher, file_size, 0, &conn).await?;
&& file_size > size_limit
{
err!("Attachment storage limit exceeded with this file");
}
let attachment_id = crypto::generate_attachment_id(); let attachment_id = crypto::generate_attachment_id();
let attachment = let attachment =
@ -1762,11 +1769,7 @@ async fn save_attachment(
Some(a) => a.file_size, // v2 API Some(a) => a.file_size, // v2 API
}; };
if let Some(size_limit) = attachment_size_limit(&cipher, size_adjust, &conn).await? check_attachment_space(&cipher, size, size_adjust, &conn).await?;
&& size > size_limit
{
err!("Attachment storage limit exceeded with this file");
}
let file_id = match &attachment { let file_id = match &attachment {
Some(attachment) => attachment.id.clone(), // v2 API Some(attachment) => attachment.id.clone(), // v2 API

37
src/api/core/organizations.rs

@ -120,11 +120,12 @@ struct OrgData {
plan_type: NumberOrString, plan_type: NumberOrString,
} }
#[derive(Deserialize, Debug)] #[derive(Deserialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
struct OrganizationUpdateData { struct OrganizationUpdateData {
billing_email: String, billing_email: String,
name: String, name: String,
keys: Option<OrgKeyData>,
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -160,18 +161,24 @@ impl FullCollectionData {
#[derive(Deserialize)] #[derive(Deserialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
struct CollectionGroupData { struct CollectionGroupData {
#[serde(default)]
hide_passwords: bool, hide_passwords: bool,
id: GroupId, id: GroupId,
#[serde(default)]
read_only: bool, read_only: bool,
#[serde(default)]
manage: bool, manage: bool,
} }
#[derive(Deserialize)] #[derive(Deserialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
struct CollectionMembershipData { struct CollectionMembershipData {
#[serde(default)]
hide_passwords: bool, hide_passwords: bool,
id: MembershipId, id: MembershipId,
#[serde(default)]
read_only: bool, read_only: bool,
#[serde(default)]
manage: bool, manage: bool,
} }
@ -309,6 +316,16 @@ async fn put_organization(
org.name = data.name; org.name = data.name;
org.billing_email = data.billing_email.to_lowercase(); org.billing_email = data.billing_email.to_lowercase();
if let Some(keys) = data.keys
&& !keys.public_key.trim().is_empty()
&& !keys.encrypted_private_key.trim().is_empty()
&& org.public_key.as_deref().is_none_or(|k| k.trim().is_empty())
&& org.private_key.as_deref().is_none_or(|k| k.trim().is_empty())
{
org.public_key = Some(keys.public_key);
org.private_key = Some(keys.encrypted_private_key);
}
org.save(&conn).await?; org.save(&conn).await?;
log_event( log_event(
@ -2294,7 +2311,9 @@ async fn post_bulk_collections(data: Json<BulkCollectionsData>, headers: Headers
// Only act on existing cipher uuid's // Only act on existing cipher uuid's
// Do not abort the operation just ignore it, it could be a cipher was just deleted for example // Do not abort the operation just ignore it, it could be a cipher was just deleted for example
if let Some(cipher) = Cipher::find_by_uuid_and_org(cipher_id, &data.organization_id, &conn).await if let Some(cipher) = Cipher::find_by_uuid_and_org(cipher_id, &data.organization_id, &conn).await
&& cipher.is_write_accessible_to_user(&headers.user.uuid, CipherAccessScope::OrganizationAdmin, &conn).await && cipher
.is_in_editable_collection_by_user(&headers.user.uuid, CipherAccessScope::OrganizationAdmin, &conn)
.await
{ {
// When selecting a specific collection from the left filter list, and use the bulk option, you can remove an item from that collection // When selecting a specific collection from the left filter list, and use the bulk option, you can remove an item from that collection
// In these cases the client will call this endpoint twice, once for adding the new collections and a second for deleting. // In these cases the client will call this endpoint twice, once for adding the new collections and a second for deleting.
@ -2344,9 +2363,15 @@ async fn list_policies_token(org_id: OrganizationId, token: &str, conn: DbConn)
return Ok(Json(json!({}))); return Ok(Json(json!({})));
} }
// TODO: We receive the invite token as ?token=<>, validate it contains the org id let Some(member) = Membership::find_by_uuid_and_org(&invite.member_id, &org_id, &conn).await else {
err!("Organization not found", "The invited membership no longer exists")
};
if member.user_uuid != invite.sub || member.status != MembershipStatus::Invited as i32 {
err!("Organization not found", "The membership is not a pending invitation of this user")
}
let policies = OrgPolicy::find_by_org(&org_id, &conn).await; let policies = OrgPolicy::find_by_org(&org_id, &conn).await;
let policies_json: Vec<Value> = policies.iter().map(OrgPolicy::to_json).collect(); let policies_json: Vec<Value> = policies.iter().filter(|p| p.enabled).map(OrgPolicy::to_json).collect();
Ok(Json(json!({ Ok(Json(json!({
"data": policies_json, "data": policies_json,
@ -2462,7 +2487,6 @@ async fn put_policy(
// Vaultwarden encouraged to use multiple orgs instead of groups because groups were not available in the past // Vaultwarden encouraged to use multiple orgs instead of groups because groups were not available in the past
// Now that groups are available we can enforce this option when wanted. // Now that groups are available we can enforce this option when wanted.
// We put this behind a config option to prevent breaking current installation. // We put this behind a config option to prevent breaking current installation.
// Maybe we want to enable this by default in the future, but currently it is disabled by default.
if CONFIG.enforce_single_org_with_reset_pw_policy() { if CONFIG.enforce_single_org_with_reset_pw_policy() {
if pol_type_enum == OrgPolicyType::ResetPassword && data.enabled { if pol_type_enum == OrgPolicyType::ResetPassword && data.enabled {
let single_org_policy_enabled = OrgPolicy::find_by_org_and_type(&org_id, OrgPolicyType::SingleOrg, &conn) let single_org_policy_enabled = OrgPolicy::find_by_org_and_type(&org_id, OrgPolicyType::SingleOrg, &conn)
@ -3000,8 +3024,11 @@ impl GroupRequest {
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
struct CollectionData { struct CollectionData {
id: CollectionId, id: CollectionId,
#[serde(default)]
read_only: bool, read_only: bool,
#[serde(default)]
hide_passwords: bool, hide_passwords: bool,
#[serde(default)]
manage: bool, manage: bool,
} }

6
src/config.rs

@ -736,6 +736,7 @@ make_config! {
/// running on the same host or container network), the string "all" to accept it from anywhere, /// running on the same host or container network), the string "all" to accept it from anywhere,
/// or a comma separated list of IPs and CIDR ranges. For a list header like X-Forwarded-For, the /// or a comma separated list of IPs and CIDR ranges. For a list header like X-Forwarded-For, the
/// client IP is the rightmost address that isn't a trusted proxy, so list every proxy in the chain. /// client IP is the rightmost address that isn't a trusted proxy, so list every proxy in the chain.
/// "local" also trusts 6to4, Teredo and local-use NAT64 addresses, which can carry clients from anywhere.
ip_header_trusted_proxies: String, true, def, "local".to_owned(); ip_header_trusted_proxies: String, true, def, "local".to_owned();
/// Icon service |> The predefined icon services are: internal, bitwarden, duckduckgo, google. /// Icon service |> The predefined icon services are: internal, bitwarden, duckduckgo, google.
/// To specify a custom icon service, set a URL template with exactly one instance of `{}`, /// To specify a custom icon service, set a URL template with exactly one instance of `{}`,
@ -770,7 +771,8 @@ make_config! {
/// Useful to hide other servers in the local network. Check the WIKI for more details /// Useful to hide other servers in the local network. Check the WIKI for more details
http_request_block_regex: String, true, option; http_request_block_regex: String, true, option;
/// Block non global IPs |> Enabling this will cause the internal HTTP client to refuse to connect to any non global IP address. /// Block non global IPs |> Enabling this will cause the internal HTTP client to refuse to connect to any non global IP address.
/// Useful to secure your internal environment: See https://en.wikipedia.org/wiki/Reserved_IP_addresses for a list of IPs which it will block /// Useful to secure your internal environment: See https://en.wikipedia.org/wiki/Reserved_IP_addresses for a list of IPs which it will block.
/// Requests through an outbound proxy (HTTP_PROXY, HTTPS_PROXY or ALL_PROXY) aren't checked, because the proxy resolves the names.
http_request_block_non_global_ips: bool, true, auto, |c| c.icon_blacklist_non_global_ips; http_request_block_non_global_ips: bool, true, auto, |c| c.icon_blacklist_non_global_ips;
/// Disable Two-Factor remember |> Enabling this would force the users to use a second factor to login every time. /// Disable Two-Factor remember |> Enabling this would force the users to use a second factor to login every time.
@ -870,7 +872,7 @@ make_config! {
/// Enforce Single Org with Reset Password Policy |> Enforce that the Single Org policy is enabled before setting the Reset Password policy /// Enforce Single Org with Reset Password Policy |> Enforce that the Single Org policy is enabled before setting the Reset Password policy
/// Bitwarden enforces this by default. In Vaultwarden we encouraged to use multiple organizations because groups were not available. /// Bitwarden enforces this by default. In Vaultwarden we encouraged to use multiple organizations because groups were not available.
/// Setting this to true will enforce the Single Org Policy to be enabled before you can enable the Reset Password policy. /// Setting this to true will enforce the Single Org Policy to be enabled before you can enable the Reset Password policy.
enforce_single_org_with_reset_pw_policy: bool, false, def, false; enforce_single_org_with_reset_pw_policy: bool, false, def, true;
/// Prefer IPv6 (AAAA) resolving |> This settings configures the DNS resolver to resolve IPv6 first, and if not available try IPv4 /// Prefer IPv6 (AAAA) resolving |> This settings configures the DNS resolver to resolve IPv6 first, and if not available try IPv4
/// This could be useful in IPv6 only environments. /// This could be useful in IPv6 only environments.

21
src/db/models/auth_request.rs

@ -4,6 +4,7 @@ use diesel::prelude::*;
use serde_json::Value; use serde_json::Value;
use crate::{ use crate::{
CONFIG,
api::{ApiResult, EmptyResult}, api::{ApiResult, EmptyResult},
crypto::ct_eq, crypto::ct_eq,
db::{DbConn, schema::auth_requests}, db::{DbConn, schema::auth_requests},
@ -12,7 +13,7 @@ use crate::{
}; };
use macros::UuidFromParam; use macros::UuidFromParam;
use super::{DeviceId, OrganizationId, UserId}; use super::{DeviceId, DeviceType, OrganizationId, UserId};
#[derive(Identifiable, Queryable, Insertable, AsChangeset, Deserialize, Serialize)] #[derive(Identifiable, Queryable, Insertable, AsChangeset, Deserialize, Serialize)]
#[diesel(table_name = auth_requests)] #[diesel(table_name = auth_requests)]
@ -73,6 +74,24 @@ impl AuthRequest {
} }
} }
pub fn to_json(&self) -> Value {
json!({
"id": self.uuid,
"publicKey": self.public_key,
"requestDeviceIdentifier": self.request_device_identifier,
"requestDeviceTypeValue": self.device_type,
"requestDeviceType": DeviceType::from_i32(self.device_type).to_string(),
"requestIpAddress": self.request_ip,
"key": self.enc_key,
"masterPasswordHash": self.master_password_hash,
"creationDate": format_date(&self.creation_date),
"responseDate": self.response_date.as_ref().map(format_date),
"requestApproved": self.approved.unwrap_or(false),
"origin": CONFIG.domain_origin(),
"object": "auth-request"
})
}
pub fn to_json_for_pending_device(&self) -> Value { pub fn to_json_for_pending_device(&self) -> Value {
json!({ json!({
"id": self.uuid, "id": self.uuid,

6
src/db/models/collection.rs

@ -995,11 +995,7 @@ impl CollectionMembership {
"id": self.membership_uuid, "id": self.membership_uuid,
"readOnly": self.read_only, "readOnly": self.read_only,
"hidePasswords": self.hide_passwords, "hidePasswords": self.hide_passwords,
"manage": membership_type >= MembershipType::Admin "manage": membership_type >= MembershipType::Admin || self.manage,
|| self.manage
|| (membership_type == MembershipType::Manager
&& !self.read_only
&& !self.hide_passwords),
}) })
} }
} }

6
src/db/models/organization.rs

@ -811,6 +811,7 @@ impl Membership {
"useResetPassword": CONFIG.mail_enabled(), "useResetPassword": CONFIG.mail_enabled(),
"ssoBound": false, // Not supported "ssoBound": false, // Not supported
"useSso": false, // Not supported "useSso": false, // Not supported
"ssoEnabled": false,
"useKeyConnector": false, "useKeyConnector": false,
"useSecretsManager": false, // Not supported (Not AGPLv3 Licensed) "useSecretsManager": false, // Not supported (Not AGPLv3 Licensed)
"usePasswordManager": true, "usePasswordManager": true,
@ -824,6 +825,7 @@ impl Membership {
"useOrganizationDomains": false, // Not supported (Linked to SSO) "useOrganizationDomains": false, // Not supported (Linked to SSO)
"usePam": false, // Not supported "usePam": false, // Not supported
"usePhishingBlocker": false, "usePhishingBlocker": false,
"useAutomaticUserConfirmation": false,
"organizationUserId": self.uuid, "organizationUserId": self.uuid,
"providerId": null, "providerId": null,
@ -831,6 +833,7 @@ impl Membership {
"providerType": null, "providerType": null,
"familySponsorshipFriendlyName": null, "familySponsorshipFriendlyName": null,
"familySponsorshipAvailable": false, "familySponsorshipAvailable": false,
"isAdminInitiated": false,
"productTierType": 3, // Enterprise tier "productTierType": 3, // Enterprise tier
"keyConnectorEnabled": false, "keyConnectorEnabled": false,
"keyConnectorUrl": null, "keyConnectorUrl": null,
@ -838,6 +841,7 @@ impl Membership {
"familySponsorshipValidUntil": null, "familySponsorshipValidUntil": null,
"familySponsorshipToDelete": null, "familySponsorshipToDelete": null,
"accessSecretsManager": false, "accessSecretsManager": false,
"accessPam": false,
// limit collection creation to managers with access_all permission to prevent issues // limit collection creation to managers with access_all permission to prevent issues
"limitCollectionCreation": self.atype < MembershipType::Manager || !self.access_all, "limitCollectionCreation": self.atype < MembershipType::Manager || !self.access_all,
"limitCollectionDeletion": true, "limitCollectionDeletion": true,
@ -905,7 +909,7 @@ impl Membership {
"id": cu.collection_uuid, "id": cu.collection_uuid,
"readOnly": cu.read_only, "readOnly": cu.read_only,
"hidePasswords": cu.hide_passwords, "hidePasswords": cu.hide_passwords,
"manage": cu.manage || (self.atype == MembershipType::Manager && !cu.read_only && !cu.hide_passwords), "manage": cu.manage,
}) })
}) })
.collect() .collect()

5
src/sso_client.rs

@ -246,14 +246,13 @@ impl Client {
let mut exchange = self.core_client.exchange_code(oidc_code); let mut exchange = self.core_client.exchange_code(oidc_code);
Self::check_client_verifier(&client_verifier, sso_auth)?;
if CONFIG.sso_pkce() { if CONFIG.sso_pkce() {
exchange = exchange.set_pkce_verifier(PkceCodeVerifier::new(client_verifier.into())); exchange = exchange.set_pkce_verifier(PkceCodeVerifier::new(client_verifier.into()));
} else {
Self::check_client_verifier(&client_verifier, sso_auth)?;
} }
match exchange.request_async(&self.http_client).await { match exchange.request_async(&self.http_client).await {
Err(err) => err!(format!("Failed to contact token endpoint: {:?}", err)), Err(err) => err!(format!("Failed to contact token endpoint: {err}")),
Ok(token_response) => { Ok(token_response) => {
let oidc_nonce = Nonce::new(sso_auth.nonce.clone()); let oidc_nonce = Nonce::new(sso_auth.nonce.clone());

8
src/util.rs

@ -147,7 +147,7 @@ impl Cors {
// Check a request's `Origin` header against the list of allowed origins. // Check a request's `Origin` header against the list of allowed origins.
// If a match exists, return it. Otherwise, return None. // If a match exists, return it. Otherwise, return None.
fn get_allowed_origin(headers: &HeaderMap<'_>) -> Option<String> { fn get_allowed_origin(headers: &HeaderMap<'_>, allow_sso: bool) -> Option<String> {
let origin = Self::get_header(headers, "Origin"); let origin = Self::get_header(headers, "Origin");
let safari_extension_origin = "file://"; let safari_extension_origin = "file://";
let desktop_custom_file_origin = "bw-desktop-file://bundle"; let desktop_custom_file_origin = "bw-desktop-file://bundle";
@ -155,7 +155,7 @@ impl Cors {
if origin == CONFIG.domain_origin() if origin == CONFIG.domain_origin()
|| origin == safari_extension_origin || origin == safari_extension_origin
|| origin == desktop_custom_file_origin || origin == desktop_custom_file_origin
|| (CONFIG.sso_enabled() && origin == CONFIG.sso_authority()) || (allow_sso && CONFIG.sso_enabled() && origin == CONFIG.sso_authority())
{ {
Some(origin) Some(origin)
} else { } else {
@ -175,8 +175,10 @@ impl Fairing for Cors {
async fn on_response<'r>(&self, request: &'r Request<'_>, response: &mut Response<'r>) { async fn on_response<'r>(&self, request: &'r Request<'_>, response: &mut Response<'r>) {
let req_headers = request.headers(); let req_headers = request.headers();
// The admin panel authenticates with a cookie, so the SSO provider's pages must not reach it
let allow_sso = !request.uri().path().as_str().starts_with(&format!("{}/admin", CONFIG.domain_path()));
if let Some(origin) = Self::get_allowed_origin(req_headers) { if let Some(origin) = Self::get_allowed_origin(req_headers, allow_sso) {
response.set_header(Header::new("Access-Control-Allow-Origin", origin)); response.set_header(Header::new("Access-Control-Allow-Origin", origin));
} }

Loading…
Cancel
Save