Add Store support and unsigned app releases
This commit is contained in:
350
crates/sf-ipc/src/sandbox.rs
Normal file
350
crates/sf-ipc/src/sandbox.rs
Normal file
@@ -0,0 +1,350 @@
|
||||
//! App sandbox: every app runs in its own bubblewrap (`bwrap`) container,
|
||||
//! the same building block Flatpak uses.
|
||||
//!
|
||||
//! Inside the sandbox an app sees:
|
||||
//! - the system read-only (`/usr`, `/etc`), no other user's or app's files;
|
||||
//! - its own files read-only at `/app`;
|
||||
//! - its own data folder as `$HOME` (on the host:
|
||||
//! `~/.local/share/smartfox/apps/<id>`), the only writable place that lasts;
|
||||
//! - the Wayland socket (it can show a window), nothing else from
|
||||
//! `$XDG_RUNTIME_DIR` (no launcher, sf-core or compositor sockets);
|
||||
//! - fresh /tmp, /run, /var and its own PID, IPC and UTS namespaces;
|
||||
//! - and only what its permissions allow (`Permission`): network, GPU,
|
||||
//! sound, game controllers, D-Bus, devices.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
use crate::manifest::Permission;
|
||||
|
||||
/// Where the app's own files are inside the sandbox.
|
||||
pub const APP_DIR: &str = "/app";
|
||||
|
||||
/// Environment variables passed through from the session when set.
|
||||
const PASS_ENV: [&str; 7] = ["LANG", "LANGUAGE", "LC_ALL", "TZ", "XCURSOR_THEME", "XCURSOR_SIZE", "RUST_LOG"];
|
||||
|
||||
/// What a host path is, for building the mount list (a function so tests
|
||||
/// can fake the file system).
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Entry {
|
||||
Missing,
|
||||
Dir,
|
||||
Other,
|
||||
Symlink(PathBuf),
|
||||
/// There, but we may not read it (bwrap's `--*-bind-try` fails on that).
|
||||
Denied,
|
||||
}
|
||||
|
||||
pub fn probe(path: &Path) -> Entry {
|
||||
if let Err(e) = std::fs::metadata(path) {
|
||||
if e.kind() == std::io::ErrorKind::PermissionDenied {
|
||||
return Entry::Denied;
|
||||
}
|
||||
}
|
||||
match std::fs::symlink_metadata(path) {
|
||||
Err(_) => Entry::Missing,
|
||||
Ok(m) if m.file_type().is_symlink() => std::fs::read_link(path).map(Entry::Symlink).unwrap_or(Entry::Missing),
|
||||
Ok(m) if m.is_dir() => Entry::Dir,
|
||||
Ok(_) => Entry::Other,
|
||||
}
|
||||
}
|
||||
|
||||
/// The session the app is started from.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Host {
|
||||
pub uid: u32,
|
||||
pub user: String,
|
||||
pub home: PathBuf,
|
||||
pub runtime_dir: PathBuf,
|
||||
pub wayland_display: Option<String>,
|
||||
pub hostname: Option<String>,
|
||||
/// Allowed variables from the session (`PASS_ENV`).
|
||||
pub env: Vec<(String, String)>,
|
||||
/// /dev/hidraw* (controllers that talk raw HID, like DualSense).
|
||||
pub hidraw: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
impl Host {
|
||||
pub fn current() -> Host {
|
||||
let var = |k: &str| std::env::var(k).ok().filter(|v| !v.is_empty());
|
||||
let home = var("HOME").map(PathBuf::from).unwrap_or_else(|| PathBuf::from("/tmp"));
|
||||
let hidraw = std::fs::read_dir("/dev")
|
||||
.map(|d| d.flatten().map(|e| e.path()).filter(|p| p.file_name().is_some_and(|n| n.to_string_lossy().starts_with("hidraw"))).collect())
|
||||
.unwrap_or_default();
|
||||
Host {
|
||||
uid: current_uid(),
|
||||
user: var("USER").unwrap_or_else(|| "tv".into()),
|
||||
home,
|
||||
runtime_dir: crate::paths::runtime_dir(),
|
||||
wayland_display: var("WAYLAND_DISPLAY"),
|
||||
hostname: std::fs::read_to_string("/etc/hostname").ok().map(|h| h.trim().to_string()).filter(|h| !h.is_empty()),
|
||||
env: PASS_ENV.iter().filter_map(|k| var(k).map(|v| (k.to_string(), v))).collect(),
|
||||
hidraw,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn current_uid() -> u32 {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
// The owner of our own /proc entry is our uid (no libc needed).
|
||||
std::fs::metadata("/proc/self").map(|m| m.uid()).unwrap_or(1000)
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn current_uid() -> u32 {
|
||||
1000
|
||||
}
|
||||
|
||||
/// One sandboxed process.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Spec<'a> {
|
||||
pub app_id: &'a str,
|
||||
/// The app's files (host path), read-only at `/app`.
|
||||
pub app_dir: &'a Path,
|
||||
/// The app's private data (host path), mounted as `$HOME`.
|
||||
pub data_dir: &'a Path,
|
||||
/// More writable folders, at the same path inside (a browser profile).
|
||||
pub extra_rw: Vec<PathBuf>,
|
||||
pub permissions: &'a [Permission],
|
||||
/// Extra environment for the app.
|
||||
pub env: Vec<(String, String)>,
|
||||
pub program: String,
|
||||
pub args: Vec<String>,
|
||||
}
|
||||
|
||||
pub fn bwrap_path() -> Option<PathBuf> {
|
||||
if let Ok(p) = std::env::var("SMARTFOX_BWRAP") {
|
||||
return Some(p.into());
|
||||
}
|
||||
["/usr/bin/bwrap", "/usr/local/bin/bwrap"].iter().map(PathBuf::from).find(|p| p.is_file())
|
||||
}
|
||||
|
||||
/// The bwrap command for `spec`.
|
||||
pub fn command(bwrap: &Path, spec: &Spec, host: &Host) -> Command {
|
||||
let mut cmd = Command::new(bwrap);
|
||||
cmd.args(args(spec, host, &probe));
|
||||
cmd
|
||||
}
|
||||
|
||||
/// The bwrap arguments. Mount order matters: later mounts go on top.
|
||||
pub fn args(spec: &Spec, host: &Host, fs: &dyn Fn(&Path) -> Entry) -> Vec<String> {
|
||||
let has = |p: Permission| spec.permissions.contains(&p);
|
||||
let mut a: Vec<String> = Vec::new();
|
||||
let mut push = |items: &[&str]| a.extend(items.iter().map(|s| s.to_string()));
|
||||
|
||||
push(&["--die-with-parent", "--unshare-all"]);
|
||||
if has(Permission::Network) {
|
||||
push(&["--share-net"]);
|
||||
}
|
||||
if host.uid == 0 {
|
||||
// Unprivileged bwrap drops every capability by itself; as root
|
||||
// (development) do it explicitly.
|
||||
push(&["--cap-drop", "ALL"]);
|
||||
}
|
||||
if let Some(h) = &host.hostname {
|
||||
push(&["--hostname", h]);
|
||||
}
|
||||
|
||||
// The system, read-only. /bin, /lib... are symlinks into /usr on Debian.
|
||||
push(&["--ro-bind", "/usr", "/usr"]);
|
||||
for top in ["/bin", "/sbin", "/lib", "/lib32", "/lib64", "/libx32"] {
|
||||
match fs(Path::new(top)) {
|
||||
Entry::Symlink(t) => push(&["--symlink", &t.to_string_lossy(), top]),
|
||||
Entry::Dir => push(&["--ro-bind", top, top]),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
push(&["--ro-bind", "/etc", "/etc", "--proc", "/proc"]);
|
||||
|
||||
// Devices.
|
||||
if has(Permission::Devices) {
|
||||
push(&["--dev-bind", "/dev", "/dev"]);
|
||||
} else {
|
||||
push(&["--dev", "/dev", "--tmpfs", "/dev/shm"]);
|
||||
if has(Permission::Gpu) {
|
||||
push(&["--dev-bind-try", "/dev/dri", "/dev/dri"]);
|
||||
}
|
||||
if has(Permission::Gamepad) {
|
||||
push(&["--dev-bind-try", "/dev/input", "/dev/input", "--dev-bind-try", "/dev/uinput", "/dev/uinput"]);
|
||||
for h in &host.hidraw {
|
||||
let h = h.to_string_lossy();
|
||||
push(&["--dev-bind-try", &h, &h]);
|
||||
}
|
||||
}
|
||||
}
|
||||
if has(Permission::Gpu) || has(Permission::Gamepad) || has(Permission::Devices) {
|
||||
push(&["--ro-bind", "/sys", "/sys"]);
|
||||
}
|
||||
|
||||
// Fresh writable scratch space.
|
||||
push(&["--tmpfs", "/tmp", "--tmpfs", "/var", "--tmpfs", "/run", "--dir", "/var/tmp", "--symlink", "../run", "/var/run"]);
|
||||
push(&["--ro-bind-try", "/var/cache/fontconfig", "/var/cache/fontconfig"]);
|
||||
if has(Permission::Gamepad) || has(Permission::Devices) {
|
||||
// Hotplug of controllers (SDL, Steam) goes through udev.
|
||||
push(&["--ro-bind-try", "/run/udev", "/run/udev"]);
|
||||
}
|
||||
if has(Permission::Network) {
|
||||
// /etc/resolv.conf points at systemd-resolved's stub file on the TV;
|
||||
// elsewhere (WSL: /mnt/wsl/resolv.conf) bind whatever it points at.
|
||||
push(&["--ro-bind-try", "/run/systemd/resolve", "/run/systemd/resolve"]);
|
||||
if let Entry::Symlink(t) = fs(Path::new("/etc/resolv.conf")) {
|
||||
let target = Path::new("/etc").join(t);
|
||||
let target = target.to_string_lossy();
|
||||
if !target.starts_with("/run/systemd/resolve/") && !target.starts_with("/etc/") && !target.starts_with("/usr/") {
|
||||
push(&["--ro-bind-try", &target, &target]);
|
||||
}
|
||||
}
|
||||
}
|
||||
if has(Permission::DbusSystem) {
|
||||
push(&["--ro-bind-try", "/run/dbus/system_bus_socket", "/run/dbus/system_bus_socket"]);
|
||||
}
|
||||
|
||||
// The session's runtime dir: only the sockets the app may use.
|
||||
let rt = host.runtime_dir.to_string_lossy().to_string();
|
||||
push(&["--perms", "0700", "--dir", &rt]);
|
||||
let mut socket = |name: &str| {
|
||||
let p = format!("{rt}/{name}");
|
||||
if fs(Path::new(&p)) != Entry::Denied {
|
||||
push(&["--ro-bind-try", &p, &p]);
|
||||
}
|
||||
};
|
||||
if let Some(wl) = &host.wayland_display {
|
||||
socket(wl);
|
||||
}
|
||||
if has(Permission::Audio) {
|
||||
socket("pipewire-0");
|
||||
socket("pulse/native");
|
||||
}
|
||||
if has(Permission::DbusSession) {
|
||||
socket("bus");
|
||||
}
|
||||
|
||||
// $HOME is the app's own data folder (at the real home path, so programs
|
||||
// that remember absolute paths keep working).
|
||||
let home = host.home.to_string_lossy().to_string();
|
||||
if let Entry::Symlink(t) = fs(Path::new("/home")) {
|
||||
push(&["--symlink", &t.to_string_lossy(), "/home"]);
|
||||
}
|
||||
push(&["--bind", &spec.data_dir.to_string_lossy(), &home]);
|
||||
for p in &spec.extra_rw {
|
||||
let p = p.to_string_lossy();
|
||||
push(&["--bind", &p, &p]);
|
||||
}
|
||||
push(&["--ro-bind", &spec.app_dir.to_string_lossy(), APP_DIR, "--chdir", &home]);
|
||||
|
||||
// A clean environment.
|
||||
push(&["--clearenv"]);
|
||||
let mut env: Vec<(String, String)> = vec![
|
||||
("PATH".into(), "/usr/local/bin:/usr/bin:/bin:/usr/games".into()),
|
||||
("HOME".into(), home.clone()),
|
||||
("USER".into(), host.user.clone()),
|
||||
("LOGNAME".into(), host.user.clone()),
|
||||
("SHELL".into(), "/bin/sh".into()),
|
||||
("XDG_RUNTIME_DIR".into(), rt.clone()),
|
||||
("XDG_SESSION_TYPE".into(), "wayland".into()),
|
||||
("SMARTFOX_APP".into(), spec.app_id.into()),
|
||||
("SMARTFOX_APP_DIR".into(), APP_DIR.into()),
|
||||
];
|
||||
if let Some(wl) = &host.wayland_display {
|
||||
env.push(("WAYLAND_DISPLAY".into(), wl.clone()));
|
||||
}
|
||||
if has(Permission::DbusSession) {
|
||||
env.push(("DBUS_SESSION_BUS_ADDRESS".into(), format!("unix:path={rt}/bus")));
|
||||
}
|
||||
env.extend(host.env.iter().cloned());
|
||||
env.extend(spec.env.iter().cloned());
|
||||
for (k, v) in env {
|
||||
push(&["--setenv", &k, &v]);
|
||||
}
|
||||
|
||||
push(&["--", &spec.program]);
|
||||
a.extend(spec.args.iter().cloned());
|
||||
a
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn host() -> Host {
|
||||
Host {
|
||||
uid: 1000,
|
||||
user: "tv".into(),
|
||||
home: "/var/home/tv".into(),
|
||||
runtime_dir: "/run/user/1000".into(),
|
||||
wayland_display: Some("wayland-1".into()),
|
||||
hostname: Some("smartfox".into()),
|
||||
env: vec![("LANG".into(), "C.UTF-8".into())],
|
||||
hidraw: vec!["/dev/hidraw0".into()],
|
||||
}
|
||||
}
|
||||
|
||||
fn fake_fs(p: &Path) -> Entry {
|
||||
match p.to_str().unwrap() {
|
||||
"/bin" => Entry::Symlink("usr/bin".into()),
|
||||
"/lib" => Entry::Symlink("usr/lib".into()),
|
||||
"/lib64" => Entry::Symlink("usr/lib64".into()),
|
||||
"/home" => Entry::Symlink("var/home".into()),
|
||||
_ => Entry::Missing,
|
||||
}
|
||||
}
|
||||
|
||||
fn has_seq(args: &[String], seq: &[&str]) -> bool {
|
||||
args.windows(seq.len()).any(|w| w.iter().zip(seq).all(|(a, b)| a == b))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn minimal_sandbox() {
|
||||
let spec = Spec {
|
||||
app_id: "io.github.fox.hello",
|
||||
app_dir: Path::new("/var/lib/sf-pkg/store-io.github.fox.hello/1.0.0"),
|
||||
data_dir: Path::new("/var/home/tv/.local/share/smartfox/apps/io.github.fox.hello"),
|
||||
extra_rw: vec![],
|
||||
permissions: &[],
|
||||
env: vec![("FOO".into(), "bar".into())],
|
||||
program: "/app/bin/hello".into(),
|
||||
args: vec!["--x".into()],
|
||||
};
|
||||
let a = args(&spec, &host(), &fake_fs);
|
||||
assert!(has_seq(&a, &["--unshare-all"]));
|
||||
assert!(!a.contains(&"--share-net".to_string()));
|
||||
assert!(!a.iter().any(|s| s == "/dev/dri" || s == "/sys"));
|
||||
assert!(!a.iter().any(|s| s.contains("pipewire") || s.ends_with("/bus")));
|
||||
assert!(has_seq(&a, &["--symlink", "usr/bin", "/bin"]));
|
||||
assert!(has_seq(&a, &["--ro-bind-try", "/run/user/1000/wayland-1", "/run/user/1000/wayland-1"]));
|
||||
assert!(has_seq(&a, &["--bind", "/var/home/tv/.local/share/smartfox/apps/io.github.fox.hello", "/var/home/tv"]));
|
||||
assert!(has_seq(&a, &["--ro-bind", "/var/lib/sf-pkg/store-io.github.fox.hello/1.0.0", "/app"]));
|
||||
assert!(has_seq(&a, &["--setenv", "SMARTFOX_APP", "io.github.fox.hello"]));
|
||||
assert!(has_seq(&a, &["--setenv", "FOO", "bar"]));
|
||||
assert!(has_seq(&a, &["--", "/app/bin/hello", "--x"]));
|
||||
assert_eq!(a.last().unwrap(), "--x");
|
||||
// /run must be fresh before the runtime dir and sockets go in.
|
||||
let run = a.iter().position(|s| s == "/run").unwrap();
|
||||
let sock = a.iter().position(|s| s == "/run/user/1000/wayland-1").unwrap();
|
||||
assert!(run < sock);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn permissions_open_doors() {
|
||||
let perms = [Permission::Network, Permission::Gpu, Permission::Audio, Permission::Gamepad, Permission::DbusSession];
|
||||
let spec = Spec {
|
||||
app_id: "steam",
|
||||
app_dir: Path::new("/usr/share/smartfox/apps/steam"),
|
||||
data_dir: Path::new("/d"),
|
||||
extra_rw: vec!["/var/home/tv/.config/smartfox/profiles/steam".into()],
|
||||
permissions: &perms,
|
||||
env: vec![],
|
||||
program: "/app/x".into(),
|
||||
args: vec![],
|
||||
};
|
||||
let a = args(&spec, &host(), &fake_fs);
|
||||
assert!(a.contains(&"--share-net".to_string()));
|
||||
assert!(has_seq(&a, &["--dev-bind-try", "/dev/dri", "/dev/dri"]));
|
||||
assert!(has_seq(&a, &["--dev-bind-try", "/dev/hidraw0", "/dev/hidraw0"]));
|
||||
assert!(has_seq(&a, &["--ro-bind", "/sys", "/sys"]));
|
||||
assert!(has_seq(&a, &["--ro-bind-try", "/run/user/1000/pipewire-0", "/run/user/1000/pipewire-0"]));
|
||||
assert!(has_seq(&a, &["--setenv", "DBUS_SESSION_BUS_ADDRESS", "unix:path=/run/user/1000/bus"]));
|
||||
assert!(has_seq(&a, &["--bind", "/var/home/tv/.config/smartfox/profiles/steam", "/var/home/tv/.config/smartfox/profiles/steam"]));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user