使用 logind D-Bus 监听锁屏变化,减少进程轮询和审计噪声 (#218)

* fix: monitor logind lock state over D-Bus instead of spawning loginctl

* docs: add redacted lock-monitor audit evidence and validation

* fix: retain logind subscription without a graphical session
This commit is contained in:
阿夜 authored and GitHub committed 2026-11-12 17:14:51 +08:00
1 parent 890c46e280
commit 50a7447b7b
6 files changed
+628 -20

No files matched your search

+74 -19
View File
@@ -11,11 +11,15 @@
//! (`loginctl unlock-session`, allowed for the session owner), which avoids remote keystrokes
//! and gives an exact wrong-password result. The password is never logged or stored.
use std::process::Command;
use std::process::{Command, Stdio};
use std::path::{Path, PathBuf};
use std::sync::OnceLock;
use std::time::Duration;
use tokio::sync::watch;
mod logind;
/// Official UnlockResult cases (LockScreenManager).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnlockResult { Success, WrongPassword, NoLoggedInUser, NoPermission, Failed }
@@ -29,10 +33,44 @@ extern "C" {
fn uu_pam_check(service: *const libc::c_char, user: *const libc::c_char, password: *const libc::c_char) -> libc::c_int;
}
// Resolve once: execvp's unsuccessful PATH candidates are also recorded by auditd.
fn loginctl_path() -> Option<&'static Path> {
static PATH: OnceLock<Option<PathBuf>> = OnceLock::new();
PATH.get_or_init(|| {
std::env::var_os("PATH").into_iter().flat_map(|p| std::env::split_paths(&p).collect::<Vec<_>>())
.map(|dir| dir.join("loginctl"))
.find(|path| path.is_file() && std::ffi::CString::new(path.as_os_str().as_encoded_bytes())
.map(|p| unsafe { libc::access(p.as_ptr(), libc::X_OK) == 0 }).unwrap_or(false))
.and_then(|path| std::fs::canonicalize(path).ok())
}).as_deref()
}
#[cfg(test)]
static COMMAND_STARTS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
fn bounded_command(path: &Path, args: &[&str], timeout: Duration) -> Option<String> {
use std::io::Read;
#[cfg(test)]
COMMAND_STARTS.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
let mut child = Command::new(path).args(args).stdin(Stdio::null()).stdout(Stdio::piped())
.stderr(Stdio::null()).spawn().ok()?;
let deadline = std::time::Instant::now() + timeout;
loop {
match child.try_wait() {
Ok(Some(status)) => {
if !status.success() { return None; }
let mut text = String::new();
child.stdout.take()?.take(4096).read_to_string(&mut text).ok()?;
return Some(text.trim().to_owned());
}
Ok(None) if std::time::Instant::now() < deadline => std::thread::sleep(Duration::from_millis(10)),
_ => { let _ = child.kill(); let _ = child.wait(); return None; }
}
}
}
fn loginctl(args: &[&str]) -> Option<String> {
let out = Command::new("loginctl").args(args).output().ok()?;
if !out.status.success() { return None; }
Some(String::from_utf8_lossy(&out.stdout).trim().to_string()).filter(|s| !s.is_empty())
bounded_command(loginctl_path()?, args, Duration::from_secs(3)).filter(|s| !s.is_empty())
}
/// The logind session that owns this user's graphical display.
@@ -44,7 +82,7 @@ fn display_session() -> Option<String> {
pub fn locked_now() -> Option<bool> { display_session().as_deref().and_then(session_locked) }
fn session_locked(session: &str) -> Option<bool> {
loginctl(&["show-session", session, "-p", "LockedHint", "--value"]).map(|v| v == "yes")
loginctl(&["show-session", session, "-p", "LockedHint", "--value"]).and_then(|v| match v.as_str() { "yes" => Some(true), "no" => Some(false), _ => None })
}
fn user_name() -> Option<String> {
@@ -78,30 +116,28 @@ pub fn supported() -> bool {
*SUPPORTED.get_or_init(|| pam_available() && display_session().is_some())
}
/// Current lock state (None = unknown), refreshed every second by one background thread.
/// Current lock state (None = unknown), shared by all desktop connections.
pub fn watch_locked() -> watch::Receiver<Option<bool>> {
static STATE: OnceLock<watch::Sender<Option<bool>>> = OnceLock::new();
STATE.get_or_init(|| {
let (tx, _) = watch::channel(None);
let sender = tx.clone();
std::thread::Builder::new().name("uu-lock-state".into()).spawn(move || {
let mut session = None;
loop {
if session.is_none() { session = display_session(); }
let locked = session.as_deref().and_then(session_locked);
if locked.is_none() { session = None; } // session ended or changed: look it up again
sender.send_if_modified(|current| if *current != locked {
log::info!("Desktop lock state: {}", match locked { Some(true) => "locked", Some(false) => "unlocked", None => "unknown" });
if locked == Some(true) { log::info!("Desktop is locked; capture continues while the compositor supplies frames"); }
*current = locked; true
} else { false });
std::thread::sleep(Duration::from_secs(1));
}
tokio::runtime::Builder::new_current_thread().enable_all().build()
.expect("lock monitor runtime").block_on(logind::monitor(sender));
}).expect("spawn lock state thread");
tx
}).subscribe()
}
fn publish_lock_state(sender: &watch::Sender<Option<bool>>, locked: Option<bool>) {
sender.send_if_modified(|current| if *current != locked {
log::info!("Desktop lock state: {}", match locked { Some(true) => "locked", Some(false) => "unlocked", None => "unknown" });
if locked == Some(true) { log::info!("Desktop is locked; capture continues while the compositor supplies frames"); }
*current = locked; true
} else { false });
}
/// Verifies the session user's password and unlocks the display session. Blocking (PAM may
/// delay a failure by seconds); call from spawn_blocking. Consumes and wipes the password.
pub fn unlock(password: String) -> UnlockResult {
@@ -117,7 +153,7 @@ fn unlock_with(password: &str) -> UnlockResult {
let Some(user) = user_name() else { return UnlockResult::NoLoggedInUser };
if password.is_empty() || password.contains('\0') { return UnlockResult::WrongPassword; }
match pam_check(&user, password) { 0 => {}, 1 => return UnlockResult::WrongPassword, _ => return UnlockResult::Failed }
if Command::new("loginctl").args(["unlock-session", &session]).status().map(|s| !s.success()).unwrap_or(true) {
if loginctl_path().and_then(|path| bounded_command(path, &["unlock-session", &session], Duration::from_secs(3))).is_none() {
return UnlockResult::NoPermission;
}
if let Err(error) = crate::capture::keep_display_awake() {
@@ -204,6 +240,25 @@ pub fn password_from_args(args: &[u8]) -> Option<String> {
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn unknown_state_is_preserved_and_repeated_states_do_not_notify() {
let (tx, mut rx) = watch::channel(Some(true));
publish_lock_state(&tx, None);
assert_eq!(*rx.borrow_and_update(), None);
publish_lock_state(&tx, None);
assert!(!rx.has_changed().unwrap());
publish_lock_state(&tx, Some(false));
assert!(rx.has_changed().unwrap());
assert_eq!(*rx.borrow_and_update(), Some(false));
}
#[test]
fn hung_fallback_is_killed_and_reaped() {
let start = std::time::Instant::now();
assert_eq!(bounded_command(Path::new("/bin/sleep"), &["10"], Duration::from_millis(30)), None);
assert!(start.elapsed() < Duration::from_secs(2));
}
#[test]
fn password_comes_from_the_official_key_field() {
assert_eq!(password_from_args(br#"{"key":"p@ss word"}"#).as_deref(), Some("p@ss word"));
+208
View File
@@ -0,0 +1,208 @@
//! logind signals replace per-second process spawning; loginctl is a bounded fallback.
use super::{publish_lock_state, Duration};
use futures_util::StreamExt;
use tokio::sync::watch;
use zbus::{Connection, MatchRule, MessageStream, Proxy, proxy::CacheProperties};
const SERVICE: &str = "org.freedesktop.login1";
const ROOT: &str = "/org/freedesktop/login1";
const CALL_TIMEOUT: Duration = Duration::from_secs(5);
const RETRY: Duration = Duration::from_secs(30);
async fn locked(connection: &Connection) -> zbus::Result<Option<bool>> {
let path = format!("{ROOT}/user/_{}", unsafe { libc::getuid() });
let user = zbus::proxy::Builder::<Proxy<'_>>::new(connection).destination(SERVICE)?
.path(path)?.interface("org.freedesktop.login1.User")?
.cache_properties(CacheProperties::No).build().await?;
// No cached property reads: signals, including invalidations, trigger a fresh snapshot.
let display: (String, zbus::zvariant::OwnedObjectPath) = user.get_property("Display").await?;
if display.0.is_empty() { return Ok(None); }
let session = zbus::proxy::Builder::<Proxy<'_>>::new(connection).destination(SERVICE)?
.path(display.1)?.interface("org.freedesktop.login1.Session")?
.cache_properties(CacheProperties::No).build().await?;
session.get_property("LockedHint").await.map(Some)
}
async fn snapshot(connection: &Connection) -> zbus::Result<Option<bool>> {
tokio::time::timeout(CALL_TIMEOUT, locked(connection)).await
.map_err(|_| zbus::Error::Failure("lock query timed out".into()))?
}
async fn monitor_connection(connection: &Connection, sender: &watch::Sender<Option<bool>>) -> zbus::Result<()> {
// Subscribe before reading: any change during the first snapshot stays queued.
// Watch all logind signals so User.Display, SessionNew/Removed and invalidated
// properties also re-resolve the graphical session instead of trusting a stale path.
let rule = MatchRule::builder().msg_type(zbus::message::Type::Signal)
.sender(SERVICE)?.path_namespace(ROOT)?.build();
let mut signals = tokio::time::timeout(CALL_TIMEOUT, MessageStream::for_match_rule(rule, connection, Some(64))).await
.map_err(|_| zbus::Error::Failure("lock subscription timed out".into()))??;
publish_lock_state(sender, snapshot(connection).await?);
let mut reconcile = tokio::time::interval(RETRY);
reconcile.tick().await;
loop {
tokio::select! {
event = signals.next() => { event.ok_or_else(|| zbus::Error::Failure("system bus closed".into()))??; },
_ = reconcile.tick() => {},
}
publish_lock_state(sender, snapshot(connection).await?);
}
}
pub(super) async fn monitor(sender: watch::Sender<Option<bool>>) {
let mut degraded = false;
loop {
let result = tokio::time::timeout(CALL_TIMEOUT, async { zbus::connection::Builder::system()?.method_timeout(CALL_TIMEOUT).build().await }).await;
if let Ok(Ok(connection)) = result {
if !degraded { log::debug!("Desktop lock monitor: logind D-Bus"); }
// Recovery is announced only after a valid snapshot, via the state channel.
let _ = monitor_connection(&connection, &sender).await;
}
publish_lock_state(&sender, None);
if !degraded { log::warn!("Desktop lock monitor unavailable; retrying D-Bus with bounded loginctl fallback every 30s"); }
degraded = true;
let fallback = tokio::task::spawn_blocking(super::locked_now).await.ok().flatten();
publish_lock_state(&sender, fallback);
tokio::time::sleep(RETRY).await;
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::{Arc, Mutex, atomic::{AtomicBool, Ordering}};
use zbus::zvariant::{OwnedObjectPath, Value};
struct User(Arc<Mutex<String>>);
#[zbus::interface(name = "org.freedesktop.login1.User")]
impl User {
#[zbus(property)]
fn display(&self) -> (String, OwnedObjectPath) {
let id = self.0.lock().unwrap().clone();
let path = if id.is_empty() { "/".into() } else { format!("{ROOT}/session/{id}") };
(id, OwnedObjectPath::try_from(path).unwrap())
}
}
struct Session { locked: Arc<AtomicBool>, valid: Arc<AtomicBool> }
#[zbus::interface(name = "org.freedesktop.login1.Session")]
impl Session {
#[zbus(property)]
fn locked_hint(&self) -> zbus::fdo::Result<bool> {
if !self.valid.load(Ordering::SeqCst) { return Err(zbus::fdo::Error::Failed("unavailable".into())); }
Ok(self.locked.load(Ordering::SeqCst))
}
}
async fn expect(rx: &mut watch::Receiver<Option<bool>>, value: Option<bool>) {
tokio::time::timeout(Duration::from_secs(3), async {
loop {
let current = *rx.borrow_and_update();
if current == value { return; }
rx.changed().await.unwrap();
}
}).await.expect("lock state update");
}
async fn invalidated(server: &Connection, path: &str, interface: &str, property: &str) {
// An invalidation has no replacement value: the client must re-read it.
let changed = std::collections::HashMap::<&str, Value<'_>>::new();
server.emit_signal(None::<&str>, path, "org.freedesktop.DBus.Properties", "PropertiesChanged",
&(interface, changed, vec![property])).await.unwrap();
}
#[tokio::test]
#[ignore = "isolated D-Bus integration; requires dbus-daemon, never changes the real desktop"]
async fn private_bus_tracks_initial_state_invalidation_session_change_and_failure() {
use tokio::io::{AsyncBufReadExt, BufReader};
let mut daemon = tokio::process::Command::new("dbus-daemon")
.args(["--session", "--nofork", "--print-address=1"])
.stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::null())
.kill_on_drop(true).spawn().unwrap();
let mut address = String::new();
tokio::time::timeout(Duration::from_secs(3), BufReader::new(daemon.stdout.take().unwrap()).read_line(&mut address)).await.unwrap().unwrap();
let address = address.trim();
let display = Arc::new(Mutex::new(String::new()));
let locked = Arc::new(AtomicBool::new(true));
let valid = Arc::new(AtomicBool::new(true));
let user_path = format!("{ROOT}/user/_{}", unsafe { libc::getuid() });
let server = zbus::connection::Builder::address(address).unwrap().name(SERVICE).unwrap()
.serve_at(user_path.clone(), User(display.clone())).unwrap()
.serve_at(format!("{ROOT}/session/a"), Session { locked: locked.clone(), valid: valid.clone() }).unwrap()
.serve_at(format!("{ROOT}/session/b"), Session { locked: Arc::new(AtomicBool::new(true)), valid: valid.clone() }).unwrap()
.build().await.unwrap();
let client = zbus::connection::Builder::address(address).unwrap().build().await.unwrap();
let (tx, mut rx) = watch::channel(Some(false));
let monitor = tokio::spawn(async move {
let result = monitor_connection(&client, &tx).await;
publish_lock_state(&tx, None);
result
});
expect(&mut rx, None).await;
assert!(!monitor.is_finished(), "no graphical session must keep the D-Bus subscription alive");
*display.lock().unwrap() = "a".into();
invalidated(&server, &user_path, "org.freedesktop.login1.User", "Display").await;
expect(&mut rx, Some(true)).await; // login is observed without waiting for the retry timer
locked.store(false, Ordering::SeqCst);
invalidated(&server, &format!("{ROOT}/session/a"), "org.freedesktop.login1.Session", "LockedHint").await;
expect(&mut rx, Some(false)).await;
*display.lock().unwrap() = "b".into();
invalidated(&server, &user_path, "org.freedesktop.login1.User", "Display").await;
expect(&mut rx, Some(true)).await;
display.lock().unwrap().clear();
invalidated(&server, &user_path, "org.freedesktop.login1.User", "Display").await;
expect(&mut rx, None).await;
assert!(!monitor.is_finished(), "logout must keep the D-Bus subscription alive");
*display.lock().unwrap() = "b".into();
invalidated(&server, &user_path, "org.freedesktop.login1.User", "Display").await;
expect(&mut rx, Some(true)).await;
valid.store(false, Ordering::SeqCst);
invalidated(&server, &format!("{ROOT}/session/b"), "org.freedesktop.login1.Session", "LockedHint").await;
expect(&mut rx, None).await; // failure must not become unlocked
assert!(monitor.await.unwrap().is_err());
// A fresh connection must recover after a service/property failure.
valid.store(true, Ordering::SeqCst);
let client = zbus::connection::Builder::address(address).unwrap().build().await.unwrap();
let close = client.clone();
let (tx, mut rx) = watch::channel(None);
let monitor = tokio::spawn(async move {
let result = monitor_connection(&client, &tx).await;
publish_lock_state(&tx, None);
result
});
expect(&mut rx, Some(true)).await;
close.close().await.unwrap();
expect(&mut rx, None).await;
assert!(monitor.await.unwrap().is_err());
daemon.kill().await.unwrap();
daemon.wait().await.unwrap();
}
#[tokio::test]
#[ignore = "manual acceptance: observes a real lock/unlock for up to three minutes"]
async fn live_lock_unlock_signals() {
let before = super::super::COMMAND_STARTS.load(Ordering::SeqCst);
let mut rx = super::super::watch_locked();
let start = std::time::Instant::now();
tokio::time::timeout(Duration::from_secs(180), async {
let mut saw_lock = false;
loop {
let state = *rx.borrow_and_update();
println!("live lock state: {state:?}; elapsed_ms={}", start.elapsed().as_millis());
if state == Some(true) { saw_lock = true; }
if saw_lock && state == Some(false) { break; }
rx.changed().await.unwrap();
}
}).await.expect("please lock and unlock the desktop during this probe");
let started = super::super::COMMAND_STARTS.load(Ordering::SeqCst) - before;
println!("lock monitor command starts: {started}");
assert_eq!(started, 0, "healthy D-Bus monitoring should not spawn loginctl");
}
#[tokio::test]
#[ignore = "read-only live logind probe; requires an active graphical logind session"]
async fn live_logind_snapshot_matches_loginctl_without_changing_lock_state() {
let connection = Connection::system().await.unwrap();
let dbus = snapshot(&connection).await.unwrap();
let command = tokio::task::spawn_blocking(super::super::locked_now).await.unwrap();
assert_eq!(dbus, command);
}
}