diff --git a/Cargo.lock b/Cargo.lock index 68fe1fb69c..3dee9d0ed8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1153,7 +1153,9 @@ dependencies = [ "notify", "serde", "serde_json", + "tokio", "xkbcommon", + "zbus", ] [[package]] @@ -1443,6 +1445,7 @@ dependencies = [ "compass-oauth-store", "compass-sandbox", "compass-sqlcipher-sys", + "mime_guess", "serde", "serde_json", "tempfile", diff --git a/SECURITY.md b/SECURITY.md index 85ccfcc0f9..43cfa2a0b9 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -65,7 +65,10 @@ attacker with a kernel exploit can still escape it. keys). - **Syscalls**: a seccomp denylist refuses interfaces no extension needs, such as `ptrace` and module loading. It is a denylist because the worker is Node, whose syscall use changes between - releases. + releases. It also refuses Unix-domain sockets (`socketpair` stays allowed for a child's pipes), + so a worker cannot reach the session bus, the engine's IPC socket or any other local service, + and the worker is started with a short allowlist of the engine's environment, without the bus, + display or agent addresses. - **Memory**: each worker is capped at 256 MiB by `MemoryMax` in its own systemd scope, with each JavaScript heap capped at 160 MiB below that. Where no systemd is reachable (inside the Flatpak) `RLIMIT_DATA` holds it at 512 MiB of committed memory. The caps are not configurable diff --git a/crates/compass-core/src/onboarding.rs b/crates/compass-core/src/onboarding.rs index 520bcb7b8b..0c04037990 100644 --- a/crates/compass-core/src/onboarding.rs +++ b/crates/compass-core/src/onboarding.rs @@ -285,7 +285,8 @@ impl Recommendation { /// first command rendering. The Raycast ones come first, because running /// Raycast store extensions on Linux is what Compass adds; none of them runs /// AppleScript or needs Homebrew, so they work without the runtime's shim -/// having to stand in for macOS. +/// having to stand in for macOS. None talks to a local daemon over a unix +/// socket either (the system bus, Docker), which the sandbox refuses. pub const RECOMMENDED_EXTENSIONS: &[Recommendation] = &[ Recommendation { store: Store::Raycast, @@ -315,13 +316,6 @@ pub const RECOMMENDED_EXTENSIONS: &[Recommendation] = &[ title: "Tailwind CSS", description: "Search the Tailwind CSS documentation.", }, - Recommendation { - store: Store::Vicinae, - owner: "gelei", - name: "bluetooth", - title: "Bluetooth", - description: "Connect and manage Bluetooth devices.", - }, Recommendation { store: Store::Vicinae, owner: "dagimg-dot", @@ -329,6 +323,13 @@ pub const RECOMMENDED_EXTENSIONS: &[Recommendation] = &[ title: "Wifi Commander", description: "Connect to Wi-Fi networks and manage saved ones.", }, + Recommendation { + store: Store::Vicinae, + owner: "costeer", + name: "color-converter", + title: "Color Converter", + description: "Convert colors between hex, RGB and HSL.", + }, Recommendation { store: Store::Vicinae, owner: "fbosch", diff --git a/crates/compass-core/src/wallpaper.rs b/crates/compass-core/src/wallpaper.rs index 8f03412d7c..b053375836 100644 --- a/crates/compass-core/src/wallpaper.rs +++ b/crates/compass-core/src/wallpaper.rs @@ -367,8 +367,16 @@ pub fn prepare( /// The Plasma script the KDE backend evaluates (`org.kde.PlasmaShell.evaluateScript`): /// every desktop switched to the image plugin with this image and fill mode. +/// +/// The path comes from an extension, and a file name may hold any byte but +/// `/` and NUL, so it never goes into the script as text: it becomes a +/// percent-encoded `file://` URI ([`kde_image_uri`]), and that URI a JSON +/// string, which is also a JavaScript string literal. A quote or a `)` in the +/// name stays inside the literal instead of ending it. #[must_use] pub fn kde_script(request: &WallpaperRequest) -> String { + let image = + serde_json::to_string(&kde_image_uri(&request.path)).unwrap_or_else(|_| "\"\"".to_owned()); format!( r#" var ds = desktops(); @@ -376,15 +384,22 @@ pub fn kde_script(request: &WallpaperRequest) -> String { var d = ds[i]; d.wallpaperPlugin = "org.kde.image"; d.currentConfigGroup = Array("Wallpaper", "org.kde.image", "General"); - d.writeConfig("Image", "{}"); + d.writeConfig("Image", {image}); d.writeConfig("FillMode", {}); }} "#, - file_uri(&request.path), kde_fill_mode(request.fit) ) } +/// The image's URI for Plasma: percent-encoded by [`url::Url::from_file_path`] +/// for an absolute path, as the engine encodes paths elsewhere, and +/// [`file_uri`] otherwise. +#[must_use] +pub fn kde_image_uri(path: &str) -> String { + url::Url::from_file_path(path).map_or_else(|()| file_uri(path), String::from) +} + /// Whether the session is the desktop `backend` belongs to, read from /// `$XDG_CURRENT_DESKTOP` (colon-separated) and `$GDMSESSION` as the C++ /// `Environment` helpers read them. `None` for the two daemons and KDE, diff --git a/crates/compass-core/tests/wallpaper.rs b/crates/compass-core/tests/wallpaper.rs index 7dc61c02f0..35522a0153 100644 --- a/crates/compass-core/tests/wallpaper.rs +++ b/crates/compass-core/tests/wallpaper.rs @@ -342,6 +342,29 @@ fn the_kde_script_sets_the_image_plugin_image_and_fill_on_every_desktop() { assert!(script.contains("for (var i = 0; i < ds.length; i++)")); } +#[test] +fn a_kde_wallpaper_path_cannot_end_the_script_s_string() { + let path = r#"/tmp/a");evil();("b.png"#; + let script = compass_core::wallpaper::kde_script(&WallpaperRequest { + path: path.into(), + screen: None, + fit: WallpaperFit::Cover, + }); + // `evil();` may appear inside the URI, but never right after a closed + // string, where Plasma would run it. + assert!(!script.contains(r#"");evil"#), "{script}"); + assert_eq!(script.matches(r#"d.writeConfig("Image", "#).count(), 1); + let start = + script.find(r#"d.writeConfig("Image", "#).unwrap() + r#"d.writeConfig("Image", "#.len(); + let rest = &script[start..]; + let end = rest.find(");\n").unwrap(); + let literal: String = serde_json::from_str(&rest[..end]).expect("one JSON string literal"); + assert_eq!( + url::Url::parse(&literal).unwrap().to_file_path().unwrap(), + std::path::PathBuf::from(path) + ); +} + #[test] fn desktops_are_recognised_as_the_cpp_environment_helpers_do() { use compass_core::wallpaper::desktop_matches; diff --git a/crates/compass-input-server/Cargo.toml b/crates/compass-input-server/Cargo.toml index cbe0ad9e67..2f1564bf29 100644 --- a/crates/compass-input-server/Cargo.toml +++ b/crates/compass-input-server/Cargo.toml @@ -21,3 +21,5 @@ xkbcommon = { version = "0.8", default-features = false } notify.workspace = true serde.workspace = true serde_json.workspace = true +tokio = { workspace = true, features = ["rt"] } +zbus.workspace = true diff --git a/crates/compass-input-server/src/lib.rs b/crates/compass-input-server/src/lib.rs index 414b2fa85b..95ec6f726f 100644 --- a/crates/compass-input-server/src/lib.rs +++ b/crates/compass-input-server/src/lib.rs @@ -13,6 +13,7 @@ //! * [`keymap`] — keycodes to text through xkbcommon (and a table for tests); //! * [`device`] — `/dev/input` and `/dev/uinput` through `evdev`; //! * [`server`] — the process and its loop; +//! * [`seat`] — serving only the user at the keyboard; //! * [`recording`] — reading `evtest` logs, for replaying real typing. //! //! The wire is `compass_core::input_server`: figura's JSON-RPC in @@ -23,13 +24,17 @@ //! Reading `/dev/input/event*` and writing `/dev/uinput` need either root //! or `CAP_DAC_OVERRIDE`. The packages grant it with //! `setcap cap_dac_override+ep` (Arch's `compass.install`) or the NixOS -//! module's `security.wrappers`; see `packaging/README.md`. +//! module's `security.wrappers`; see `packaging/README.md`. A file +//! capability goes to whoever runs the file, so a privileged helper reads +//! keys and injects only while its user has the active session on a seat +//! ([`seat`]). #![deny(missing_docs)] pub mod device; pub mod keymap; pub mod recording; +pub mod seat; pub mod server; pub mod service; pub mod tracker; diff --git a/crates/compass-input-server/src/seat.rs b/crates/compass-input-server/src/seat.rs new file mode 100644 index 0000000000..cc4f76cee9 --- /dev/null +++ b/crates/compass-input-server/src/seat.rs @@ -0,0 +1,315 @@ +//! Who may use the helper's privilege: the person at the keyboard. +//! +//! The capability is a file capability, so it is granted to whoever runs the +//! file, and the helper speaks to whoever holds its stdin. Without a check, +//! another account on the machine could run it to read every keyboard and to +//! type into the focused window. So a privileged helper serves only a user +//! whose logind session is the active one on a seat, and asks again while it +//! runs: after a switch to another user it stops reading keys and refuses to +//! inject, and starts again when its own user is back. +//! +//! Unprivileged, the helper can open nothing its caller could not, and none +//! of this applies; that is also how the tests run it. +//! +//! The system bus is reached at its fixed address, never through +//! `DBUS_SYSTEM_BUS_ADDRESS`: whoever runs the helper chooses its +//! environment, and could point it at a bus that answers "active". Where no +//! logind answers there (a seatd-only system) the helper cannot tell, says +//! so, and relies on who the install lets run it (`packaging/README.md`). + +use std::time::{Duration, Instant}; + +use zbus::zvariant::OwnedObjectPath; + +/// `CAP_DAC_OVERRIDE`'s bit in `CapEff`. +const CAP_DAC_OVERRIDE: u32 = 1; + +/// The system bus's socket, where the D-Bus specification fixes it. +const SYSTEM_BUS_SOCKET: &str = "/var/run/dbus/system_bus_socket"; + +/// How long an answer is trusted before logind is asked again. +pub const RECHECK: Duration = Duration::from_secs(1); + +/// What `/proc/self/status` says about this process: its real user, and +/// whether it holds `CAP_DAC_OVERRIDE` (or is root, who needs no capability). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Credentials { + /// The real user id: who ran the helper, whatever the file grants. + pub uid: u32, + /// Whether the process can open what its user could not. + pub privileged: bool, +} + +/// Reads [`Credentials`] from the text of `/proc/self/status`. +#[must_use] +pub fn credentials(status: &str) -> Option { + let field = |name: &str| { + status + .lines() + .find_map(|line| line.strip_prefix(name)) + .map(str::trim) + }; + let mut ids = field("Uid:")?.split_whitespace(); + let uid: u32 = ids.next()?.parse().ok()?; + let euid: u32 = ids.next()?.parse().ok()?; + let effective = u64::from_str_radix(field("CapEff:")?, 16).ok()?; + Some(Credentials { + uid, + privileged: euid == 0 || effective & (1 << CAP_DAC_OVERRIDE) != 0, + }) +} + +/// A session as logind lists it: its user, its seat (empty for a remote +/// one), and whether it is the one in front on that seat. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Session { + /// The session's user. + pub uid: u32, + /// The seat, or empty for an SSH or other seatless session. + pub seat: String, + /// Whether it is the active session of its seat. + pub active: bool, +} + +/// Whether `uid` is at a keyboard: it has the active session on some seat. +#[must_use] +pub fn at_the_keyboard(uid: u32, sessions: &[Session]) -> bool { + sessions + .iter() + .any(|session| session.uid == uid && !session.seat.is_empty() && session.active) +} + +/// What the gate decided. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Verdict { + /// Serve: unprivileged, or the caller has the active session. + Allowed, + /// Do not read keys or inject: the caller is not at the keyboard. + Refused, + /// Privileged, and no logind to ask; the install's permissions decide. + Unknown, +} + +#[zbus::proxy( + interface = "org.freedesktop.login1.Manager", + default_service = "org.freedesktop.login1", + default_path = "/org/freedesktop/login1" +)] +trait Manager { + fn list_sessions(&self) -> zbus::Result>; +} + +#[zbus::proxy( + interface = "org.freedesktop.login1.Session", + default_service = "org.freedesktop.login1" +)] +trait LoginSession { + #[zbus(property)] + fn active(&self) -> zbus::Result; +} + +/// Asks logind, and remembers the answer for [`RECHECK`]. +#[derive(Debug)] +pub struct Gate { + credentials: Option, + runtime: Option, + connection: Option, + last: Option<(Instant, Verdict)>, +} + +impl Gate { + /// A gate for this process. + #[must_use] + pub fn new() -> Self { + let credentials = std::fs::read_to_string("/proc/self/status") + .ok() + .as_deref() + .and_then(credentials); + Self { + credentials, + runtime: None, + connection: None, + last: None, + } + } + + /// Whether to serve now, asking logind when the last answer is stale. + pub fn verdict(&mut self) -> Verdict { + if let Some((at, verdict)) = self.last + && at.elapsed() < RECHECK + { + return verdict; + } + let verdict = self.ask(); + self.last = Some((Instant::now(), verdict)); + verdict + } + + /// Whether keys may be read and injected now. + pub fn allows(&mut self) -> bool { + self.verdict() != Verdict::Refused + } + + fn ask(&mut self) -> Verdict { + let credentials = match self.credentials { + Some(credentials) if !credentials.privileged => return Verdict::Allowed, + Some(credentials) => credentials, + // Unreadable status: assume the worst about the privilege, and + // there is no user to look for. + None => return Verdict::Refused, + }; + if self.runtime.is_none() { + match tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + { + Ok(runtime) => self.runtime = Some(runtime), + Err(error) => { + eprintln!("could not start the logind client: {error}"); + return Verdict::Refused; + } + } + } + let Some(runtime) = &self.runtime else { + return Verdict::Refused; + }; + let connection = &mut self.connection; + runtime.block_on(async { + if connection.is_none() { + match connect().await { + Ok(made) => *connection = Some(made), + // No system bus at all: nothing to ask. One that is there + // and will not answer is not taken as absent, since a + // caller can starve the helper of descriptors. + Err(_) if !std::path::Path::new(SYSTEM_BUS_SOCKET).exists() => { + return Verdict::Unknown; + } + Err(error) => { + eprintln!("could not reach the system bus: {error}"); + return Verdict::Refused; + } + } + } + let Some(bus) = connection.as_ref() else { + return Verdict::Unknown; + }; + match sessions(bus).await { + Ok(sessions) if at_the_keyboard(credentials.uid, &sessions) => Verdict::Allowed, + Ok(_) => Verdict::Refused, + Err(zbus::Error::MethodError(name, _, _)) + if name.as_str() == "org.freedesktop.DBus.Error.ServiceUnknown" + || name.as_str() == "org.freedesktop.DBus.Error.NameHasNoOwner" => + { + Verdict::Unknown + } + Err(error) => { + eprintln!("could not ask logind who is at the keyboard: {error}"); + *connection = None; + Verdict::Refused + } + } + }) + } +} + +impl Default for Gate { + fn default() -> Self { + Self::new() + } +} + +async fn connect() -> zbus::Result { + zbus::connection::Builder::address(format!("unix:path={SYSTEM_BUS_SOCKET}").as_str())? + .build() + .await +} + +async fn sessions(bus: &zbus::Connection) -> zbus::Result> { + let listed = ManagerProxy::new(bus).await?.list_sessions().await?; + let mut sessions = Vec::with_capacity(listed.len()); + for (_, uid, _, seat, path) in listed { + let active = LoginSessionProxy::builder(bus) + .path(path)? + .cache_properties(zbus::proxy::CacheProperties::No) + .build() + .await? + .active() + .await?; + sessions.push(Session { uid, seat, active }); + } + Ok(sessions) +} + +#[cfg(test)] +mod tests { + use super::*; + + const STATUS: &str = "Name:\tcompass-input-s\nUid:\t1000\t1000\t1000\t1000\n\ + Gid:\t1000\t1000\t1000\t1000\nCapInh:\t0000000000000000\n\ + CapPrm:\t0000000000000002\nCapEff:\t0000000000000002\n"; + + #[test] + fn the_capability_and_the_real_user_are_read_from_status() { + assert_eq!( + credentials(STATUS), + Some(Credentials { + uid: 1000, + privileged: true + }) + ); + let plain = STATUS.replace("CapEff:\t0000000000000002", "CapEff:\t0000000000000000"); + assert_eq!( + credentials(&plain).map(|c| c.privileged), + Some(false), + "a helper without the capability is not privileged" + ); + let root = plain.replace("Uid:\t1000\t1000", "Uid:\t1000\t0"); + assert_eq!(credentials(&root).map(|c| c.privileged), Some(true)); + assert_eq!(credentials("Name:\tx\n"), None); + } + + fn session(uid: u32, seat: &str, active: bool) -> Session { + Session { + uid, + seat: seat.to_owned(), + active, + } + } + + #[test] + fn only_the_active_session_on_a_seat_is_at_the_keyboard() { + let sessions = [ + session(1000, "seat0", true), + session(1001, "seat0", false), + session(1002, "", true), + ]; + assert!(at_the_keyboard(1000, &sessions)); + assert!( + !at_the_keyboard(1001, &sessions), + "a user switched away from reads the next user's keys" + ); + assert!( + !at_the_keyboard(1002, &sessions), + "an SSH login is not at the keyboard" + ); + assert!(!at_the_keyboard(1003, &sessions)); + } + + #[test] + fn an_unprivileged_helper_is_never_refused() { + let mut gate = Gate { + credentials: Some(Credentials { + uid: 1000, + privileged: false, + }), + runtime: None, + connection: None, + last: None, + }; + assert_eq!(gate.verdict(), Verdict::Allowed); + assert!( + gate.runtime.is_none(), + "no bus is asked without a privilege" + ); + } +} diff --git a/crates/compass-input-server/src/server.rs b/crates/compass-input-server/src/server.rs index 8e1addf4cf..59d03b5a54 100644 --- a/crates/compass-input-server/src/server.rs +++ b/crates/compass-input-server/src/server.rs @@ -17,6 +17,7 @@ use compass_platform_linux::keyboard::VirtualKeyboard; use crate::device::{self, DeviceMessage, Kind, UinputSink}; use crate::keymap::XkbKeys; use crate::recording::EV_KEY; +use crate::seat::{Gate, Verdict}; use crate::service::{LiveInput, Service}; use crate::tracker::MODIFIER_TIMEOUT; @@ -58,6 +59,18 @@ pub fn run() -> u8 { eprintln!("{error}; triggers are detected but nothing can be injected"); } let mut service = Service::new(keys, keyboard); + let mut gate = Gate::new(); + match gate.verdict() { + Verdict::Allowed => {} + Verdict::Refused => eprintln!( + "this user does not have the active session on a seat; no key is read or typed until \ + it does" + ), + Verdict::Unknown => eprintln!( + "no logind on the system bus to say who is at the keyboard; serving whoever the \ + install lets run this helper" + ), + } let (tx, rx) = mpsc::channel::(); spawn_stdin_reader(tx.clone()); @@ -123,6 +136,9 @@ pub fn run() -> u8 { Message::Control(bytes) => { for request in buffer.push(&bytes) { let answer = match Call::decode(&request) { + Ok((id, call)) if injects(&call) && !gate.allows() => { + wire::reply_error(id, NOT_AT_THE_KEYBOARD) + } Ok((id, call)) => match service.call(call, &mut input) { Ok(result) => wire::reply(id, &result), Err(error) => { @@ -160,6 +176,12 @@ pub fn run() -> u8 { if !kind.keyboard || event.kind != EV_KEY { continue; } + if !gate.allows() { + // Another user's typing: not one key of it reaches the + // tracker, and nothing typed before the switch is kept. + service.forget_typing(); + continue; + } if let Some(event) = service.key(event.code, event.value) { send(&mut out, &event.encode()); } @@ -168,6 +190,17 @@ pub fn run() -> u8 { } } +/// Why an injection was refused. +const NOT_AT_THE_KEYBOARD: &str = "not injecting: this user does not have the active session"; + +/// Whether `call` types into the focused window. +fn injects(call: &Call) -> bool { + matches!( + call, + Call::InjectExpand(_) | Call::InjectUndo(_) | Call::InjectPaste { .. } + ) +} + /// Opens `node` with `open` and, if it is a keyboard or a pointer, starts /// reading it. fn register( diff --git a/crates/compass-input-server/src/service.rs b/crates/compass-input-server/src/service.rs index 157abcea6e..10ff3c8ace 100644 --- a/crates/compass-input-server/src/service.rs +++ b/crates/compass-input-server/src/service.rs @@ -67,6 +67,11 @@ impl Service { self.tracker.key(code, value) } + /// Forgets what has been typed, as `resetContext` does. + pub fn forget_typing(&mut self) { + self.tracker.reset(); + } + /// The modifier wait ran out. pub fn flush_pending(&mut self) -> Option { self.tracker.flush_pending() @@ -82,8 +87,9 @@ impl Service { /// /// # Errors /// - /// Only a keymap that does not compile; every other call succeeds, as in - /// the C++ (an injection without a virtual keyboard does nothing). + /// A keymap that does not compile, and a snippet with an empty keyword; + /// every other call succeeds, as in the C++ (an injection without a + /// virtual keyboard does nothing). pub fn call(&mut self, call: Call, input: &mut dyn LiveInput) -> Result { match call { Call::SetKeymap(layout) => { @@ -93,6 +99,11 @@ impl Service { } Ok(Value::Null) } + Call::CreateSnippet { trigger, .. } if trigger.is_empty() => { + // An empty keyword matches after every key, so all it could + // do is report when each key is pressed. + Err("refusing a snippet with an empty keyword".to_owned()) + } Call::CreateSnippet { trigger, mode } => { self.tracker.add(trigger, mode.into()); Ok(wire::create_snippet_result()) diff --git a/crates/compass-input-server/tests/service.rs b/crates/compass-input-server/tests/service.rs index 8f52789dfb..f13943250f 100644 --- a/crates/compass-input-server/tests/service.rs +++ b/crates/compass-input-server/tests/service.rs @@ -96,6 +96,23 @@ fn registered_keywords_fire_and_removed_ones_do_not() { assert_eq!(service.key(45, 1), None); } +#[test] +fn an_empty_keyword_is_refused_rather_than_reporting_every_key() { + let mut service = service(); + assert!( + service + .call( + Call::CreateSnippet { + trigger: String::new(), + mode: ExpansionMode::Keydown, + }, + &mut Scripted::default(), + ) + .is_err() + ); + assert_eq!(service.key(45, 1), None, "a key press fired a trigger"); +} + #[test] fn an_expansion_erases_the_keyword_then_pastes() { let mut service = service(); diff --git a/crates/compass-ipc/src/error.rs b/crates/compass-ipc/src/error.rs index af27618176..c1a8b99247 100644 --- a/crates/compass-ipc/src/error.rs +++ b/crates/compass-ipc/src/error.rs @@ -53,6 +53,18 @@ pub enum Error { reason: String, }, + /// A connection came from a process running as another user. + /// + /// The socket's directory is the owner's alone, so this means its mode + /// was loosened by someone else; the connection is closed unanswered. + #[error("refusing an ipc connection from uid {peer}: the engine runs as uid {owner}")] + ForeignPeer { + /// The connecting process's user. + peer: u32, + /// The user the socket belongs to. + owner: u32, + }, + /// Something is already listening on the socket path. #[error("Compass is already running (socket {} is live)", .path.display())] AlreadyRunning { diff --git a/crates/compass-ipc/src/transport.rs b/crates/compass-ipc/src/transport.rs index f99051f45a..c18a707919 100644 --- a/crates/compass-ipc/src/transport.rs +++ b/crates/compass-ipc/src/transport.rs @@ -36,6 +36,9 @@ pub async fn is_listening(path: impl AsRef) -> bool { pub struct Listener { inner: UnixListener, path: PathBuf, + /// The user who bound the socket: the only one whose connections are + /// served. + owner: u32, } impl Listener { @@ -63,7 +66,7 @@ impl Listener { } match UnixListener::bind(&path) { - Ok(inner) => Ok(Self { inner, path }), + Ok(inner) => Self::owned(inner, path), Err(err) if err.kind() == std::io::ErrorKind::AddrInUse => { if is_listening(&path).await { return Err(Error::AlreadyRunning { path }); @@ -78,12 +81,30 @@ impl Listener { tracing::info!(path = %path.display(), "reclaiming stale ipc socket"); std::fs::remove_file(&path).map_err(Error::Io)?; let inner = UnixListener::bind(&path).map_err(Error::Io)?; - Ok(Self { inner, path }) + Self::owned(inner, path) } Err(err) => Err(Error::Io(err)), } } + /// The socket file was just made by this process, so its owner is the + /// user this process runs as; `std` has no portable `geteuid`. + fn owned(inner: UnixListener, path: PathBuf) -> Result { + use std::os::unix::fs::MetadataExt; + let owner = std::fs::symlink_metadata(&path).map_err(Error::Io)?.uid(); + Ok(Self { inner, path, owner }) + } + + /// Refuses a connection from another user's process. + /// + /// The `0700` directory should already keep them out; this holds when its + /// mode does not. A sandboxed extension runs as the same user and is kept + /// from the socket by the sandbox's syscall filter, not by this. + fn admit(&self, stream: &UnixStream) -> Result<()> { + let peer = stream.peer_cred().map_err(Error::Io)?.uid(); + admits(self.owner, peer) + } + /// The path this listener is bound to. #[must_use] pub fn path(&self) -> &Path { @@ -93,6 +114,7 @@ impl Listener { /// Accepts one connection. pub async fn accept(&self) -> Result { let (stream, _addr) = self.inner.accept().await.map_err(Error::Io)?; + self.admit(&stream)?; Ok(stream) } @@ -169,6 +191,10 @@ impl Listener { } accepted = self.inner.accept() => { let (stream, _addr) = accepted.map_err(Error::Io)?; + if let Err(err) = self.admit(&stream) { + tracing::warn!(error = %err, "ipc connection refused"); + continue; + } let handler = Arc::clone(&handler); let on_attach = Arc::clone(&on_attach); tokio::spawn(async move { @@ -186,6 +212,15 @@ impl Listener { } } +/// Whether a peer running as `peer` may talk to a socket `owner` bound. +fn admits(owner: u32, peer: u32) -> Result<()> { + if peer == owner { + Ok(()) + } else { + Err(Error::ForeignPeer { peer, owner }) + } +} + impl Drop for Listener { fn drop(&mut self) { // Best effort: if this fails the next start reclaims the stale socket. @@ -528,3 +563,33 @@ impl Client { client.request(request).await } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_the_owner_is_admitted() { + assert!(admits(1000, 1000).is_ok()); + assert!(matches!( + admits(1000, 1001), + Err(Error::ForeignPeer { + peer: 1001, + owner: 1000 + }) + )); + assert!(admits(1000, 0).is_err(), "not even root is served"); + } + + #[tokio::test] + async fn a_connection_from_the_owner_is_accepted() { + let dir = tempfile::tempdir().expect("tempdir"); + let listener = Listener::bind(dir.path().join("compass/ipc.sock")) + .await + .expect("binds"); + let path = listener.path().to_owned(); + let (accepted, connected) = tokio::join!(listener.accept(), UnixStream::connect(&path)); + connected.expect("connects"); + accepted.expect("the owner's own connection is accepted"); + } +} diff --git a/crates/compass-sandbox/src/bin/probe.rs b/crates/compass-sandbox/src/bin/probe.rs index 535b2ab0a2..0697b52cab 100644 --- a/crates/compass-sandbox/src/bin/probe.rs +++ b/crates/compass-sandbox/src/bin/probe.rs @@ -21,6 +21,12 @@ //! - `stream-socket`: `socket(AF_INET, SOCK_STREAM, 0)`, which must work //! behind the filter: the control that the socket rules are not a ban on //! sockets. +//! - `unix-connect=`: `socket(AF_UNIX, SOCK_STREAM, 0)` and `connect` +//! to `path`. Unfiltered, with something listening there, this succeeds; +//! behind the filter the `socket` call answers `EPERM`. +//! - `unix-socketpair`: `socketpair(AF_UNIX, SOCK_STREAM, 0)`, which must work +//! behind the filter: it is how Node makes a child's stdio pipes, and the +//! pair it returns can reach nothing but itself. //! - `alloc-512m`: reserves 512 MiB, answering `ENOMEM` when the data limit //! refuses it. //! @@ -29,7 +35,7 @@ //! exactly the ambiguity being avoided. use nix::sys::ptrace; -use nix::sys::socket::{AddressFamily, SockFlag, SockType, socket}; +use nix::sys::socket::{AddressFamily, SockFlag, SockType, UnixAddr, connect, socket, socketpair}; use nix::unistd::Pid; fn main() { @@ -56,6 +62,25 @@ fn main() { None, ) .map(drop), + "unix-socketpair" => socketpair( + AddressFamily::Unix, + SockType::Stream, + None, + SockFlag::empty(), + ) + .map(drop), + unix if unix.starts_with("unix-connect=") => { + let path = &unix["unix-connect=".len()..]; + UnixAddr::new(path).and_then(|address| { + let fd = socket( + AddressFamily::Unix, + SockType::Stream, + SockFlag::empty(), + None, + )?; + connect(std::os::fd::AsRawFd::as_raw_fd(&fd), &address) + }) + } // `try_reserve` rather than an allocation, so a refusal is an error // to print rather than an abort; the reservation is a private // writable mapping, which is what RLIMIT_DATA counts. diff --git a/crates/compass-sandbox/src/syscalls.rs b/crates/compass-sandbox/src/syscalls.rs index 01d0156b9d..edafa6cc55 100644 --- a/crates/compass-sandbox/src/syscalls.rs +++ b/crates/compass-sandbox/src/syscalls.rs @@ -200,9 +200,20 @@ pub const DENIED_SOCKET_TYPES: &[(&str, i32)] = &[ ("SOCK_PACKET", 10), ]; -/// The address families a worker may not open a socket in, whatever the type: +/// The address families a worker may not open a socket in, whatever the type. +/// /// `AF_PACKET` is link-layer access, raw in every type it offers. -pub const DENIED_SOCKET_FAMILIES: &[(&str, i32)] = &[("AF_PACKET", libc::AF_PACKET)]; +/// +/// `AF_UNIX` is the way out of the filesystem boundary that never opens a +/// file: Landlock V1 does not mediate `connect` to a pathname socket, and the +/// session bus, the engine's own IPC socket and every other local service +/// listen on one. Over the session bus a worker can ask systemd or a portal to +/// start a process that has none of these rules. The worker's own channel to +/// the host is its stdin and stdout, and Node makes the pipes for a child's +/// stdio with `socketpair`, which is a different syscall and stays allowed; +/// only a socket that could be pointed at an address is refused. +pub const DENIED_SOCKET_FAMILIES: &[(&str, i32)] = + &[("AF_PACKET", libc::AF_PACKET), ("AF_UNIX", libc::AF_UNIX)]; /// The low bits of `socket`'s type argument that name the type. const SOCKET_TYPE_MASK: u64 = 0xf; @@ -232,8 +243,7 @@ fn socket_rules() -> Result, Error> { } /// Installs a filter denying `numbers` on the calling thread, for good, and -/// the raw sockets [`DENIED_SOCKET_TYPES`] and [`DENIED_SOCKET_FAMILIES`] -/// name. +/// the sockets [`DENIED_SOCKET_TYPES`] and [`DENIED_SOCKET_FAMILIES`] name. /// /// Everything unnamed stays allowed — see the module docs. /// diff --git a/crates/compass-sandbox/tests/boundary.rs b/crates/compass-sandbox/tests/boundary.rs index a6a80a1f1f..b928acf82b 100644 --- a/crates/compass-sandbox/tests/boundary.rs +++ b/crates/compass-sandbox/tests/boundary.rs @@ -522,6 +522,40 @@ fn a_raw_socket_is_refused_while_an_ordinary_one_is_not() { ); } +#[test] +fn a_unix_socket_outside_every_grant_cannot_be_reached() { + // The session bus and the engine's IPC socket are pathname sockets that + // no grant names, and Landlock V1 does not look at `connect`. A worker + // that reached either would be out of the boundary without opening a + // file, so the filter refuses the socket itself. + let dir = tempfile::tempdir().expect("a temporary directory"); + let path = dir.path().join("bus.sock"); + let _listener = std::os::unix::net::UnixListener::bind(&path).expect("a listening socket"); + let mode = format!("unix-connect={}", path.display()); + assert_eq!( + probe_plain(&mode), + "errno=ok", + "the unsandboxed control could not connect, so a denial below would prove nothing" + ); + assert_eq!( + probe_mode(&probe_policy().without_syscall_filter(), &mode), + "errno=ok", + "with the filter off the connect should get through: Landlock V1 does not mediate it" + ); + assert_eq!( + probe_mode(&probe_policy(), &mode), + "errno=EPERM", + "a sandboxed worker connected to a unix socket outside its policy" + ); + // Node makes a child process's stdio with `socketpair`; refusing that + // would break every extension that runs a program. + assert_eq!( + probe_mode(&probe_policy(), "unix-socketpair"), + "errno=ok", + "socketpair was refused: an extension could no longer run a child process" + ); +} + #[test] fn a_program_the_worker_wrote_itself_cannot_be_run() { if !landlock_enforces() { diff --git a/crates/compass-worker-host/Cargo.toml b/crates/compass-worker-host/Cargo.toml index 5baf41c5e7..73d23e4867 100644 --- a/crates/compass-worker-host/Cargo.toml +++ b/crates/compass-worker-host/Cargo.toml @@ -20,6 +20,7 @@ serde_json.workspace = true thiserror.workspace = true zbus = { workspace = true } url.workspace = true +mime_guess.workspace = true [dev-dependencies] compass-local-storage = { path = "../compass-local-storage" } diff --git a/crates/compass-worker-host/src/application_service.rs b/crates/compass-worker-host/src/application_service.rs index c3c46cdc2c..2878e2a301 100644 --- a/crates/compass-worker-host/src/application_service.rs +++ b/crates/compass-worker-host/src/application_service.rs @@ -10,6 +10,22 @@ //! `mimeapps` already resolves default openers. What this module owns is the //! translation: which query each method makes, what it does when the query //! comes back empty, and the exact shape of an `Application` on the wire. +//! +//! Two calls differ from upstream, which has no sandbox and so gives an +//! extension nothing it did not already have. Here the worker is confined and +//! the engine is not, so: +//! +//! - `runInTerminal` runs nothing and answers `false` ([`TERMINAL_REFUSED`](crate::application_service::TERMINAL_REFUSED)). +//! The engine would start the command line on the host, unconfined, and +//! only `HostCommand/run` may do that, for a program the overrides list +//! names and after asking the person. +//! - `open` of a file the extension could have written (under its support or +//! assets directory, see [`ApplicationService::with_writable`](crate::application_service::ApplicationService::with_writable)) goes only to +//! the default opener, and only for a type a viewer shows +//! ([`is_viewer_type`](crate::application_service::is_viewer_type)): an `appId` naming `java -jar %f` or `wine` would +//! otherwise run a file the extension wrote. + +use std::path::{Path, PathBuf}; use crate::tsapi::{self, Call}; @@ -25,6 +41,12 @@ pub const METHODS: &[&str] = &[ /// The error `getDefault` fails with, verbatim from the C++. pub const NO_DEFAULT: &str = "No default application found"; +/// Why `runInTerminal` answered `false`. Extensions see the `false`; this is +/// for the engine's log and the documentation. +pub const TERMINAL_REFUSED: &str = "Compass does not run terminal commands for extensions: a \ + command line would run on your computer outside the extension sandbox. Extensions run \ + host programs through HostCommand/run, which asks first."; + /// One application, as `appToTsapi` builds it. #[derive(Debug, Clone, PartialEq, Eq, Default)] pub struct Application { @@ -80,12 +102,29 @@ pub trait Apps { #[derive(Debug)] pub struct ApplicationService { apps: A, + /// The directories the extension may write, resolved. + writable: Vec, } impl ApplicationService { /// Serves `apps`. pub const fn new(apps: A) -> Self { - Self { apps } + Self { + apps, + writable: Vec::new(), + } + } + + /// Treats a file under any of `dirs`, the directories the extension may + /// write, as one it may have written: `open` ignores `appId` for it and + /// opens it only when [`is_viewer_type`] says a viewer shows it. + #[must_use] + pub fn with_writable(mut self, dirs: impl IntoIterator) -> Self { + self.writable = dirs + .into_iter() + .map(|dir| dir.canonicalize().unwrap_or(dir)) + .collect(); + self } /// The database this serves. @@ -142,35 +181,10 @@ impl ApplicationService { self.apps.show_in_file_browser(&target, select); tsapi::reply(id, serde_json::Value::Null) } - _ => { - let opts = call.params.get("opts"); - let field = |name: &str| { - opts.and_then(|opts| opts.get(name)) - .filter(|value| !value.is_null()) - .and_then(serde_json::Value::as_str) - .map(str::to_owned) - }; - let cmdline: Vec = opts - .and_then(|opts| opts.get("cmdline")) - .and_then(serde_json::Value::as_array) - .map(|args| { - args.iter() - .map(|arg| arg.as_str().unwrap_or_default().to_owned()) - .collect() - }) - .unwrap_or_default(); - let options = TerminalOptions { - hold: opts - .and_then(|opts| opts.get("hold")) - .and_then(serde_json::Value::as_bool) - .unwrap_or(false), - app_id: field("appId"), - title: field("title"), - working_directory: field("workingDirectory"), - }; - let ok = self.apps.run_in_terminal(&cmdline, &options); - tsapi::reply(id, serde_json::Value::Bool(ok)) - } + // `Application/runInTerminal`: refused, see [`TERMINAL_REFUSED`]. + // A `false` result, which an extension written for upstream reads + // as a terminal that would not start, not a rejected promise. + _ => tsapi::reply(id, serde_json::Value::Bool(false)), }) } @@ -181,6 +195,14 @@ impl ApplicationService { /// naming an application that is not installed still gets the file opened /// by the default handler rather than nothing happening. fn open(&self, target: &str, app_id: Option<&str>) { + if let Some(file) = self.written_by_extension(target) { + if is_viewer_type(&file) + && let Some(opener) = self.apps.default_opener(target) + { + self.apps.launch(&opener, target); + } + return; + } if let Some(app) = app_id.and_then(|id| self.apps.by_id(id)) { self.apps.launch(&app, target); return; @@ -191,6 +213,42 @@ impl ApplicationService { } } +impl ApplicationService { + /// The local file `target` names, when it is under a directory the + /// extension may write. Links are resolved first, so a link there to a + /// file elsewhere is that file, and a link elsewhere to a file there is + /// this one. + fn written_by_extension(&self, target: &str) -> Option { + if self.writable.is_empty() { + return None; + } + let path = if target.starts_with("file:") { + url::Url::parse(target).ok()?.to_file_path().ok()? + } else if target.starts_with('/') { + PathBuf::from(target) + } else { + return None; + }; + let path = path.canonicalize().unwrap_or(path); + self.writable + .iter() + .any(|dir| path.starts_with(dir)) + .then_some(path) + } +} + +/// Whether a viewer shows `path`'s type, going by its name: an image, audio, +/// video, plain text or a PDF. Nothing a program would run. +#[must_use] +pub fn is_viewer_type(path: &Path) -> bool { + mime_guess::from_path(path).first().is_some_and(|mime| { + matches!( + mime.type_(), + mime_guess::mime::IMAGE | mime_guess::mime::AUDIO | mime_guess::mime::VIDEO + ) || matches!(mime.essence_str(), "text/plain" | "application/pdf") + }) +} + impl tsapi::Service for ApplicationService { fn handle(&self, call: &Call) -> Option { Self::handle(self, call) diff --git a/crates/compass-worker-host/tests/application.rs b/crates/compass-worker-host/tests/application.rs index 93752d8644..6135454e87 100644 --- a/crates/compass-worker-host/tests/application.rs +++ b/crates/compass-worker-host/tests/application.rs @@ -262,7 +262,10 @@ fn show_in_file_browser_carries_the_select_flag() { } #[test] -fn run_in_terminal_passes_every_option_and_returns_the_backends_answer() { +fn run_in_terminal_runs_nothing_and_answers_false() { + // The engine is not sandboxed: a command line it started would run on + // the host with the person's permissions. `HostCommand/run` is the + // brokered way to run a host program. let service = ApplicationService::new(Stub { terminal_ok: true, ..Stub::default() @@ -271,51 +274,94 @@ fn run_in_terminal_passes_every_option_and_returns_the_backends_answer() { &service, "Application/runInTerminal", serde_json::json!({"opts": { - "cmdline": ["htop", "-d", "5"], + "cmdline": ["sh", "-c", "true"], "hold": true, "appId": "org.gnome.Console.desktop", - "title": "Processes", - "workingDirectory": "/home/u", }}), ); - assert_eq!(answer["result"], serde_json::Value::Bool(true)); + assert_eq!(answer["result"], serde_json::Value::Bool(false)); + assert!(answer.get("error").is_none(), "{answer}"); + assert_eq!(did(&service), [], "no terminal was started"); +} + +#[test] +fn open_ignores_the_app_id_for_a_file_the_extension_may_have_written() { + let support = tempfile::tempdir().unwrap(); + let jar = support.path().join("payload.jar"); + std::fs::write(&jar, b"PK").unwrap(); + let service = ApplicationService::new(Stub { + by_id: Some(app("runner.desktop")), + default_opener: Some(app("archive.desktop")), + ..Stub::default() + }) + .with_writable([support.path().to_path_buf()]); + let target = jar.to_string_lossy().into_owned(); + let _ = reply( + &service, + "Application/open", + serde_json::json!({"target": target, "appId": "runner.desktop"}), + ); + + assert!( + !did(&service) + .iter() + .any(|did| matches!(did, Did::Launch(..))), + "{:?}", + did(&service) + ); +} + +#[test] +fn open_shows_an_image_the_extension_wrote_with_the_default_viewer_only() { + let support = tempfile::tempdir().unwrap(); + let image = support.path().join("cover.png"); + std::fs::write(&image, b"png").unwrap(); + let service = ApplicationService::new(Stub { + by_id: Some(app("runner.desktop")), + default_opener: Some(app("eog.desktop")), + ..Stub::default() + }) + .with_writable([support.path().to_path_buf()]); + let url = url::Url::from_file_path(&image).unwrap().to_string(); + let _ = reply( + &service, + "Application/open", + serde_json::json!({"target": url, "appId": "runner.desktop"}), + ); + assert_eq!( did(&service), - [Did::RunInTerminal( - vec!["htop".to_owned(), "-d".to_owned(), "5".to_owned()], - TerminalOptions { - hold: true, - app_id: Some("org.gnome.Console.desktop".to_owned()), - title: Some("Processes".to_owned()), - working_directory: Some("/home/u".to_owned()), - }, - )] + [ + Did::DefaultOpener(url.clone()), + Did::Launch("eog.desktop".to_owned(), url) + ] ); } #[test] -fn run_in_terminal_reports_a_failure_rather_than_swallowing_it() { - // `return Result::ok(ok)` -- a terminal that would not launch is a - // `false` result, not a rejected promise. +fn open_keeps_the_app_id_for_a_file_elsewhere() { + let support = tempfile::tempdir().unwrap(); let service = ApplicationService::new(Stub { - terminal_ok: false, + by_id: Some(app("eog.desktop")), ..Stub::default() - }); - let answer = reply( + }) + .with_writable([support.path().to_path_buf()]); + let _ = reply( &service, - "Application/runInTerminal", - serde_json::json!({"opts": {"cmdline": ["false"], "hold": false}}), + "Application/open", + serde_json::json!({"target": "/usr/share/backgrounds/hills.jpg", "appId": "eog.desktop"}), ); - assert_eq!(answer["result"], serde_json::Value::Bool(false)); - assert!(answer.get("error").is_none(), "{answer}"); assert_eq!( did(&service), - [Did::RunInTerminal( - vec!["false".to_owned()], - TerminalOptions::default() - )] + [ + Did::ById("eog.desktop".to_owned()), + Did::Launch( + "eog.desktop".to_owned(), + "/usr/share/backgrounds/hills.jpg".to_owned() + ) + ] ); } diff --git a/crates/compass/src/extension_commands.rs b/crates/compass/src/extension_commands.rs index 7dbec6ad20..bbe322e90e 100644 --- a/crates/compass/src/extension_commands.rs +++ b/crates/compass/src/extension_commands.rs @@ -139,6 +139,8 @@ impl Launches { /// One installed command, as `launchCommand` finds it. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Known { + /// The extension the command belongs to, `@/`. + pub extension_id: String, /// The manifest's `name`. pub extension_name: String, /// The manifest's `author`. @@ -159,6 +161,7 @@ impl Known { .extensions() .iter() .map(|command| Self { + extension_id: command.extension_id.clone(), extension_name: command.extension_name.clone(), author: command.author.clone(), owner: command.owner.clone(), @@ -191,18 +194,30 @@ impl std::fmt::Debug for EngineCommands { } impl EngineCommands { - /// Serves the command `command_id`, finding siblings among `known`, - /// keeping launches in `launches` and handing their tokens to `deliver`. + /// Serves the command `command_id` of `extension_id`, finding siblings + /// among `known`, keeping launches in `launches` and handing their tokens + /// to `deliver`. + /// + /// Only `extension_id`'s own commands are kept. `launchCommand` launches + /// a sibling: a command of another extension would run with arguments + /// and context this one chose, under that extension's storage, tokens and + /// host-program grants, without the person picking it. Raycast asks + /// before one extension launches another's command; until Compass asks + /// too, such a launch is `No such command`. #[must_use] pub fn new( command_id: String, + extension_id: &str, known: Vec, launches: Arc, deliver: Deliver, ) -> Self { Self { command_id, - known, + known: known + .into_iter() + .filter(|known| known.extension_id == extension_id) + .collect(), launches, deliver, } @@ -293,13 +308,25 @@ mod tests { let delivered = Arc::new(Mutex::new(Vec::new())); let commands = EngineCommands::new( "@ada/notes:list".into(), - vec![Known { - extension_name: "notes".into(), - author: "ada".into(), - owner: None, - name: "create".into(), - id: "@ada/notes:create".into(), - }], + "@ada/notes", + vec![ + Known { + extension_id: "@ada/notes".into(), + extension_name: "notes".into(), + author: "ada".into(), + owner: None, + name: "create".into(), + id: "@ada/notes:create".into(), + }, + Known { + extension_id: "@bob/mail".into(), + extension_name: "mail".into(), + author: "bob".into(), + owner: None, + name: "send".into(), + id: "@bob/mail:send".into(), + }, + ], Arc::clone(&launches), Arc::new({ let delivered = Arc::clone(&delivered); @@ -353,6 +380,23 @@ mod tests { assert_eq!(launches.take_context("@ada/notes:create"), None); } + #[test] + fn another_extension_s_command_is_no_such_command() { + let (service, launches, delivered) = service(); + let reply = service + .handle(&call( + "Command/launchCommand", + serde_json::json!({"options": { + "extensionName": "mail", "ownerOrAuthorName": "bob", "name": "send", + "arguments": {"to": "someone@example.invalid"}, + }}), + )) + .unwrap(); + assert!(reply.contains("No such command"), "{reply}"); + assert!(delivered.lock().unwrap().is_empty(), "nothing was launched"); + assert_eq!(launches.take_context("@bob/mail:send"), None); + } + #[test] fn a_command_that_is_not_installed_is_no_such_command() { let (service, _, delivered) = service(); diff --git a/crates/compass/src/extension_runner.rs b/crates/compass/src/extension_runner.rs index ba2d37d800..bb178750c0 100644 --- a/crates/compass/src/extension_runner.rs +++ b/crates/compass/src/extension_runner.rs @@ -254,6 +254,8 @@ pub fn start( process } }; + process.env_clear(); + process.envs(sandbox::worker_env(std::env::vars_os())); process.env("TMPDIR", tmp_dir(data_dir, command)); // `environment.vicinaeVersion` in the SDK. The runtime reads these, and // the `VICINAE_*` names the C++ set only when they are absent. @@ -333,6 +335,10 @@ pub fn start( let extension_id = command.extension_id.clone(); let extension_title = command.extension_title.clone(); let assets = command.extension_dir.join("assets"); + let writable = vec![ + support_dir(data_dir, command), + assets_dir(data_dir, command), + ]; let handle = tokio::runtime::Handle::try_current().ok(); let started = view .as_ref() @@ -353,6 +359,7 @@ pub fn start( files, commands, assets, + writable, launcher, }, storage, diff --git a/crates/compass/src/extension_runner/sandbox.rs b/crates/compass/src/extension_runner/sandbox.rs index 32b2fc3d45..a325e9b5aa 100644 --- a/crates/compass/src/extension_runner/sandbox.rs +++ b/crates/compass/src/extension_runner/sandbox.rs @@ -140,6 +140,57 @@ pub fn assets_dir(data_dir: &Path, command: &ExtensionCommand) -> PathBuf { .join("assets") } +/// The variables of the engine's environment a worker is given; everything +/// else is withheld. +/// +/// What is left out matters more than what is kept: `DBUS_SESSION_BUS_ADDRESS`, +/// `XDG_RUNTIME_DIR`, `WAYLAND_DISPLAY`, `DISPLAY`, `SSH_AUTH_SOCK` and +/// `COMPASS_SOCKET` each name a socket outside the filesystem boundary, and +/// `NODE_OPTIONS` would change what Node loads before the bundle does. The +/// syscall filter already refuses the socket; not handing over the address is +/// the second layer, and the one that still holds where no filter is applied. +const WORKER_ENV: &[&str] = &[ + "PATH", + "HOME", + "USER", + "LOGNAME", + "LANG", + "LANGUAGE", + "TZ", + "XDG_CONFIG_HOME", + "XDG_DATA_HOME", + "XDG_CACHE_HOME", + "XDG_STATE_HOME", + "NODE_EXTRA_CA_CERTS", + "SSL_CERT_FILE", + "SSL_CERT_DIR", + "http_proxy", + "https_proxy", + "no_proxy", + "all_proxy", + "HTTP_PROXY", + "HTTPS_PROXY", + "NO_PROXY", + "ALL_PROXY", +]; + +/// The part of `vars` a worker is given: [`WORKER_ENV`] and the locale's +/// `LC_*`. +#[must_use] +pub fn worker_env(vars: I) -> Vec<(std::ffi::OsString, std::ffi::OsString)> +where + I: IntoIterator, +{ + vars.into_iter() + .filter(|(key, _)| { + key.to_str().is_some_and(|key| { + WORKER_ENV.contains(&key) + || key.strip_prefix("LC_").is_some_and(|rest| !rest.is_empty()) + }) + }) + .collect() +} + #[cfg(test)] mod tests { use super::*; @@ -242,4 +293,29 @@ mod tests { "only the linked-out file, not what /etc already covers" ); } + + #[test] + fn the_worker_is_not_handed_the_session_bus_or_any_other_socket() { + let engine = [ + ("PATH", "/usr/bin"), + ("HOME", "/home/me"), + ("LANG", "en_GB.UTF-8"), + ("LC_TIME", "C"), + ("LC_", "x"), + ("https_proxy", "http://proxy:3128"), + ("DBUS_SESSION_BUS_ADDRESS", "unix:path=/run/user/1000/bus"), + ("XDG_RUNTIME_DIR", "/run/user/1000"), + ("WAYLAND_DISPLAY", "wayland-0"), + ("DISPLAY", ":0"), + ("SSH_AUTH_SOCK", "/run/user/1000/ssh-agent"), + ("COMPASS_SOCKET", "/run/user/1000/compass/ipc.sock"), + ("NODE_OPTIONS", "--require /tmp/x.js"), + ] + .map(|(key, value)| (key.into(), value.into())); + let given: Vec = worker_env(engine) + .into_iter() + .map(|(key, _)| key.to_string_lossy().into_owned()) + .collect(); + assert_eq!(given, ["PATH", "HOME", "LANG", "LC_TIME", "https_proxy"]); + } } diff --git a/crates/compass/src/extension_runner/session.rs b/crates/compass/src/extension_runner/session.rs index ef866102ea..9da7ef6f22 100644 --- a/crates/compass/src/extension_runner/session.rs +++ b/crates/compass/src/extension_runner/session.rs @@ -45,6 +45,8 @@ pub(super) struct Served { pub(super) files: Option>, pub(super) commands: Option, pub(super) assets: PathBuf, + /// The directories the extension may write: a file there may be its own. + pub(super) writable: Vec, pub(super) launcher: Option, } @@ -68,6 +70,7 @@ pub(super) fn serve( files, commands, assets, + writable, launcher, } = served; let title = title.as_str(); @@ -116,7 +119,7 @@ pub(super) fn serve( if let Some(service) = &storage_service { router = router.with(service); } - let applications = apps.map(ApplicationService::new); + let applications = apps.map(|apps| ApplicationService::new(apps).with_writable(writable)); if let Some(service) = &applications { router = router.with(service); } diff --git a/crates/compass/src/serve/extensions.rs b/crates/compass/src/serve/extensions.rs index 3e15d50567..bc3abb664a 100644 --- a/crates/compass/src/serve/extensions.rs +++ b/crates/compass/src/serve/extensions.rs @@ -270,6 +270,7 @@ async fn run_extension_command( context: launches.take_context(&id), commands: Some(crate::extension_commands::EngineCommands::new( id.clone(), + &command.extension_id, known, launches, deliver, diff --git a/docs/rust-engine/PARITY.md b/docs/rust-engine/PARITY.md index d18d881f07..c9d76eb96c 100644 --- a/docs/rust-engine/PARITY.md +++ b/docs/rust-engine/PARITY.md @@ -2671,6 +2671,24 @@ the channel that matters. Behaviour that intentionally differs from the C++ engine. Each is pinned by a test that fails if the behaviour changes, so a future fix is loud rather than silent. +### Extension calls the engine serves outside the sandbox + +Upstream Vicinae has no extension sandbox, so these calls give an extension nothing it did not +already have there. In Compass the worker is confined and the engine is not, so each one is held to +what the sandbox allows: + +- `Application/runInTerminal` starts nothing and answers `false` + (`compass_worker_host::application_service::TERMINAL_REFUSED`). A host program goes through + `HostCommand/run`, which takes a bare program name the overrides list names and asks first. +- `Application/open` of a file under the extension's support or assets directory ignores `appId` + and opens only a type a viewer shows (image, audio, video, plain text, PDF) with the default + opener (`application_service::is_viewer_type`). Links and files elsewhere open as upstream. +- `Command/launchCommand` finds only the running extension's own commands + (`EngineCommands::new`); another extension's command is `No such command`. Raycast asks before a + cross-extension launch; Compass may add that dialog later. +- `Wallpaper/set` on KDE passes the image to Plasma as a JSON string literal of a percent-encoded + URI (`compass_core::wallpaper::kde_script`), never as script text. + ### `compass-core::builtin_icon` — GNOME symbolic icons over Vicinae's artwork Builtin icons with a freedesktop counterpart (`cog` → `emblem-system-symbolic`, `copy-clipboard` → @@ -3633,6 +3651,7 @@ The negative tests are §8.2's list; each has a positive control beside it. |---|---|---|---| | 1 | An extension may run a program it wrote itself (Raycast's `speedtest` downloads its CLI into `supportPath` and runs it). | Execute is granted on the system trees (`/usr`, `/bin`, `/lib*`, `/app`), Node and the extension's installed directory, never on the directories it may write: running what it wrote fails with `EACCES`. The Landlock crate's "read" set includes `Execute`, which had made every readable path executable; read no longer implies execute. Suite 1's `speedtest` fails here, by design. | `a_program_the_worker_wrote_itself_cannot_be_run`, `a_command_sees_its_own_paths_and_preferences_and_may_exec_but_not_unshare` | | 2 | A raw socket is whatever the kernel allows the process. | `socket()` with `SOCK_RAW` or `SOCK_PACKET`, or in `AF_PACKET`, answers `EPERM` from the seccomp filter, root or not; an ordinary socket is unaffected. | `a_raw_socket_is_refused_while_an_ordinary_one_is_not` | +| 2a | An extension may connect to any Unix socket the user can (the session bus, the engine's IPC socket, `ssh-agent`, Docker), and inherits the launcher's whole environment. | `socket(AF_UNIX, …)` answers `EPERM` from the seccomp filter; `socketpair`, which Node uses for a child's stdio, still works. The worker's environment is cleared and given back only `PATH`, `HOME`, the user and locale, the `XDG_*_HOME` directories, the CA and proxy variables, `TMPDIR` and `COMPASS_VERSION`/`COMPASS_COMMIT`. An extension that talks to a local daemon over its socket (Docker, `ssh-agent`, a desktop's own bus) fails, by design: through the session bus it could ask systemd or a portal to start a process outside the sandbox. | `a_unix_socket_outside_every_grant_cannot_be_reached`, `the_worker_is_not_handed_the_session_bus_or_any_other_socket` | | 3 | No memory limit; the worker asks V8 for 1000 MB of heap. | The heap is capped at 160 MiB (`--max-old-space-size`), and `RLIMIT_DATA` at 512 MiB, which bounds `Buffer`s and native allocations where no cgroup is reachable (a Flatpak): a 512 MiB `Buffer` is a `RangeError` the extension can catch. Measured over Suite 1 the worker's `VmData` peaks at 340 MiB. The heap cap costs one real extension, **kept deliberately**: `dashboard-icons` groups a 1.2 MB catalogue into 4,473 grid items, each with its own action panel. Measured (2026-09-24, caps lifted one at a time): it runs out of heap at 160 MiB and renders at 192 MiB, and at 192 MiB the worker peaks at about 450 MiB resident and 490 MiB `VmData`. That is past the 256 MiB process budget (§6) by more than the heap alone, so raising the heap flag would only move its failure to the cgroup or `RLIMIT_DATA`; admitting it means a different budget, not a different flag. It also needed row 1 of "The extension host API" (a view past a mebibyte). | `an_allocation_past_the_data_limit_fails_and_the_process_carries_on`, `an_extension_that_allocates_past_the_heap_cap_is_stopped` | | 4 | Writes anywhere the user may. | Writes only its support and asset directories: `reminders` (Vicinae store) fails making `~/.local/share/vicinae-reminders`. | `an_installed_extension_command_is_found_and_a_no_view_one_runs` | | 5 | TLS trusts whatever `NODE_EXTRA_CA_CERTS` names. | The same, because the file it names (and `SSL_CERT_FILE`, `SSL_CERT_DIR`) is granted read; otherwise Node could not load a corporate CA from `$HOME`. | — | diff --git a/packaging/README.md b/packaging/README.md index 99e39f5bee..d2db313811 100644 --- a/packaging/README.md +++ b/packaging/README.md @@ -53,6 +53,28 @@ one small program, which speaks only JSON-RPC to its parent over stdin and stdou itself runs unprivileged. Adding the user to the `input` group instead would hand every program they run the keyboard, and still leave `/dev/uinput` closed on most distributions. +A file capability is granted to whoever runs the file, so the helper checks who that is. While it +holds the capability it reads keys and types only when its real user has the active logind +session on a seat; it asks logind over the system bus at its fixed address, never through the +environment, and again at most once a second. Another account (an SSH login, or a user switched +away from) gets no keys and no injection. Where no logind answers on the system bus (a seatd-only +system) it says so and serves whoever can run it. + +On a machine shared with accounts that should not run the helper at all, restrict the file to a +group as well. Each package leaves this to the administrator, because it needs the desktop users +added to the group: + +```sh +groupadd -r compass-input +usermod -aG compass-input # each desktop user; takes effect at their next login +chgrp compass-input # before setcap: chown and chgrp clear file capabilities +chmod 0750 +setcap cap_dac_override+ep +``` + +On NixOS the same is `group = "compass-input"; permissions = "u+rx,g+x";` on the wrapper, with +`users.groups.compass-input = {};` and the users' `extraGroups`. + | Output | How the helper gets its capability | |---|---| | Arch | `arch/compass.install`: `setcap cap_dac_override+ep /usr/lib/compass/compass-input-server` after install and upgrade | diff --git a/scripts/suite1/expected.json b/scripts/suite1/expected.json index b45155be0a..7a4bc337d7 100644 --- a/scripts/suite1/expected.json +++ b/scripts/suite1/expected.json @@ -113,7 +113,8 @@ "verdict": "rendered" }, "store.vicinae.bluetooth:devices": { - "verdict": "rendered" + "verdict": "crashed", + "why": "Devices crashed: connect EPERM /var/run/dbus/system_bus_socket" }, "store.vicinae.brotab:tabs-list": { "verdict": "rendered" @@ -148,7 +149,8 @@ "why": "Search Icons crashed: Error [ERR_WORKER_OUT_OF_MEMORY]: Worker terminated due to reaching memory limit: JS heap out of memory" }, "store.vicinae.dbus:explore-bus": { - "verdict": "rendered" + "verdict": "crashed", + "why": "Explore The Bus crashed: could not get DISPLAY environment variable to get dbus address" }, "store.vicinae.dms-integration:dsearch": { "verdict": "error-toast", @@ -305,7 +307,8 @@ "verdict": "rendered" }, "store.vicinae.podman:containers": { - "verdict": "rendered" + "verdict": "error-toast", + "why": "Failed to list Podman connections: Command failed: podman system connection list --format json" }, "store.vicinae.port-killer:port-killer": { "verdict": "rendered" @@ -370,7 +373,8 @@ "verdict": "rendered" }, "store.vicinae.systemd:services": { - "verdict": "rendered", + "verdict": "crashed", + "why": "Services crashed: connect EPERM /var/run/dbus/system_bus_socket", "flatpak": { "verdict": "error-toast", "why": "Failed to list services: org.freedesktop.DBus.Error.ServiceUnknown: the Flatpak does not talk to systemd on the system bus"