Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

Bitwarden two-step login: one device for every try, and a refused code is not a wrong password (#527)

skullsdev721fe9c3a902
diff --git a/frontend/src/components/PasswordStorePanel.tsx b/frontend/src/components/PasswordStorePanel.tsx
index 824154e2..c24f9c7a 100644
--- a/frontend/src/components/PasswordStorePanel.tsx
+++ b/frontend/src/components/PasswordStorePanel.tsx
@@ -180,7 +180,13 @@ export const BitwardenLoginForm: React.FC<{
const p = err instanceof StoreError ? err.problem : ({ kind: 'error', message: 'Couldn’t reach the server.' } as UnlockProblem);
setProblem(p);
setTriedServer(server);
- if (p.kind === 'two-factor') {
+ if (p.kind === 'code-rejected') {
+ // Keep the master password: it was never the problem, and re-typing it hides the real one.
+ // Keep the list already shown: the server names only the method that was tried.
+ setStep((s) => (s?.kind === 'two-factor' ? s : { kind: 'two-factor', providers: p.providers }));
+ setCode('');
+ codeRef.current?.focus();
+ } else if (p.kind === 'two-factor') {
setStep(p);
setProvider(p.providers.find((x) => x.usable)?.id ?? null);
setCode('');
diff --git a/frontend/src/passwordStore.ts b/frontend/src/passwordStore.ts
index a6e57d99..9f24259b 100644
--- a/frontend/src/passwordStore.ts
+++ b/frontend/src/passwordStore.ts
@@ -139,6 +139,7 @@ export type UnlockProblem =
| { kind: 'needs-token' }
| { kind: 'wrong-password' }
| { kind: 'two-factor'; providers: Array<{ id: number; name: string; usable: boolean }> }
+ | { kind: 'code-rejected'; providers: Array<{ id: number; name: string; usable: boolean }> }
| { kind: 'new-device-code' }
| { kind: 'other-account' }
| { kind: 'invalid'; message: string }
@@ -151,6 +152,8 @@ export function unlockProblemFor(status: number, body: unknown): UnlockProblem {
const message = str(o.error) ?? '';
if (status === 401 && isPersonOnlyBody(body)) return { kind: 'needs-token' };
if (o.wrong_password === true) return { kind: 'wrong-password' };
+ if (o.needs === 'two_factor' && o.code_rejected === true)
+ return { kind: 'code-rejected', providers: twoFactorChoices(o.providers) };
if (o.needs === 'two_factor') return { kind: 'two-factor', providers: twoFactorChoices(o.providers) };
if (o.needs === 'new_device_otp') return { kind: 'new-device-code' };
if (status === 409) return { kind: 'other-account' };
@@ -171,6 +174,11 @@ export function unlockProblemText(p: UnlockProblem): string {
return p.providers.some((x) => x.usable)
? 'Your account uses two-step login. Enter the code to continue.'
: `Your account’s two-step login (${p.providers.map((x) => x.name).join(', ') || 'unknown'}) can’t be done here. Use an API key instead.`;
+ case 'code-rejected':
+ // An authenticator code (0) goes stale every 30 seconds; an emailed one (1) or a key's (3) doesn't
+ return p.providers.some((x) => x.id === 0)
+ ? 'That code wasn’t accepted. Codes change every 30 seconds — enter the one showing now, and check the clock on your phone.'
+ : 'That code wasn’t accepted. Check it and try again, or ask for a new one.';
case 'new-device-code':
return 'Bitwarden emailed you a code to confirm this new device. Enter it to continue.';
case 'other-account':
diff --git a/frontend/tests/bitwardenStore.test.mjs b/frontend/tests/bitwardenStore.test.mjs
index d0fcb2d9..a4141593 100644
--- a/frontend/tests/bitwardenStore.test.mjs
+++ b/frontend/tests/bitwardenStore.test.mjs
@@ -79,6 +79,13 @@ test('unlock answers: token, wrong password, two-step, new device, other account
assert.deepEqual(m.unlockProblemFor(401, { person_only: true }), { kind: 'needs-token' });
assert.deepEqual(m.unlockProblemFor(401, { wrong_password: true, error: 'x' }), { kind: 'wrong-password' });
assert.equal(m.unlockProblemFor(401, { needs: 'two_factor', providers: ['0'] }).kind, 'two-factor');
+ // A refused code is its own problem, never the master password (PR #527)
+ const rejected = m.unlockProblemFor(401, { needs: 'two_factor', code_rejected: true, providers: ['0'] });
+ assert.equal(rejected.kind, 'code-rejected');
+ assert.deepEqual(rejected.providers.map((x) => x.id), [0]);
+ assert.match(m.unlockProblemText(rejected), /30 seconds/);
+ assert.doesNotMatch(m.unlockProblemText(m.unlockProblemFor(401, { needs: 'two_factor', code_rejected: true, providers: ['1'] })), /30 seconds/);
+ assert.doesNotMatch(m.unlockProblemText(rejected), /master password/i);
assert.deepEqual(m.unlockProblemFor(401, { needs: 'new_device_otp' }), { kind: 'new-device-code' });
assert.deepEqual(m.unlockProblemFor(409, {}), { kind: 'other-account' });
assert.deepEqual(m.unlockProblemFor(400, { error: 'the Bitwarden server must be an https address' }), { kind: 'invalid', message: 'the Bitwarden server must be an https address' });
diff --git a/src/sandbox/bitwarden.rs b/src/sandbox/bitwarden.rs
index 06a8f34b..267d678c 100644
--- a/src/sandbox/bitwarden.rs
+++ b/src/sandbox/bitwarden.rs
@@ -52,6 +52,8 @@ pub enum UnlockError {
Wrong,
#[error("Bitwarden asks for a two-step login code")]
TwoFactor(Vec<String>),
+ #[error("that two-step login code was not accepted")]
+ TwoFactorRejected(Vec<String>),
#[error("Bitwarden emailed a code to confirm this new device")]
NewDeviceOtp,
#[error("another Bitwarden account is set up; forget it first")]
@@ -73,6 +75,7 @@ impl UnlockError {
match self {
UnlockError::Wrong => "wrong",
UnlockError::TwoFactor(_) => "two_factor",
+ UnlockError::TwoFactorRejected(_) => "two_factor_rejected",
UnlockError::NewDeviceOtp => "new_device_otp",
UnlockError::OtherAccount => "other_account",
UnlockError::Invalid(_) => "invalid",
@@ -421,6 +424,11 @@ pub struct BitwardenStore {
session: tokio::sync::Mutex<Option<Session>>,
http: reqwest::Client,
rng: SystemRandom,
+ /// The device id sent before any account is set up: random, and the same on every try while
+ /// kwnt runs, so the code Bitwarden emails for a new device matches the device that types it.
+ /// Saved with the settings once a connect succeeds. Never derived from the server or email:
+ /// anyone could work that out and pass for a device the account already trusts.
+ pending_device_id: String,
}
impl std::fmt::Debug for BitwardenStore {
@@ -464,6 +472,7 @@ impl BitwardenStore {
.build()
.unwrap_or_default(),
rng: SystemRandom::new(),
+ pending_device_id: uuid::Uuid::new_v4().to_string(),
}
}
@@ -547,10 +556,10 @@ impl BitwardenStore {
return Err(UnlockError::Invalid("the API key's client secret is missing".into()));
}
let cfg = BitwardenConfig {
- server_url: base,
+ server_url: base.clone(),
email: email.clone(),
client_id: client_id.clone(),
- device_id: existing.as_ref().map(|c| c.device_id.clone()).unwrap_or_else(|| uuid::Uuid::new_v4().to_string()),
+ device_id: existing.as_ref().map(|c| c.device_id.clone()).unwrap_or_else(|| self.pending_device_id.clone()),
};
let (kdf, salt) = self.prelogin(&ep, &email, status).await?;
@@ -578,7 +587,7 @@ impl BitwardenStore {
if let (Some(p), Some(t)) = (req.two_factor_provider, req.two_factor_token.as_deref()) {
form.extend([
("twoFactorProvider", p.to_string()),
- ("twoFactorToken", t.trim().to_string()),
+ ("twoFactorToken", normalize_code(p, t)),
("twoFactorRemember", "0".into()),
]);
}
@@ -748,6 +757,12 @@ impl BitwardenStore {
if form.iter().any(|(k, v)| *k == "grant_type" && v == "password") {
rb = rb.header("Auth-Email", URL_SAFE_NO_PAD.encode(email));
}
+ // Bitwarden answers `invalid_grant` both for a wrong password and for a rejected
+ // two-step code, so remember whether one was sent: that is the only thing that tells
+ // the two apart, and calling a stale code a wrong password sends the person back to
+ // the password field for a code they cannot fix there.
+ let sent_code = form.iter().any(|(k, _)| *k == "twoFactorToken");
+ let sent_provider = form.iter().find(|(k, _)| *k == "twoFactorProvider").map(|(_, v)| v.clone());
drop(form);
let resp = rb.send().await.map_err(|e| UnlockError::Unreachable(short(&e.without_url().to_string())))?;
let status = resp.status();
@@ -756,12 +771,6 @@ impl BitwardenStore {
if status.is_success() {
return Ok(body);
}
- if let Some(p) = field(&body, "TwoFactorProviders2").and_then(Value::as_object) {
- return Err(UnlockError::TwoFactor(p.keys().cloned().collect()));
- }
- if let Some(p) = field(&body, "TwoFactorProviders").and_then(Value::as_array) {
- return Err(UnlockError::TwoFactor(p.iter().map(|v| v.as_str().map(str::to_string).unwrap_or_else(|| v.to_string())).collect()));
- }
let message = [
field_str(&body, "error_description"),
field(&body, "ErrorModel").and_then(|m| field_str(m, "Message")),
@@ -772,11 +781,29 @@ impl BitwardenStore {
.find(|m| !m.trim().is_empty())
.unwrap_or_default()
.to_string();
- if message.to_lowercase().contains("new device") {
- return Err(UnlockError::NewDeviceOtp);
- }
let error = field_str(&body, "error").unwrap_or_default();
let lower = message.to_lowercase();
+
+ // A rejected code comes back looking exactly like a fresh challenge: the same
+ // `TwoFactorProviders2` list, the same 400. Reading that list first therefore reported every
+ // wrong code as "a code is needed", handing the person the same empty box back for as long as
+ // they kept trying, with nothing to say their code had been looked at and refused. Whether a
+ // code was sent is the only thing that separates the two cases, so that is what decides now.
+ // Only a refusal (4xx) is about the code; a 429 or a 5xx says nothing about it. No log line
+ // here: unlock() already logs the kind and status, and the server's text can quote the
+ // person's IP address (spec C3).
+ if sent_code && status.is_client_error() && status != reqwest::StatusCode::TOO_MANY_REQUESTS {
+ return Err(UnlockError::TwoFactorRejected(sent_provider.into_iter().collect()));
+ }
+ if lower.contains("new device") {
+ return Err(UnlockError::NewDeviceOtp);
+ }
+ if let Some(p) = field(&body, "TwoFactorProviders2").and_then(Value::as_object) {
+ return Err(UnlockError::TwoFactor(p.keys().cloned().collect()));
+ }
+ if let Some(p) = field(&body, "TwoFactorProviders").and_then(Value::as_array) {
+ return Err(UnlockError::TwoFactor(p.iter().map(|v| v.as_str().map(str::to_string).unwrap_or_else(|| v.to_string())).collect()));
+ }
if matches!(error, "invalid_grant" | "invalid_client")
|| status == reqwest::StatusCode::UNAUTHORIZED
|| lower.contains("password is incorrect")
@@ -1256,3 +1283,28 @@ mod tests {
assert!(matches!(store.unlock(req).await, Err(UnlockError::OtherAccount)));
}
}
+
+
+/// The Bitwarden app shows a code as `123 456`, and people paste it that way. The server matches
+/// digits only, so a code carrying its space was refused as if it were wrong. Typed-digit methods are
+/// reduced to their digits; a YubiKey (3) sends a long string and is passed through untouched.
+fn normalize_code(provider: u32, code: &str) -> String {
+ let code = code.trim();
+ if provider == 0 || provider == 1 {
+ code.chars().filter(|c| c.is_ascii_digit()).collect()
+ } else {
+ code.to_string()
+ }
+}
+
+#[cfg(test)]
+mod code_tests {
+ use super::normalize_code;
+
+ #[test]
+ fn a_code_pasted_with_its_space_still_matches() {
+ assert_eq!(normalize_code(0, " 123 456 "), "123456");
+ assert_eq!(normalize_code(1, "123456"), "123456");
+ assert_eq!(normalize_code(3, "cccccccc"), "cccccccc");
+ }
+}
diff --git a/src/server/passwords.rs b/src/server/passwords.rs
index 59f0f876..83528e72 100644
--- a/src/server/passwords.rs
+++ b/src/server/passwords.rs
@@ -539,6 +539,7 @@ pub async fn unlock_bitwarden(State(state): State<AppState>, headers: HeaderMap,
let (status, extra) = match e {
UnlockError::Wrong => (StatusCode::UNAUTHORIZED, json!({"wrong_password": true})),
UnlockError::TwoFactor(providers) => (StatusCode::UNAUTHORIZED, json!({"needs": "two_factor", "providers": providers})),
+ UnlockError::TwoFactorRejected(providers) => (StatusCode::UNAUTHORIZED, json!({"needs": "two_factor", "code_rejected": true, "providers": providers})),
UnlockError::NewDeviceOtp => (StatusCode::UNAUTHORIZED, json!({"needs": "new_device_otp"})),
UnlockError::OtherAccount => (StatusCode::CONFLICT, json!({})),
UnlockError::Invalid(_) | UnlockError::Unsupported(_) => (StatusCode::BAD_REQUEST, json!({})),
diff --git a/tests/bitwarden_test.rs b/tests/bitwarden_test.rs
index a98226e3..c85f494c 100644
--- a/tests/bitwarden_test.rs
+++ b/tests/bitwarden_test.rs
@@ -400,12 +400,12 @@ fn kwnt_is_not_dumpable() {
// ---- 0.7.3 C1, C2, C4 (github-connect-073/spec.md): a mock Bitwarden on this machine ----
mod mock {
- use axum::{extract::State, routing::{get, post}, Form, Json, Router};
+ use axum::{extract::State, http::StatusCode, routing::{get, post}, Form, Json, Router};
use kwnt::sandbox::bitwarden::{self, Kdf, SymKey};
use ring::rand::SystemRandom;
use serde_json::{json, Value};
use std::collections::HashMap;
- use std::sync::Arc;
+ use std::sync::{Arc, Mutex};
pub const PASSWORD: &str = "DUMMY-master-pw-073";
pub const EMAIL: &str = "[email protected]";
@@ -429,6 +429,24 @@ mod mock {
/// Serves prelogin, token and sync for one account whose master-key salt is `salt`.
/// `prelogin_salt`: what prelogin says about it (None: nothing, as older servers).
pub async fn serve(salt: &str, prelogin_salt: Option<&str>, key_in: KeyIn) -> String {
+ let state = Arc::new(account(salt, prelogin_salt, key_in));
+ let app = Router::new()
+ .route("/identity/accounts/prelogin", post(|State(m): State<Arc<Mock>>| async move { Json(m.prelogin.clone()) }))
+ .route(
+ "/identity/connect/token",
+ post(|State(m): State<Arc<Mock>>, Form(f): Form<HashMap<String, String>>| async move {
+ if f.get("password") == Some(&m.hash) {
+ (StatusCode::OK, Json(m.token.clone()))
+ } else {
+ (StatusCode::BAD_REQUEST, Json(wrong_password()))
+ }
+ }),
+ )
+ .with_state(state);
+ listen(app).await
+ }
+
+ fn account(salt: &str, prelogin_salt: Option<&str>, key_in: KeyIn) -> Mock {
let rng = SystemRandom::new();
let kdf = Kdf::Pbkdf2 { iterations: ITERATIONS };
let mk = bitwarden::master_key_salted(PASSWORD, salt, kdf).unwrap();
@@ -452,27 +470,62 @@ mod mock {
"masterKeyEncryptedUserKey": user_key, "salt": salt}});
}
}
- let state = Arc::new(Mock { prelogin, hash: bitwarden::auth_hash(&mk, PASSWORD).to_string(), token });
+ Mock { prelogin, hash: bitwarden::auth_hash(&mk, PASSWORD).to_string(), token }
+ }
+
+ fn wrong_password() -> Value {
+ json!({"error": "invalid_grant", "error_description": "invalid_username_or_password",
+ "ErrorModel": {"Message": "Username or password is incorrect. Try again."}})
+ }
+
+ /// Adds sync and serves `app` on a free local port.
+ async fn listen(app: Router) -> String {
+ let app = app.route("/api/sync", get(|| async { Json(json!({"profile": {"id": "u-073"}, "folders": [], "ciphers": []})) }));
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
+ format!("http://{addr}")
+ }
+
+ /// The authenticator code the two-step account takes.
+ pub const CODE: &str = "123456";
+ /// A code the two-step mock answers with 429, as a server that is rate limiting.
+ pub const CODE_429: &str = "429429";
+
+ #[derive(Clone)]
+ struct TwoStep {
+ mock: Arc<Mock>,
+ devices: Arc<Mutex<Vec<String>>>,
+ }
+
+ /// One account (email salt, key at the top level) with authenticator two-step login whose code
+ /// is `CODE`. Each `deviceIdentifier` the token endpoint sees is pushed onto `devices`.
+ pub async fn serve_two_step(devices: Arc<Mutex<Vec<String>>>) -> String {
+ let salt = bitwarden::email_salt(EMAIL);
+ let state = TwoStep { mock: Arc::new(account(&salt, Some(&salt), KeyIn::TopLevel)), devices };
let app = Router::new()
- .route("/identity/accounts/prelogin", post(|State(m): State<Arc<Mock>>| async move { Json(m.prelogin.clone()) }))
+ .route("/identity/accounts/prelogin", post(|State(t): State<TwoStep>| async move { Json(t.mock.prelogin.clone()) }))
.route(
"/identity/connect/token",
- post(|State(m): State<Arc<Mock>>, Form(f): Form<HashMap<String, String>>| async move {
- if f.get("password") == Some(&m.hash) {
- (axum::http::StatusCode::OK, Json(m.token.clone()))
- } else {
- let wrong = json!({"error": "invalid_grant", "error_description": "invalid_username_or_password",
- "ErrorModel": {"Message": "Username or password is incorrect. Try again."}});
- (axum::http::StatusCode::BAD_REQUEST, Json(wrong))
+ post(|State(t): State<TwoStep>, Form(f): Form<HashMap<String, String>>| async move {
+ t.devices.lock().unwrap().push(f.get("deviceIdentifier").cloned().unwrap_or_default());
+ if f.get("password") != Some(&t.mock.hash) {
+ return (StatusCode::BAD_REQUEST, Json(wrong_password()));
+ }
+ // A refused code and a first try look the same, as Bitwarden's do: the same
+ // 400, `invalid_grant` and list of methods
+ let challenge = json!({"error": "invalid_grant", "error_description": "invalid_username_or_password",
+ "TwoFactorProviders": ["0"], "TwoFactorProviders2": {"0": null},
+ "ErrorModel": {"Message": "Two-step token is invalid. Try again."}});
+ match (f.get("twoFactorProvider").map(String::as_str), f.get("twoFactorToken").map(String::as_str)) {
+ (Some("0"), Some(CODE)) => (StatusCode::OK, Json(t.mock.token.clone())),
+ (_, Some(CODE_429)) => (StatusCode::TOO_MANY_REQUESTS, Json(json!({"message": "Slow down."}))),
+ _ => (StatusCode::BAD_REQUEST, Json(challenge)),
}
}),
)
- .route("/api/sync", get(|| async { Json(json!({"profile": {"id": "u-073"}, "folders": [], "ciphers": []})) }))
.with_state(state);
- let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
- let addr = listener.local_addr().unwrap();
- tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
- format!("http://{addr}")
+ listen(app).await
}
}
@@ -550,3 +603,64 @@ async fn a_failed_connect_sets_nothing_up() {
assert_eq!(v["store"], "bitwarden", "{v}");
assert!(config.exists());
}
+
+// ---- PR #527: a refused two-step code is not a wrong master password, and every try before the
+// account is set up comes from one device ----
+
+fn code_req(server: &str, provider: u32, code: &str) -> bitwarden::UnlockRequest {
+ let mut req = unlock_req(server, mock::PASSWORD);
+ req.two_factor_provider = Some(provider);
+ req.two_factor_token = Some(code.into());
+ req
+}
+
+#[tokio::test]
+async fn a_refused_two_step_code_is_not_a_wrong_password() {
+ let devices = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
+ let server = mock::serve_two_step(devices.clone()).await;
+ let dir = tempdir().unwrap();
+ let store = bitwarden::BitwardenStore::open(dir.path());
+ let err = store.unlock(unlock_req(&server, mock::PASSWORD)).await.expect_err("asks for a code");
+ assert!(matches!(err, bitwarden::UnlockError::TwoFactor(ref p) if *p == ["0"]), "{err:?}");
+ let err = store.unlock(code_req(&server, 0, "000000")).await.expect_err("refused");
+ assert!(matches!(err, bitwarden::UnlockError::TwoFactorRejected(ref p) if *p == ["0"]), "{err:?}");
+ // A 429 says nothing about the code
+ let err = store.unlock(code_req(&server, 0, mock::CODE_429)).await.expect_err("rate limited");
+ assert_eq!(err.kind(), "server", "{err:?}");
+ // A wrong password without a code is still a wrong password
+ let err = store.unlock(unlock_req(&server, "DUMMY-wrong-pw")).await.expect_err("wrong");
+ assert_eq!(err.kind(), "wrong");
+ assert!(!dir.path().join(bitwarden::CONFIG_FILE).exists(), "nothing set up yet");
+ // The code as the app shows it, with its space
+ store.unlock(code_req(&server, 0, "123 456")).await.expect("the right code connects");
+ assert!(store.is_unlocked().await);
+ let id = store.config().expect("set up").device_id;
+ assert!(uuid::Uuid::parse_str(&id).is_ok(), "{id}");
+ let seen = devices.lock().unwrap().clone();
+ assert_eq!(seen.len(), 5, "{seen:?}");
+ assert!(seen.iter().all(|d| *d == id), "one device for every try: {seen:?}");
+
+ // Another kwnt with the same server and account is another device: the id is not worked out
+ // from them, or anyone could pass for a device the account already trusts
+ let dir2 = tempdir().unwrap();
+ let other = bitwarden::BitwardenStore::open(dir2.path());
+ other.unlock(unlock_req(&server, mock::PASSWORD)).await.expect_err("asks for a code");
+ let other_id = devices.lock().unwrap().last().cloned().unwrap();
+ assert!(uuid::Uuid::parse_str(&other_id).is_ok(), "{other_id}");
+ assert_ne!(other_id, id);
+}
+
+#[tokio::test]
+async fn a_refused_code_is_answered_as_one() {
+ let server = mock::serve_two_step(Default::default()).await;
+ let e = setup().await;
+ let body = json!({"server_url": server, "email": mock::EMAIL, "master_password": mock::PASSWORD,
+ "two_factor_provider": 0, "two_factor_token": "000000"});
+ let (s, v) = e.person("POST", "/api/passwords/bitwarden/unlock", Some(body)).await;
+ assert_eq!(s, StatusCode::UNAUTHORIZED, "{v}");
+ assert_eq!(v["needs"], "two_factor", "{v}");
+ assert_eq!(v["code_rejected"], true, "{v}");
+ assert_eq!(v["providers"], json!(["0"]), "{v}");
+ assert_ne!(v["wrong_password"], true, "{v}");
+ assert!(!v.to_string().contains("DUMMY"), "{v}");
+}