use serde_json::{json, Value};
use crate::crypto::{b64, generate_nonce, increment_nonce, IdKeyPair, SessionCrypto, NONCE_LEN};
use crate::error::{KxcError, Result};
use crate::protocol::*;
use crate::transport::Transport;
const ERR_DATABASE_NOT_OPENED: i64 = 1;
const ERR_ASSOCIATION_FAILED: i64 = 8;
pub struct KxcClient<T: Transport> {
transport: T,
crypto: SessionCrypto,
client_id: String,
pending_signals: Vec<Signal>,
association: Option<Association>,
}
#[derive(Debug, Clone)]
pub struct Association {
pub id: String,
pub id_key_public_b64: String,
}
impl<T: Transport> KxcClient<T> {
pub fn new(transport: T) -> Self {
Self {
transport,
crypto: SessionCrypto::new(),
client_id: b64::enc(&generate_nonce()), pending_signals: Vec::new(),
association: None,
}
}
pub fn association(&self) -> Option<&Association> {
self.association.as_ref()
}
pub fn take_signals(&mut self) -> Vec<Signal> {
std::mem::take(&mut self.pending_signals)
}
pub async fn change_public_keys(&mut self) -> Result<()> {
let nonce = generate_nonce();
let req = json!({
"action": "change-public-keys",
"publicKey": self.crypto.public_key_b64(),
"nonce": b64::enc(&nonce),
"clientID": self.client_id,
});
self.transport.send_json(&req).await?;
let frame = self.recv_frame_skipping_signals().await?;
if frame.action.as_deref() != Some("change-public-keys") {
return Err(KxcError::UnexpectedResponse {
action: "change-public-keys".into(),
detail: format!("{:?}", frame.action),
});
}
self.verify_nonce(&nonce, frame.nonce.as_deref())?;
let peer = frame.public_key.ok_or(KxcError::UnexpectedResponse {
action: "change-public-keys".into(),
detail: "missing publicKey".into(),
})?;
self.crypto.set_peer_public_key_b64(&peer)?;
Ok(())
}
pub async fn associate(&mut self, id_key: &IdKeyPair) -> Result<Association> {
let body = json!({
"action": "associate",
"key": self.crypto.public_key_b64(),
"idKey": id_key.public_b64(),
});
let resp = self.request("associate", body).await?;
let parsed: AssociateResponse = serde_json::from_value(resp)?;
let assoc = Association {
id: parsed.id,
id_key_public_b64: id_key.public_b64(),
};
self.association = Some(assoc.clone());
Ok(assoc)
}
pub async fn test_associate(&mut self, id: &str, id_key: &IdKeyPair) -> Result<()> {
let body = json!({
"action": "test-associate",
"id": id,
"key": id_key.public_b64(),
});
match self.request("test-associate", body).await {
Ok(_) => {
self.association = Some(Association {
id: id.to_string(),
id_key_public_b64: id_key.public_b64(),
});
Ok(())
}
Err(KxcError::KeePassXc { code: Some(c), .. }) if c == ERR_ASSOCIATION_FAILED => {
Err(KxcError::NotAssociated)
}
Err(e) => Err(e),
}
}
fn keys_param(&self) -> Result<Value> {
let a = self.association.as_ref().ok_or(KxcError::NotAssociated)?;
Ok(json!([{ "id": a.id, "key": a.id_key_public_b64 }]))
}
pub async fn get_database_hash(&mut self) -> Result<String> {
let resp = self
.request("get-databasehash", json!({"action": "get-databasehash"}))
.await?;
resp.get("hash")
.and_then(Value::as_str)
.map(str::to_owned)
.ok_or(KxcError::UnexpectedResponse {
action: "get-databasehash".into(),
detail: "missing hash".into(),
})
}
pub async fn get_logins(&mut self, url: &str) -> Result<Vec<LoginEntry>> {
let body = json!({
"action": "get-logins",
"url": url,
"keys": self.keys_param()?,
});
match self.request("get-logins", body).await {
Ok(resp) => {
let parsed: GetLoginsResponse = serde_json::from_value(resp)?;
Ok(parsed.entries)
}
Err(KxcError::KeePassXc { code: Some(15), .. }) => Ok(Vec::new()),
Err(e) => Err(e),
}
}
#[allow(clippy::too_many_arguments)]
pub async fn set_login(
&mut self,
url: &str,
login: &str,
password: &str,
uuid: Option<&str>,
group: Option<&str>,
group_uuid: Option<&str>,
) -> Result<()> {
let mut body = json!({
"action": "set-login",
"url": url,
"submitUrl": url,
"login": login,
"password": password,
});
let obj = body.as_object_mut().expect("object");
if let Some(u) = uuid {
obj.insert("uuid".into(), json!(u));
}
if let Some(g) = group {
obj.insert("group".into(), json!(g));
}
if let Some(gu) = group_uuid {
obj.insert("groupUuid".into(), json!(gu));
}
self.request("set-login", body).await.map(|_| ())
}
pub async fn delete_entry(&mut self, uuid: &str) -> Result<()> {
let body = json!({ "action": "delete-entry", "uuid": uuid });
self.request("delete-entry", body).await.map(|_| ())
}
pub async fn get_database_groups(&mut self) -> Result<Vec<(String, String)>> {
let resp = self
.request("get-database-groups", json!({"action": "get-database-groups"}))
.await?;
let parsed: GetDatabaseGroupsResponse = serde_json::from_value(resp)?;
let mut flat = Vec::new();
for g in &parsed.groups.groups {
g.flatten("", &mut flat);
}
Ok(flat)
}
pub async fn create_new_group(&mut self, name: &str) -> Result<Value> {
self.request(
"create-new-group",
json!({"action": "create-new-group", "groupName": name}),
)
.await
}
pub async fn get_totp(&mut self, uuid: &str) -> Result<Option<String>> {
let resp = self
.request("get-totp", json!({"action": "get-totp", "uuid": uuid}))
.await?;
Ok(resp.get("totp").and_then(Value::as_str).map(str::to_owned))
}
pub async fn lock_database(&mut self) -> Result<()> {
self.request("lock-database", json!({"action": "lock-database"}))
.await
.map(|_| ())
}
async fn request(&mut self, action: &str, body: Value) -> Result<Value> {
let nonce = generate_nonce();
let plaintext = serde_json::to_vec(&body)?;
let ct = self.crypto.encrypt(&plaintext, &nonce)?;
let envelope = json!({
"action": action,
"message": b64::enc(&ct),
"nonce": b64::enc(&nonce),
"clientID": self.client_id,
});
self.transport.send_json(&envelope).await?;
let frame = self.recv_frame_skipping_signals().await?;
if frame.message.is_none() {
if let Some(err) = frame.error.clone() {
return Err(self.map_error(frame.error_code_i64(), err));
}
return Err(KxcError::UnexpectedResponse {
action: action.into(),
detail: "frame without message or error".into(),
});
}
self.verify_nonce(&nonce, frame.nonce.as_deref())?;
let ct = b64::dec(frame.message.as_deref().unwrap())?;
let resp_nonce = decode_nonce(frame.nonce.as_deref().unwrap())?;
let pt = self.crypto.decrypt(&ct, &resp_nonce)?;
let resp: Value = serde_json::from_slice(&pt)?;
let succeeded = matches!(
resp.get("success"),
Some(Value::String(s)) if s.eq_ignore_ascii_case("true")
) || resp.get("success") == Some(&Value::Bool(true));
if !succeeded {
if let Some(err) = resp
.get("error")
.and_then(Value::as_str)
.filter(|e| !e.is_empty() && !e.eq_ignore_ascii_case("success"))
{
let code = resp.get("errorCode").and_then(|c| match c {
Value::Number(n) => n.as_i64(),
Value::String(s) => s.parse().ok(),
_ => None,
});
return Err(self.map_error(code, err.to_string()));
}
}
Ok(resp)
}
fn map_error(&self, code: Option<i64>, message: String) -> KxcError {
match code {
Some(ERR_DATABASE_NOT_OPENED) => KxcError::DatabaseLocked,
Some(ERR_ASSOCIATION_FAILED) => KxcError::NotAssociated,
_ => KxcError::KeePassXc { code, message },
}
}
fn verify_nonce(&self, request_nonce: &[u8; NONCE_LEN], got: Option<&str>) -> Result<()> {
let got = got.ok_or(KxcError::NonceMismatch)?;
let got = decode_nonce(got)?;
if got != increment_nonce(request_nonce) {
return Err(KxcError::NonceMismatch);
}
Ok(())
}
async fn recv_frame_skipping_signals(&mut self) -> Result<IncomingFrame> {
loop {
let doc = self.transport.recv_json().await?;
let frame: IncomingFrame = serde_json::from_value(doc)?;
if frame.is_signal() {
let s = match frame.action.as_deref() {
Some("database-locked") => Signal::DatabaseLocked,
_ => Signal::DatabaseUnlocked,
};
tracing::info!(?s, "signal from KeePassXC");
self.pending_signals.push(s);
continue;
}
return Ok(frame);
}
}
}
fn decode_nonce(s: &str) -> Result<[u8; NONCE_LEN]> {
let raw = b64::dec(s)?;
raw.try_into().map_err(|_| KxcError::NonceMismatch)
}