Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
18 changes: 17 additions & 1 deletion client/src/file/api/legacy_keyring/encrypted.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,22 @@ pub struct Keyring {

impl Keyring {
pub fn decrypt_items(self, secret: &Secret) -> Result<Vec<UnlockedItem>, Error> {
let content = self.decrypt_content(secret)?;
self.read_items(&content)
}

/// Check whether the secret can decrypt this keyring.
#[cfg(any(feature = "unstable", test))]
pub fn validate_secret(&self, secret: &Secret) -> Result<bool, Error> {
match self.decrypt_content(secret) {
Ok(_) => Ok(true),
Err(Error::ChecksumMismatch) => Ok(false),
Err(err) => Err(err),
}
}

/// Decrypt the keyring content, verifying its checksum.
fn decrypt_content(&self, secret: &Secret) -> Result<Vec<u8>, Error> {
let (key, iv) = crypto::legacy_derive_key_and_iv(
&**secret,
&self.salt,
Expand All @@ -38,7 +54,7 @@ impl Keyring {
if !crypto::verify_checksum_md5(digest, content) {
return Err(Error::ChecksumMismatch);
}
self.read_items(content)
Ok(content.to_vec())
}

fn read_attributes<'a>(
Expand Down
65 changes: 65 additions & 0 deletions client/src/file/api/legacy_keyring/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,12 @@ pub enum Keyring {
}

impl Keyring {
/// Whether this keyring is stored in the encrypted binary format.
#[cfg(any(feature = "unstable", test))]
pub fn is_encrypted(&self) -> bool {
matches!(self, Self::Encrypted(_))
}

/// Retrieve the keyring items.
///
/// The secret is ignored for plain keyrings.
Expand All @@ -47,6 +53,17 @@ impl Keyring {
Self::Plain(keyring) => Ok(keyring.into_items()),
}
}

/// Check whether the secret can decrypt this keyring.
///
/// Plain keyrings are not encrypted and accept any secret.
#[cfg(any(feature = "unstable", test))]
pub fn validate_secret(&self, secret: &Secret) -> Result<bool, Error> {
match self {
Self::Encrypted(keyring) => keyring.validate_secret(secret),
Self::Plain(_) => Ok(true),
}
}
}

impl TryFrom<&[u8]> for Keyring {
Expand All @@ -62,3 +79,51 @@ impl TryFrom<&[u8]> for Keyring {
}
}
}

#[cfg(test)]
mod tests {
use super::*;

fn fixture(name: &str) -> Vec<u8> {
let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("fixtures")
.join(name);
std::fs::read(path).unwrap()
}

#[test]
fn encrypted_keyring() {
let keyring = Keyring::try_from(fixture("legacy.keyring").as_slice()).unwrap();
assert!(keyring.is_encrypted());

assert!(
keyring
.validate_secret(&Secret::from("test"))
.expect("validation should not fail")
);
assert!(
!keyring
.validate_secret(&Secret::from("wrong-password"))
.expect("validation should not fail")
);

let items = keyring
.decrypt_items(&Secret::from("test"))
.expect("decryption should not fail");
assert_eq!(items.len(), 1);
assert_eq!(items[0].label(), "foo");
}

#[test]
fn plain_keyring() {
let keyring = Keyring::try_from(fixture("plain.keyring").as_slice()).unwrap();
assert!(!keyring.is_encrypted());

// Plain keyrings accept any secret
assert!(
keyring
.validate_secret(&Secret::from("anything"))
.expect("validation should not fail")
);
}
}
2 changes: 1 addition & 1 deletion client/src/file/api/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ mod encrypted_item;
mod legacy_keyring;

pub(super) use encrypted_item::EncryptedItem;
pub(super) use legacy_keyring::{Keyring as LegacyKeyring, MAJOR_VERSION as LEGACY_MAJOR_VERSION};
pub use legacy_keyring::{Keyring as LegacyKeyring, MAJOR_VERSION as LEGACY_MAJOR_VERSION};
use zeroize::{Zeroize, ZeroizeOnDrop};

use crate::{
Expand Down
2 changes: 1 addition & 1 deletion server/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ kwallet-parser = { version = "0.8.0-alpha", path = "../kwallet/parser", optional
libc.workspace = true
num.workspace = true
num-bigint-dig.workspace = true
oo7 = { workspace = true, features = ["tokio"] }
oo7 = { workspace = true, features = ["tokio", "unstable"] }
openssl = { workspace = true, optional = true }
rpassword.workspace = true
rustix = { version = "1.1", default-features = false, features = ["process", "std", "thread", "mm", "fs", "net", "event"] }
Expand Down
62 changes: 47 additions & 15 deletions server/src/collection/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -676,25 +676,57 @@ impl Collection {
keyring_items.len(),
self.path
);
let mut items = self.items.lock().await;
let object_server = self.service.object_server();
let mut n_items = 1;
drop(keyring_guard);

for keyring_item in keyring_items {
let item_path = OwnedObjectPath::try_from(format!("{}/{n_items}", self.path)).unwrap();
let item = item::Item::new(
keyring_item,
self.service.clone(),
self.path.clone(),
item_path.clone(),
);
n_items += 1;
let mut dispatched_items = Vec::new();
{
let mut items = self.items.lock().await;
let object_server = self.service.object_server();
let mut n_items = 1;

for keyring_item in keyring_items {
let item_path =
OwnedObjectPath::try_from(format!("{}/{n_items}", self.path)).unwrap();
let item = item::Item::new(
keyring_item,
self.service.clone(),
self.path.clone(),
item_path.clone(),
);
n_items += 1;

items.push(item.clone());
dispatched_items.push(item.clone());
object_server.at(item_path, item).await?;
}

*self.item_index.write().await = n_items;
}

items.push(item.clone());
object_server.at(item_path, item).await?;
// Notify clients about the newly dispatched items.
let signal_emitter = self.service.signal_emitter(&self.path)?;
for item in &dispatched_items {
Self::item_created(&signal_emitter, item.path()).await?;
}
self.items_changed(&signal_emitter).await?;

*self.item_index.write().await = n_items;
Ok(())
}

/// Replace the keyring with a just-migrated one, dispatch its items
/// and emit the corresponding change signals.
pub async fn apply_migrated_keyring(&self, keyring: Keyring) -> Result<(), Error> {
*self.keyring.write().await = Some(keyring);

self.dispatch_items().await?;

// The keyring swap bypasses set_locked, so emit Locked here.
let signal_emitter = self.service.signal_emitter(&self.path)?;
self.locked_changed(&signal_emitter).await?;

let service_path = oo7::dbus::api::Service::PATH.as_ref().unwrap();
let signal_emitter = self.service.signal_emitter(service_path)?;
Service::collection_changed(&signal_emitter, &self.path).await?;

Ok(())
}
Expand Down
11 changes: 11 additions & 0 deletions server/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,17 @@ impl From<zbus::Error> for Error {
}
}

impl From<ServiceError> for Error {
fn from(err: ServiceError) -> Self {
match err {
ServiceError::ZBus(err) => Self::Zbus(err),
err => Self::Zbus(zbus::Error::FDO(Box::new(zbus::fdo::Error::Failed(
err.to_string(),
)))),
}
}
}

impl From<oo7::file::Error> for Error {
fn from(err: oo7::file::Error) -> Self {
Self::File(err)
Expand Down
31 changes: 31 additions & 0 deletions server/src/migration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,37 @@ pub enum PendingMigration {
}

impl PendingMigration {
/// Check whether the secret can decrypt the legacy keyring, as the
/// placeholder keyring of a pending migration accepts any secret.
pub async fn validate_secret(&self, secret: &Secret) -> Result<bool, Error> {
match self {
Self::V0 { path, .. } => {
let content = tokio::fs::read(path).await?;
let keyring = oo7::file::api::LegacyKeyring::try_from(content.as_slice())?;
Ok(keyring.validate_secret(secret)?)
}
#[cfg(feature = "kwallet_migration")]
Self::KWallet { path, .. } => {
let path = path.clone();
let password = secret.to_vec();
match tokio::task::spawn_blocking(move || {
kwallet_parser::KWalletFile::open(&path, &password)
})
.await
{
Ok(Ok(_)) => Ok(true),
Ok(Err(err)) => {
tracing::debug!("Failed to validate KWallet keyring secret: {err}");
Ok(false)
}
Err(err) => Err(Error::IO(std::io::Error::other(format!(
"Task join error: {err}"
)))),
}
}
}
}

/// Attempt to migrate this keyring with the provided secret
pub async fn migrate(
&self,
Expand Down
19 changes: 18 additions & 1 deletion server/src/prompt/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,24 @@ impl Prompt {
let collection = self.collection().expect("Unlock requires a collection");
let label = self.label();

let is_valid = if let Some(ref secret) = secret {
// The placeholder of a pending migration accepts any secret;
// validate against the legacy keyring instead.
let pending_migration = {
let pending = self.service.pending_migrations.lock().await;
pending.get(collection.name()).cloned()
};

let is_valid = if let Some(migration) = pending_migration {
match secret.as_ref() {
Some(secret) => migration.validate_secret(secret).await.map_err(|err| {
custom_service_error(&format!(
"Failed to validate secret for {label} keyring: {err}."
))
})?,
// A pending migration always requires a secret.
None => false,
}
} else if let Some(ref secret) = secret {
// Validate the secret using the already-open keyring
let keyring_guard = collection.keyring.read().await;
let valid = keyring_guard
Expand Down
22 changes: 11 additions & 11 deletions server/src/service/locking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -145,13 +145,11 @@ impl Service {
migration_name
);

// Replace the keyring in the collection
let mut keyring_guard = collection.keyring.write().await;
*keyring_guard = Some(Keyring::Unlocked(unlocked_keyring));
drop(keyring_guard);

// Dispatch items from the migrated keyring
if let Err(e) = collection.dispatch_items().await {
// Replace the placeholder and notify clients
if let Err(e) = collection
.apply_migrated_keyring(Keyring::Unlocked(unlocked_keyring))
.await
{
tracing::error!("Failed to dispatch items after migration: {}", e);
}

Expand All @@ -164,7 +162,8 @@ impl Service {
migration_name,
e
);
let _ = collection.set_locked(false, secret.clone()).await;
// Keep the placeholder locked so the migration
// can be retried.
}
}
} else {
Expand Down Expand Up @@ -230,9 +229,10 @@ impl Service {
};

if let Some(collection) = placeholder {
*collection.keyring.write().await = Some(Keyring::Unlocked(unlocked));

if let Err(e) = collection.dispatch_items().await {
if let Err(e) = collection
.apply_migrated_keyring(Keyring::Unlocked(unlocked))
.await
{
tracing::error!(
"Failed to dispatch items for migrated keyring '{name}': {e}",
);
Expand Down
Loading
Loading