#[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);
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 {
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()
}
#[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>)> {
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()))
}
#[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)
}