AnyBot/src/landlock.rs

433 lines
20 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//! Linux 的指令沙盒 (R6). Linux has no sandbox-exec: a command on the person's computer starts
//! through AnyBot itself (`/proc/self/exe __anybot_sandbox … -- /bin/sh -c 指令`), which closes
//! itself in with Landlock and then becomes the shell — the way sandbox-exec wraps it on macOS, so
//! a 互動終端機 (pty.rs copies only the program and its arguments) is closed in too.
//!
//! Landlock only allows; it has no "but not this folder". So what macOS denies is left out of what
//! is allowed: every entry on the way to a protected folder is allowed one by one, the protected
//! one is skipped. Reading: everything but the protected folders (listing names works everywhere,
//! contents don't). Writing: the same, also without the shell startup files; the work folder as a
//! whole. What follows from allowing only: in a folder on the way to a protected one (the home
//! folder, ~/.config, ~/.local/share…) nothing new can be made at its top level (in its other
//! folders it can), and the work folder's .git/hooks stay writable (macOS denies them).
//! A kernel without Landlock (before 5.13, or not turned on) is said as it is (`/doctor`, the
//! log): commands run as they did, without a sandbox, never pretending to have one.
use std::collections::BTreeMap;
use std::ffi::{OsStr, OsString};
use std::path::{Path, PathBuf};
/// The first argument that makes AnyBot the sandbox instead of the app.
pub const ARG: &str = "__anybot_sandbox";
/// Landlock's file system rights (linux/landlock.h).
pub mod access {
pub const EXECUTE: u64 = 1 << 0;
pub const WRITE_FILE: u64 = 1 << 1;
pub const READ_FILE: u64 = 1 << 2;
pub const READ_DIR: u64 = 1 << 3;
pub const REMOVE_DIR: u64 = 1 << 4;
pub const REMOVE_FILE: u64 = 1 << 5;
pub const MAKE_CHAR: u64 = 1 << 6;
pub const MAKE_DIR: u64 = 1 << 7;
pub const MAKE_REG: u64 = 1 << 8;
pub const MAKE_SOCK: u64 = 1 << 9;
pub const MAKE_FIFO: u64 = 1 << 10;
pub const MAKE_BLOCK: u64 = 1 << 11;
pub const MAKE_SYM: u64 = 1 << 12;
/// Since version 2: moving or linking into another folder (without it, never allowed).
pub const REFER: u64 = 1 << 13;
/// Since version 3.
pub const TRUNCATE: u64 = 1 << 14;
/// Since version 5.
pub const IOCTL_DEV: u64 = 1 << 15;
}
use access::*;
const READ: u64 = EXECUTE | READ_FILE;
const WRITE: u64 = WRITE_FILE | REMOVE_DIR | REMOVE_FILE | MAKE_CHAR | MAKE_DIR | MAKE_REG | MAKE_SOCK | MAKE_FIFO | MAKE_BLOCK | MAKE_SYM | REFER | TRUNCATE | IOCTL_DEV;
/// The rights a rule on a file (not a folder) may carry.
const FILE_ONLY: u64 = EXECUTE | WRITE_FILE | READ_FILE | TRUNCATE | IOCTL_DEV;
/// What this kernel's Landlock (its version) can govern.
pub fn handled(abi: u32) -> u64 {
let mut h = (1 << 13) - 1;
if abi >= 2 {
h |= REFER;
}
if abi >= 3 {
h |= TRUNCATE;
}
if abi >= 5 {
h |= IOCTL_DEV;
}
h
}
/// What a command is kept from.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Spec {
/// Neither read nor written: AnyBot's data, ~/.ssh, ~/.gnupg…
pub hidden: Vec<PathBuf>,
/// Inside those, what may still be read (never written): the chat's attachments, skills, ~/.ssh.
pub readable: Vec<PathBuf>,
/// Not written: shell startup files…
pub no_write: Vec<PathBuf>,
/// The work folder: read and written as a whole.
pub work: PathBuf,
}
impl Spec {
/// As arguments for the sandbox (`-h`, `-r`, `-w`, `-C`, each with a path).
pub fn to_args(&self) -> Vec<OsString> {
let mut v = vec![];
for (flag, paths) in [("-h", &self.hidden), ("-r", &self.readable), ("-w", &self.no_write)] {
for p in paths {
v.push(OsString::from(flag));
v.push(p.clone().into_os_string());
}
}
v.push("-C".into());
v.push(self.work.clone().into_os_string());
v
}
/// Read back: the spec, then the program and its arguments (after `--`).
pub fn from_args(args: &[OsString]) -> Result<(Spec, Vec<OsString>), String> {
let mut s = Spec::default();
let mut it = args.iter();
while let Some(a) = it.next() {
if a == "--" {
let rest: Vec<OsString> = it.cloned().collect();
if rest.is_empty() {
return Err("沒有要執行的程式".into());
}
return Ok((s, rest));
}
let p = PathBuf::from(it.next().ok_or_else(|| format!("{} 後面少了路徑", a.to_string_lossy()))?);
match a.to_str() {
Some("-h") => s.hidden.push(p),
Some("-r") => s.readable.push(p),
Some("-w") => s.no_write.push(p),
Some("-C") => s.work = p,
_ => return Err(format!("看不懂 {}", a.to_string_lossy())),
}
}
Err("少了 --".into())
}
}
/// The path as the kernel sees it (links resolved), also for one that isn't there yet.
fn real(p: &Path) -> PathBuf {
if let Ok(r) = std::fs::canonicalize(p) {
return r;
}
match (p.parent(), p.file_name()) {
(Some(parent), Some(name)) if parent != p => real(parent).join(name),
_ => p.to_path_buf(),
}
}
/// Everything under `dir` but `avoid`: an entry not on the way to an avoided path as a whole, one
/// on the way entry by entry. Links are skipped (what they point to has a path of its own).
fn around(dir: &Path, avoid: &[PathBuf], grant: &mut dyn FnMut(PathBuf, bool)) {
let Ok(entries) = std::fs::read_dir(dir) else { return };
for e in entries.flatten() {
let p = e.path();
let Ok(t) = e.file_type() else { continue };
if t.is_symlink() || avoid.contains(&p) {
continue;
}
if t.is_dir() && avoid.iter().any(|a| a.starts_with(&p)) {
around(&p, avoid, grant);
} else {
grant(p, t.is_dir());
}
}
}
/// What a sandboxed command may do: (path, rights), each for everything under that path.
pub fn plan(spec: &Spec, abi: u32) -> Vec<(PathBuf, u64)> {
let hidden: Vec<PathBuf> = spec.hidden.iter().map(|p| real(p)).collect();
let work = real(&spec.work);
// The work folder is allowed whole — unless a hidden folder is inside it (the home folder as
// work folder: ~/.ssh): then it gets what every other folder gets, entry by entry.
let whole = work.is_dir() && !hidden.iter().any(|h| work.starts_with(h) || h.starts_with(&work));
// (Inside a work folder allowed whole nothing can be kept from writing.)
let no_write: Vec<PathBuf> = hidden.iter().cloned().chain(spec.no_write.iter().map(|p| real(p)).filter(|p| !(whole && p.starts_with(&work)))).collect();
let mut rules: BTreeMap<PathBuf, (u64, bool)> = BTreeMap::new();
let mut add = |p: PathBuf, r: u64, dir: bool| rules.entry(p).or_insert((0, dir)).0 |= r;
let root = Path::new("/");
add(root.to_path_buf(), READ_DIR, true);
around(root, &hidden, &mut |p, dir| add(p, READ, dir));
around(root, &no_write, &mut |p, dir| add(p, WRITE, dir));
for r in spec.readable.iter().map(|r| real(r)) {
if hidden.iter().any(|h| r.starts_with(h)) && r.exists() {
let dir = r.is_dir();
add(r, READ, dir);
}
}
if whole {
add(work, READ | WRITE, true);
}
let h = handled(abi);
rules.into_iter().map(|(p, (r, dir))| (p, r & h & if dir { u64::MAX } else { FILE_ONLY })).filter(|(_, r)| *r != 0).collect()
}
/// The program AnyBot is (the sandbox runs as it). In `cargo test` that is the test runner, which
/// can't be the sandbox: commands there run unwrapped unless a test names a real AnyBot.
fn helper() -> Option<PathBuf> {
if cfg!(test) {
return std::env::var_os("ANYBOT_TEST_SANDBOX_EXE").map(PathBuf::from);
}
Some(PathBuf::from("/proc/self/exe"))
}
/// This kernel's Landlock version (None: no Landlock here). Asked once.
pub fn abi() -> Option<u32> {
static ABI: std::sync::OnceLock<Option<u32>> = std::sync::OnceLock::new();
*ABI.get_or_init(|| {
let v = sys::abi();
if cfg!(target_os = "linux") && v.is_none() {
log::warn!("{NONE}");
}
v
})
}
/// What `/doctor` and the log say on a Linux without Landlock.
pub const NONE: &str = "這台的指令沒有沙盒:Linux 核心沒有 Landlock(要 5.13 以上,而且有開:/sys/kernel/security/lsm 裡要有 landlock)。指令照樣能跑,但讀得到 .ssh 這類私密資料夾";
/// Commands here run in the Linux sandbox.
pub fn active() -> bool {
cfg!(target_os = "linux") && abi().is_some() && helper().is_some()
}
/// `/bin/sh -c cmd` inside the sandbox (None: no sandbox here — run it as before).
pub fn wrap(cmd: &str, spec: &Spec) -> Option<std::process::Command> {
if !active() || spec.hidden.is_empty() {
return None;
}
// (Whole paths: the sandbox starts in the command's work folder, not where AnyBot is.)
let whole = |v: &[PathBuf]| v.iter().map(|p| std::path::absolute(p).unwrap_or_else(|_| p.clone())).collect::<Vec<_>>();
let spec = Spec { hidden: whole(&spec.hidden), readable: whole(&spec.readable), no_write: whole(&spec.no_write), work: std::path::absolute(&spec.work).unwrap_or_else(|_| spec.work.clone()) };
let mut c = std::process::Command::new(helper()?);
c.arg(ARG).args(spec.to_args()).args(["--", "/bin/sh", "-c", cmd]);
Some(c)
}
/// After a command failed this way it may have been the sandbox: a word for the bot.
pub const NOTE: &str = "(如果是 AnyBot 的指令沙盒擋的,不是電腦壞了:在 Linux 上指令讀不到也寫不到 AnyBot 的資料和私密資料夾(.ssh、.gnupg、.aws…),改不了 shell 的啟動檔;家目錄、~/.config、~/.local、~/.local/share 這幾層的最上層不能新增檔案或資料夾,但它們裡面的其他資料夾可以。改在工作資料夾裡做,或請使用者自己做。)";
/// `anybot __anybot_sandbox … -- program args`: close this process in, then become the program.
/// Anything wrong and the program doesn't run (never without the sandbox it was asked for).
pub fn run_helper(args: &[OsString]) -> ! {
let fail = |e: String| -> ! {
eprintln!("AnyBot 的指令沙盒沒有套上,指令沒有執行:{e}");
std::process::exit(126)
};
let (spec, program) = Spec::from_args(args).unwrap_or_else(|e| fail(e));
let abi = sys::abi().unwrap_or_else(|| fail("這台的 Linux 核心沒有 Landlock".into()));
sys::restrict(&plan(&spec, abi), handled(abi)).unwrap_or_else(|e| fail(e));
exec(&program[0], &program[1..])
}
#[cfg(unix)]
fn exec(program: &OsStr, args: &[OsString]) -> ! {
use std::os::unix::process::CommandExt;
let e = std::process::Command::new(program).args(args).exec();
eprintln!("無法執行 {}:{e}", program.to_string_lossy());
std::process::exit(127)
}
#[cfg(not(unix))]
fn exec(program: &OsStr, _: &[OsString]) -> ! {
eprintln!("無法執行 {}:這台沒有指令沙盒", program.to_string_lossy());
std::process::exit(126)
}
#[cfg(target_os = "linux")]
mod sys {
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
use std::os::unix::fs::OpenOptionsExt;
use std::path::PathBuf;
#[repr(C)]
struct RulesetAttr {
handled_access_fs: u64,
}
#[repr(C, packed)]
struct PathBeneath {
allowed_access: u64,
parent_fd: i32,
}
const CREATE_RULESET_VERSION: u32 = 1;
const RULE_PATH_BENEATH: u32 = 1;
pub fn abi() -> Option<u32> {
// SAFETY: asking for the version: no attributes, no memory written.
let v = unsafe { libc::syscall(libc::SYS_landlock_create_ruleset, std::ptr::null::<RulesetAttr>(), 0usize, CREATE_RULESET_VERSION) };
(v > 0).then_some(v as u32)
}
/// From now on this thread (and what it starts) may do only what `rules` allow.
pub fn restrict(rules: &[(PathBuf, u64)], handled: u64) -> Result<(), String> {
let os = || std::io::Error::last_os_error();
let attr = RulesetAttr { handled_access_fs: handled };
// SAFETY: attr lives across the call; the kernel reads size_of bytes of it.
let fd = unsafe { libc::syscall(libc::SYS_landlock_create_ruleset, &attr as *const RulesetAttr, std::mem::size_of::<RulesetAttr>(), 0u32) };
if fd < 0 {
return Err(format!("建立規則失敗:{}", os()));
}
// SAFETY: a new descriptor the kernel just gave us, owned only here.
let ruleset = unsafe { OwnedFd::from_raw_fd(fd as i32) };
for (p, rights) in rules {
// (Gone since the plan was made: nothing to allow there.)
let Ok(f) = std::fs::OpenOptions::new().read(true).custom_flags(libc::O_PATH | libc::O_CLOEXEC).open(p) else { continue };
let rule = PathBeneath { allowed_access: *rights, parent_fd: f.as_raw_fd() };
// SAFETY: rule lives across the call; both descriptors are open.
let r = unsafe { libc::syscall(libc::SYS_landlock_add_rule, ruleset.as_raw_fd(), RULE_PATH_BENEATH, &rule as *const PathBeneath, 0u32) };
if r < 0 {
return Err(format!("允許「{}」失敗:{}", p.display(), os()));
}
}
// SAFETY: plain prctl and syscall on this thread; the ruleset descriptor is open.
if unsafe { libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) } != 0 {
return Err(format!("no_new_privs 失敗:{}", os()));
}
if unsafe { libc::syscall(libc::SYS_landlock_restrict_self, ruleset.as_raw_fd(), 0u32) } < 0 {
return Err(format!("套上規則失敗:{}", os()));
}
Ok(())
}
}
#[cfg(not(target_os = "linux"))]
mod sys {
pub fn abi() -> Option<u32> {
None
}
pub fn restrict(_: &[(std::path::PathBuf, u64)], _: u64) -> Result<(), String> {
Err("只有 Linux 有 Landlock".into())
}
}
#[cfg(test)]
mod tests {
use super::*;
fn tree(name: &str) -> PathBuf {
let d = real(&std::env::temp_dir().join(format!("anybot-ll-{name}-{}", std::process::id())));
let _ = std::fs::remove_dir_all(&d);
for sub in ["home/.ssh", "home/.config/gcloud", "home/.config/nvim", "home/Documents", "home/data/attachments", "home/work/.git/hooks"] {
std::fs::create_dir_all(d.join(sub)).unwrap();
}
for f in ["home/.bashrc", "home/notes.txt", "home/.ssh/id_ed25519", "home/data/state.json"] {
std::fs::write(d.join(f), "x").unwrap();
}
d
}
fn rights(rules: &[(PathBuf, u64)], p: &Path) -> Option<u64> {
rules.iter().find(|(q, _)| q == p).map(|(_, r)| *r)
}
/// What is reachable from a rule list (Landlock's way: a rule covers everything under it).
fn may(rules: &[(PathBuf, u64)], p: &Path, want: u64) -> bool {
let got = rules.iter().filter(|(q, _)| p.starts_with(q)).fold(0, |a, (_, r)| a | r);
got & want == want
}
#[test]
fn the_plan_leaves_out_what_macos_denies() {
let d = tree("plan");
let h = d.join("home");
let spec = Spec { hidden: vec![h.join(".ssh"), h.join("data"), h.join(".config/gcloud"), h.join(".gnupg")], readable: vec![h.join("data/attachments"), h.join(".ssh")], no_write: vec![h.join(".bashrc"), h.join("work/.git/hooks")], work: h.join("work") };
let r = plan(&spec, 5);
// Secrets: neither read nor written; the attachments and ~/.ssh readable only.
assert!(!may(&r, &h.join("data/state.json"), READ_FILE) && !may(&r, &h.join("data/state.json"), WRITE_FILE));
assert!(!may(&r, &h.join(".config/gcloud/creds"), READ_FILE));
assert!(may(&r, &h.join("data/attachments/p.png"), READ_FILE) && !may(&r, &h.join("data/attachments/p.png"), WRITE_FILE));
assert!(may(&r, &h.join(".ssh/id_ed25519"), READ_FILE) && !may(&r, &h.join(".ssh/id_ed25519"), WRITE_FILE));
// A folder not yet there (~/.gnupg) can't be made: its parent isn't allowed to make things.
assert!(!may(&r, &h, MAKE_DIR));
// The rest: read and write as before, the startup file read only.
assert!(may(&r, &h.join("Documents/a.txt"), READ_FILE | WRITE_FILE | MAKE_REG));
assert!(may(&r, &h.join(".config/nvim/init.lua"), READ_FILE | WRITE_FILE));
assert!(may(&r, &h.join("notes.txt"), READ_FILE | WRITE_FILE));
assert!(may(&r, &h.join(".bashrc"), READ_FILE) && !may(&r, &h.join(".bashrc"), WRITE_FILE));
assert!(may(&r, Path::new("/usr/bin/env"), READ_FILE | EXECUTE));
// The work folder whole (its .git/hooks too: Landlock can't carve inside it).
assert!(may(&r, &h.join("work/new/file.rs"), READ_FILE | WRITE_FILE | MAKE_REG | REMOVE_FILE));
assert!(may(&r, &h.join("work/.git/index.lock"), MAKE_REG));
// The home folder as the work folder: its secrets stay hidden, its startup file read-only.
let r2 = plan(&Spec { work: h.clone(), ..spec.clone() }, 5);
assert!(!may(&r2, &h.join("data/state.json"), READ_FILE) && !may(&r2, &h.join(".ssh/id_ed25519"), WRITE_FILE) && !may(&r2, &h.join(".bashrc"), WRITE_FILE));
assert!(may(&r2, &h.join("Documents/a.txt"), READ_FILE | WRITE_FILE | MAKE_REG));
// Names can be listed everywhere; a file's rule carries only file rights.
assert_eq!(rights(&r, Path::new("/")), Some(READ_DIR));
assert_eq!(rights(&r, &h.join("notes.txt")).map(|x| x & !FILE_ONLY), Some(0));
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn older_kernels_get_only_what_they_know() {
assert_eq!(handled(1), (1 << 13) - 1);
assert_eq!(handled(2) & REFER, REFER);
assert_eq!(handled(4) & (TRUNCATE | IOCTL_DEV), TRUNCATE);
assert_eq!(handled(6) & IOCTL_DEV, IOCTL_DEV);
let d = tree("abi");
let r = plan(&Spec { hidden: vec![d.join("home/.ssh")], work: d.join("home/work"), ..Default::default() }, 1);
assert!(r.iter().all(|(_, x)| x & !handled(1) == 0), "{r:?}");
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn the_spec_goes_through_arguments() {
let s = Spec { hidden: vec!["/h/.ssh".into(), "/h/data".into()], readable: vec!["/h/data/attachments".into()], no_write: vec!["/h/.bashrc".into()], work: "/h/工作區".into() };
let mut args = s.to_args();
args.extend(["--", "/bin/sh", "-c", "echo hi"].map(OsString::from));
let (back, program) = Spec::from_args(&args).unwrap();
assert_eq!(back, s);
assert_eq!(program, ["/bin/sh", "-c", "echo hi"].map(OsString::from));
assert!(Spec::from_args(&["-h".into()]).is_err());
assert!(Spec::from_args(&["-C".into(), "/w".into(), "--".into()]).is_err());
}
/// The real thing on a Linux with Landlock (CI's anybot-linux): a thread closed in can't read
/// the secret or write outside, and still works in its folder.
#[cfg(target_os = "linux")]
#[test]
fn landlock_keeps_a_command_out() {
let Some(abi) = sys::abi() else {
eprintln!("這台沒有 Landlock:略過");
return;
};
let d = tree("real");
let h = d.join("home");
let spec = Spec { hidden: vec![h.join("data")], readable: vec![h.join("data/attachments")], no_write: vec![h.join(".bashrc")], work: h.join("work") };
std::fs::write(h.join("data/attachments/p.txt"), "photo").unwrap();
let rules = plan(&spec, abi);
let out = std::thread::spawn(move || {
sys::restrict(&rules, handled(abi)).unwrap();
let sh = |c: &str| std::process::Command::new("/bin/sh").arg("-c").arg(c).current_dir(&spec.work).output().unwrap();
let said = |c: &str| String::from_utf8_lossy(&sh(c).stdout).trim().to_string();
let h = spec.work.parent().unwrap().to_path_buf();
vec![
said(&format!("cat '{}' 2>/dev/null || echo HIDDEN", h.join("data/state.json").display())),
said(&format!("cat '{}'", h.join("data/attachments/p.txt").display())),
said(&format!("echo x >> '{}' 2>/dev/null && echo WROTE || echo KEPT", h.join(".bashrc").display())),
said("echo hi > mine.txt && cat mine.txt"),
said(&format!("echo y > '{}' 2>/dev/null && echo WROTE || echo KEPT", h.join("Documents/a.txt").display())),
]
})
.join()
.unwrap();
assert_eq!(out, ["HIDDEN", "photo", "KEPT", "hi", "WROTE"]);
let _ = std::fs::remove_dir_all(&d);
}
}