From 854b40b6bc3e2bc740b49d9177d2f770da69e83b Mon Sep 17 00:00:00 2001 From: Davide Galassi Date: Fri, 20 Nov 2026 15:41:23 +0100 Subject: [PATCH] feat: unlock and lock LUKS devices --- src/drives.rs | 153 ++++++++++++++++++++++++++++++++++++++++++++++++-- src/tui.rs | 136 +++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 280 insertions(+), 9 deletions(-) diff --git a/src/drives.rs b/src/drives.rs index ebd46f6..5a33c31 100644 --- a/src/drives.rs +++ b/src/drives.rs @@ -2,6 +2,19 @@ use crate::config::Config; use crate::mountpoints; use std::collections::HashMap; +#[derive(Debug, Clone)] +pub enum Encryption { + Unencrypted, + Locked, + Unlocked(Cleartext), +} + +#[derive(Debug, Clone)] +pub struct Cleartext { + pub object_path: String, + pub devices: Vec, +} + #[derive(Debug, Clone)] pub struct Block { pub object_path: String, @@ -12,6 +25,15 @@ pub struct Block { pub fstype: String, pub mounted: bool, pub size: String, + pub encryption: Encryption, +} + +impl Block { + fn has_device(&self, dev: &str) -> bool { + self.dev == dev + || matches!(&self.encryption, Encryption::Unlocked(cleartext) + if cleartext.devices.iter().any(|name| name == dev)) + } } #[derive(Debug, Clone)] @@ -23,6 +45,34 @@ pub struct Drive { pub blocks: Vec, } +fn device_name(bytes: &[u8]) -> String { + String::from_utf8_lossy(bytes) + .chars() + .filter(|c| c != &'\0') + .collect() +} + +async fn encryption_of( + client: &udisks2::Client, + object: &udisks2::Object, +) -> udisks2::Result { + let Ok(encrypted) = object.encrypted().await else { + return Ok(Encryption::Unencrypted); + }; + let cleartext_path = encrypted.cleartext_device().await?.to_string(); + if cleartext_path == "/" { + return Ok(Encryption::Locked); + } + let cleartext = client.object(cleartext_path.clone())?.block().await?; + Ok(Encryption::Unlocked(Cleartext { + object_path: cleartext_path, + devices: vec![ + device_name(&cleartext.device().await?), + device_name(&cleartext.preferred_device().await?), + ], + })) +} + pub async fn collect_drives_from_udisk() -> udisks2::Result> { let mut drives: Vec = Vec::new(); let client = udisks2::Client::new().await?; @@ -58,6 +108,9 @@ pub async fn collect_drives_from_udisk() -> udisks2::Result> { drives.push(drv); } } else if let Ok(blk) = i.block().await { + if blk.crypto_backing_device().await?.as_str() != "/" { + continue; + } let drv_path = blk.drive().await?.to_string(); let size = if let Ok(size) = blk.size().await { client.size_for_display(size, true, false) @@ -67,15 +120,13 @@ pub async fn collect_drives_from_udisk() -> udisks2::Result> { let block = Block { object_path: path, drive_path: drv_path.clone(), - dev: String::from_utf8_lossy(&blk.device().await?) - .chars() - .filter(|c| c != &'\0') - .collect::(), + dev: device_name(&blk.device().await?), label: blk.id_label().await?, mount: None, fstype: blk.id_type().await?, mounted: false, size, + encryption: encryption_of(&client, &i).await?, }; if let Some(d) = drives.iter_mut().find(|i| i.object_path == drv_path) { @@ -110,8 +161,8 @@ pub async fn collect_all(config: &Config) -> udisks2::Result> { for i in mounts { let block = drives .iter_mut() - .find(|d| d.blocks.iter().any(|b| b.dev == i.dev)) - .and_then(|d| d.blocks.iter_mut().find(|b| b.dev == i.dev)); + .find(|d| d.blocks.iter().any(|b| b.has_device(&i.dev))) + .and_then(|d| d.blocks.iter_mut().find(|b| b.has_device(&i.dev))); if let Some(block) = block { block.mount = i.path; block.mounted = i.mounted; @@ -125,6 +176,7 @@ pub async fn collect_all(config: &Config) -> udisks2::Result> { fstype: i.fs, mounted: i.mounted, size: String::new(), + encryption: Encryption::Unencrypted, }); } } @@ -140,9 +192,32 @@ pub async fn collect_all(config: &Config) -> udisks2::Result> { pub async fn mount(block: &Block) -> udisks2::Result<()> { let client = udisks2::Client::new().await?; + let filesystem_path = match &block.encryption { + Encryption::Unlocked(cleartext) => cleartext.object_path.clone(), + Encryption::Unencrypted | Encryption::Locked => block.object_path.clone(), + }; client + .object(filesystem_path)? + .filesystem() + .await? + .mount(HashMap::new()) + .await?; + + Ok(()) +} + +pub async fn unlock_and_mount(block: &Block, passphrase: &str) -> udisks2::Result<()> { + let client = udisks2::Client::new().await?; + + let cleartext_path = client .object(block.object_path.clone())? + .encrypted() + .await? + .unlock(passphrase, HashMap::new()) + .await?; + client + .object(cleartext_path)? .filesystem() .await? .mount(HashMap::new()) @@ -154,6 +229,25 @@ pub async fn mount(block: &Block) -> udisks2::Result<()> { pub async fn unmount(block: &Block) -> udisks2::Result<()> { let client = udisks2::Client::new().await?; + if let Encryption::Unlocked(cleartext) = &block.encryption { + if let Ok(filesystem) = client + .object(cleartext.object_path.clone())? + .filesystem() + .await + { + if !filesystem.mount_points().await?.is_empty() { + filesystem.unmount(HashMap::new()).await?; + } + } + client + .object(block.object_path.clone())? + .encrypted() + .await? + .lock(HashMap::new()) + .await?; + return Ok(()); + } + client .object(block.object_path.clone())? .filesystem() @@ -176,3 +270,50 @@ pub async fn eject(block: &Block) -> udisks2::Result<()> { Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + + fn luks_block(encryption: Encryption) -> Block { + Block { + object_path: "/org/freedesktop/UDisks2/block_devices/sdc2".to_owned(), + drive_path: "/org/freedesktop/UDisks2/drives/disk".to_owned(), + dev: "/dev/sdc2".to_owned(), + label: String::new(), + mount: None, + fstype: "crypto_LUKS".to_owned(), + mounted: false, + size: String::new(), + encryption, + } + } + + fn unlocked() -> Encryption { + Encryption::Unlocked(Cleartext { + object_path: "/org/freedesktop/UDisks2/block_devices/dm_2d0".to_owned(), + devices: vec!["/dev/dm-0".to_owned(), "/dev/mapper/luks-1234".to_owned()], + }) + } + + // An unlocked LUKS partition shows as one row. /proc/self/mounts names its + // filesystem /dev/mapper/ (mount tools) or /dev/dm-N, never the LUKS + // partition, so the row must match both names to show its mount point. + #[test] + fn unlocked_row_matches_cleartext_device_names() { + let block = luks_block(unlocked()); + assert!(block.has_device("/dev/mapper/luks-1234")); + assert!(block.has_device("/dev/dm-0")); + assert!(block.has_device("/dev/sdc2")); + assert!(!block.has_device("/dev/mapper/other")); + } + + // A locked row must not take the mount of a cleartext device: the row of + // a locked partition always shows "not mounted". + #[test] + fn locked_row_matches_only_its_own_device() { + let block = luks_block(Encryption::Locked); + assert!(block.has_device("/dev/sdc2")); + assert!(!block.has_device("/dev/mapper/luks-1234")); + } +} diff --git a/src/tui.rs b/src/tui.rs index b8d8942..7985efe 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -1,10 +1,10 @@ use crate::drives; use crossterm::event::{KeyCode, KeyEvent}; use ratatui::{ - layout::{Alignment, Constraint, Layout}, + layout::{Alignment, Constraint, Flex, Layout}, style::Color, text::Line, - widgets::{Block, BorderType, Padding, Paragraph, Row, Table, TableState, Widget, Wrap}, + widgets::{Block, BorderType, Clear, Padding, Paragraph, Row, Table, TableState, Widget, Wrap}, Frame, }; @@ -20,9 +20,16 @@ pub struct Tui { pub drv: Vec, pub selected: Option, pub last_status: String, + passphrase_prompt: Option, +} + +struct PassphrasePrompt { + block: drives::Block, + passphrase: String, } const HELP: &str = "j/▲⋮k/▼⋮l/o/▶ - CD⋮m - Mount⋮u - Unmount⋮e - Eject⋮q - Quit"; +const PROMPT_HELP: &str = "Enter - Unlock⋮Esc - Cancel"; impl Tui { fn set_status(&mut self, res: udisks2::Result<()>) { @@ -33,6 +40,25 @@ impl Tui { } pub async fn input(&mut self, key: KeyEvent) -> InputResult { + if let Some(prompt) = &mut self.passphrase_prompt { + match key.code { + KeyCode::Char(character) => prompt.passphrase.push(character), + KeyCode::Backspace => { + prompt.passphrase.pop(); + } + KeyCode::Esc => self.passphrase_prompt = None, + KeyCode::Enter => { + if let Some(prompt) = self.passphrase_prompt.take() { + self.set_status( + drives::unlock_and_mount(&prompt.block, &prompt.passphrase).await, + ); + } + } + _ => {} + } + return InputResult::None; + } + match key.code { KeyCode::Up | KeyCode::Char('k') => { self.ts.select_previous(); @@ -44,7 +70,14 @@ impl Tui { } KeyCode::Char('m') => { if let Some(b) = &self.selected { - self.set_status(drives::mount(b).await); + if let drives::Encryption::Locked = b.encryption { + self.passphrase_prompt = Some(PassphrasePrompt { + block: b.clone(), + passphrase: String::new(), + }); + } else { + self.set_status(drives::mount(b).await); + } } InputResult::None } @@ -155,5 +188,102 @@ impl Tui { let info = format!("{} | {HELP}\n{descr}", self.last_status); let info = Paragraph::new(info).wrap(Wrap { trim: true }); frame.render_widget(info, layout[1]); + + if let Some(prompt) = &self.passphrase_prompt { + let [area] = Layout::vertical([Constraint::Length(3)]) + .flex(Flex::Center) + .areas(frame.area()); + let [area] = Layout::horizontal([Constraint::Percentage(60)]) + .flex(Flex::Center) + .areas(area); + let block = Block::bordered() + .title(Line::styled( + format!("Passphrase for {}", prompt.block.dev), + Color::White, + )) + .title_bottom(PROMPT_HELP) + .title_alignment(Alignment::Center) + .border_type(BorderType::Rounded) + .border_style(Color::Yellow); + let hidden_passphrase = "*".repeat(prompt.passphrase.chars().count()); + frame.render_widget(Clear, area); + frame.render_widget(Paragraph::new(hidden_passphrase).block(block), area); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn tui_with_locked_luks_row() -> Tui { + let block = drives::Block { + object_path: "/org/freedesktop/UDisks2/block_devices/sdc2".to_owned(), + drive_path: "/org/freedesktop/UDisks2/drives/disk".to_owned(), + dev: "/dev/sdc2".to_owned(), + label: String::new(), + mount: None, + fstype: "crypto_LUKS".to_owned(), + mounted: false, + size: String::new(), + encryption: drives::Encryption::Locked, + }; + Tui { + selected: Some(block), + ..Tui::default() + } + } + + async fn press(tui: &mut Tui, code: KeyCode) -> InputResult { + tui.input(KeyEvent::from(code)).await + } + + async fn type_text(tui: &mut Tui, text: &str) { + for character in text.chars() { + press(tui, KeyCode::Char(character)).await; + } + } + + // udisks cannot mount a locked device. `m` must ask for the passphrase of + // the selected device and must not send a mount request. + #[tokio::test] + async fn mount_of_locked_device_asks_for_passphrase() { + let mut tui = tui_with_locked_luks_row(); + press(&mut tui, KeyCode::Char('m')).await; + let prompt = tui.passphrase_prompt.expect("no passphrase prompt"); + assert_eq!(prompt.block.dev, "/dev/sdc2"); + assert_eq!(tui.last_status, ""); + } + + // A passphrase can contain command keys, for example `q`. In the prompt + // they must become passphrase text, and must not quit or start a command. + #[tokio::test] + async fn prompt_takes_command_keys_as_passphrase_text() { + let mut tui = tui_with_locked_luks_row(); + press(&mut tui, KeyCode::Char('m')).await; + for character in "qmuejkl".chars() { + let result = press(&mut tui, KeyCode::Char(character)).await; + assert!(matches!(result, InputResult::None)); + } + press(&mut tui, KeyCode::Backspace).await; + let prompt = tui.passphrase_prompt.expect("prompt closed"); + assert_eq!(prompt.passphrase, "qmuejk"); + } + + // Esc must cancel: no unlock request (it sets a status), and the normal + // keys work again. + #[tokio::test] + async fn escape_closes_prompt_without_unlock() { + let mut tui = tui_with_locked_luks_row(); + press(&mut tui, KeyCode::Char('m')).await; + type_text(&mut tui, "secret").await; + let result = press(&mut tui, KeyCode::Esc).await; + assert!(matches!(result, InputResult::None)); + assert!(tui.passphrase_prompt.is_none()); + assert_eq!(tui.last_status, ""); + assert!(matches!( + press(&mut tui, KeyCode::Char('q')).await, + InputResult::Quit + )); } }