diff --git a/Cargo.toml b/Cargo.toml index f5124b9..ceb4fdd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,11 +2,17 @@ name = "yoke" version = "0.1.0" authors = [ "atagen" ] -description = "A simple sandboxing tool, similar to bwrap" +description = "CLI sandboxing tool similar to landrun or bwrap" repository = "https://git.atagen.co/atagen/yoke" license = "GPL-3.0-or-later" edition = "2024" +[features] +default = [] +ldd = ["dep:elb-dl"] +which = ["dep:which"] + + [profile.release] strip = true opt-level = "s" @@ -14,7 +20,7 @@ codegen-units = 1 [dependencies] anyhow = "1.0.100" -elb-dl = { version = "0.3.2", features = ["glibc"], default-features = false } -exec = "0.3.1" landlock = "0.4.3" -which = "8.0.0" +exec = "0.3.1" +elb-dl = { version = "0.3.2", features = ["glibc"], default-features = false, optional = true } +which = { version = "8.0.0", optional = true } diff --git a/src/main.rs b/src/main.rs index f315ec4..b37cd4b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,26 +1,28 @@ mod parse; mod types; -use std::collections::VecDeque; use anyhow::{Context, Result, anyhow}; -use elb_dl::{DependencyTree, DynamicLoader, glibc}; use landlock::{ ABI, Access, AccessFs, AccessNet, BitFlags, Compatible, NetPort, Ruleset, RulesetAttr, RulesetCreatedAttr, Scope, make_bitflags, path_beneath_rules, }; -use crate::types::BasePermission; +#[cfg(feature = "ldd")] +use elb_dl::{DependencyTree, DynamicLoader, glibc}; +#[cfg(feature = "ldd")] +use std::{collections::VecDeque, path::PathBuf, str::FromStr}; fn main() -> Result<()> { let opts = parse::parse_args()?; if opts.exec.is_empty() { + // print help eprintln!( " -yoke -- simple command sandboxer +yoke -- simple sandboxer use: yoke [ruletype] [space separated rules] -- [command] -rule types +rules ------------ filesystem: --fs | -f [access]=/path:/another/path @@ -40,16 +42,22 @@ rule types allow sending signals to other processes: --signals | -k - resolve process dependencies and add to sandbox: + resolve process dependencies and add to sandbox + (with `ldd` feature): --ldd | -l + unsandbox: + --no-fs | -nf + --no-tcp | -nt -specifiers + +access specifiers ------------ fs: - r - read (implies execute) - w - write (implies read+execute) - i - allow ioctls (implies nothing - may require read or write) + r - read + w - write + x - execute + i - ioctl tcp: i - in/bind @@ -65,27 +73,36 @@ examples ); std::process::exit(1); } + + // set up scope of our intial ruleset let mut preempt = Ruleset::default(); + // TODO FIXME set up for lesser ABI versions preempt = preempt.set_compatibility(landlock::CompatLevel::HardRequirement); + + // disallow signals to other processes if !opts.signals { preempt = preempt.scope(Scope::Signal).context("scoping signals")?; } + + // disallow connections to unix domain sockets if !opts.sockets { preempt = preempt .scope(Scope::AbstractUnixSocket) .context("scoping sockets")?; } - let is_fs = !opts.fs.is_empty(); - let is_tcp = !opts.tcp.is_empty(); - preempt = if is_fs { + + // lock down fs access + preempt = if !opts.unsandbox.fs { preempt .handle_access(AccessFs::from_all(ABI::V6)) .context("handling fs access")? } else { preempt }; - preempt = if is_tcp { + + // lock down tcp access + preempt = if !opts.unsandbox.tcp { preempt .handle_access(AccessNet::BindTcp) .context("handling tcp bind access")? @@ -94,15 +111,38 @@ examples } else { preempt }; + + // create ruleset and begin inserting rules let mut ruleset = preempt.create().context("creating ruleset")?; + + // allow each path specified, grouped by access specifier for (perms, paths) in opts.fs { - let mut access = match perms.base { - BasePermission::Unset => BitFlags::empty(), - BasePermission::Read => AccessFs::from_read(ABI::V6), - BasePermission::Write => AccessFs::from_write(ABI::V6), - }; + let mut access = BitFlags::empty(); + if perms.read { + access.insert(make_bitflags!(AccessFs::{ReadFile | ReadDir})); + } + if perms.write { + access.insert(make_bitflags!( + AccessFs::{ WriteFile + | RemoveDir + | RemoveFile + | MakeChar + | MakeDir + | MakeReg + | MakeSock + | MakeFifo + | MakeBlock + | MakeSym + | Refer + | Truncate + } + )); + } + if perms.execute { + access.insert(AccessFs::Execute); + } if perms.ioctl { - access.insert(make_bitflags!(AccessFs::IoctlDev)); + access.insert(AccessFs::IoctlDev); } if access == BitFlags::empty() { return Err(anyhow!("invalid filesystem permissions requested")); @@ -111,6 +151,8 @@ examples .add_rules(path_beneath_rules(paths, access)) .context("adding fs rule")?; } + + // allow each tcp action specified, grouped by access specifier for (dir, ports) in opts.tcp { let mut access = BitFlags::empty(); if dir.inbound { @@ -125,14 +167,29 @@ examples .context("adding tcp rule")?; } } + + // locate our executable + #[cfg(feature = "which")] let fullpath = which::which(&opts.exec[0]).context("finding executable")?; - ruleset = ruleset.add_rules(path_beneath_rules( - std::slice::from_ref(&fullpath), - AccessFs::from_read(ABI::V6), - ))?; + #[cfg(not(feature = "which"))] + let fullpath = &opts.exec[0]; + + // add executeable as read+execute + if !opts.unsandbox.fs { + ruleset = ruleset.add_rules(path_beneath_rules( + std::slice::from_ref(&fullpath), + AccessFs::from_read(ABI::V6), + ))?; + } + + // if requested, trace dependencies and add as read+execute + #[cfg(feature = "ldd")] if opts.ldd { let loader = DynamicLoader::options() .search_dirs(glibc::get_hard_coded_search_dirs(None)?) + .search_dirs(glibc::get_search_dirs( + PathBuf::from_str("/").context("finding root")?, + )?) .new_loader(); let mut tree = DependencyTree::new(); let mut queue = VecDeque::new(); @@ -151,11 +208,17 @@ examples )) .context("tracking dependencies")?; } + + // enforce the ruleset on ourselves ruleset.restrict_self().context("enforcing ruleset")?; + + // construct a command for the target program let mut cmd = exec::Command::new(fullpath); if opts.exec.len() > 1 { cmd.args(&opts.exec[1..]); } + + // clear env unless retention is requested if !opts.retain_env { for (k, _) in std::env::vars() { unsafe { @@ -163,6 +226,8 @@ examples } } } + + // add specified env vars if !opts.env.is_empty() { for (k, v) in opts.env { unsafe { @@ -170,6 +235,8 @@ examples } } } + + // execute and hopefully never return let err = cmd.exec(); eprintln!("failed to run process: {}", err); Ok(()) diff --git a/src/parse.rs b/src/parse.rs index 6e38e62..0ce3731 100644 --- a/src/parse.rs +++ b/src/parse.rs @@ -1,4 +1,4 @@ -use crate::types::{BasePermission, Direction, Permissions, Yoke}; +use crate::types::{Direction, Permissions, Yoke}; use anyhow::{Context, Result, anyhow}; use std::{collections::HashMap, path::PathBuf, str::FromStr}; @@ -32,17 +32,18 @@ fn fs_parse(pairs: &[String]) -> Result>> { .ok_or(anyhow!("invalid filesystem pair"))?; let mut perms = Permissions::default(); - - use BasePermission::*; for c in s_perm.chars() { match c { - 'r' | 'R' if perms.base == Unset => { - perms.base = Read; + 'r' => { + perms.read = true; } - 'w' | 'W' => { - perms.base = Write; + 'w' => { + perms.write = true; } - 'i' | 'I' => { + 'x' => { + perms.execute = true; + } + 'i' => { perms.ioctl = true; } s => return Err(anyhow!("invalid access specifier {}", s)), @@ -144,12 +145,27 @@ pub fn parse_args() -> Result { cur_arg = Unset; yoke.retain_env = true; } + + #[cfg(feature = "ldd")] "--ldd" | "-l" => { collect_args(&mut yoke, &collector, &cur_arg)?; collector.clear(); cur_arg = Unset; yoke.ldd = true; } + + "--no-fs" | "-nf" => { + collect_args(&mut yoke, &collector, &cur_arg)?; + collector.clear(); + cur_arg = Unset; + yoke.unsandbox.fs = true; + } + "--no-tcp" | "-nt" => { + collect_args(&mut yoke, &collector, &cur_arg)?; + collector.clear(); + cur_arg = Unset; + yoke.unsandbox.tcp = true; + } "--" => { collect_args(&mut yoke, &collector, &cur_arg)?; collector.clear(); diff --git a/src/types.rs b/src/types.rs index 50876bc..fffb4be 100644 --- a/src/types.rs +++ b/src/types.rs @@ -1,5 +1,11 @@ use std::{collections::HashMap, path::PathBuf}; +#[derive(Debug, Default)] +pub struct Unsandbox { + pub fs: bool, + pub tcp: bool, +} + #[derive(Debug, Default)] pub struct Yoke { pub fs: HashMap>, @@ -8,21 +14,16 @@ pub struct Yoke { pub retain_env: bool, pub signals: bool, pub sockets: bool, + pub unsandbox: Unsandbox, pub ldd: bool, pub exec: Vec, } -#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, Default)] -pub enum BasePermission { - #[default] - Unset, - Read, - Write, -} - #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, Default)] pub struct Permissions { - pub base: BasePermission, + pub read: bool, + pub write: bool, + pub execute: bool, pub ioctl: bool, }