Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weโ€™ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[PM-14863] Force unlock when keys are cleared / on first unlock and fix account switching behavior #11994

Merged
merged 13 commits into from
Dec 2, 2024
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/desktop/desktop_native/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

40 changes: 20 additions & 20 deletions apps/desktop/desktop_native/core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,22 @@ default = ["sys"]
manual_test = []

sys = [
"dep:widestring",
"dep:windows",
"dep:core-foundation",
"dep:security-framework",
"dep:security-framework-sys",
"dep:gio",
"dep:libsecret",
"dep:zbus",
"dep:zbus_polkit",
"dep:widestring",
"dep:windows",
"dep:core-foundation",
"dep:security-framework",
"dep:security-framework-sys",
"dep:gio",
"dep:libsecret",
"dep:zbus",
"dep:zbus_polkit",
]

[dependencies]
aes = "=0.8.4"
anyhow = "=1.0.93"
arboard = { version = "=3.4.1", default-features = false, features = [
"wayland-data-control",
"wayland-data-control",
] }
async-stream = "=0.3.5"
base64 = "=0.22.1"
Expand All @@ -50,7 +50,7 @@ ssh-key = { version = "=0.6.6", default-features = false, features = [
"rsa",
"getrandom",
] }
bitwarden-russh = { git = "https://github.com/bitwarden/bitwarden-russh.git", branch = "km/PM-14863/allow-unlock-on-list" }
bitwarden-russh = { git = "https://github.com/bitwarden/bitwarden-russh.git", rev = "b4e7f2f" }
tokio = { version = "=1.40.0", features = ["io-util", "sync", "macros", "net"] }
tokio-stream = { version = "=0.1.15", features = ["net"] }
tokio-util = { version = "0.7.11", features = ["codec"] }
Expand All @@ -64,15 +64,15 @@ ed25519 = { version = "=2.2.3", features = ["pkcs8"] }
[target.'cfg(windows)'.dependencies]
widestring = { version = "=1.1.0", optional = true }
windows = { version = "=0.57.0", features = [
"Foundation",
"Security_Credentials_UI",
"Security_Cryptography",
"Storage_Streams",
"Win32_Foundation",
"Win32_Security_Credentials",
"Win32_System_WinRT",
"Win32_UI_Input_KeyboardAndMouse",
"Win32_UI_WindowsAndMessaging",
"Foundation",
"Security_Credentials_UI",
"Security_Cryptography",
"Storage_Streams",
"Win32_Foundation",
"Win32_Security_Credentials",
"Win32_System_WinRT",
"Win32_UI_Input_KeyboardAndMouse",
"Win32_UI_WindowsAndMessaging",
], optional = true }

[target.'cfg(windows)'.dev-dependencies]
Expand Down
46 changes: 25 additions & 21 deletions apps/desktop/desktop_native/core/src/ssh_agent/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,12 @@ pub mod importer;
pub struct BitwardenDesktopAgent {
keystore: ssh_agent::KeyStore,
cancellation_token: CancellationToken,
show_ui_request_tx: tokio::sync::mpsc::Sender<(u32, String)>,
show_ui_request_tx: tokio::sync::mpsc::Sender<(u32, (String, bool))>,
get_ui_response_rx: Arc<Mutex<tokio::sync::broadcast::Receiver<(u32, bool)>>>,
request_id: Arc<Mutex<u32>>,
// before first unlock, or after account switching, listing keys should require an unlock to get a list of public keys
/// before first unlock, or after account switching, listing keys should require an unlock to get a list of public keys
needs_unlock: Arc<Mutex<bool>>,
}

impl BitwardenDesktopAgent {
async fn get_request_id(&self) -> u32 {
let mut request_id = self.request_id.lock().await;
*request_id += 1;
*request_id
}
is_running: Arc<tokio::sync::Mutex<bool>>,
}

impl ssh_agent::Agent for BitwardenDesktopAgent {
Expand All @@ -42,8 +35,9 @@ impl ssh_agent::Agent for BitwardenDesktopAgent {
let request_id = self.get_request_id().await;

let mut rx_channel = self.get_ui_response_rx.lock().await.resubscribe();
let message = (request_id, (ssh_key.cipher_uuid.clone(), false));
self.show_ui_request_tx
.send((request_id, ssh_key.cipher_uuid.clone()))
.send(message)
.await
.expect("Should send request to ui");
while let Ok((id, response)) = rx_channel.recv().await {
Expand All @@ -55,17 +49,16 @@ impl ssh_agent::Agent for BitwardenDesktopAgent {
}

async fn can_list(&self) -> bool {
let needs_unlock = self.needs_unlock.lock().await;
if !*needs_unlock {
if !*self.needs_unlock.lock().await{
return true;
}
drop(needs_unlock);

let request_id = self.get_request_id().await;

let mut rx_channel = self.get_ui_response_rx.lock().await.resubscribe();
let message = (request_id, ("".to_string(), true));
self.show_ui_request_tx
.send((request_id, "".to_string()))
.send(message)
.await
.expect("Should send request to ui");
while let Ok((id, response)) = rx_channel.recv().await {
Expand Down Expand Up @@ -106,9 +99,7 @@ impl BitwardenDesktopAgent {
let keystore = &mut self.keystore;
keystore.0.write().expect("RwLock is not poisoned").clear();

let mut needs_unlock = self.needs_unlock.blocking_lock();
*needs_unlock = false;
drop(needs_unlock);
*self.needs_unlock.blocking_lock() = false;

for (key, name, cipher_id) in new_keys.iter() {
match parse_key_safe(&key) {
Expand Down Expand Up @@ -157,12 +148,25 @@ impl BitwardenDesktopAgent {
pub fn clear_keys(&mut self) -> Result<(), anyhow::Error> {
let keystore = &mut self.keystore;
keystore.0.write().expect("RwLock is not poisoned").clear();
let mut needs_unlock = self.needs_unlock.blocking_lock();
*needs_unlock = true;
drop(needs_unlock);
*self.needs_unlock.blocking_lock() = true;

Ok(())
}

async fn get_request_id(&self) -> u32 {
if !*self.is_running.lock().await {
println!("[BitwardenDesktopAgent] Agent is not running, but tried to get request id");
return 0;
}

let mut request_id = self.request_id.lock().await;
*request_id += 1;
*request_id
}

pub fn is_running(self) -> bool {
return self.is_running.blocking_lock().clone();
}
}

fn parse_key_safe(pem: &str) -> Result<ssh_key::private::PrivateKey, anyhow::Error> {
Expand Down
3 changes: 2 additions & 1 deletion apps/desktop/desktop_native/core/src/ssh_agent/unix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use super::BitwardenDesktopAgent;

impl BitwardenDesktopAgent {
pub async fn start_server(
auth_request_tx: tokio::sync::mpsc::Sender<(u32, String)>,
auth_request_tx: tokio::sync::mpsc::Sender<(u32, (String, bool))>,
auth_response_rx: Arc<Mutex<tokio::sync::broadcast::Receiver<(u32, bool)>>>,
) -> Result<Self, anyhow::Error> {
let agent = BitwardenDesktopAgent {
Expand All @@ -24,6 +24,7 @@ impl BitwardenDesktopAgent {
get_ui_response_rx: auth_response_rx,
request_id: Arc::new(tokio::sync::Mutex::new(0)),
needs_unlock: Arc::new(tokio::sync::Mutex::new(true)),
is_running: Arc::new(tokio::sync::Mutex::new(false)),
};
let cloned_agent_state = agent.clone();
tokio::spawn(async move {
Expand Down
3 changes: 2 additions & 1 deletion apps/desktop/desktop_native/core/src/ssh_agent/windows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use super::BitwardenDesktopAgent;

impl BitwardenDesktopAgent {
pub async fn start_server(
auth_request_tx: tokio::sync::mpsc::Sender<(u32, String)>,
auth_request_tx: tokio::sync::mpsc::Sender<(u32, (String, bool))>,
auth_response_rx: Arc<Mutex<tokio::sync::broadcast::Receiver<(u32, bool)>>>,
) -> Result<Self, anyhow::Error> {
let agent_state = BitwardenDesktopAgent {
Expand All @@ -22,6 +22,7 @@ impl BitwardenDesktopAgent {
cancellation_token: CancellationToken::new(),
request_id: Arc::new(tokio::sync::Mutex::new(0)),
needs_unlock: Arc::new(tokio::sync::Mutex::new(true)),
is_running: Arc::new(tokio::sync::Mutex::new(true)),
};
let stream = named_pipe_listener_stream::NamedPipeServerStream::new(
agent_state.cancellation_token.clone(),
Expand Down
2 changes: 1 addition & 1 deletion apps/desktop/desktop_native/napi/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ export declare namespace sshagent {
status: SshKeyImportStatus
sshKey?: SshKey
}
export function serve(callback: (err: Error | null, arg: string) => any): Promise<SshAgentState>
export function serve(callback: (err: Error | null, arg0: string, arg1: boolean) => any): Promise<SshAgentState>
export function stop(agentState: SshAgentState): void
export function isRunning(agentState: SshAgentState): boolean
export function setKeys(agentState: SshAgentState, newKeys: Array<PrivateKey>): void
Expand Down
8 changes: 4 additions & 4 deletions apps/desktop/desktop_native/napi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -247,15 +247,15 @@ pub mod sshagent {

#[napi]
pub async fn serve(
callback: ThreadsafeFunction<String, CalleeHandled>,
callback: ThreadsafeFunction<(String, bool), CalleeHandled>,
) -> napi::Result<SshAgentState> {
let (auth_request_tx, mut auth_request_rx) = tokio::sync::mpsc::channel::<(u32, String)>(32);
let (auth_request_tx, mut auth_request_rx) = tokio::sync::mpsc::channel::<(u32, (String, bool))>(32);
let (auth_response_tx, auth_response_rx) = tokio::sync::broadcast::channel::<(u32, bool)>(32);
let auth_response_tx_arc = Arc::new(Mutex::new(auth_response_tx));
tokio::spawn(async move {
let _ = auth_response_rx;

while let Some((request_id, cipher_uuid)) = auth_request_rx.recv().await {
while let Some((request_id, (cipher_uuid, is_list_request))) = auth_request_rx.recv().await {
let cloned_request_id = request_id.clone();
let cloned_cipher_uuid = cipher_uuid.clone();
let cloned_response_tx_arc = auth_response_tx_arc.clone();
Expand All @@ -266,7 +266,7 @@ pub mod sshagent {
let auth_response_tx_arc = cloned_response_tx_arc;
let callback = cloned_callback;
let promise_result: Result<Promise<bool>, napi::Error> =
callback.call_async(Ok(cipher_uuid)).await;
callback.call_async(Ok((cipher_uuid, is_list_request))).await;
match promise_result {
Ok(promise_result) => match promise_result.await {
Ok(result) => {
Expand Down
3 changes: 2 additions & 1 deletion apps/desktop/src/platform/main/main-ssh-agent.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
init() {
// handle sign request passing to UI
sshagent
.serve(async (err: Error, cipherId: string) => {
.serve(async (err: Error, cipherId: string, isListRequest: boolean) => {

Check warning on line 30 in apps/desktop/src/platform/main/main-ssh-agent.service.ts

View check run for this annotation

Codecov / codecov/patch

apps/desktop/src/platform/main/main-ssh-agent.service.ts#L30

Added line #L30 was not covered by tests
// clear all old (> SIGN_TIMEOUT) requests
this.requestResponses = this.requestResponses.filter(
(response) => response.timestamp > new Date(Date.now() - this.SIGN_TIMEOUT),
Expand All @@ -37,6 +37,7 @@
const id_for_this_request = this.request_id;
this.messagingService.send("sshagent.signrequest", {
cipherId,
isListRequest,
requestId: id_for_this_request,
});

Expand Down Expand Up @@ -112,9 +113,9 @@
}
});

ipcMain.handle("sshagent.clearkeys", async (event: any) => {

Check warning on line 116 in apps/desktop/src/platform/main/main-ssh-agent.service.ts

View check run for this annotation

Codecov / codecov/patch

apps/desktop/src/platform/main/main-ssh-agent.service.ts#L116

Added line #L116 was not covered by tests
if (this.agentState != null) {
sshagent.clearKeys(this.agentState);

Check warning on line 118 in apps/desktop/src/platform/main/main-ssh-agent.service.ts

View check run for this annotation

Codecov / codecov/patch

apps/desktop/src/platform/main/main-ssh-agent.service.ts#L118

Added line #L118 was not covered by tests
}
});
}
Expand Down
67 changes: 38 additions & 29 deletions apps/desktop/src/platform/services/ssh-agent.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
withLatestFrom,
} from "rxjs";

import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";

Check warning on line 21 in apps/desktop/src/platform/services/ssh-agent.service.ts

View check run for this annotation

Codecov / codecov/patch

apps/desktop/src/platform/services/ssh-agent.service.ts#L21

Added line #L21 was not covered by tests
import { AuthService } from "@bitwarden/common/auth/abstractions/auth.service";
import { AuthenticationStatus } from "@bitwarden/common/auth/enums/authentication-status";
import { FeatureFlag } from "@bitwarden/common/enums/feature-flag.enum";
Expand Down Expand Up @@ -54,7 +54,7 @@
private i18nService: I18nService,
private desktopSettingsService: DesktopSettingsService,
private configService: ConfigService,
private accountService: AccountService,

Check warning on line 57 in apps/desktop/src/platform/services/ssh-agent.service.ts

View check run for this annotation

Codecov / codecov/patch

apps/desktop/src/platform/services/ssh-agent.service.ts#L57

Added line #L57 was not covered by tests
) {}

async init() {
Expand Down Expand Up @@ -115,39 +115,36 @@
),
),
// This concatMap handles showing the dialog to approve the request.
concatMap(([message, ciphers]) => {
switchMap(([message, ciphers]) => {
const cipherId = message.cipherId as string;
const isListRequest = message.isListRequest as boolean;

Check warning on line 120 in apps/desktop/src/platform/services/ssh-agent.service.ts

View check run for this annotation

Codecov / codecov/patch

apps/desktop/src/platform/services/ssh-agent.service.ts#L120

Added line #L120 was not covered by tests
const requestId = message.requestId as number;

// cipherid is empty has the special meaning of "unlock in order to list public keys"
if (cipherId == "") {
return of(true).pipe(
switchMap(async (result) => {
const sshCiphers = ciphers.filter(
(cipher) => cipher.type === CipherType.SshKey && !cipher.isDeleted,
);
const keys = sshCiphers.map((cipher) => {
return {
name: cipher.name,
privateKey: cipher.sshKey.privateKey,
cipherId: cipher.id,
};
});
await ipc.platform.sshAgent.setKeys(keys);
await ipc.platform.sshAgent.signRequestResponse(requestId, Boolean(result));
}),
);
if (isListRequest) {
(async () => {
const sshCiphers = ciphers.filter(

Check warning on line 125 in apps/desktop/src/platform/services/ssh-agent.service.ts

View check run for this annotation

Codecov / codecov/patch

apps/desktop/src/platform/services/ssh-agent.service.ts#L124-L125

Added lines #L124 - L125 were not covered by tests
(cipher) => cipher.type === CipherType.SshKey && !cipher.isDeleted,
);
const keys = sshCiphers.map((cipher) => {
return {

Check warning on line 129 in apps/desktop/src/platform/services/ssh-agent.service.ts

View check run for this annotation

Codecov / codecov/patch

apps/desktop/src/platform/services/ssh-agent.service.ts#L128-L129

Added lines #L128 - L129 were not covered by tests
name: cipher.name,
privateKey: cipher.sshKey.privateKey,
cipherId: cipher.id,
};
});
await ipc.platform.sshAgent.setKeys(keys);
await ipc.platform.sshAgent.signRequestResponse(requestId, true);
})().catch((e) => this.logService.error("Failed to respond to SSH request", e));
coroiu marked this conversation as resolved.
Show resolved Hide resolved
return;

Check warning on line 138 in apps/desktop/src/platform/services/ssh-agent.service.ts

View check run for this annotation

Codecov / codecov/patch

apps/desktop/src/platform/services/ssh-agent.service.ts#L135-L138

Added lines #L135 - L138 were not covered by tests
}

if (ciphers === undefined) {
return of(false).pipe(
switchMap((result) =>
ipc.platform.sshAgent.signRequestResponse(requestId, Boolean(result)),
),
);
ipc.platform.sshAgent

Check warning on line 142 in apps/desktop/src/platform/services/ssh-agent.service.ts

View check run for this annotation

Codecov / codecov/patch

apps/desktop/src/platform/services/ssh-agent.service.ts#L142

Added line #L142 was not covered by tests
.signRequestResponse(requestId, false)
.catch((e) => this.logService.error("Failed to respond to SSH request", e));

Check warning on line 144 in apps/desktop/src/platform/services/ssh-agent.service.ts

View check run for this annotation

Codecov / codecov/patch

apps/desktop/src/platform/services/ssh-agent.service.ts#L144

Added line #L144 was not covered by tests
}

const cipher = ciphers.find((cipher) => cipher.id == cipherId);

Check warning on line 147 in apps/desktop/src/platform/services/ssh-agent.service.ts

View check run for this annotation

Codecov / codecov/patch

apps/desktop/src/platform/services/ssh-agent.service.ts#L147

Added line #L147 was not covered by tests
coroiu marked this conversation as resolved.
Show resolved Hide resolved

ipc.platform.focusWindow();
const dialogRef = ApproveSshRequestComponent.open(
Expand All @@ -158,22 +155,34 @@

return dialogRef.closed.pipe(
switchMap((result) => {
return ipc.platform.sshAgent.signRequestResponse(requestId, Boolean(result));
return ipc.platform.sshAgent.signRequestResponse(requestId, result);

Check warning on line 158 in apps/desktop/src/platform/services/ssh-agent.service.ts

View check run for this annotation

Codecov / codecov/patch

apps/desktop/src/platform/services/ssh-agent.service.ts#L158

Added line #L158 was not covered by tests
}),
);
}),
takeUntil(this.destroy$),
)
.subscribe();

this.accountService.activeAccount$
.pipe(skip(1), takeUntil(this.destroy$))
.subscribe((account) => {
this.accountService.activeAccount$.pipe(skip(1), takeUntil(this.destroy$)).subscribe({

Check warning on line 166 in apps/desktop/src/platform/services/ssh-agent.service.ts

View check run for this annotation

Codecov / codecov/patch

apps/desktop/src/platform/services/ssh-agent.service.ts#L166

Added line #L166 was not covered by tests
next: (account) => {
this.logService.info("Active account changed, clearing SSH keys");
ipc.platform.sshAgent

Check warning on line 169 in apps/desktop/src/platform/services/ssh-agent.service.ts

View check run for this annotation

Codecov / codecov/patch

apps/desktop/src/platform/services/ssh-agent.service.ts#L168-L169

Added lines #L168 - L169 were not covered by tests
.clearKeys()
.catch((e) => this.logService.error("Failed to clear SSH keys", e));

Check warning on line 171 in apps/desktop/src/platform/services/ssh-agent.service.ts

View check run for this annotation

Codecov / codecov/patch

apps/desktop/src/platform/services/ssh-agent.service.ts#L171

Added line #L171 was not covered by tests
});
},
error: (e: unknown) => {
this.logService.error("Error in active account observable", e);
ipc.platform.sshAgent

Check warning on line 175 in apps/desktop/src/platform/services/ssh-agent.service.ts

View check run for this annotation

Codecov / codecov/patch

apps/desktop/src/platform/services/ssh-agent.service.ts#L174-L175

Added lines #L174 - L175 were not covered by tests
.clearKeys()
.catch((e) => this.logService.error("Failed to clear SSH keys", e));

Check warning on line 177 in apps/desktop/src/platform/services/ssh-agent.service.ts

View check run for this annotation

Codecov / codecov/patch

apps/desktop/src/platform/services/ssh-agent.service.ts#L177

Added line #L177 was not covered by tests
},
complete: () => {
this.logService.info("Active account observable completed, clearing SSH keys");
ipc.platform.sshAgent

Check warning on line 181 in apps/desktop/src/platform/services/ssh-agent.service.ts

View check run for this annotation

Codecov / codecov/patch

apps/desktop/src/platform/services/ssh-agent.service.ts#L180-L181

Added lines #L180 - L181 were not covered by tests
.clearKeys()
.catch((e) => this.logService.error("Failed to clear SSH keys", e));

Check warning on line 183 in apps/desktop/src/platform/services/ssh-agent.service.ts

View check run for this annotation

Codecov / codecov/patch

apps/desktop/src/platform/services/ssh-agent.service.ts#L183

Added line #L183 was not covered by tests
},
});

combineLatest([
timer(0, this.SSH_REFRESH_INTERVAL),
Expand All @@ -182,7 +191,7 @@
.pipe(
concatMap(async ([, enabled]) => {
if (!enabled) {
await ipc.platform.sshAgent.clearKeys();

Check warning on line 194 in apps/desktop/src/platform/services/ssh-agent.service.ts

View check run for this annotation

Codecov / codecov/patch

apps/desktop/src/platform/services/ssh-agent.service.ts#L194

Added line #L194 was not covered by tests
return;
}

Expand Down
Loading