8000 feat(minimald,sandbox2): wire net switch into live OwnIp launch path by gominimal-aw-bot[bot] · Pull Request #547 · gominimal/minimal · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions crates/minimald/src/main.rs
8000
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,7 @@ async fn async_main() -> Result<(), MainError> {
},
minimal_state_dir: cli.minimal_state_dir(),
minimal_cache_dir: cli.minimal_cache_dir(),
gvproxy_bin: None,
};
// Ensure the SSH host key is accessible in a instance-specific known_hosts file.
russh::keys::known_hosts::learn_known_hosts_path(
Expand Down
14 changes: 14 additions & 0 deletions crates/minimald/src/net/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,13 @@ impl SwitchSubnet {
}
}

/// The prefix length (the `/N` of the subnet), used to render a PTask's
/// address as CIDR when configuring its tap.
#[must_use]
pub fn prefix(self) -> u8 {
self.prefix
}

/// The network address (host bits zeroed).
#[must_use]
pub fn network(self) -> Ipv4Addr {
Expand Down Expand Up @@ -370,6 +377,13 @@ impl GvproxySwitch {
self.state_dir.join("gvproxy-api.sock")
}

/// The subnet this switch hands PTask addresses out of. The launcher needs
/// it to render a lease's CIDR and the gateway when configuring a tap.
#[must_use]
pub fn subnet(&self) -> SwitchSubnet {
self.allocator.subnet()
}

fn config_path(&self) -> PathBuf {
self.state_dir.join("gvproxy.yaml")
}
Expand Down
166 changes: 165 additions & 1 deletion crates/minimald/src/net/switch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::UnixStream;
use tokio::task::JoinHandle;

use super::DEFAULT_MTU;
use super::{DEFAULT_MTU, PtaskLease, SwitchSubnet};

/// `ioctl` request number for `TUNSETIFF` (set the tap/tun interface a fd backs).
///
Expand Down Expand Up @@ -115,6 +115,131 @@ pub fn open_tap(name: &str) -> io::Result<OwnedFd> {
Ok(tap)
}

/// The `ip`/`nsenter` command lines that move an opened tap into the network
/// namespace of `netns_pid` and configure it there as an `OwnIp` PTask's switch
/// interface (set the lease MAC, assign the lease address within `subnet`, bring
/// the interface and loopback up, install a default route via the switch
/// gateway).
///
/// Each command is returned as an argv vector rather than executed, so the two
/// callers can run them under the privileges they have: the daemon
/// ([`move_tap_into_netns`]) execs them directly with `CAP_NET_ADMIN`, while the
/// unprivileged `ci-netns.yml` proof wraps each in `sudo`. Single-sourcing the
/// command construction keeps the proof driving the same wiring the daemon does.
///
/// The namespace is identified by PID, addressing `/proc/<pid>/ns/net` — the
/// namespace `sandbox2` unshared for the PTask, surfaced to the launcher via the
/// `hakoniwa::Child`'s PID.
#[must_use]
pub fn tap_netns_commands(
tap: &str,
netns_pid: u32,
lease: PtaskLease,
subnet: SwitchSubnet,
) -> Vec<Vec<String>> {
let pid = netns_pid.to_string();
let mac = lease.mac.to_string();
let cidr = format!("{}/{}", lease.ip, subnet.prefix());
let gw = subnet.gateway().to_string();

// Enter the PTask's net namespace (by PID) to run an `ip` subcommand there.
let nsenter = |args: &[&str]| -> Vec<String> {
["nsenter", "-t", &pid, "-n"]
.into_iter()
.chain(args.iter().copied())
.map(str::to_string)
.collect()
};

vec![
// Move the interface into the PTask's namespace (run in the host ns).
["ip", "link", "set", tap, "netns", &pid]
.into_iter()
.map(str::to_string)
.collect(),
// Configure it inside that namespace, mirroring the gvproxy spike's
// static-lease recipe.
nsenter(&["ip", "link", "set", tap, "address", &mac]),
nsenter(&["ip", "addr", "add", &cidr, "dev", tap]),
nsenter(&["ip", "link", "set", tap, "up"]),
nsenter(&["ip", "link", "set", "lo", "up"]),
nsenter(&["ip", "route", "add", "default", "via", &gw]),
]
}

/// Moves the opened tap `tap` into the PTask network namespace held by
/// `netns_pid` and configures its switch address there, by execing the
/// [`tap_netns_commands`] directly. The host-side tap fd keeps working after the
/// interface moves namespaces, which is what [`attach_to_switch`] relays on.
///
/// Run on the `minimald` (daemon) side; requires `CAP_NET_ADMIN` in the host
/// namespace. `sandbox2` never calls this — it only unshares the namespace and
/// surfaces the PID (no dependency cycle).
///
/// # Errors
///
/// Returns an error if `ip`/`nsenter` cannot be spawned or any command exits
/// non-zero, naming the failing command line.
/// Trusted directories (and the `PATH` handed to the children) searched for the
/// privileged `ip`/`nsenter` binaries, ordered most- to least-specific. Using a
/// fixed list instead of the inherited `PATH` is what keeps a tampered `PATH`
/// from shadowing them when they exec with `CAP_NET_ADMIN`.
const TRUSTED_EXEC_PATH: &str = "/usr/sbin:/sbin:/usr/bin:/bin";

/// Resolves `program` to an absolute path under [`TRUSTED_EXEC_PATH`]. Falls
/// back to the bare name if it is in none of those directories (an unusual
/// layout still works, just without the hardening).
fn trusted_program(program: &str) -> String {
for dir in TRUSTED_EXEC_PATH.split(':') {
let candidate = std::path::Path::new(dir).join(program);
if candidate.exists() {
return candidate.to_string_lossy().into_owned();
}
}
program.to_string()
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LOW · security — When trusted_program returns a bare name (the fallback for unusual layouts), Command::new(bare_name) resolves the executable using the parent process's PATH environment variable, not TRUSTED_EXEC_PATH. The .env("PATH", TRUSTED_EXEC_PATH) call on the Command is the child's environment — it applies to programs the child invokes (e.g. the ip that nsenter -n re-execs inside the PTask namespace), not to the initial exec lookup. A tampered parent PATH in this fallback branch could shadow ip or nsenter at CAP_NET_ADMIN.

The code comment correctly notes "just without the hardening" and in practice ip / nsenter will be under /sbin or /usr/sbin on every standard Linux distribution, so the fallback is rare. No change is strictly required, but extending the comment to clarify that .env("PATH", ...) does not protect the initial exec lookup (only the child's inner calls) would prevent a future maintainer from assuming full coverage when the fallback fires.

}

pub async fn move_tap_into_netns(
tap: &str,
netns_pid: u32,
lease: PtaskLease,
subnet: SwitchSubnet,
) -> io::Result<()> {
for (index, argv) in tap_netns_commands(tap, netns_pid, lease, subnet)
.into_iter()
.enumerate()
{
let (program, rest) = argv
.split_first()
.expect("tap_netns_commands never yields an empty argv");
// These run with `CAP_NET_ADMIN` in the host namespace, so resolve the
// binary against a fixed trusted directory list rather than an inherited
// `PATH` (a malicious `ip`/`nsenter` shadow placed early in `PATH` would
// otherwise execute at that capability). The pinned `PATH` covers the
// inner `ip` that `nsenter -n` execs inside the PTask namespace, which
// resolves against this child's environment.
let status = tokio::process::Command::new(trusted_program(program))
.args(rest)
.env("PATH", TRUSTED_EXEC_PATH)
.status()
.await?;
if !status.success() {
// Command 0 moves the tap into the PTask namespace; the rest
// configure it there, so name the phase the failing command is in.
let phase = if index == 0 {
"moving PTask tap into its namespace"
} else {
"configuring PTask tap"
};
return Err(io::Error::other(format!(
"{phase} failed (`{}` exited with {status})",
argv.join(" ")
)));
}
}
Ok(())
}

/// Sets `O_NONBLOCK` on `fd` so the tap device can be epoll-driven via
/// [`AsyncFd`]. `std::fs::File` has no `set_nonblocking`, so this goes through
/// `fcntl` directly.
Expand Down Expand Up @@ -296,4 +421,43 @@ mod tests {
let err = open_tap("this-name-is-way-too-long").unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
}

#[test]
fn tap_netns_commands_move_then_configure_by_pid() {
use std::net::Ipv4Addr;

let lease = PtaskLease {
ip: Ipv4Addr::new(100, 64, 0, 2),
mac: super::super::MacAddr::for_switch_ip(Ipv4Addr::new(100, 64, 0, 2)),
};
let cmds = tap_netns_commands("mtap0_2", 4321, lease, SwitchSubnet::default());

// First the interface is moved into the PTask's namespace by PID; every
// later command enters that namespace via `nsenter -t <pid> -n`.
assert_eq!(cmds[0], ["ip", "link", "set", "mtap0_2", "netns", "4321"]);
assert!(
cmds[1..]
.iter()
.all(|c| c[..4] == ["nsenter", "-t", "4321", "-n"])
);

// The lease's address is configured as CIDR with the subnet prefix, and
// the default route points at the switch gateway.
let joined: Vec<String> = cmds.iter().map(|c| c.join(" ")).collect();
assert!(
joined
.iter()
.any(|c| c.ends_with("ip addr add 100.64.0.2/16 dev mtap0_2"))
);
assert!(
joined
.iter()
.any(|c| c.ends_with("ip route add default via 100.64.0.1"))
);
assert!(
joined
.iter()
.any(|c| c.contains(&format!("address {}", lease.mac)))
);
}
}
30 changes: 29 additions & 1 deletion crates/minimald/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,32 @@ pub enum HostKey {
},
}

/// Default install path for the gvproxy ("gvisor-tap-vsock") switch binary,
/// used when [`Config::gvproxy_bin`] is unset. The `GVPROXY_BIN` env var is
/// scoped to the `#[ignore]` netns proof and is never consulted by the daemon.
const DEFAULT_GVPROXY_BIN: &str = "/usr/lib/minimal/bin/gvproxy";

/// Global Configuration for the minimald server.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Config {
pub host_key: HostKey,
pub minimal_state_dir: DaemonAbsPath,
pub minimal_cache_dir: DaemonAbsPath,
/// Path to the gvproxy binary backing the per-host `OwnIp` switch. Defaults
/// to [`DEFAULT_GVPROXY_BIN`] when unset.
#[serde(default)]
pub gvproxy_bin: Option<PathBuf>,
}

impl Config {
/// Resolves the configured gvproxy binary path, falling back to the fixed
/// install path when unset.
fn gvproxy_bin_path(&self) -> PathBuf {
self.gvproxy_bin
.clone()
.unwrap_or_else(|| PathBuf::from(DEFAULT_GVPROXY_BIN))
}

/// Returns the SSH host key to use.
///
/// For [`HostKey`] variant `OnDisk{ create_on_missing: true, ..}`,
Expand Down Expand Up @@ -83,9 +100,20 @@ impl ServerState {
pub async fn new(config: Config) -> Result<Self, std::io::Error> {
let minimal_state_dir = config.minimal_state_dir.clone();
let minimal_cache_dir = config.minimal_cache_dir.clone();
// Construct the per-host switch once, here at daemon scope, so a single
// gvproxy runs for the host and a single allocator never reuses an
// address for the daemon's lifetime (R1.4/R1.6). Its config/socket/pid
// live under a dedicated subdir of the daemon state dir. The shared
// `Arc` is the single source of truth, injected into every per-launch
// `SandboxLauncher` through the sessions manager.
let net_switch = Arc::new(Mutex::new(crate::net::GvproxySwitch::new(
config.gvproxy_bin_path(),
minimal_state_dir.as_utf8_path().join("gvproxy"),
)));
Ok(Self {
sessions: sessions::Manager::init(minimal_state_dir, minimal_cache_dir, net_switch)
.await?,
config,
sessions: sessions::Manager::init(minimal_state_dir, minimal_cache_dir).await?,
host_key: None,
})
}
Expand Down
14 changes: 13 additions & 1 deletion crates/minimald/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ use russh::{Channel, server::Msg};
use sessions::{Record, store::SessionObject};
use std::fmt::{self};
use std::ops::ControlFlow;
use tokio::sync::{mpsc, oneshot};
use std::sync::Arc;
use tokio::sync::{Mutex, mpsc, oneshot};
use tokio::task::JoinHandle;

/// An error that occurred when attaching to a running session/its-shell.
Expand Down Expand Up @@ -66,6 +67,14 @@ pub struct Session<S: SessionObject> {
minimal_cache_dir: DaemonAbsPath,
session: S,

/// The daemon-scoped gvproxy switch, injected into each `SandboxLauncher`
/// this session mints so an `OwnIp` PTask attaches to the one per-host
/// switch (R1.5). Read only by the production `session_launcher`
/// (`cfg(not(test))`); the `cfg(test)` mock launcher ignores it, so the
/// unused-field lint is silenced under test rather than threaded through.
#[cfg_attr(test, allow(dead_code))]
net_switch: Arc<Mutex<crate::net::GvproxySwitch>>,

/// The running host, if minted, paired with the `JoinHandle` of its runtime
/// loop so teardown can be awaited on destroy.
host: Option<(
Expand All @@ -80,6 +89,7 @@ impl<S: SessionObject> Session<S> {
minimal_state_dir: DaemonAbsPath,
minimal_cache_dir: DaemonAbsPath,
session: S,
net_switch: Arc<Mutex<crate::net::GvproxySwitch>>,
) -> Result<SessionHandle, std::io::Error> {
std::fs::create_dir_all(session.workspace_path())?;
std::fs::create_dir_all(session.home_path())?;
Expand All @@ -92,6 +102,7 @@ impl<S: SessionObject> Session<S> {
session,
minimal_state_dir,
minimal_cache_dir,
net_switch,
};

tokio::spawn(mngr.mainloop());
Expand Down Expand Up @@ -234,6 +245,7 @@ impl<S: SessionObject> Session<S> {
Ok(session_host::SandboxLauncher {
ctx: self.context().map_err(AttachError::ContextCreationFailed)?,
network_mode: self.session.record().network,
net_switch: Arc::clone(&self.net_switch),
session,
})
}
Expand Down
Loading
Loading
0