fix: audit fixes — double-unlock guard, PAM OOM code, GPU blur, async fp stop (v0.5.1)

Security: prevent double unlock() when PAM and fingerprint succeed
simultaneously (ext-session-lock protocol error). Fix PAM callback
returning PAM_AUTH_ERR instead of PAM_BUF_ERR on calloc OOM.

Performance: replace CPU-side Gaussian blur (image crate) with GPU blur
via GskBlurNode + GskRenderer::render_texture(). Eliminates 500ms-2s
main-thread blocking on cold cache for 4K wallpapers. Remove image and
dirs dependencies (~15 transitive crates). Make fingerprint stop()
fire-and-forget async to avoid 6s UI block after successful auth.
This commit is contained in:
2026-03-28 22:06:38 +01:00
parent 48706e5a29
commit 4026f6dafa
8 changed files with 87 additions and 447 deletions
+3 -2
View File
@@ -8,6 +8,7 @@ use zeroize::Zeroizing;
// PAM return codes
const PAM_SUCCESS: i32 = 0;
const PAM_BUF_ERR: i32 = 5;
const PAM_AUTH_ERR: i32 = 7;
// PAM message styles
const PAM_PROMPT_ECHO_OFF: libc::c_int = 1;
@@ -73,7 +74,7 @@ unsafe extern "C" fn pam_conv_callback(
// Safety: appdata_ptr was set to a valid *const CString in authenticate()
let password = appdata_ptr as *const CString;
if password.is_null() {
return 7; // PAM_AUTH_ERR
return PAM_AUTH_ERR;
}
// Safety: calloc returns zeroed memory for num_msg PamResponse structs.
@@ -84,7 +85,7 @@ unsafe extern "C" fn pam_conv_callback(
) as *mut PamResponse;
if resp_array.is_null() {
return 7; // PAM_AUTH_ERR
return PAM_BUF_ERR;
}
for i in 0..num_msg as isize {
+11 -15
View File
@@ -290,7 +290,8 @@ impl FingerprintListener {
}
/// Stop listening and release the device.
/// Uses a short timeout (3s) to avoid blocking the UI indefinitely.
/// Signal disconnect is synchronous to prevent further callbacks.
/// D-Bus cleanup (VerifyStop + Release) is fire-and-forget to avoid blocking the UI.
pub fn stop(&mut self) {
if !self.running {
return;
@@ -301,20 +302,15 @@ impl FingerprintListener {
if let Some(id) = self.signal_id.take() {
proxy.disconnect(id);
}
let _ = proxy.call_sync(
"VerifyStop",
None,
gio::DBusCallFlags::NONE,
3000,
gio::Cancellable::NONE,
);
let _ = proxy.call_sync(
"Release",
None,
gio::DBusCallFlags::NONE,
3000,
gio::Cancellable::NONE,
);
let proxy = proxy.clone();
glib::spawn_future_local(async move {
let _ = proxy
.call_future("VerifyStop", None, gio::DBusCallFlags::NONE, 3000)
.await;
let _ = proxy
.call_future("Release", None, gio::DBusCallFlags::NONE, 3000)
.await;
});
}
}
+47 -203
View File
@@ -4,16 +4,12 @@
use gdk4 as gdk;
use gdk_pixbuf::Pixbuf;
use glib::clone;
use graphene_rs as graphene;
use gtk4::prelude::*;
use gtk4::{self as gtk, gio};
use image::imageops;
use std::cell::RefCell;
use std::fs;
use std::io::Write;
use std::os::unix::fs::OpenOptionsExt;
use std::path::{Path, PathBuf};
use std::path::Path;
use std::rc::Rc;
use std::time::SystemTime;
use zeroize::Zeroizing;
@@ -47,7 +43,7 @@ struct LockscreenState {
/// Fingerprint is not initialized here — use `wire_fingerprint()` after async init.
pub fn create_lockscreen_window(
bg_texture: &gdk::Texture,
_config: &Config,
config: &Config,
app: &gtk::Application,
unlock_callback: Rc<dyn Fn()>,
) -> LockscreenHandles {
@@ -87,7 +83,7 @@ pub fn create_lockscreen_window(
window.set_child(Some(&overlay));
// Background wallpaper
let background = create_background_picture(bg_texture);
let background = create_background_picture(bg_texture, config.background_blur);
overlay.set_child(Some(&background));
// Centered vertical box
@@ -419,11 +415,11 @@ pub fn start_fingerprint(
}
/// Load the wallpaper as a texture once, for sharing across all windows.
/// When `blur_radius` is `Some(sigma)` with sigma > 0, a Gaussian blur is applied.
pub fn load_background_texture(bg_path: &Path, blur_radius: Option<f32>) -> gdk::Texture {
/// Blur is applied at render time via GPU (GskBlurNode), not here.
pub fn load_background_texture(bg_path: &Path) -> gdk::Texture {
let fallback = "/dev/moonarch/moonlock/wallpaper.jpg";
let texture = if bg_path.starts_with("/dev/moonarch/moonlock") {
if bg_path.starts_with("/dev/moonarch/moonlock") {
let resource_path = bg_path.to_str().unwrap_or(fallback);
gdk::Texture::from_resource(resource_path)
} else {
@@ -431,152 +427,56 @@ pub fn load_background_texture(bg_path: &Path, blur_radius: Option<f32>) -> gdk:
gdk::Texture::from_file(&file).unwrap_or_else(|_| {
gdk::Texture::from_resource(fallback)
})
};
match blur_radius {
Some(sigma) if sigma > 0.0 => load_blurred_with_cache(bg_path, &texture, sigma),
_ => texture,
}
}
// -- Blur cache ----------------------------------------------------------------
const CACHE_PNG: &str = "blur-cache.png";
const CACHE_META: &str = "blur-cache.meta";
fn blur_cache_dir() -> Option<PathBuf> {
dirs::cache_dir().map(|d| d.join("moonlock"))
}
/// Build the cache key string for the current wallpaper + sigma.
fn build_cache_meta(bg_path: &Path, sigma: f32) -> Option<String> {
if bg_path.starts_with("/dev/moonarch/") {
let binary = std::env::current_exe().ok()?;
let binary_mtime = fs::metadata(&binary)
.ok()?
.modified()
.ok()?
.duration_since(SystemTime::UNIX_EPOCH)
.ok()?
.as_secs();
Some(format!(
"path={}\nbinary_mtime={}\nsigma={}\n",
bg_path.display(), binary_mtime, sigma,
))
} else {
let meta = fs::metadata(bg_path).ok()?;
let mtime = meta
.modified()
.ok()?
.duration_since(SystemTime::UNIX_EPOCH)
.ok()?
.as_secs();
Some(format!(
"path={}\nsize={}\nmtime={}\nsigma={}\n",
bg_path.display(), meta.len(), mtime, sigma,
))
}
}
/// Try to load a cached blurred texture if the cache key matches.
fn load_cached_blur(cache_dir: &Path, expected_meta: &str) -> Option<gdk::Texture> {
let stored_meta = fs::read_to_string(cache_dir.join(CACHE_META)).ok()?;
if stored_meta != expected_meta {
log::debug!("Blur cache meta mismatch, will re-blur");
return None;
}
let file = gio::File::for_path(cache_dir.join(CACHE_PNG));
match gdk::Texture::from_file(&file) {
Ok(texture) => {
log::debug!("Loaded blurred wallpaper from cache");
Some(texture)
}
Err(e) => {
log::debug!("Failed to load cached blur PNG: {e}");
None
}
}
}
/// Save a blurred texture to the cache directory.
fn save_blur_cache(cache_dir: &Path, texture: &gdk::Texture, meta: &str) {
if let Err(e) = save_blur_cache_inner(cache_dir, texture, meta) {
log::debug!("Failed to save blur cache: {e}");
}
}
fn save_blur_cache_inner(
cache_dir: &Path,
texture: &gdk::Texture,
meta: &str,
) -> Result<(), Box<dyn std::error::Error>> {
fs::create_dir_all(cache_dir)?;
let png_bytes = texture.save_to_png_bytes();
let mut f = fs::OpenOptions::new()
.create(true).write(true).truncate(true).mode(0o600)
.open(cache_dir.join(CACHE_PNG))?;
f.write_all(&png_bytes)?;
let mut f = fs::OpenOptions::new()
.create(true).write(true).truncate(true).mode(0o600)
.open(cache_dir.join(CACHE_META))?;
f.write_all(meta.as_bytes())?;
log::debug!("Saved blur cache to {}", cache_dir.display());
Ok(())
}
/// Load blurred texture, using disk cache when available.
fn load_blurred_with_cache(bg_path: &Path, texture: &gdk::Texture, sigma: f32) -> gdk::Texture {
if let Some(cache_dir) = blur_cache_dir() {
if let Some(meta) = build_cache_meta(bg_path, sigma) {
if let Some(cached) = load_cached_blur(&cache_dir, &meta) {
return cached;
}
let blurred = apply_blur(texture, sigma);
save_blur_cache(&cache_dir, &blurred, &meta);
return blurred;
}
}
apply_blur(texture, sigma)
}
// -- Blur implementation -------------------------------------------------------
/// Apply Gaussian blur to a texture and return a blurred texture.
fn apply_blur(texture: &gdk::Texture, sigma: f32) -> gdk::Texture {
let width = texture.width() as u32;
let height = texture.height() as u32;
let stride = width as usize * 4;
let mut pixel_data = vec![0u8; stride * height as usize];
texture.download(&mut pixel_data, stride);
let img = image::RgbaImage::from_raw(width, height, pixel_data)
.expect("pixel buffer size matches texture dimensions");
let blurred = imageops::blur(&image::DynamicImage::ImageRgba8(img), sigma);
let bytes = glib::Bytes::from(blurred.as_raw());
let mem_texture = gdk::MemoryTexture::new(
width as i32,
height as i32,
gdk::MemoryFormat::B8g8r8a8Premultiplied,
&bytes,
stride,
);
mem_texture.upcast()
}
/// Create a Picture widget for the wallpaper background from a shared texture.
fn create_background_picture(texture: &gdk::Texture) -> gtk::Picture {
/// Create a Picture widget for the wallpaper background.
/// When `blur_radius` is `Some(sigma)` with sigma > 0, blur is applied via GPU
/// (GskBlurNode). The blur is rendered to a concrete texture on `realize` (when
/// the GPU renderer is available), avoiding lazy-render artifacts.
fn create_background_picture(texture: &gdk::Texture, blur_radius: Option<f32>) -> gtk::Picture {
let background = gtk::Picture::for_paintable(texture);
background.set_content_fit(gtk::ContentFit::Cover);
background.set_hexpand(true);
background.set_vexpand(true);
if let Some(sigma) = blur_radius {
if sigma > 0.0 {
let texture = texture.clone();
background.connect_realize(move |picture| {
if let Some(blurred) = render_blurred_texture(picture, &texture, sigma) {
picture.set_paintable(Some(&blurred));
}
});
}
}
background
}
/// Render a blurred texture using the widget's GPU renderer.
/// Returns None if the renderer is not available.
fn render_blurred_texture(
widget: &impl IsA<gtk::Widget>,
texture: &gdk::Texture,
sigma: f32,
) -> Option<gdk::Texture> {
let native = widget.native()?;
let renderer = native.renderer()?;
let snapshot = gtk::Snapshot::new();
let bounds = graphene::Rect::new(
0.0,
0.0,
texture.width() as f32,
texture.height() as f32,
);
snapshot.push_blur(sigma as f64);
snapshot.append_texture(texture, &bounds);
snapshot.pop();
let node = snapshot.to_node()?;
Some(renderer.render_texture(&node, None))
}
/// Load an image file and set it as the avatar.
fn set_avatar_from_file(image: &gtk::Image, path: &Path) {
match Pixbuf::from_file_at_scale(path.to_str().unwrap_or(""), AVATAR_SIZE, AVATAR_SIZE, true) {
@@ -727,60 +627,4 @@ mod tests {
fn avatar_size_matches_css() {
assert_eq!(AVATAR_SIZE, 128);
}
// -- Blur cache tests --
#[test]
fn build_cache_meta_for_file() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("wallpaper.jpg");
fs::write(&file, b"fake image").unwrap();
let meta = build_cache_meta(&file, 20.0);
assert!(meta.is_some());
let meta = meta.unwrap();
assert!(meta.contains("path="));
assert!(meta.contains("size=10"));
assert!(meta.contains("sigma=20"));
}
#[test]
fn build_cache_meta_for_gresource() {
let path = Path::new("/dev/moonarch/moonlock/wallpaper.jpg");
let meta = build_cache_meta(path, 15.0);
assert!(meta.is_some());
let meta = meta.unwrap();
assert!(meta.contains("binary_mtime="));
assert!(meta.contains("sigma=15"));
assert!(!meta.contains("size="));
}
#[test]
fn build_cache_meta_missing_file() {
let meta = build_cache_meta(Path::new("/nonexistent/wallpaper.jpg"), 20.0);
assert!(meta.is_none());
}
#[test]
fn cache_meta_mismatch_returns_none() {
let dir = tempfile::tempdir().unwrap();
fs::write(
dir.path().join(CACHE_META),
"path=/old.jpg\nsize=100\nmtime=1\nsigma=20\n",
).unwrap();
let result = load_cached_blur(
dir.path(),
"path=/new.jpg\nsize=200\nmtime=2\nsigma=20\n",
);
assert!(result.is_none());
}
#[test]
fn cache_missing_meta_returns_none() {
let dir = tempfile::tempdir().unwrap();
let result = load_cached_blur(
dir.path(),
"path=/any.jpg\nsize=1\nmtime=1\nsigma=20\n",
);
assert!(result.is_none());
}
}
+11 -3
View File
@@ -13,7 +13,7 @@ use gdk4 as gdk;
use gtk4::prelude::*;
use gtk4::{self as gtk, gio};
use gtk4_session_lock;
use std::cell::RefCell;
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use crate::fingerprint::FingerprintListener;
@@ -41,7 +41,7 @@ fn activate(app: &gtk::Application) {
let config = config::load_config(None);
let bg_path = config::resolve_background_path(&config);
let bg_texture = lockscreen::load_background_texture(&bg_path, config.background_blur);
let bg_texture = lockscreen::load_background_texture(&bg_path);
if gtk4_session_lock::is_supported() {
activate_with_session_lock(app, &display, &bg_texture, &config);
@@ -70,10 +70,18 @@ fn activate_with_session_lock(
let monitors = display.monitors();
// Shared unlock callback — unlocks session and quits
// Shared unlock callback — unlocks session and quits.
// Guard prevents double-unlock if PAM and fingerprint succeed simultaneously.
let lock_clone = lock.clone();
let app_clone = app.clone();
let already_unlocked = Rc::new(Cell::new(false));
let au = already_unlocked.clone();
let unlock_callback: Rc<dyn Fn()> = Rc::new(move || {
if au.get() {
log::debug!("Unlock already triggered, ignoring duplicate");
return;
}
au.set(true);
lock_clone.unlock();
app_clone.quit();
});