refactor, auto add target executable, allow tracing deps
This commit is contained in:
parent
168ec6d5e9
commit
fd5de5e9bb
5 changed files with 451 additions and 200 deletions
297
src/main.rs
297
src/main.rs
|
|
@ -1,117 +1,81 @@
|
|||
use std::{collections::HashMap, path::PathBuf, str::FromStr};
|
||||
mod parse;
|
||||
mod types;
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use anyhow::{Context, Result, anyhow};
|
||||
use gumdrop::Options;
|
||||
use elb_dl::{DependencyTree, DynamicLoader, glibc};
|
||||
use landlock::{
|
||||
ABI, Access, AccessFs, AccessNet, Compatible, NetPort, Ruleset, RulesetAttr,
|
||||
RulesetCreatedAttr, Scope, path_beneath_rules,
|
||||
ABI, Access, AccessFs, AccessNet, BitFlags, Compatible, NetPort, Ruleset, RulesetAttr,
|
||||
RulesetCreatedAttr, Scope, make_bitflags, path_beneath_rules,
|
||||
};
|
||||
|
||||
#[derive(Clone, Copy, Debug, Hash, Eq, PartialEq)]
|
||||
enum Direction {
|
||||
In,
|
||||
Out,
|
||||
}
|
||||
|
||||
#[derive(Debug, Options)]
|
||||
struct Chas {
|
||||
#[options(no_multi, parse(try_from_str = "fs_parse"))]
|
||||
fs: HashMap<Permissions, Vec<PathBuf>>,
|
||||
#[options(no_multi, parse(try_from_str = "tcp_parse"))]
|
||||
tcp: HashMap<Direction, Vec<u16>>,
|
||||
#[options(no_multi, parse(try_from_str = "env_parse"))]
|
||||
env: HashMap<String, String>,
|
||||
clear_env: bool,
|
||||
#[options(free)]
|
||||
exec: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
|
||||
enum Permissions {
|
||||
Read,
|
||||
Write,
|
||||
}
|
||||
|
||||
fn env_parse(s: &str) -> Result<HashMap<String, String>> {
|
||||
let pairs = s.split(',');
|
||||
let mut envs = HashMap::new();
|
||||
for pair in pairs {
|
||||
let (k, v) = pair.split_once('=').ok_or(anyhow!("invalid env var"))?;
|
||||
envs.entry(k.to_string())
|
||||
.and_modify(|iv: &mut String| {
|
||||
*iv = v.to_string();
|
||||
})
|
||||
.or_insert(v.to_string());
|
||||
}
|
||||
Ok(envs)
|
||||
}
|
||||
|
||||
// TODO handle ioctl perms
|
||||
fn fs_parse(s: &str) -> Result<HashMap<Permissions, Vec<PathBuf>>> {
|
||||
let pairs = s.split(',');
|
||||
let mut rules = HashMap::new();
|
||||
for pair in pairs {
|
||||
let (s_perm, s_path) = pair
|
||||
.split_once('=')
|
||||
.ok_or(anyhow!("invalid filesystem pair"))?;
|
||||
if s_perm.len() > 1 {
|
||||
return Err(anyhow!("permission specifier too long"));
|
||||
}
|
||||
let perm = unsafe {
|
||||
match s_perm.get_unchecked(0..1) {
|
||||
"r" | "R" => Permissions::Read,
|
||||
"w" | "W" => Permissions::Write,
|
||||
_ => {
|
||||
return Err(anyhow!("invalid permission specifier"));
|
||||
}
|
||||
}
|
||||
};
|
||||
for sub in s_path.split(':') {
|
||||
let path = PathBuf::from_str(sub).context("invalid path specifier")?;
|
||||
rules
|
||||
.entry(perm)
|
||||
.and_modify(|v: &mut Vec<PathBuf>| {
|
||||
v.push(path.clone());
|
||||
})
|
||||
.or_insert(vec![path]);
|
||||
}
|
||||
}
|
||||
Ok(rules)
|
||||
}
|
||||
|
||||
fn tcp_parse(s: &str) -> Result<HashMap<Direction, Vec<u16>>> {
|
||||
let pairs = s.split(',');
|
||||
let mut rules = HashMap::new();
|
||||
for pair in pairs {
|
||||
let (s_io, s_port) = pair.split_once('=').context("invalid tcp pair")?;
|
||||
let dir = match s_io {
|
||||
"i" => Direction::In,
|
||||
"o" => Direction::Out,
|
||||
_ => {
|
||||
return Err(anyhow!("invalid tcp specifier"));
|
||||
}
|
||||
};
|
||||
for sub in s_port.split(':') {
|
||||
let port = sub.parse().context("invalid port")?;
|
||||
rules
|
||||
.entry(dir)
|
||||
.and_modify(|v: &mut Vec<u16>| {
|
||||
v.push(port);
|
||||
})
|
||||
.or_insert(vec![port]);
|
||||
}
|
||||
}
|
||||
Ok(rules)
|
||||
}
|
||||
use crate::types::BasePermission;
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let opts = Chas::parse_args_or_exit(gumdrop::ParsingStyle::StopAtFirstFree);
|
||||
let opts = parse::parse_args()?;
|
||||
if opts.exec.is_empty() {
|
||||
eprintln!(
|
||||
"
|
||||
yoke -- simple command sandboxer
|
||||
|
||||
use: yoke [ruletype] [space separated rules] -- [command]
|
||||
|
||||
rule types
|
||||
------------
|
||||
filesystem:
|
||||
--fs | -f [access]=/path:/another/path
|
||||
|
||||
tcp port:
|
||||
--tcp | -t [access]=1234:5678
|
||||
|
||||
env vars:
|
||||
--env | -e [key]=[value]
|
||||
|
||||
clear inherited env vars:
|
||||
--clear-env | -c
|
||||
|
||||
allow use of external unix domain sockets:
|
||||
--sockets | -s
|
||||
|
||||
allow sending signals to other processes:
|
||||
--signals | -k
|
||||
|
||||
resolve process dependencies and add to sandbox:
|
||||
--ldd | -l
|
||||
|
||||
|
||||
specifiers
|
||||
------------
|
||||
fs:
|
||||
r - read (implies execute)
|
||||
w - write (implies read+execute)
|
||||
i - allow ioctls (implies nothing - may require read or write)
|
||||
|
||||
tcp:
|
||||
i - in/bind
|
||||
o - out/connect
|
||||
|
||||
examples
|
||||
------------
|
||||
yoke --fs r=/etc -l -- ls /etc
|
||||
|
||||
yoke --tcp io=80:443 --fs r=/srv/web --clear-env --env SERVE_FROM=/srv/web \
|
||||
-- myhttpserver
|
||||
"
|
||||
);
|
||||
std::process::exit(1);
|
||||
}
|
||||
let mut preempt = Ruleset::default();
|
||||
// TODO FIXME set up for lesser ABI versions
|
||||
preempt = preempt.set_compatibility(landlock::CompatLevel::HardRequirement);
|
||||
preempt = preempt.scope(Scope::Signal).context("scoping signals")?;
|
||||
preempt = preempt
|
||||
.scope(Scope::AbstractUnixSocket)
|
||||
.context("scoping sockets")?;
|
||||
if !opts.signals {
|
||||
preempt = preempt.scope(Scope::Signal).context("scoping signals")?;
|
||||
}
|
||||
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 {
|
||||
|
|
@ -132,80 +96,81 @@ fn main() -> Result<()> {
|
|||
};
|
||||
let mut ruleset = preempt.create().context("creating ruleset")?;
|
||||
for (perms, paths) in opts.fs {
|
||||
let access = match perms {
|
||||
Permissions::Read => AccessFs::from_read(ABI::V6),
|
||||
Permissions::Write => AccessFs::from_write(ABI::V6),
|
||||
let mut access = match perms.base {
|
||||
BasePermission::Unset => BitFlags::empty(),
|
||||
BasePermission::Read => AccessFs::from_read(ABI::V6),
|
||||
BasePermission::Write => AccessFs::from_write(ABI::V6),
|
||||
};
|
||||
if perms.ioctl {
|
||||
access.insert(make_bitflags!(AccessFs::IoctlDev));
|
||||
}
|
||||
if access == BitFlags::empty() {
|
||||
return Err(anyhow!("invalid filesystem permissions requested"));
|
||||
}
|
||||
ruleset = ruleset
|
||||
.add_rules(path_beneath_rules(paths, access))
|
||||
.context("adding fs rule")?;
|
||||
}
|
||||
for (dir, ports) in opts.tcp {
|
||||
let access = match dir {
|
||||
Direction::In => AccessNet::BindTcp,
|
||||
Direction::Out => AccessNet::ConnectTcp,
|
||||
};
|
||||
let mut access = BitFlags::empty();
|
||||
if dir.inbound {
|
||||
access.insert(make_bitflags!(AccessNet::BindTcp));
|
||||
}
|
||||
if dir.outbound {
|
||||
access.insert(make_bitflags!(AccessNet::ConnectTcp))
|
||||
}
|
||||
for port in ports {
|
||||
ruleset = ruleset
|
||||
.add_rule(NetPort::new(port, access))
|
||||
.context("adding tcp rule")?;
|
||||
}
|
||||
}
|
||||
ruleset.restrict_self().context("enforcing ruleset")?;
|
||||
if !opts.exec.is_empty() {
|
||||
let mut cmd = exec::Command::new(&opts.exec[0]);
|
||||
if opts.exec.len() > 1 {
|
||||
cmd.args(&opts.exec[1..]);
|
||||
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),
|
||||
))?;
|
||||
if opts.ldd {
|
||||
let loader = DynamicLoader::options()
|
||||
.search_dirs(glibc::get_hard_coded_search_dirs(None)?)
|
||||
.new_loader();
|
||||
let mut tree = DependencyTree::new();
|
||||
let mut queue = VecDeque::new();
|
||||
queue.push_back(fullpath.clone());
|
||||
while let Some(path) = queue.pop_front() {
|
||||
let deps = loader.resolve_dependencies(&path, &mut tree)?;
|
||||
queue.extend(deps);
|
||||
}
|
||||
if opts.clear_env {
|
||||
for (k, _) in std::env::vars() {
|
||||
unsafe {
|
||||
std::env::remove_var(k);
|
||||
}
|
||||
}
|
||||
}
|
||||
if !opts.env.is_empty() {
|
||||
for (k, v) in opts.env {
|
||||
unsafe {
|
||||
std::env::set_var(k, v);
|
||||
}
|
||||
}
|
||||
}
|
||||
let err = cmd.exec();
|
||||
eprintln!("failed to run process: {}", err);
|
||||
} else {
|
||||
eprintln!(
|
||||
"
|
||||
yoke -- simple command sandboxer
|
||||
|
||||
use: yoke [rules] [command]
|
||||
|
||||
rules:
|
||||
filesystem rules:
|
||||
--fs [access]=/path:/another/path,[access]=/more/path
|
||||
|
||||
tcp port rules:
|
||||
--tcp [access]=1234:5678,[access]=91011
|
||||
|
||||
env vars:
|
||||
--env [key]=[value]
|
||||
|
||||
clear inherited env vars:
|
||||
--clear-env
|
||||
|
||||
access specifiers (only one may be used per entry):
|
||||
fs:
|
||||
r - read (implies execute)
|
||||
w - write (implies read+execute)
|
||||
tcp:
|
||||
i - in/bind
|
||||
o - out/connect
|
||||
|
||||
example:
|
||||
yoke --fs r=$(which ls):/etc ls /etc
|
||||
yoke --tcp i=80:443,o=80:443 --fs r=/srv/web --clear-env --env SERVE_FROM=/srv/web myhttpserver
|
||||
"
|
||||
);
|
||||
ruleset = ruleset
|
||||
.add_rules(path_beneath_rules(
|
||||
tree.into_iter().fold(Vec::new(), |mut acc, (_, deps)| {
|
||||
acc.extend(deps);
|
||||
acc
|
||||
}),
|
||||
AccessFs::from_read(ABI::V6),
|
||||
))
|
||||
.context("tracking dependencies")?;
|
||||
}
|
||||
ruleset.restrict_self().context("enforcing ruleset")?;
|
||||
let mut cmd = exec::Command::new(fullpath);
|
||||
if opts.exec.len() > 1 {
|
||||
cmd.args(&opts.exec[1..]);
|
||||
}
|
||||
if opts.clear_env {
|
||||
for (k, _) in std::env::vars() {
|
||||
unsafe {
|
||||
std::env::remove_var(k);
|
||||
}
|
||||
}
|
||||
}
|
||||
if !opts.env.is_empty() {
|
||||
for (k, v) in opts.env {
|
||||
unsafe {
|
||||
std::env::set_var(k, v);
|
||||
}
|
||||
}
|
||||
}
|
||||
let err = cmd.exec();
|
||||
eprintln!("failed to run process: {}", err);
|
||||
Ok(())
|
||||
}
|
||||
|
|
|
|||
168
src/parse.rs
Normal file
168
src/parse.rs
Normal file
|
|
@ -0,0 +1,168 @@
|
|||
use crate::types::{BasePermission, Direction, Permissions, Yoke};
|
||||
use anyhow::{Context, Result, anyhow};
|
||||
use std::{collections::HashMap, path::PathBuf, str::FromStr};
|
||||
|
||||
#[derive(PartialEq)]
|
||||
enum Arg {
|
||||
Unset,
|
||||
Filesystem,
|
||||
Tcp,
|
||||
Env,
|
||||
Exec,
|
||||
}
|
||||
|
||||
fn env_parse(pairs: &[String]) -> Result<HashMap<String, String>> {
|
||||
let mut envs = HashMap::new();
|
||||
for pair in pairs {
|
||||
let (k, v) = pair.split_once('=').ok_or(anyhow!("invalid env var"))?;
|
||||
envs.entry(k.to_string())
|
||||
.and_modify(|iv: &mut String| {
|
||||
*iv = v.to_string();
|
||||
})
|
||||
.or_insert(v.to_string());
|
||||
}
|
||||
Ok(envs)
|
||||
}
|
||||
|
||||
fn fs_parse(pairs: &[String]) -> Result<HashMap<Permissions, Vec<PathBuf>>> {
|
||||
let mut rules = HashMap::new();
|
||||
for pair in pairs {
|
||||
let (s_perm, s_path) = pair
|
||||
.split_once('=')
|
||||
.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;
|
||||
}
|
||||
'w' | 'W' => {
|
||||
perms.base = Write;
|
||||
}
|
||||
'i' | 'I' => {
|
||||
perms.ioctl = true;
|
||||
}
|
||||
s => return Err(anyhow!("invalid access specifier {}", s)),
|
||||
}
|
||||
}
|
||||
|
||||
for sub in s_path.split(':') {
|
||||
let path = PathBuf::from_str(sub).context("invalid path specifier")?;
|
||||
rules
|
||||
.entry(perms)
|
||||
.and_modify(|v: &mut Vec<PathBuf>| {
|
||||
v.push(path.clone());
|
||||
})
|
||||
.or_insert(vec![path]);
|
||||
}
|
||||
}
|
||||
Ok(rules)
|
||||
}
|
||||
|
||||
fn tcp_parse(pairs: &[String]) -> Result<HashMap<Direction, Vec<u16>>> {
|
||||
let mut rules = HashMap::new();
|
||||
for pair in pairs {
|
||||
let (s_io, s_port) = pair.split_once('=').context("invalid tcp pair")?;
|
||||
let mut dir = Direction::default();
|
||||
for c in s_io.chars() {
|
||||
match c {
|
||||
'i' | 'I' => {
|
||||
dir.inbound = true;
|
||||
}
|
||||
'o' | 'O' => {
|
||||
dir.outbound = true;
|
||||
}
|
||||
_ => {
|
||||
return Err(anyhow!("invalid tcp specifier"));
|
||||
}
|
||||
}
|
||||
}
|
||||
for sub in s_port.split(':') {
|
||||
let port = sub.parse().context("invalid port")?;
|
||||
rules
|
||||
.entry(dir)
|
||||
.and_modify(|v: &mut Vec<u16>| {
|
||||
v.push(port);
|
||||
})
|
||||
.or_insert(vec![port]);
|
||||
}
|
||||
}
|
||||
Ok(rules)
|
||||
}
|
||||
|
||||
pub fn parse_args() -> Result<Yoke> {
|
||||
let mut yoke = Yoke::default();
|
||||
let mut collector = Vec::new();
|
||||
let mut cur_arg = Unset;
|
||||
use Arg::*;
|
||||
fn collect_args(yoke: &mut Yoke, collector: &[String], cur_arg: &Arg) -> Result<()> {
|
||||
match cur_arg {
|
||||
Unset => (),
|
||||
Filesystem => yoke.fs.extend(fs_parse(collector)?),
|
||||
Tcp => yoke.tcp.extend(tcp_parse(collector)?),
|
||||
Env => yoke.env.extend(env_parse(collector)?),
|
||||
Exec => yoke.exec.extend(collector.iter().cloned()),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
for mut arg in std::env::args().skip(1) {
|
||||
arg.make_ascii_lowercase();
|
||||
match arg.as_str() {
|
||||
"--fs" | "-f" => {
|
||||
collect_args(&mut yoke, &collector, &cur_arg)?;
|
||||
collector.clear();
|
||||
cur_arg = Filesystem;
|
||||
}
|
||||
"--tcp" | "-t" => {
|
||||
collect_args(&mut yoke, &collector, &cur_arg)?;
|
||||
collector.clear();
|
||||
cur_arg = Tcp;
|
||||
}
|
||||
"--env" | "-e" => {
|
||||
collect_args(&mut yoke, &collector, &cur_arg)?;
|
||||
collector.clear();
|
||||
cur_arg = Env;
|
||||
}
|
||||
"--sockets" | "-s" => {
|
||||
collect_args(&mut yoke, &collector, &cur_arg)?;
|
||||
collector.clear();
|
||||
cur_arg = Unset;
|
||||
yoke.sockets = true;
|
||||
}
|
||||
"--signals" | "-k" => {
|
||||
collect_args(&mut yoke, &collector, &cur_arg)?;
|
||||
collector.clear();
|
||||
cur_arg = Unset;
|
||||
yoke.signals = true;
|
||||
}
|
||||
"--clear-env" | "-c" => {
|
||||
collect_args(&mut yoke, &collector, &cur_arg)?;
|
||||
collector.clear();
|
||||
cur_arg = Unset;
|
||||
yoke.clear_env = true;
|
||||
}
|
||||
"--ldd" | "-l" => {
|
||||
collect_args(&mut yoke, &collector, &cur_arg)?;
|
||||
collector.clear();
|
||||
cur_arg = Unset;
|
||||
yoke.ldd = true;
|
||||
}
|
||||
"--" => {
|
||||
collect_args(&mut yoke, &collector, &cur_arg)?;
|
||||
collector.clear();
|
||||
cur_arg = Exec;
|
||||
}
|
||||
_ if cur_arg != Unset => {
|
||||
collector.push(arg.clone());
|
||||
}
|
||||
a => {
|
||||
return Err(anyhow!("invalid argument: {}", a));
|
||||
}
|
||||
}
|
||||
}
|
||||
collect_args(&mut yoke, &collector, &cur_arg)?;
|
||||
Ok(yoke)
|
||||
}
|
||||
33
src/types.rs
Normal file
33
src/types.rs
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
use std::{collections::HashMap, path::PathBuf};
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Yoke {
|
||||
pub fs: HashMap<Permissions, Vec<PathBuf>>,
|
||||
pub tcp: HashMap<Direction, Vec<u16>>,
|
||||
pub env: HashMap<String, String>,
|
||||
pub clear_env: bool,
|
||||
pub signals: bool,
|
||||
pub sockets: bool,
|
||||
pub ldd: bool,
|
||||
pub exec: Vec<String>,
|
||||
}
|
||||
|
||||
#[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 ioctl: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Hash, Eq, PartialEq, Default)]
|
||||
pub struct Direction {
|
||||
pub inbound: bool,
|
||||
pub outbound: bool,
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue