tilo-secrets 0.5.2

App-scoped secret storage on Linux, macOS, Windows and the web: the Secret Service, the Keychain, Credential Manager, and WebCrypto-wrapped IndexedDB.
Documentation
//! How a process that holds the device identity is recognised by
//! `tilo-secret-service`, although it cannot look at it.
//!
//! The store names each caller by its executable, read from `/proc/<pid>/exe`, and a
//! process that loads the device key makes itself non-dumpable, so the kernel refuses
//! that link to every other process of the user, the store included. Such a process
//! proves the identity instead.

#[cfg(feature = "host-keyring")]
use std::os::unix::ffi::OsStringExt;
use std::sync::Mutex;

use tilo_seal::secret_service::CallerKey;

#[cfg(feature = "host-keyring")]
const SERVICE: &str = "org.freedesktop.secrets";
#[cfg(feature = "host-keyring")]
const MANAGEMENT_PATH: &str = "/so/tilo/Secrets1";
#[cfg(feature = "host-keyring")]
const MANAGEMENT: &str = "so.tilo.Secrets1";

static ARMED: Mutex<Option<CallerKey>> = Mutex::new(None);

/// Arm this process with the device secret it just read; only the key derived for
/// proofs is kept.
pub fn arm(device_secret: &[u8]) {
    let Ok(store) = CallerKey::derive(device_secret) else {
        return;
    };
    if let Ok(mut armed) = ARMED.lock() {
        *armed = Some(store);
    }
}

#[cfg(feature = "host-keyring")]
fn dumpable() -> bool {
    // SAFETY: PR_GET_DUMPABLE takes no pointers and only reads a flag.
    unsafe { libc::prctl(libc::PR_GET_DUMPABLE, 0, 0, 0, 0) == 1 }
}

#[cfg(feature = "host-keyring")]
fn key() -> Option<CallerKey> {
    if dumpable() {
        return None;
    }
    ARMED.lock().ok()?.clone()
}

/// Whether this process identifies itself to the store by proof. A refusal is then
/// worth one more attempt on a fresh connection, since a store that restarted has
/// forgotten the proof.
#[cfg(feature = "host-keyring")]
pub(crate) fn in_use() -> bool {
    key().is_some()
}

#[cfg(feature = "host-keyring")]
fn answer(key: &CallerKey, challenge: &[u8], caller: &str) -> Option<(Vec<u8>, Vec<u8>)> {
    // A process may always read its own link, dumpable or not.
    let program = std::fs::read_link("/proc/self/exe")
        .ok()?
        .into_os_string()
        .into_vec();
    let proof = key.prove(challenge, caller, &program).ok()?;
    Some((program, proof.to_vec()))
}

/// Prove the device identity on `connection`, if this process must.
/// `Ok(false)` when it need not or cannot (dumpable, or never read the
/// device key); a store that does not speak `so.tilo.Secrets1` (another
/// Secret Service) answers with an error, and the caller carries on
/// unproven.
#[cfg(feature = "host-keyring")]
pub(crate) fn prove_blocking(connection: &zbus::blocking::Connection) -> zbus::Result<bool> {
    let Some(key) = key() else {
        return Ok(false);
    };
    let caller = connection
        .unique_name()
        .ok_or_else(|| zbus::Error::Failure("a bus connection has no unique name".into()))?
        .to_string();
    let store = zbus::blocking::Proxy::new(connection, SERVICE, MANAGEMENT_PATH, MANAGEMENT)?;
    let challenge: Vec<u8> = store.call("CallerChallenge", &())?;
    let Some((program, proof)) = answer(&key, &challenge, &caller) else {
        return Ok(false);
    };
    let _identity: String = store.call("ProveCaller", &(program, proof))?;
    Ok(true)
}

#[cfg(feature = "host-keyring")]
pub async fn prove(connection: &zbus::Connection) -> zbus::Result<bool> {
    let Some(key) = key() else {
        return Ok(false);
    };
    let caller = connection
        .unique_name()
        .ok_or_else(|| zbus::Error::Failure("a bus connection has no unique name".into()))?
        .to_string();
    let store = zbus::Proxy::new(connection, SERVICE, MANAGEMENT_PATH, MANAGEMENT).await?;
    let challenge: Vec<u8> = store.call("CallerChallenge", &()).await?;
    let Some((program, proof)) = answer(&key, &challenge, &caller) else {
        return Ok(false);
    };
    let _identity: String = store.call("ProveCaller", &(program, proof)).await?;
    Ok(true)
}