pub mod dns;
mod nftables;
mod resources;
mod seccomp;
#[cfg(target_os = "linux")]
pub mod docker;
use super::Jail;
use super::JailConfig;
use crate::sys_resource::{ManagedResource, SystemResource};
use anyhow::{Context, Result};
use resources::{NFTable, NetnsResolv, NetworkNamespace, VethPair};
use std::os::unix::process::CommandExt;
use std::process::{Command, ExitStatus};
use tracing::{debug, info, warn};
pub fn format_ip(ip: [u8; 4]) -> String {
format!("{}.{}.{}.{}", ip[0], ip[1], ip[2], ip[3])
}
pub struct LinuxJail {
config: JailConfig,
netns_resolv: Option<ManagedResource<NetnsResolv>>,
nftables: Option<ManagedResource<NFTable>>,
veth_pair: Option<ManagedResource<VethPair>>,
namespace: Option<ManagedResource<NetworkNamespace>>,
host_dns_server: Option<dns::DummyDnsServer>,
host_ip: [u8; 4],
host_cidr: String,
guest_cidr: String,
subnet_cidr: String,
}
impl LinuxJail {
fn validate_invoking_user() -> Result<()> {
let uid = std::env::var("SUDO_UID")
.ok()
.and_then(|value| value.parse::<u32>().ok());
let gid = std::env::var("SUDO_GID")
.ok()
.and_then(|value| value.parse::<u32>().ok());
anyhow::ensure!(
uid.is_some_and(|uid| uid != 0) && gid.is_some(),
"Linux strong mode requires sudo from a non-root user"
);
Ok(())
}
fn build_command(&self, command: &[String], extra_env: &[(String, String)]) -> Result<Command> {
if command.is_empty() {
anyhow::bail!("No command specified");
}
debug!(
"Executing command in namespace {}: {:?}",
self.namespace_name(),
command
);
let current_uid = unsafe { libc::getuid() };
let drop_privs = if current_uid == 0 {
match (std::env::var("SUDO_UID"), std::env::var("SUDO_GID")) {
(Ok(uid), Ok(gid))
if uid.parse::<u32>().is_ok_and(|uid| uid != 0)
&& gid.parse::<u32>().is_ok() =>
{
debug!(
"Will drop privileges to uid={} gid={} after entering namespace",
uid, gid
);
Some((uid, gid))
}
_ => {
anyhow::bail!(
"Linux strong mode requires sudo from a non-root user so the command cannot alter its own network policy"
);
}
}
} else {
None
};
let mut cmd = Command::new("/usr/sbin/ip");
cmd.args([
"netns",
"exec",
&self.namespace_name(),
"/usr/bin/unshare",
"--pid",
"--fork",
"--kill-child=SIGKILL",
"--mount-proc",
]);
if let Some((uid, gid)) = drop_privs {
cmd.arg("/usr/bin/setpriv");
cmd.arg("--no-new-privs");
cmd.arg(format!("--reuid={}", uid));
cmd.arg(format!("--regid={}", gid));
cmd.arg("--clear-groups");
cmd.arg("--");
}
for arg in command {
cmd.arg(arg);
}
for (key, value) in extra_env {
cmd.env(key, value);
}
if let Ok(sudo_user) = std::env::var("SUDO_USER") {
cmd.env("SUDO_USER", sudo_user);
}
if let Ok(sudo_uid) = std::env::var("SUDO_UID") {
cmd.env("SUDO_UID", sudo_uid);
}
if let Ok(sudo_gid) = std::env::var("SUDO_GID") {
cmd.env("SUDO_GID", sudo_gid);
}
debug!("Executing command: {:?}", cmd);
unsafe { cmd.pre_exec(seccomp::block_unix_sockets) };
Ok(cmd)
}
pub fn new(config: JailConfig) -> Result<Self> {
let (host_ip, host_cidr, guest_cidr, subnet_cidr) =
Self::compute_subnet_for_jail(&config.jail_id);
Ok(Self {
config,
netns_resolv: None,
nftables: None,
veth_pair: None,
namespace: None,
host_dns_server: None,
host_ip,
host_cidr,
guest_cidr,
subnet_cidr,
})
}
fn check_root() -> Result<()> {
#[cfg(target_os = "linux")]
let uid = unsafe { libc::getuid() };
#[cfg(not(target_os = "linux"))]
let uid = 1000;
if uid != 0 {
anyhow::bail!(
"Network namespace operations require root access. Please run with sudo."
);
}
Ok(())
}
fn namespace_name(&self) -> String {
format!("httpjail_{}", self.config.jail_id)
}
fn veth_host(&self) -> String {
format!("vh_{}", self.config.jail_id)
}
fn veth_ns(&self) -> String {
format!("vn_{}", self.config.jail_id)
}
fn compute_subnet_for_jail(jail_id: &str) -> ([u8; 4], String, String, String) {
use std::hash::{Hash, Hasher};
let mut hasher = std::collections::hash_map::DefaultHasher::new();
jail_id.hash(&mut hasher);
let h = hasher.finish();
let idx = (h % 16384) as u32; let base = idx * 4; let third = ((base >> 8) & 0xFF) as u8;
let fourth = (base & 0xFF) as u8;
let network = [10u8, 99u8, third, fourth];
let host_ip = [
network[0],
network[1],
network[2],
network[3].saturating_add(1),
];
let guest_ip = [
network[0],
network[1],
network[2],
network[3].saturating_add(2),
];
let host_cidr = format!("{}/30", format_ip(host_ip));
let guest_cidr = format!("{}/30", format_ip(guest_ip));
let subnet_cidr = format!("{}/30", format_ip(network));
(host_ip, host_cidr, guest_cidr, subnet_cidr)
}
pub fn compute_host_ip_for_jail_id(jail_id: &str) -> [u8; 4] {
let (host_ip, _host_cidr, _guest_cidr, _subnet_cidr) =
Self::compute_subnet_for_jail(jail_id);
host_ip
}
fn create_namespace(&mut self) -> Result<()> {
self.namespace = Some(ManagedResource::<NetworkNamespace>::create(
&self.config.jail_id,
)?);
info!("Created network namespace: {}", self.namespace_name());
Ok(())
}
fn setup_veth_pair(&mut self) -> Result<()> {
self.veth_pair = Some(ManagedResource::<VethPair>::create(&self.config.jail_id)?);
debug!(
"Created veth pair: {} <-> {}",
self.veth_host(),
self.veth_ns()
);
let output = Command::new("/usr/sbin/ip")
.args([
"link",
"set",
&self.veth_ns(),
"netns",
&self.namespace_name(),
])
.output()
.context("Failed to move veth to namespace")?;
if !output.status.success() {
anyhow::bail!(
"Failed to move veth to namespace: {}",
String::from_utf8_lossy(&output.stderr)
);
}
Ok(())
}
fn configure_namespace_networking(&self) -> Result<()> {
let namespace_name = self.namespace_name();
let veth_ns = self.veth_ns();
let host_ip = format_ip(self.host_ip);
let commands = vec![
vec!["/usr/sbin/ip", "link", "set", "lo", "up"],
vec![
"/usr/sbin/ip",
"addr",
"add",
&self.guest_cidr,
"dev",
&veth_ns,
],
vec!["/usr/sbin/ip", "link", "set", &veth_ns, "up"],
vec!["/usr/sbin/ip", "route", "add", "default", "via", &host_ip],
];
for cmd_args in commands {
let mut cmd = Command::new("/usr/sbin/ip");
cmd.args(["netns", "exec", &namespace_name]);
cmd.args(&cmd_args);
debug!("Executing in namespace: {:?}", cmd);
let output = cmd.output().context(format!(
"Failed to execute: ip netns exec {} {:?}",
namespace_name, cmd_args
))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
anyhow::bail!(
"Failed to configure namespace networking ({}): {}",
cmd_args.join(" "),
stderr
);
}
}
let mut verify_cmd = Command::new("/usr/sbin/ip");
verify_cmd.args([
"netns",
"exec",
&namespace_name,
"/usr/sbin/ip",
"route",
"show",
]);
if let Ok(output) = verify_cmd.output() {
let routes = String::from_utf8_lossy(&output.stdout);
info!(
"Routes in namespace {} after configuration:\n{}",
namespace_name, routes
);
if !routes.contains(&host_ip) && !routes.contains("default") {
warn!(
"WARNING: No route to host {} found in namespace. Network may not work properly.",
host_ip
);
}
}
debug!("Configured networking inside namespace {}", namespace_name);
Ok(())
}
fn configure_host_networking(&self) -> Result<()> {
let veth_host = self.veth_host();
let commands = vec![
vec!["addr", "add", &self.host_cidr, "dev", &veth_host],
vec!["link", "set", &veth_host, "up"],
];
for cmd_args in commands {
let output = Command::new("/usr/sbin/ip")
.args(&cmd_args)
.output()
.context(format!("Failed to execute: ip {:?}", cmd_args))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
if !stderr.contains("File exists") {
anyhow::bail!(
"Failed to configure host networking (ip {}): {}",
cmd_args.join(" "),
stderr
);
}
}
}
debug!("Configured host side networking for {}", veth_host);
Ok(())
}
fn setup_namespace_nftables(&self) -> Result<()> {
let namespace_name = self.namespace_name();
let host_ip = format_ip(self.host_ip);
let _table = nftables::NFTable::new_namespace_table_with_dns(
&namespace_name,
&host_ip,
self.config.http_proxy_port,
self.config.https_proxy_port,
53, )?;
std::mem::forget(_table);
Ok(())
}
fn setup_host_nat(&mut self) -> Result<()> {
let mut nftable = ManagedResource::<NFTable>::create(&self.config.jail_id)?;
if let Some(table_wrapper) = nftable.inner_mut() {
let table = nftables::NFTable::new_host_table(
&self.config.jail_id,
&self.subnet_cidr,
self.config.http_proxy_port,
self.config.https_proxy_port,
)?;
table_wrapper.set_table(table);
info!(
"Set up NAT rules for namespace {} with subnet {}",
self.namespace_name(),
self.subnet_cidr
);
}
self.nftables = Some(nftable);
Ok(())
}
fn start_dns_server(&mut self) -> Result<()> {
let host_ip_str = format!(
"{}.{}.{}.{}",
self.host_ip[0], self.host_ip[1], self.host_ip[2], self.host_ip[3]
);
info!(
"Creating /etc/netns resolv.conf with nameserver {}",
host_ip_str
);
let netns_resolv = NetnsResolv::create_with_nameserver(&self.config.jail_id, &host_ip_str)
.context("Failed to create /etc/netns resolv.conf")?;
self.netns_resolv = Some(ManagedResource::from_resource(netns_resolv));
info!("Starting host DNS server on {}", host_ip_str);
let mut host_server = dns::DummyDnsServer::new();
let host_addr = format!("{}:53", host_ip_str);
host_server
.start(&host_addr)
.context("Failed to start host DNS server")?;
info!("Started host DNS server on {}", host_addr);
self.host_dns_server = Some(host_server);
Ok(())
}
fn stop_dns_server(&mut self) {
if let Some(_server) = self.host_dns_server.take() {
debug!("Stopping host DNS server (cleanup on drop)");
}
}
}
impl Drop for LinuxJail {
fn drop(&mut self) {
self.stop_dns_server();
}
}
impl Jail for LinuxJail {
fn setup(&mut self, _proxy_port: u16) -> Result<()> {
Self::check_root()?;
Self::validate_invoking_user()?;
self.create_namespace()?;
self.setup_veth_pair()?;
self.configure_host_networking()?;
self.configure_namespace_networking()?;
self.start_dns_server()?;
self.setup_host_nat()?;
self.setup_namespace_nftables()?;
info!(
"Linux jail setup complete using namespace {} with HTTP proxy on port {} and HTTPS proxy on port {}",
self.namespace_name(),
self.config.http_proxy_port,
self.config.https_proxy_port
);
Ok(())
}
fn execute(&self, command: &[String], extra_env: &[(String, String)]) -> Result<ExitStatus> {
super::run_command(self.build_command(command, extra_env)?, None)
}
fn execute_with_timeout(
&self,
command: &[String],
extra_env: &[(String, String)],
timeout: std::time::Duration,
) -> Result<ExitStatus> {
super::run_command(self.build_command(command, extra_env)?, Some(timeout))
}
fn cleanup(&self) -> Result<()> {
info!("Triggering jail cleanup for {}", self.config.jail_id);
Self::cleanup_orphaned(&self.config.jail_id)?;
Ok(())
}
fn jail_id(&self) -> &str {
&self.config.jail_id
}
fn cleanup_orphaned(jail_id: &str) -> Result<()>
where
Self: Sized,
{
debug!("Cleaning up orphaned Linux jail: {}", jail_id);
NetnsResolv::for_existing(jail_id).cleanup()?;
NFTable::for_existing(jail_id).cleanup()?;
VethPair::for_existing(jail_id).cleanup()?;
NetworkNamespace::for_existing(jail_id).cleanup()?;
Ok(())
}
}
impl Clone for LinuxJail {
fn clone(&self) -> Self {
Self {
config: self.config.clone(),
netns_resolv: None,
nftables: None,
veth_pair: None,
namespace: None,
host_dns_server: None,
host_ip: self.host_ip,
host_cidr: self.host_cidr.clone(),
guest_cidr: self.guest_cidr.clone(),
subnet_cidr: self.subnet_cidr.clone(),
}
}
}