From 34ac16e9d77272a74c17eaaa90e79ca9d20f3af2 Mon Sep 17 00:00:00 2001
From: BlackDex <black.dex@gmail.com>
Date: Fri, 20 Jan 2023 15:43:45 +0100
Subject: [PATCH] Validate note sizes on key-rotation.

We also need to validate the note sizes on key-rotation.
If we do not validate them before we store them, that could lead to a
partial or total loss of the password vault. Validating these
restrictions before actually processing them to store/replace the
existing ciphers should prevent this.

There was also a small bug when using web-sockets. The client which is
triggering the password/key-rotation change should not be forced to
logout via a web-socket request. That is something the client will
handle it self. Refactored the logout notification to either send the
device uuid or not on specific actions.

Fixes #3152
---
 src/api/admin.rs         |  6 +++---
 src/api/core/accounts.rs | 22 +++++++++++++++++-----
 src/api/notifications.rs | 10 ++++++++++
 3 files changed, 30 insertions(+), 8 deletions(-)

diff --git a/src/api/admin.rs b/src/api/admin.rs
index 6e0c2acf..f22d3bc2 100644
--- a/src/api/admin.rs
+++ b/src/api/admin.rs
@@ -13,7 +13,7 @@ use rocket::{
 };
 
 use crate::{
-    api::{core::log_event, ApiResult, EmptyResult, JsonResult, Notify, NumberOrString, UpdateType},
+    api::{core::log_event, ApiResult, EmptyResult, JsonResult, Notify, NumberOrString},
     auth::{decode_admin, encode_jwt, generate_admin_claims, ClientIp},
     config::ConfigBuilder,
     db::{backup_database, get_sql_server_version, models::*, DbConn, DbConnType},
@@ -372,7 +372,7 @@ async fn deauth_user(uuid: String, _token: AdminToken, mut conn: DbConn, nt: Not
 
     let save_result = user.save(&mut conn).await;
 
-    nt.send_user_update(UpdateType::LogOut, &user).await;
+    nt.send_logout(&user, None).await;
 
     save_result
 }
@@ -386,7 +386,7 @@ async fn disable_user(uuid: String, _token: AdminToken, mut conn: DbConn, nt: No
 
     let save_result = user.save(&mut conn).await;
 
-    nt.send_user_update(UpdateType::LogOut, &user).await;
+    nt.send_logout(&user, None).await;
 
     save_result
 }
diff --git a/src/api/core/accounts.rs b/src/api/core/accounts.rs
index 758d9028..6220c1b5 100644
--- a/src/api/core/accounts.rs
+++ b/src/api/core/accounts.rs
@@ -323,7 +323,10 @@ async fn post_password(
     user.akey = data.Key;
     let save_result = user.save(&mut conn).await;
 
-    nt.send_user_update(UpdateType::LogOut, &user).await;
+    // Prevent loging out the client where the user requested this endpoint from.
+    // If you do logout the user it will causes issues at the client side.
+    // Adding the device uuid will prevent this.
+    nt.send_logout(&user, Some(headers.device.uuid)).await;
 
     save_result
 }
@@ -354,7 +357,7 @@ async fn post_kdf(data: JsonUpcase<ChangeKdfData>, headers: Headers, mut conn: D
     user.akey = data.Key;
     let save_result = user.save(&mut conn).await;
 
-    nt.send_user_update(UpdateType::LogOut, &user).await;
+    nt.send_logout(&user, Some(headers.device.uuid)).await;
 
     save_result
 }
@@ -392,6 +395,12 @@ async fn post_rotatekey(
         err!("Invalid password")
     }
 
+    // Validate the import before continuing
+    // 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.
+    // TODO: See if we can optimize the whole cipher adding/importing and prevent duplicate code and checks.
+    Cipher::validate_notes(&data.Ciphers)?;
+
     let user_uuid = &headers.user.uuid;
 
     // Update folder data
@@ -438,7 +447,10 @@ async fn post_rotatekey(
 
     let save_result = user.save(&mut conn).await;
 
-    nt.send_user_update(UpdateType::LogOut, &user).await;
+    // Prevent loging out the client where the user requested this endpoint from.
+    // If you do logout the user it will causes issues at the client side.
+    // Adding the device uuid will prevent this.
+    nt.send_logout(&user, Some(headers.device.uuid)).await;
 
     save_result
 }
@@ -461,7 +473,7 @@ async fn post_sstamp(
     user.reset_security_stamp();
     let save_result = user.save(&mut conn).await;
 
-    nt.send_user_update(UpdateType::LogOut, &user).await;
+    nt.send_logout(&user, None).await;
 
     save_result
 }
@@ -564,7 +576,7 @@ async fn post_email(
     user.akey = data.Key;
     let save_result = user.save(&mut conn).await;
 
-    nt.send_user_update(UpdateType::LogOut, &user).await;
+    nt.send_logout(&user, None).await;
 
     save_result
 }
diff --git a/src/api/notifications.rs b/src/api/notifications.rs
index b51e1380..b4dc55e9 100644
--- a/src/api/notifications.rs
+++ b/src/api/notifications.rs
@@ -170,6 +170,16 @@ impl WebSocketUsers {
         self.send_update(&user.uuid, &data).await;
     }
 
+    pub async fn send_logout(&self, user: &User, acting_device_uuid: Option<String>) {
+        let data = create_update(
+            vec![("UserId".into(), user.uuid.clone().into()), ("Date".into(), serialize_date(user.updated_at))],
+            UpdateType::LogOut,
+            acting_device_uuid,
+        );
+
+        self.send_update(&user.uuid, &data).await;
+    }
+
     pub async fn send_folder_update(&self, ut: UpdateType, folder: &Folder, acting_device_uuid: &String) {
         let data = create_update(
             vec![