use nlink::netlink::tc::NetemConfig;
use crate::Error;
use crate::hardening::{CgroupLimits, SeccompProfile};
use crate::netns::{fork_and_enter, fork_and_enter_with_chaos, fork_and_enter_with_options};
use crate::veth::{VethEnd, fork_veth_pair};
#[derive(Debug, Default)]
pub struct Sandbox {
netem: Option<NetemConfig>,
cgroup: Option<CgroupLimits>,
seccomp: Option<SeccompProfile>,
}
impl Sandbox {
pub fn new() -> Self {
Self {
netem: None,
cgroup: None,
seccomp: None,
}
}
pub fn paired() -> PairedSandbox {
PairedSandbox
}
#[must_use]
pub fn chaos(mut self, netem: NetemConfig) -> Self {
self.netem = Some(netem);
self
}
#[must_use]
pub fn cgroup_limits(mut self, limits: CgroupLimits) -> Self {
self.cgroup = Some(limits);
self
}
#[must_use]
pub fn seccomp(mut self, profile: SeccompProfile) -> Self {
self.seccomp = Some(profile);
self
}
pub fn enter<F>(self, f: F) -> Result<i32, Error>
where
F: FnOnce() -> i32,
{
let has_cgroup = self.cgroup.is_some();
let cgroup = self.cgroup.map(CgroupLimits::create).transpose()?;
match (self.netem, has_cgroup, self.seccomp) {
(None, false, None) => fork_and_enter(f),
(Some(netem), false, None) => fork_and_enter_with_chaos(netem, f),
(netem, _, seccomp) => fork_and_enter_with_options(netem, seccomp, cgroup.as_ref(), f),
}
}
}
#[derive(Debug)]
pub struct PairedSandbox;
impl PairedSandbox {
pub fn enter<FA, FB>(self, a_fn: FA, b_fn: FB) -> Result<(i32, i32), Error>
where
FA: FnOnce(VethEnd) -> i32,
FB: FnOnce(VethEnd) -> i32,
{
fork_veth_pair(a_fn, b_fn)
}
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use super::*;
#[test]
fn sandbox_new_enters_a_real_namespace() {
use std::fs;
let parent_netns =
fs::read_link("/proc/self/ns/net").expect("read parent /proc/self/ns/net");
let exit_code = Sandbox::new()
.enter(move || match fs::read_link("/proc/self/ns/net") {
Ok(link) if link != parent_netns => 0,
_ => 2,
})
.expect("Sandbox::new().enter should run to completion");
assert_eq!(
exit_code, 0,
"sandbox did not enter a distinct namespace (code {exit_code})"
);
}
#[test]
fn sandbox_chaos_applies_real_kernel_delay() {
use std::net::UdpSocket;
use std::time::Instant;
let netem = NetemConfig::new().delay(Duration::from_millis(200)).build();
let exit_code = Sandbox::new()
.chaos(netem)
.enter(|| {
let socket = match UdpSocket::bind("127.0.0.1:0") {
Ok(s) => s,
Err(_) => return 2,
};
let addr = match socket.local_addr() {
Ok(a) => a,
Err(_) => return 3,
};
if socket
.set_read_timeout(Some(Duration::from_secs(5)))
.is_err()
{
return 4;
}
let start = Instant::now();
if socket.send_to(b"ping", addr).is_err() {
return 5;
}
let mut buf = [0u8; 4];
if socket.recv_from(&mut buf).is_err() {
return 6;
}
if start.elapsed() >= Duration::from_millis(150) {
0
} else {
7
}
})
.expect("Sandbox::new().chaos(..).enter should run to completion");
assert_eq!(
exit_code, 0,
"did not observe the expected chaos delay (code {exit_code})"
);
}
#[test]
fn sandbox_seccomp_blocks_namespace_changes() {
use nix::sched::{CloneFlags, unshare};
let exit_code = Sandbox::new()
.seccomp(SeccompProfile::deny_namespace_changes())
.enter(|| match unshare(CloneFlags::CLONE_NEWUTS) {
Err(nix::Error::EPERM) => 0,
_ => 1,
})
.expect("Sandbox::new().seccomp(..).enter should run to completion");
assert_eq!(
exit_code, 0,
"seccomp profile did not deny CLONE_NEWUTS (code {exit_code})"
);
}
#[test]
fn sandbox_paired_carries_real_udp_traffic() {
let (a_code, b_code) = Sandbox::paired()
.enter(
|end: VethEnd| {
use std::net::UdpSocket;
let socket = match UdpSocket::bind((end.address, 0)) {
Ok(s) => s,
Err(_) => return 2,
};
if socket
.set_read_timeout(Some(Duration::from_millis(200)))
.is_err()
{
return 3;
}
let peer = (end.peer_address, 9998);
let mut buf = [0u8; 4];
for _ in 0..10 {
if socket.send_to(b"ping", peer).is_err() {
std::thread::sleep(Duration::from_millis(20));
continue;
}
match socket.recv_from(&mut buf) {
Ok((n, from))
if &buf[..n] == b"pong" && from.ip() == end.peer_address =>
{
return 0;
}
_ => continue,
}
}
4
},
|end: VethEnd| {
use std::net::UdpSocket;
let socket = match UdpSocket::bind((end.address, 9998)) {
Ok(s) => s,
Err(_) => return 2,
};
if socket
.set_read_timeout(Some(Duration::from_secs(6)))
.is_err()
{
return 3;
}
let mut buf = [0u8; 4];
loop {
match socket.recv_from(&mut buf) {
Ok((n, from)) if &buf[..n] == b"ping" => {
return if socket.send_to(b"pong", from).is_ok() {
0
} else {
4
};
}
Ok(_) => continue,
Err(_) => return 5,
}
}
},
)
.expect("Sandbox::paired().enter should run to completion");
assert_eq!(a_code, 0, "side A failed (code {a_code})");
assert_eq!(b_code, 0, "side B failed (code {b_code})");
}
}