Linux / WSL 2: harden netns lock, container socket gate, and Host routing (#970)
This commit is contained in:
1 parent
2ccef3e96a
commit
e8acc5d9ab
8 files changed
+710
-136
No files matched your search
@@ -134,6 +134,7 @@ fn serve_loop(mut conn: File, paths: &Paths, procs: &mut HashMap<libc::pid_t, Pr
|
||||
// and interfaces/routes (foreign bridges, default-route bridges, VPNs) may appear or change.
|
||||
let firewall = if host_process { net::firewall_events() } else { None };
|
||||
let link_events = if host_process { net::link_route_events() } else { None };
|
||||
let netns_lock = if host_process { net::netns_lock_fd() } else { None };
|
||||
let mut bridges = Bridges::default();
|
||||
// In the VM, lookups the gateway's resolver fails go through the host.
|
||||
let mut dns = super::dns::Dns::default();
|
||||
@@ -198,6 +199,7 @@ fn serve_loop(mut conn: File, paths: &Paths, procs: &mut HashMap<libc::pid_t, Pr
|
||||
fds.push(libc::pollfd { fd: term.as_ref().map_or(-1, |f| f.as_raw_fd()), events: libc::POLLIN, revents: 0 });
|
||||
fds.push(libc::pollfd { fd: firewall.as_ref().map_or(-1, |f| f.as_raw_fd()), events: libc::POLLIN, revents: 0 });
|
||||
fds.push(libc::pollfd { fd: link_events.as_ref().map_or(-1, |f| f.as_raw_fd()), events: libc::POLLIN, revents: 0 });
|
||||
fds.push(libc::pollfd { fd: netns_lock.unwrap_or(-1), events: libc::POLLIN, revents: 0 });
|
||||
fds.push(libc::pollfd { fd: measuring.as_ref().map_or(-1, super::usage::Job::fd), events: libc::POLLIN, revents: 0 });
|
||||
super::copy::interest(&mut fds);
|
||||
for r in &relays {
|
||||
@@ -286,6 +288,10 @@ fn serve_loop(mut conn: File, paths: &Paths, procs: &mut HashMap<libc::pid_t, Pr
|
||||
net::link_route_changed(l);
|
||||
continue;
|
||||
}
|
||||
if netns_lock == Some(pfd.fd) {
|
||||
net::drain_netns_lock(pfd.fd);
|
||||
continue;
|
||||
}
|
||||
if measuring.as_ref().is_some_and(|j| j.fd() == pfd.fd) {
|
||||
// The child is reaped like any other (`reap`).
|
||||
if let Some(lines) = measuring.as_mut().and_then(super::usage::Job::read) {
|
||||
|
||||
@@ -222,9 +222,14 @@ fn mount_kernel_filesystems() -> io::Result<()> {
|
||||
fn host_dirs() -> io::Result<container::Paths> {
|
||||
// SAFETY: umask only changes this process's file-creation mask.
|
||||
unsafe { libc::umask(0o022) };
|
||||
// Claim the network namespace BEFORE touching `/var/lib/kiri` mounts so a
|
||||
// second engine never detaches a running engine's mount before failing.
|
||||
net::claim_host_netns()?;
|
||||
let root = PathBuf::from(DATA);
|
||||
if let Some(data) = std::env::var_os("KIRI_AGENT_DATA").map(PathBuf::from).filter(|p| p.is_absolute() && p != &root) {
|
||||
mount_agent_data(&data, &root)?;
|
||||
} else {
|
||||
detach_deleted_bind_mount(&root);
|
||||
}
|
||||
if let Some(kind) = sys::detect_readonly_fs(&root) {
|
||||
return Err(sys::readonly_storage_error(kind));
|
||||
@@ -250,7 +255,6 @@ fn host_dirs() -> io::Result<container::Paths> {
|
||||
}
|
||||
};
|
||||
take_over(&root, leftovers)?;
|
||||
net::claim_host_netns()?;
|
||||
let (cgroup_root, cgroup) = host_cgroup()?;
|
||||
let paths = container::Paths {
|
||||
layers: root.join("layers"),
|
||||
@@ -299,6 +303,32 @@ fn mount_agent_data(src: &std::path::Path, target: &std::path::Path) -> io::Resu
|
||||
check(unsafe { libc::mount(c_src.as_ptr(), c_target.as_ptr(), std::ptr::null(), libc::MS_BIND, std::ptr::null()) } as _, "bind-mount KIRI_AGENT_DATA").map(drop)
|
||||
}
|
||||
|
||||
/// If `target` (`/var/lib/kiri`) is currently covered by a stale bind mount
|
||||
/// whose backing directory was deleted (`st_nlink == 0`), detaches it so
|
||||
/// `create_dir_all` can use the underlying `/var/lib/kiri` directory instead
|
||||
/// of failing with `ENOENT`. Real filesystem roots always have `st_nlink >= 2`.
|
||||
fn detach_deleted_bind_mount(target: &std::path::Path) {
|
||||
use std::ffi::CString;
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
let Ok(c_target) = CString::new(target.as_os_str().as_bytes()) else { return };
|
||||
for _ in 0..4 {
|
||||
let Ok(md) = std::fs::symlink_metadata(target) else { break };
|
||||
if md.file_type().is_symlink() || md.nlink() != 0 {
|
||||
break;
|
||||
}
|
||||
if !std::fs::read_to_string("/proc/self/mountinfo").is_ok_and(|m| is_mounted_at(&m, target)) {
|
||||
break;
|
||||
}
|
||||
// SAFETY: valid NUL-terminated non-symlink mountpoint; `UMOUNT_NOFOLLOW`
|
||||
// prevents following any racing symlink replacement.
|
||||
if unsafe { libc::umount2(c_target.as_ptr(), libc::MNT_DETACH | libc::UMOUNT_NOFOLLOW) } != 0 {
|
||||
eprintln!("kiri-init: detach deleted bind mount on {}: {}", target.display(), io::Error::last_os_error());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `/proc/self/mountinfo` lists a mount whose target is `target`.
|
||||
fn is_mounted_at(mountinfo: &str, target: &std::path::Path) -> bool {
|
||||
let want = target.to_string_lossy();
|
||||
|
||||
@@ -297,20 +297,31 @@ fn make_abstract_sockaddr(name: &[u8]) -> io::Result<(libc::sockaddr_un, libc::s
|
||||
Ok((addr, addr_len))
|
||||
}
|
||||
|
||||
/// Checks whether an active listener on `name` belongs to `owner` (prevents an
|
||||
/// unprivileged local process from squatting the abstract socket name to deny
|
||||
/// service to a root `kiri-init`).
|
||||
fn abstract_lock_owned_by(name: &[u8], owner: u32) -> bool {
|
||||
let Ok((addr, addr_len)) = make_abstract_sockaddr(name) else { return false };
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum LockProbe {
|
||||
/// Connected and `SO_PEERCRED.uid == owner`.
|
||||
OwnedByOwner,
|
||||
/// Connected and `SO_PEERCRED.uid != owner` (unprivileged squatter).
|
||||
OwnedByOther,
|
||||
/// `connect()` failed transiently (`EAGAIN` backlog full, `ECONNREFUSED`
|
||||
/// bind-to-listen window or closing holder, `EINTR`, etc.). Never treated
|
||||
/// as an unprivileged squatter.
|
||||
TransientBusy,
|
||||
}
|
||||
|
||||
/// Probes an active listener on `name` to distinguish a legitimate `owner`
|
||||
/// engine from an unprivileged squatter or transient backlog/startup state.
|
||||
fn probe_abstract_lock(name: &[u8], owner: u32) -> LockProbe {
|
||||
let Ok((addr, addr_len)) = make_abstract_sockaddr(name) else { return LockProbe::TransientBusy };
|
||||
let raw = unsafe { libc::socket(libc::AF_UNIX, libc::SOCK_STREAM | libc::SOCK_CLOEXEC | libc::SOCK_NONBLOCK, 0) };
|
||||
if raw < 0 {
|
||||
return false;
|
||||
return LockProbe::TransientBusy;
|
||||
}
|
||||
// SAFETY: `raw` is a freshly created socket descriptor owned here.
|
||||
let fd = unsafe { OwnedFd::from_raw_fd(raw) };
|
||||
// SAFETY: `addr` is initialized through `addr_len` bytes.
|
||||
if unsafe { libc::connect(fd.as_raw_fd(), (&raw const addr).cast(), addr_len) } != 0 {
|
||||
return false;
|
||||
return LockProbe::TransientBusy;
|
||||
}
|
||||
// SAFETY: zeroed `ucred` is valid for `getsockopt(SO_PEERCRED)`.
|
||||
let mut peer: libc::ucred = unsafe { std::mem::zeroed() };
|
||||
@@ -324,12 +335,19 @@ fn abstract_lock_owned_by(name: &[u8], owner: u32) -> bool {
|
||||
&mut len,
|
||||
)
|
||||
};
|
||||
rc == 0 && len == std::mem::size_of::<libc::ucred>() as libc::socklen_t && peer.uid == owner
|
||||
if rc != 0 || len != std::mem::size_of::<libc::ucred>() as libc::socklen_t {
|
||||
return LockProbe::TransientBusy;
|
||||
}
|
||||
if peer.uid == owner {
|
||||
LockProbe::OwnedByOwner
|
||||
} else {
|
||||
LockProbe::OwnedByOther
|
||||
}
|
||||
}
|
||||
|
||||
fn try_bind_abstract_socket(name: &[u8]) -> Result<OwnedFd, i32> {
|
||||
let (addr, addr_len) = make_abstract_sockaddr(name).map_err(|_| libc::EINVAL)?;
|
||||
let raw = unsafe { libc::socket(libc::AF_UNIX, libc::SOCK_STREAM | libc::SOCK_CLOEXEC, 0) };
|
||||
let raw = unsafe { libc::socket(libc::AF_UNIX, libc::SOCK_STREAM | libc::SOCK_CLOEXEC | libc::SOCK_NONBLOCK, 0) };
|
||||
if raw < 0 {
|
||||
return Err(io::Error::last_os_error().raw_os_error().unwrap_or(libc::EIO));
|
||||
}
|
||||
@@ -339,49 +357,108 @@ fn try_bind_abstract_socket(name: &[u8]) -> Result<OwnedFd, i32> {
|
||||
if unsafe { libc::bind(fd.as_raw_fd(), (&raw const addr).cast(), addr_len) } != 0 {
|
||||
return Err(io::Error::last_os_error().raw_os_error().unwrap_or(libc::EIO));
|
||||
}
|
||||
// Listen so peer engines can verify ownership without `accept()`.
|
||||
// SAFETY: `fd` is a bound `SOCK_STREAM` socket owned here.
|
||||
let _ = unsafe { libc::listen(fd.as_raw_fd(), 16) };
|
||||
if unsafe { libc::listen(fd.as_raw_fd(), 128) } != 0 {
|
||||
return Err(io::Error::last_os_error().raw_os_error().unwrap_or(libc::EIO));
|
||||
}
|
||||
Ok(fd)
|
||||
}
|
||||
|
||||
/// Descriptor of the held abstract netns lock socket, polled by the
|
||||
/// single-threaded `agent::serve_loop` (`kiri-init` never spawns threads, so
|
||||
/// `signalfd` and `clone3` stay single-threaded).
|
||||
pub fn netns_lock_fd() -> Option<std::os::fd::RawFd> {
|
||||
HOST_NETNS_LOCK.get().map(AsRawFd::as_raw_fd)
|
||||
}
|
||||
|
||||
/// Drains up to 64 pending `SO_PEERCRED` probe connections per `poll()` tick so
|
||||
/// `sk_max_ack_backlog` does not fill under normal retries while a local
|
||||
/// `connect()` flood can never starve `agent::serve_loop`.
|
||||
pub fn drain_netns_lock(fd: std::os::fd::RawFd) {
|
||||
for _ in 0..64 {
|
||||
// SAFETY: `fd` is a non-blocking listening `AF_UNIX` socket.
|
||||
let cfd = unsafe { libc::accept4(fd, std::ptr::null_mut(), std::ptr::null_mut(), libc::SOCK_CLOEXEC | libc::SOCK_NONBLOCK) };
|
||||
if cfd >= 0 {
|
||||
// SAFETY: `cfd` is a freshly accepted descriptor owned here.
|
||||
unsafe { libc::close(cfd) };
|
||||
continue;
|
||||
}
|
||||
let err = io::Error::last_os_error().raw_os_error().unwrap_or(libc::EAGAIN);
|
||||
if err == libc::EMFILE || err == libc::ENFILE {
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const NETNS_BUSY_MSG: &str =
|
||||
"another Kiri engine is already running in this network namespace (for example in another WSL 2 distribution): stop it first";
|
||||
const MAX_NETNS_LOCK_SLOTS: usize = 64;
|
||||
|
||||
fn netns_slot_name(base: &[u8], idx: usize) -> Vec<u8> {
|
||||
if idx == 0 {
|
||||
base.to_vec()
|
||||
} else {
|
||||
let mut v = Vec::with_capacity(base.len() + 8);
|
||||
v.extend_from_slice(base);
|
||||
v.extend_from_slice(format!("-{idx}").as_bytes());
|
||||
v
|
||||
}
|
||||
}
|
||||
|
||||
/// Claims ownership of Kiri's bridge and firewall tables in the current Linux
|
||||
/// network namespace (#443). All WSL 2 distributions share one network
|
||||
/// namespace; refusing early prevents a second engine from overwriting
|
||||
/// `nft table ip kiri` or deleting `kiri0` when stopping.
|
||||
pub fn claim_host_netns() -> io::Result<()> {
|
||||
claim_host_netns_on(HOST_NETNS_LOCK_NAME, &HOST_NETNS_LOCK, &HOST_NETNS_CLAIMED)
|
||||
}
|
||||
|
||||
fn claim_host_netns_on(
|
||||
base: &[u8],
|
||||
slot: &std::sync::OnceLock<OwnedFd>,
|
||||
claimed: &std::sync::atomic::AtomicBool,
|
||||
) -> io::Result<()> {
|
||||
use std::sync::atomic::Ordering;
|
||||
if HOST_NETNS_CLAIMED.load(Ordering::Acquire) {
|
||||
if claimed.load(Ordering::Acquire) {
|
||||
return Ok(());
|
||||
}
|
||||
// SAFETY: `geteuid` has no preconditions.
|
||||
let me = unsafe { libc::geteuid() };
|
||||
let start = Instant::now();
|
||||
loop {
|
||||
match try_bind_abstract_socket(HOST_NETNS_LOCK_NAME) {
|
||||
Ok(fd) => {
|
||||
let _ = HOST_NETNS_LOCK.set(fd);
|
||||
HOST_NETNS_CLAIMED.store(true, Ordering::Release);
|
||||
return Ok(());
|
||||
}
|
||||
Err(code) if code == libc::EADDRINUSE => {
|
||||
if !abstract_lock_owned_by(HOST_NETNS_LOCK_NAME, me) {
|
||||
eprintln!("kiri-init: ignoring unprivileged holder on abstract netns socket");
|
||||
HOST_NETNS_CLAIMED.store(true, Ordering::Release);
|
||||
let mut idx = 0usize;
|
||||
while idx < MAX_NETNS_LOCK_SLOTS {
|
||||
let candidate = netns_slot_name(base, idx);
|
||||
let start = Instant::now();
|
||||
loop {
|
||||
match try_bind_abstract_socket(&candidate) {
|
||||
Ok(fd) => {
|
||||
let _ = slot.set(fd);
|
||||
claimed.store(true, Ordering::Release);
|
||||
return Ok(());
|
||||
}
|
||||
if start.elapsed() < Duration::from_millis(500) {
|
||||
std::thread::sleep(Duration::from_millis(25));
|
||||
continue;
|
||||
}
|
||||
return Err(io::Error::new(io::ErrorKind::AddrInUse, NETNS_BUSY_MSG));
|
||||
Err(code) if code == libc::EADDRINUSE => match probe_abstract_lock(&candidate, me) {
|
||||
LockProbe::OwnedByOther => {
|
||||
// Unprivileged squatter on `candidate`: advance to the next
|
||||
// deterministic slot so the first root engine still binds a
|
||||
// real lock and a second root engine hits that bound slot
|
||||
// (preventing split-brain without arming `claimed` unlocked).
|
||||
eprintln!("kiri-init: skipping unprivileged squatter on abstract netns socket slot {idx}");
|
||||
idx += 1;
|
||||
break;
|
||||
}
|
||||
LockProbe::OwnedByOwner | LockProbe::TransientBusy => {
|
||||
if start.elapsed() < Duration::from_millis(500) {
|
||||
std::thread::sleep(Duration::from_millis(25));
|
||||
continue;
|
||||
}
|
||||
return Err(io::Error::new(io::ErrorKind::AddrInUse, NETNS_BUSY_MSG));
|
||||
}
|
||||
},
|
||||
Err(code) => return Err(io::Error::from_raw_os_error(code)),
|
||||
}
|
||||
Err(code) => return Err(io::Error::from_raw_os_error(code)),
|
||||
}
|
||||
}
|
||||
Err(io::Error::new(io::ErrorKind::AddrInUse, NETNS_BUSY_MSG))
|
||||
}
|
||||
|
||||
/// On a Linux host: claims the network namespace, enables IPv4 forwarding,
|
||||
@@ -1582,15 +1659,34 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn abstract_netns_lock_rejects_second_holder_until_first_drops() {
|
||||
fn abstract_netns_lock_rejects_second_holder_across_full_retry_loop() {
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::OnceLock;
|
||||
let name = format!("kiri-netns-test-{}", std::process::id());
|
||||
let first = try_bind_abstract_socket(name.as_bytes()).expect("first holder binds abstract netns lock");
|
||||
let code = try_bind_abstract_socket(name.as_bytes()).expect_err("second holder in same netns must fail");
|
||||
assert_eq!(code, libc::EADDRINUSE);
|
||||
let slot1 = OnceLock::new();
|
||||
let claimed1 = AtomicBool::new(false);
|
||||
claim_host_netns_on(name.as_bytes(), &slot1, &claimed1).expect("first holder claims abstract netns lock");
|
||||
|
||||
// Run 8 full 500ms `claim_host_netns_on` retry loops (> 160 probes,
|
||||
// exceeding `listen(128)` when drained between ticks as `agent::serve_loop`
|
||||
// does) to verify `drain_netns_lock` prevents `EAGAIN` false negatives.
|
||||
for _ in 0..8 {
|
||||
let slot2 = OnceLock::new();
|
||||
let claimed2 = AtomicBool::new(false);
|
||||
let err = claim_host_netns_on(name.as_bytes(), &slot2, &claimed2)
|
||||
.expect_err("second holder in same netns must fail after full retry window");
|
||||
assert_eq!(err.kind(), io::ErrorKind::AddrInUse);
|
||||
assert!(!claimed2.load(std::sync::atomic::Ordering::Acquire));
|
||||
drain_netns_lock(slot1.get().unwrap().as_raw_fd());
|
||||
}
|
||||
|
||||
let me = unsafe { libc::geteuid() };
|
||||
assert!(abstract_lock_owned_by(name.as_bytes(), me));
|
||||
assert!(!abstract_lock_owned_by(name.as_bytes(), me.wrapping_add(1)));
|
||||
drop(first);
|
||||
assert_eq!(probe_abstract_lock(name.as_bytes(), me), LockProbe::OwnedByOwner);
|
||||
assert_eq!(probe_abstract_lock(name.as_bytes(), me.wrapping_add(1)), LockProbe::OwnedByOther);
|
||||
|
||||
drop(slot1);
|
||||
// Unbound socket returns TransientBusy (`ECONNREFUSED`), never OwnedByOther.
|
||||
assert_eq!(probe_abstract_lock(name.as_bytes(), me), LockProbe::TransientBusy);
|
||||
let rebound = try_bind_abstract_socket(name.as_bytes()).expect("rebind succeeds once first fd closes");
|
||||
drop(rebound);
|
||||
}
|
||||
|
||||
@@ -269,19 +269,44 @@ enum GetentRaw {
|
||||
Ran(std::process::ExitStatus, Vec<u8>),
|
||||
}
|
||||
|
||||
/// Runs `program -- <args...>` with a sanitized environment, bounded duration,
|
||||
#[derive(Clone, Copy)]
|
||||
enum GetentDb {
|
||||
Passwd,
|
||||
Group,
|
||||
Initgroups,
|
||||
}
|
||||
|
||||
impl GetentDb {
|
||||
fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Passwd => "passwd",
|
||||
Self::Group => "group",
|
||||
Self::Initgroups => "initgroups",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `program <db> <keys...>` with a sanitized environment, bounded duration,
|
||||
/// and bounded stdout capture. Kills the child process group and reaps it on
|
||||
/// timeout or oversized output.
|
||||
fn exec_getent(program: &Path, args: &[&OsStr], timeout: Duration, max_bytes: usize) -> io::Result<GetentRaw> {
|
||||
///
|
||||
/// `db` is a closed enum (`passwd`, `group`, `initgroups`) and every element of
|
||||
/// `keys` is validated against empty or dash-prefixed values so no option flag
|
||||
/// can be injected without needing `"--"` (which `musl-utils` `getent` rejects).
|
||||
fn exec_getent(program: &Path, db: GetentDb, keys: &[&OsStr], timeout: Duration, max_bytes: usize) -> io::Result<GetentRaw> {
|
||||
use std::io::Read;
|
||||
use std::os::unix::process::CommandExt;
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
if keys.is_empty() || keys.iter().any(|a| a.as_bytes().is_empty() || a.as_bytes()[0] == b'-') {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidInput, "invalid getent argument"));
|
||||
}
|
||||
|
||||
let mut cmd = Command::new(program);
|
||||
cmd.env_clear()
|
||||
.env("LC_ALL", "C")
|
||||
.arg("--")
|
||||
.args(args)
|
||||
.arg(db.as_str())
|
||||
.args(keys)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
@@ -394,8 +419,8 @@ fn getent_account_lookup_with(program: &Path, key: &[u8], timeout: Duration, max
|
||||
if !valid_key(key) {
|
||||
return Ok(LookupResult::NotFound);
|
||||
}
|
||||
let args = [OsStr::new("passwd"), OsStr::from_bytes(key)];
|
||||
match exec_getent(program, &args, timeout, max_bytes)? {
|
||||
let keys = [OsStr::from_bytes(key)];
|
||||
match exec_getent(program, GetentDb::Passwd, &keys, timeout, max_bytes)? {
|
||||
GetentRaw::NoBinary => Ok(LookupResult::NotFound),
|
||||
GetentRaw::Ran(status, stdout) => match status.code() {
|
||||
Some(0) => passwd_line(&stdout)
|
||||
@@ -453,12 +478,8 @@ fn getent_accounts_batch_with(program: &Path, keys: &[&CStr], timeout: Duration,
|
||||
if keys.is_empty() {
|
||||
return Ok(BatchAccounts::default());
|
||||
}
|
||||
let mut args: Vec<&OsStr> = Vec::with_capacity(1 + keys.len());
|
||||
args.push(OsStr::new("passwd"));
|
||||
for k in keys {
|
||||
args.push(OsStr::from_bytes(k.to_bytes()));
|
||||
}
|
||||
match exec_getent(program, &args, timeout, max_bytes)? {
|
||||
let args: Vec<&OsStr> = keys.iter().map(|k| OsStr::from_bytes(k.to_bytes())).collect();
|
||||
match exec_getent(program, GetentDb::Passwd, &args, timeout, max_bytes)? {
|
||||
GetentRaw::NoBinary => Ok(BatchAccounts::default()),
|
||||
GetentRaw::Ran(status, stdout) => match status.code() {
|
||||
Some(0) => {
|
||||
@@ -508,8 +529,8 @@ fn getent_group_lookup_with(program: &Path, key: &[u8]) -> io::Result<Option<Loo
|
||||
if !valid_key(key) {
|
||||
return Ok(Some(LookupResult::NotFound));
|
||||
}
|
||||
let args = [OsStr::new("group"), OsStr::from_bytes(key)];
|
||||
match exec_getent(program, &args, GETENT_TIMEOUT, GETENT_MAX_STDOUT)? {
|
||||
let keys = [OsStr::from_bytes(key)];
|
||||
match exec_getent(program, GetentDb::Group, &keys, GETENT_TIMEOUT, GETENT_MAX_STDOUT)? {
|
||||
GetentRaw::NoBinary => Ok(None),
|
||||
GetentRaw::Ran(status, stdout) => match status.code() {
|
||||
Some(0) => group_line(&stdout)
|
||||
@@ -557,8 +578,8 @@ fn initgroups_has_detailed_with_limits(program: &Path, user: &CStr, gid: u32, ti
|
||||
if !valid_key(key) {
|
||||
return Ok(InitgroupsResult::NotMember);
|
||||
}
|
||||
let args = [OsStr::new("initgroups"), OsStr::from_bytes(key)];
|
||||
match exec_getent(program, &args, timeout, max_bytes)? {
|
||||
let keys = [OsStr::from_bytes(key)];
|
||||
match exec_getent(program, GetentDb::Initgroups, &keys, timeout, max_bytes)? {
|
||||
GetentRaw::NoBinary => Ok(InitgroupsResult::NotMember),
|
||||
GetentRaw::Ran(status, stdout) => match status.code() {
|
||||
Some(0) => {
|
||||
@@ -833,6 +854,93 @@ fn peer_uid(conn: &UnixStream) -> io::Result<u32> {
|
||||
Ok(cred.uid)
|
||||
}
|
||||
|
||||
/// Parses a `/proc/<pid>/status` `Groups:` line into GIDs.
|
||||
fn parse_status_groups(status: &str) -> Vec<u32> {
|
||||
status
|
||||
.lines()
|
||||
.find_map(|l| l.strip_prefix("Groups:"))
|
||||
.map(|line| line.split_whitespace().filter_map(|tok| tok.parse::<u32>().ok()).collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn status_groups_contain(status: &str, want_gid: u32) -> bool {
|
||||
parse_status_groups(status).contains(&want_gid)
|
||||
}
|
||||
|
||||
/// Verifies that the effective UID in `/proc/<pid>/status` (`Uid:\treal\teff...`)
|
||||
/// matches `want_uid` from `SO_PEERCRED`, defeating PID-reuse races.
|
||||
fn status_euid_matches(status: &str, want_uid: u32) -> bool {
|
||||
status
|
||||
.lines()
|
||||
.find_map(|l| l.strip_prefix("Uid:"))
|
||||
.and_then(|line| line.split_whitespace().nth(1))
|
||||
.and_then(|tok| tok.parse::<u32>().ok())
|
||||
== Some(want_uid)
|
||||
}
|
||||
|
||||
fn read_proc_file_at(dir_fd: std::os::fd::RawFd, name: &CStr) -> Option<String> {
|
||||
use std::io::Read;
|
||||
use std::os::fd::FromRawFd;
|
||||
// SAFETY: `dir_fd` is a valid open directory fd and `name` is NUL-terminated.
|
||||
let raw = unsafe { libc::openat(dir_fd, name.as_ptr(), libc::O_RDONLY | libc::O_CLOEXEC | libc::O_NOFOLLOW) };
|
||||
if raw < 0 {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: `raw` is a freshly opened descriptor owned here.
|
||||
let mut f = unsafe { std::fs::File::from_raw_fd(raw) };
|
||||
let mut out = String::new();
|
||||
f.take(64 * 1024).read_to_string(&mut out).ok()?;
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Snapshot of a peer's credentials and `/proc/<pid>` state captured
|
||||
/// synchronously at `accept()` time through a single pinned `/proc/<pid>`
|
||||
/// directory descriptor before spawning `kiri-api` (prevents short-lived client
|
||||
/// exit races and multi-step `/proc/<pid>` PID-reuse TOCTOU).
|
||||
pub struct PinnedPeer {
|
||||
uid: u32,
|
||||
gid: u32,
|
||||
groups: Vec<u32>,
|
||||
cgroup: String,
|
||||
}
|
||||
|
||||
impl PinnedPeer {
|
||||
pub fn capture(conn: &UnixStream) -> Option<Self> {
|
||||
use std::os::fd::FromRawFd;
|
||||
// SAFETY: connected socket and zeroed `ucred` storage.
|
||||
let mut cred: libc::ucred = unsafe { std::mem::zeroed() };
|
||||
let mut len = std::mem::size_of::<libc::ucred>() as libc::socklen_t;
|
||||
// SAFETY: valid output pointers and buffer length.
|
||||
let r = unsafe { libc::getsockopt(conn.as_raw_fd(), libc::SOL_SOCKET, libc::SO_PEERCRED, (&mut cred as *mut libc::ucred).cast(), &mut len) };
|
||||
if r != 0 || len as usize != std::mem::size_of::<libc::ucred>() || cred.pid <= 0 {
|
||||
return None;
|
||||
}
|
||||
let proc_path = CString::new(format!("/proc/{}", cred.pid)).ok()?;
|
||||
// SAFETY: valid NUL-terminated path; pins the `/proc/<pid>` directory inode.
|
||||
let raw_dir = unsafe { libc::open(proc_path.as_ptr(), libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC) };
|
||||
if raw_dir < 0 {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: `raw_dir` is a freshly opened directory descriptor owned here.
|
||||
let dir_fd = unsafe { std::os::fd::OwnedFd::from_raw_fd(raw_dir) };
|
||||
let status = read_proc_file_at(dir_fd.as_raw_fd(), c"status")?;
|
||||
if !status_euid_matches(&status, cred.uid) {
|
||||
return None;
|
||||
}
|
||||
let cgroup = read_proc_file_at(dir_fd.as_raw_fd(), c"cgroup")?;
|
||||
Some(PinnedPeer {
|
||||
uid: cred.uid,
|
||||
gid: cred.gid,
|
||||
groups: parse_status_groups(&status),
|
||||
cgroup,
|
||||
})
|
||||
}
|
||||
|
||||
fn holds_gid(&self, want_gid: u32) -> bool {
|
||||
self.gid == want_gid || self.groups.contains(&want_gid)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the account is in the group by name or as its primary group.
|
||||
fn group_member(user: &CStr, primary_gid: libc::gid_t, group: &Group) -> bool {
|
||||
primary_gid == group.gid || group.members.iter().any(|m| m.as_c_str() == user)
|
||||
@@ -1025,6 +1133,17 @@ impl AclState {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
enum PeerSubject {
|
||||
HostUser(u32),
|
||||
/// Containerized client on `docker.container.sock` verified to belong to a
|
||||
/// live Kiri container cgroup and holding `gid`, whose numeric `uid` had no
|
||||
/// host account at connect time (#127). Retains `uid` so sweeps re-verify
|
||||
/// both group GID validity (with `DIRECTORY_MISS_GRACE`) and host user
|
||||
/// absence.
|
||||
ContainerGroup { uid: u32, gid: u32 },
|
||||
}
|
||||
|
||||
/// Who may use the engine's socket: root, the account the daemon runs as, and
|
||||
/// the members of one group, checked when they connect and again while they
|
||||
/// stay connected.
|
||||
@@ -1033,18 +1152,23 @@ pub struct Gate {
|
||||
/// The daemon's socket, and the one containers are given (caller.rs).
|
||||
sockets: Vec<PathBuf>,
|
||||
owner: u32,
|
||||
open: Mutex<HashMap<u64, (u32, UnixStream)>>,
|
||||
open: Mutex<HashMap<u64, (PeerSubject, UnixStream)>>,
|
||||
next: AtomicU64,
|
||||
failing: AtomicBool,
|
||||
/// Recent per-uid decisions, in-flight coalescing, and concurrency cap so
|
||||
/// bursts of connections or local lookup storms stay bounded.
|
||||
lookup: Mutex<LookupState>,
|
||||
lookup_slot: Condvar,
|
||||
/// Bounded/cached host-account absence checks for container UIDs (#127) so
|
||||
/// bursts of container socket connections never spawn unthrottled `getent`.
|
||||
container_uid_absent: Mutex<HashMap<u32, (bool, Instant)>>,
|
||||
/// Short-TTL group lookup cache for the accept path, invalidated when
|
||||
/// `/etc/group` changes.
|
||||
group_cache: Mutex<Option<CachedGroup>>,
|
||||
/// Consecutive ambiguous exit-2 misses per connected uid.
|
||||
misses: Mutex<HashMap<u32, u32>>,
|
||||
/// Consecutive ambiguous exit-2 group misses per container subject.
|
||||
container_misses: Mutex<HashMap<PeerSubject, u32>>,
|
||||
/// UIDs written by `grant()` at startup, used to seed `watch()` so an
|
||||
/// outage right after boot does not shrink the initial ACL on tick 1.
|
||||
startup_uids: Mutex<Option<Vec<u32>>>,
|
||||
@@ -1076,8 +1200,10 @@ impl Gate {
|
||||
failing: AtomicBool::new(false),
|
||||
lookup: Mutex::default(),
|
||||
lookup_slot: Condvar::new(),
|
||||
container_uid_absent: Mutex::default(),
|
||||
group_cache: Mutex::default(),
|
||||
misses: Mutex::default(),
|
||||
container_misses: Mutex::default(),
|
||||
startup_uids: Mutex::default(),
|
||||
}))
|
||||
}
|
||||
@@ -1223,13 +1349,30 @@ impl Gate {
|
||||
}
|
||||
|
||||
let closed_uids = if connected {
|
||||
self.sweep_membership_with(|uid| {
|
||||
if uid == 0 || uid == self.owner {
|
||||
return Ok(Membership::Allowed);
|
||||
}
|
||||
let g = group.as_ref().map_err(|e| io::Error::new(e.kind(), e.to_string()))?;
|
||||
check_member(uid, g)
|
||||
})
|
||||
self.sweep_subjects_with(
|
||||
|uid| {
|
||||
if uid == 0 || uid == self.owner {
|
||||
return Ok(Membership::Allowed);
|
||||
}
|
||||
let g = group.as_ref().map_err(|e| io::Error::new(e.kind(), e.to_string()))?;
|
||||
check_member(uid, g)
|
||||
},
|
||||
|uid, gid| {
|
||||
let g = group.as_ref().map_err(|e| io::Error::new(e.kind(), e.to_string()))?;
|
||||
match g {
|
||||
LookupResult::Found(found) if found.gid == gid => {
|
||||
// Re-verify `uid` is still not a revoked host account
|
||||
// (e.g., if NSS recovered after an ambiguous connect-time miss).
|
||||
match account_by_uid_detailed(uid)? {
|
||||
LookupResult::Found(_) => check_member(uid, g),
|
||||
LookupResult::NotFound | LookupResult::UnavailableOrNotFound => Ok(Membership::Allowed),
|
||||
}
|
||||
}
|
||||
LookupResult::Found(_) | LookupResult::NotFound => Ok(Membership::Revoked),
|
||||
LookupResult::UnavailableOrNotFound => Ok(Membership::MissingFromDirectory),
|
||||
}
|
||||
},
|
||||
)
|
||||
} else {
|
||||
HashSet::new()
|
||||
};
|
||||
@@ -1434,11 +1577,108 @@ impl Gate {
|
||||
set_each(&self.sockets, uids, set)
|
||||
}
|
||||
|
||||
/// Checks a new connection. `None`: refused, and the reason logged.
|
||||
/// Checks a new host connection. `None`: refused, and the reason logged.
|
||||
pub fn admit(self: &Arc<Self>, conn: &UnixStream) -> Option<Seat> {
|
||||
self.admit_with(conn, |uid| self.allowed(uid))
|
||||
}
|
||||
|
||||
/// Checks a new connection on `docker.container.sock`: admits host group
|
||||
/// members as usual, and also admits containerized clients inside a live
|
||||
/// Kiri container cgroup holding the access group's GID whose numeric UID
|
||||
/// has no host account (#127).
|
||||
pub fn admit_container(
|
||||
self: &Arc<Self>,
|
||||
conn: &UnixStream,
|
||||
pinned: Option<PinnedPeer>,
|
||||
is_running_container_cgroup: impl FnOnce(&str) -> bool,
|
||||
) -> Option<Seat> {
|
||||
let uid = match pinned.as_ref().map(|p| Ok(p.uid)).unwrap_or_else(|| peer_uid(conn)) {
|
||||
Ok(u) => u,
|
||||
Err(e) => {
|
||||
crate::diag::warn!("socket connection refused: access check failed", group = self.name(), error = e);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let subject = match self.allowed(uid) {
|
||||
Ok(true) => PeerSubject::HostUser(uid),
|
||||
Ok(false) => match self.container_group_subject(pinned, is_running_container_cgroup) {
|
||||
Ok(Some(sub)) => sub,
|
||||
Ok(None) => {
|
||||
crate::diag::warn!("socket connection refused: user is not in the access group", group = self.name(), uid = uid);
|
||||
return None;
|
||||
}
|
||||
Err(e) => {
|
||||
crate::diag::warn!("socket connection refused: access check failed", group = self.name(), error = e);
|
||||
return None;
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
crate::diag::warn!("socket connection refused: access check failed", group = self.name(), error = e);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
self.track_seat(conn, subject)
|
||||
}
|
||||
|
||||
fn uid_absent_throttled(&self, uid: u32) -> io::Result<bool> {
|
||||
{
|
||||
let mut cache = self.container_uid_absent.lock().unwrap_or_else(|e| e.into_inner());
|
||||
cache.retain(|_, (_, at)| at.elapsed() < RECHECK);
|
||||
if let Some(&(absent, _)) = cache.get(&uid) {
|
||||
return Ok(absent);
|
||||
}
|
||||
}
|
||||
// Acquire one of Gate's bounded lookup slots (MAX_CONCURRENT_LOOKUPS = 4)
|
||||
// so container connection bursts never spawn unthrottled `getent` children.
|
||||
{
|
||||
let mut state = self.lookup.lock().unwrap_or_else(|e| e.into_inner());
|
||||
while state.active >= MAX_CONCURRENT_LOOKUPS {
|
||||
if state.waiting >= MAX_WAITING_LOOKUPS {
|
||||
return Err(io::Error::new(io::ErrorKind::WouldBlock, "too many concurrent access checks"));
|
||||
}
|
||||
state.waiting += 1;
|
||||
state = self.lookup_slot.wait(state).unwrap_or_else(|e| e.into_inner());
|
||||
state.waiting -= 1;
|
||||
}
|
||||
state.active += 1;
|
||||
}
|
||||
let lookup_res = account_by_uid_detailed(uid);
|
||||
{
|
||||
let mut state = self.lookup.lock().unwrap_or_else(|e| e.into_inner());
|
||||
state.active = state.active.saturating_sub(1);
|
||||
self.lookup_slot.notify_all();
|
||||
}
|
||||
let absent = match lookup_res? {
|
||||
LookupResult::NotFound | LookupResult::UnavailableOrNotFound => true,
|
||||
LookupResult::Found(_) => false,
|
||||
};
|
||||
let mut cache = self.container_uid_absent.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if cache.len() >= MAX_RECENT_ENTRIES
|
||||
&& !cache.contains_key(&uid)
|
||||
&& let Some(&oldest) = cache.iter().min_by_key(|(_, (_, at))| *at).map(|(k, _)| k)
|
||||
{
|
||||
cache.remove(&oldest);
|
||||
}
|
||||
cache.insert(uid, (absent, Instant::now()));
|
||||
Ok(absent)
|
||||
}
|
||||
|
||||
fn container_group_subject(
|
||||
&self,
|
||||
pinned: Option<PinnedPeer>,
|
||||
is_running_container_cgroup: impl FnOnce(&str) -> bool,
|
||||
) -> io::Result<Option<PeerSubject>> {
|
||||
let Some(peer) = pinned else { return Ok(None) };
|
||||
let LookupResult::Found(group) = self.cached_group()? else { return Ok(None) };
|
||||
if !peer.holds_gid(group.gid) || !is_running_container_cgroup(&peer.cgroup) {
|
||||
return Ok(None);
|
||||
}
|
||||
if !self.uid_absent_throttled(peer.uid)? {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Some(PeerSubject::ContainerGroup { uid: peer.uid, gid: group.gid }))
|
||||
}
|
||||
|
||||
fn admit_with(self: &Arc<Self>, conn: &UnixStream, check: impl Fn(u32) -> io::Result<bool>) -> Option<Seat> {
|
||||
let checked = peer_uid(conn).and_then(|uid| Ok((uid, check(uid)?)));
|
||||
let uid = match checked {
|
||||
@@ -1452,6 +1692,10 @@ impl Gate {
|
||||
return None;
|
||||
}
|
||||
};
|
||||
self.track_seat(conn, PeerSubject::HostUser(uid))
|
||||
}
|
||||
|
||||
fn track_seat(self: &Arc<Self>, conn: &UnixStream, subject: PeerSubject) -> Option<Seat> {
|
||||
let keep = match conn.try_clone() {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
@@ -1460,44 +1704,88 @@ impl Gate {
|
||||
}
|
||||
};
|
||||
let id = self.next.fetch_add(1, Ordering::Relaxed);
|
||||
self.open.lock().unwrap_or_else(|e| e.into_inner()).insert(id, (uid, keep));
|
||||
self.open.lock().unwrap_or_else(|e| e.into_inner()).insert(id, (subject, keep));
|
||||
Some(Seat { gate: self.clone(), id })
|
||||
}
|
||||
|
||||
/// Checks everyone still connected, once per account, and closes the
|
||||
#[cfg(test)]
|
||||
fn sweep_membership_with(&self, check: impl Fn(u32) -> io::Result<Membership>) -> HashSet<u32> {
|
||||
self.sweep_subjects_with(check, |_, _| Ok(Membership::Allowed))
|
||||
}
|
||||
|
||||
/// Checks everyone still connected, once per subject, and closes the
|
||||
/// connections of anyone no longer allowed. A failed lookup leaves the
|
||||
/// connections open (new ones are refused until lookups work again).
|
||||
/// Ambiguous directory exit-2 misses use a grace window before closing.
|
||||
fn sweep_membership_with(&self, check: impl Fn(u32) -> io::Result<Membership>) -> HashSet<u32> {
|
||||
let uids: HashSet<u32> = self.open.lock().unwrap_or_else(|e| e.into_inner()).values().map(|(u, _)| *u).collect();
|
||||
let mut removed = HashSet::new();
|
||||
fn sweep_subjects_with(
|
||||
&self,
|
||||
check_user: impl Fn(u32) -> io::Result<Membership>,
|
||||
check_container: impl Fn(u32, u32) -> io::Result<Membership>,
|
||||
) -> HashSet<u32> {
|
||||
let subjects: HashSet<PeerSubject> = self.open.lock().unwrap_or_else(|e| e.into_inner()).values().map(|(s, _)| *s).collect();
|
||||
let host_uids: HashSet<u32> = subjects
|
||||
.iter()
|
||||
.filter_map(|s| match s {
|
||||
PeerSubject::HostUser(u) => Some(*u),
|
||||
PeerSubject::ContainerGroup { .. } => None,
|
||||
})
|
||||
.collect();
|
||||
let mut removed_subjects = HashSet::new();
|
||||
let mut removed_uids = HashSet::new();
|
||||
let mut removed_container_uids = HashSet::new();
|
||||
let mut failed = None;
|
||||
let mut misses = self.misses.lock().unwrap_or_else(|e| e.into_inner());
|
||||
misses.retain(|u, _| uids.contains(u));
|
||||
drop(misses);
|
||||
self.misses.lock().unwrap_or_else(|e| e.into_inner()).retain(|u, _| host_uids.contains(u));
|
||||
self.container_misses.lock().unwrap_or_else(|e| e.into_inner()).retain(|s, _| subjects.contains(s));
|
||||
|
||||
for uid in uids {
|
||||
match check(uid) {
|
||||
Ok(Membership::Allowed) => {
|
||||
self.misses.lock().unwrap_or_else(|e| e.into_inner()).remove(&uid);
|
||||
self.remember_decision(uid, CachedDecision::Allowed);
|
||||
}
|
||||
Ok(Membership::Revoked) => {
|
||||
self.misses.lock().unwrap_or_else(|e| e.into_inner()).remove(&uid);
|
||||
self.remember_decision(uid, CachedDecision::Denied);
|
||||
removed.insert(uid);
|
||||
}
|
||||
Ok(Membership::MissingFromDirectory) => {
|
||||
self.remember_decision(uid, CachedDecision::Denied);
|
||||
let mut misses = self.misses.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let count = misses.entry(uid).or_insert(0);
|
||||
*count = count.saturating_add(1);
|
||||
if *count >= DIRECTORY_MISS_GRACE {
|
||||
misses.remove(&uid);
|
||||
removed.insert(uid);
|
||||
for subject in subjects {
|
||||
match subject {
|
||||
PeerSubject::HostUser(uid) => match check_user(uid) {
|
||||
Ok(Membership::Allowed) => {
|
||||
self.misses.lock().unwrap_or_else(|e| e.into_inner()).remove(&uid);
|
||||
self.remember_decision(uid, CachedDecision::Allowed);
|
||||
}
|
||||
}
|
||||
Err(e) => failed = Some(e),
|
||||
Ok(Membership::Revoked) => {
|
||||
self.misses.lock().unwrap_or_else(|e| e.into_inner()).remove(&uid);
|
||||
self.remember_decision(uid, CachedDecision::Denied);
|
||||
removed_subjects.insert(subject);
|
||||
removed_uids.insert(uid);
|
||||
}
|
||||
Ok(Membership::MissingFromDirectory) => {
|
||||
self.remember_decision(uid, CachedDecision::Denied);
|
||||
let mut misses = self.misses.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let count = misses.entry(uid).or_insert(0);
|
||||
*count = count.saturating_add(1);
|
||||
if *count >= DIRECTORY_MISS_GRACE {
|
||||
misses.remove(&uid);
|
||||
removed_subjects.insert(subject);
|
||||
removed_uids.insert(uid);
|
||||
}
|
||||
}
|
||||
Err(e) => failed = Some(e),
|
||||
},
|
||||
PeerSubject::ContainerGroup { uid, gid } => match check_container(uid, gid) {
|
||||
Ok(Membership::Allowed) => {
|
||||
self.container_misses.lock().unwrap_or_else(|e| e.into_inner()).remove(&subject);
|
||||
}
|
||||
Ok(Membership::Revoked) => {
|
||||
self.container_misses.lock().unwrap_or_else(|e| e.into_inner()).remove(&subject);
|
||||
self.container_uid_absent.lock().unwrap_or_else(|e| e.into_inner()).remove(&uid);
|
||||
removed_subjects.insert(subject);
|
||||
removed_container_uids.insert(uid);
|
||||
}
|
||||
Ok(Membership::MissingFromDirectory) => {
|
||||
let mut misses = self.container_misses.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let count = misses.entry(subject).or_insert(0);
|
||||
*count = count.saturating_add(1);
|
||||
if *count >= DIRECTORY_MISS_GRACE {
|
||||
misses.remove(&subject);
|
||||
self.container_uid_absent.lock().unwrap_or_else(|e| e.into_inner()).remove(&uid);
|
||||
removed_subjects.insert(subject);
|
||||
removed_container_uids.insert(uid);
|
||||
}
|
||||
}
|
||||
Err(e) => failed = Some(e),
|
||||
},
|
||||
}
|
||||
}
|
||||
match failed {
|
||||
@@ -1505,13 +1793,13 @@ impl Gate {
|
||||
None if self.failing.swap(false, Ordering::Relaxed) => crate::diag::info!("access check works again", group = self.name()),
|
||||
_ => {}
|
||||
}
|
||||
if removed.is_empty() {
|
||||
return removed;
|
||||
if removed_subjects.is_empty() {
|
||||
return removed_uids;
|
||||
}
|
||||
// Taken out as they're closed, so a thread that takes a while to
|
||||
// notice isn't closed and logged again on every recheck.
|
||||
self.open.lock().unwrap_or_else(|e| e.into_inner()).retain(|_, (uid, conn)| {
|
||||
if !removed.contains(uid) {
|
||||
self.open.lock().unwrap_or_else(|e| e.into_inner()).retain(|_, (subject, conn)| {
|
||||
if !removed_subjects.contains(subject) {
|
||||
return true;
|
||||
}
|
||||
// Ends the connection for every thread using it: reads see the
|
||||
@@ -1519,10 +1807,10 @@ impl Gate {
|
||||
let _ = conn.shutdown(Shutdown::Both);
|
||||
false
|
||||
});
|
||||
for uid in &removed {
|
||||
for uid in removed_uids.iter().chain(removed_container_uids.iter()) {
|
||||
crate::diag::warn!("connections closed: user is no longer in the access group", group = self.name(), uid = uid);
|
||||
}
|
||||
removed
|
||||
removed_uids
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -1964,8 +2252,7 @@ mod tests {
|
||||
let touched = dir.join("touched");
|
||||
let script = format!(
|
||||
"#!/bin/sh\n\
|
||||
[ \"$1\" = \"--\" ] || exit 9\n\
|
||||
shift\n\
|
||||
[ \"$1\" = \"--\" ] && exit 1\n\
|
||||
db=\"$1\"; key=\"$2\"\n\
|
||||
case \"$key\" in -*) echo bad > \"{}\"; exit 9 ;; esac\n\
|
||||
case \"$db:$key\" in\n\
|
||||
@@ -2087,8 +2374,7 @@ mod tests {
|
||||
"fake-getent",
|
||||
&format!(
|
||||
"#!/bin/sh\n\
|
||||
[ \"$1\" = \"--\" ] || exit 9\n\
|
||||
shift\n\
|
||||
[ \"$1\" = \"--\" ] && exit 1\n\
|
||||
case \"$1\" in\n\
|
||||
passwd) export -p > \"{}\"; echo 'alice:x:5001:5001::/:/bin/sh'; exit 0 ;;\n\
|
||||
initgroups) export -p > \"{}\"; echo 'alice 998'; exit 0 ;;\n\
|
||||
@@ -2128,8 +2414,7 @@ mod tests {
|
||||
&dir,
|
||||
"fake-getent",
|
||||
"#!/bin/sh\n\
|
||||
[ \"$1\" = \"--\" ] || exit 9\n\
|
||||
shift\n\
|
||||
[ \"$1\" = \"--\" ] && exit 1\n\
|
||||
case \"$2\" in\n\
|
||||
hang) [ -x /bin/sleep ] && /bin/sleep 30 || /usr/bin/sleep 30; exit 0 ;;\n\
|
||||
hang_closed) exec >&-; [ -x /bin/sleep ] && /bin/sleep 30 || /usr/bin/sleep 30; exit 0 ;;\n\
|
||||
@@ -2193,8 +2478,7 @@ mod tests {
|
||||
&dir,
|
||||
"fake-getent",
|
||||
"#!/bin/sh\n\
|
||||
[ \"$1\" = \"--\" ] || exit 9\n\
|
||||
shift\n\
|
||||
[ \"$1\" = \"--\" ] && exit 1\n\
|
||||
case \"$1:$2\" in\n\
|
||||
passwd:alice|passwd:Alice@corp.example) echo 'alice@corp.example:x:5001:5001::/home/alice:/bin/sh'; exit 0 ;;\n\
|
||||
passwd:0|'passwd:+0'|'passwd: 0'|'passwd: -0') echo 'root:x:0:0:root:/root:/bin/sh'; exit 0 ;;\n\
|
||||
@@ -2245,8 +2529,7 @@ mod tests {
|
||||
&dir,
|
||||
"fake-getent",
|
||||
"#!/bin/sh\n\
|
||||
[ \"$1\" = \"--\" ] || exit 9\n\
|
||||
shift\n\
|
||||
[ \"$1\" = \"--\" ] && exit 1\n\
|
||||
case \"$1:$2\" in\n\
|
||||
initgroups:alice) echo 'alice -2147483648 -1000 998'; exit 0 ;;\n\
|
||||
*) exit 2 ;;\n\
|
||||
@@ -2267,8 +2550,7 @@ mod tests {
|
||||
"fake-getent",
|
||||
&format!(
|
||||
"#!/bin/sh\n\
|
||||
[ \"$1\" = \"--\" ] || exit 9\n\
|
||||
shift\n\
|
||||
[ \"$1\" = \"--\" ] && exit 1\n\
|
||||
db=\"$1\"; shift\n\
|
||||
echo x >> \"{}\"\n\
|
||||
[ \"$db\" = \"passwd\" ] || exit 2\n\
|
||||
@@ -3037,4 +3319,28 @@ mod tests {
|
||||
assert_eq!(state.uids, Some(vec![1001, 5002]), "bob must get a fresh grace window after alice was dropped");
|
||||
assert_eq!(state.shrink_streak, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn container_group_subject_parses_supplementary_groups_and_revokes_on_gid_change() {
|
||||
let status = "Name:\tpython3\nUid:\t54321\t54321\t54321\t54321\nGid:\t54321\t54321\t54321\t54321\nGroups:\t100 998 65534 \n";
|
||||
assert!(status_groups_contain(status, 998));
|
||||
assert!(!status_groups_contain(status, 999));
|
||||
assert!(status_euid_matches(status, 54321));
|
||||
assert!(!status_euid_matches(status, 1000));
|
||||
assert!(exec_getent(Path::new("/usr/bin/getent"), GetentDb::Passwd, &[OsStr::new("-V")], Duration::from_secs(1), 1024).is_err());
|
||||
|
||||
let g = gate();
|
||||
let (a, _b) = UnixStream::pair().unwrap();
|
||||
let _seat = g.track_seat(&a, PeerSubject::ContainerGroup { uid: 54321, gid: 998 }).unwrap();
|
||||
// Matching GID keeps the container connection open across sweeps.
|
||||
assert!(g.sweep_subjects_with(|_| unreachable!(), |u, gid| Ok(if u == 54321 && gid == 998 { Membership::Allowed } else { Membership::Revoked })).is_empty());
|
||||
assert_eq!(g.open.lock().unwrap().len(), 1);
|
||||
// Transient directory exit-2 misses honor DIRECTORY_MISS_GRACE before closing.
|
||||
for _ in 1..DIRECTORY_MISS_GRACE {
|
||||
assert!(g.sweep_subjects_with(|_| unreachable!(), |_, _| Ok(Membership::MissingFromDirectory)).is_empty());
|
||||
assert_eq!(g.open.lock().unwrap().len(), 1);
|
||||
}
|
||||
assert!(g.sweep_subjects_with(|_| unreachable!(), |_, _| Ok(Membership::MissingFromDirectory)).is_empty());
|
||||
assert!(g.open.lock().unwrap().is_empty());
|
||||
}
|
||||
}
|
||||
@@ -418,10 +418,15 @@ fn route(client: &mut impl ReadWrite, engine: &Engine, scheme: &str) -> io::Resu
|
||||
}
|
||||
};
|
||||
let text = String::from_utf8_lossy(&head[..end]);
|
||||
let host = text
|
||||
let mut hosts = text
|
||||
.lines()
|
||||
.find_map(|l| l.split_once(':').filter(|(k, _)| k.eq_ignore_ascii_case("host")).map(|(_, v)| v.trim().to_owned()))
|
||||
.unwrap_or_default();
|
||||
.skip(1)
|
||||
.filter_map(|l| l.split_once(':').filter(|(k, _)| k.eq_ignore_ascii_case("host")).map(|(_, v)| v.trim().to_owned()));
|
||||
let host = hosts.next().unwrap_or_default();
|
||||
if hosts.next().is_some() {
|
||||
respond(client, 400, "Bad Request", "")?;
|
||||
return Ok(None);
|
||||
}
|
||||
let Some(target) = engine.route(&host) else {
|
||||
// The running containers are listed only for this machine's own
|
||||
// names. A page reached through DNS rebinding asks with its own
|
||||
@@ -628,27 +633,42 @@ fn respond(client: &mut impl Write, status: u16, reason: &str, body: &str) -> io
|
||||
)
|
||||
}
|
||||
|
||||
/// Parses a request `Host` header (`[::1]:80`, `127.0.0.1:80`,
|
||||
/// `web.kiri.local:8080`, `web.kiri.local.`), rejecting malformed or zero
|
||||
/// ports, non-IPv6 bracketed hosts, and multiple trailing dots.
|
||||
pub(super) fn parse_host_name(host: &str) -> Option<String> {
|
||||
let host = host.trim();
|
||||
if host.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let valid_port = |p: &str| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()) && p.parse::<u16>().is_ok_and(|n| n != 0);
|
||||
if let Some(v6) = host.strip_prefix('[') {
|
||||
let addr = match v6.split_once(']') {
|
||||
Some((addr, "")) => addr,
|
||||
Some((addr, rest)) if rest.strip_prefix(':').is_some_and(valid_port) => addr,
|
||||
_ => return None,
|
||||
};
|
||||
addr.parse::<std::net::Ipv6Addr>().ok()?;
|
||||
return Some(addr.to_ascii_lowercase());
|
||||
}
|
||||
let name = match host.rsplit_once(':') {
|
||||
Some((name, port)) if !name.contains(':') && valid_port(port) => name,
|
||||
Some(_) => return None,
|
||||
None => host,
|
||||
};
|
||||
let name = name.strip_suffix('.').unwrap_or(name);
|
||||
if name.is_empty() || name.ends_with('.') {
|
||||
return None;
|
||||
}
|
||||
Some(name.to_ascii_lowercase())
|
||||
}
|
||||
|
||||
/// Whether a request's Host is a name for this machine itself: `localhost`,
|
||||
/// anything under `.localhost` (which always resolves to loopback), a
|
||||
/// `.kiri.local` name, or a loopback address. Another site's domain is not,
|
||||
/// even when its DNS answers with 127.0.0.1.
|
||||
fn local_host(host: &str) -> bool {
|
||||
let host = host.trim();
|
||||
// Without the port: `[::1]:80`, `127.0.0.1:80`, `web.kiri.localhost:8080`.
|
||||
let valid_port = |p: &str| p.bytes().all(|b| b.is_ascii_digit()) && p.parse::<u16>().is_ok_and(|n| n != 0);
|
||||
let name = match host.strip_prefix('[') {
|
||||
Some(v6) => match v6.split_once(']') {
|
||||
Some((addr, "")) => addr,
|
||||
Some((addr, rest)) if rest.strip_prefix(':').is_some_and(valid_port) => addr,
|
||||
_ => return false,
|
||||
},
|
||||
None => match host.rsplit_once(':') {
|
||||
Some((name, port)) if valid_port(port) => name,
|
||||
Some(_) => return false,
|
||||
None => host,
|
||||
},
|
||||
};
|
||||
let name = name.trim_end_matches('.').to_ascii_lowercase();
|
||||
let Some(name) = parse_host_name(host) else { return false };
|
||||
name == "localhost" || name.ends_with(".localhost") || name.ends_with(".kiri.local") || name.parse::<std::net::IpAddr>().is_ok_and(|ip| ip.is_loopback())
|
||||
}
|
||||
|
||||
@@ -743,4 +763,14 @@ mod tests {
|
||||
// Listening elsewhere only: keep the first candidate.
|
||||
assert_eq!(choose(&[3000], Some(&[9229])), 3000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_host_name_trims_trailing_dot_and_rejects_bad_ports() {
|
||||
assert_eq!(super::parse_host_name("web.kiri.local."), Some("web.kiri.local".into()));
|
||||
assert_eq!(super::parse_host_name("WEB.KIRI.LOCAL:8080"), Some("web.kiri.local".into()));
|
||||
assert_eq!(super::parse_host_name("[::1]:8080"), Some("::1".into()));
|
||||
for bad in ["", "web.kiri.local:0", "web.kiri.local:65536", "web.kiri.local:abc", "web.kiri.local:", "web.kiri.local:+80", "a:b:80", "[web.kiri.local]:80", "[localhost]", "web.kiri.local.."] {
|
||||
assert_eq!(super::parse_host_name(bad), None, "{bad}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4712,7 +4712,7 @@ impl Engine {
|
||||
/// Names are the container name, or `<service>.<project>` for Compose
|
||||
/// services.
|
||||
pub fn route(&self, host: &str) -> Option<super::domains::Target> {
|
||||
let host = host.split(':').next()?.to_ascii_lowercase();
|
||||
let host = super::domains::parse_host_name(host)?;
|
||||
let name = host.strip_suffix(".kiri.localhost").or_else(|| host.strip_suffix(".kiri.local"))?.to_owned();
|
||||
let st = self.lock();
|
||||
let c = st.containers.values().find(|c| {
|
||||
@@ -4743,6 +4743,41 @@ impl Engine {
|
||||
c.first_if = Some(0);
|
||||
}
|
||||
|
||||
/// Checks whether a `/proc/<pid>/cgroup` snapshot belongs to one of this
|
||||
/// engine's currently running containers under a root-owned `kiri/<id>`
|
||||
/// cgroup directory (#127). Prevents unprivileged host `unshare -Um` +
|
||||
/// `newuidmap` processes from impersonating containers on `docker.container.sock`.
|
||||
#[cfg(target_os = "linux")]
|
||||
pub fn has_running_container_cgroup(&self, cgroup_text: &str) -> bool {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
for line in cgroup_text.lines() {
|
||||
let Some((_, rest)) = line.split_once(':') else { continue };
|
||||
let Some((_, rel_path)) = rest.split_once(':') else { continue };
|
||||
if !rel_path.starts_with('/') {
|
||||
continue;
|
||||
}
|
||||
let segs: Vec<&str> = rel_path.split('/').filter(|s| !s.is_empty()).collect();
|
||||
for i in 1..segs.len() {
|
||||
let id = segs[i];
|
||||
if segs[i - 1] != "kiri" || id.len() != 64 || !id.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) {
|
||||
continue;
|
||||
}
|
||||
let is_running = self.lock().containers.get(id).is_some_and(|c| c.status == Status::Running);
|
||||
if !is_running {
|
||||
continue;
|
||||
}
|
||||
let prefix = format!("/sys/fs/cgroup/{}", segs[..=i].join("/"));
|
||||
let parent = format!("/sys/fs/cgroup/{}", segs[..i].join("/"));
|
||||
if std::fs::symlink_metadata(&prefix).is_ok_and(|m| m.is_dir() && m.uid() == 0)
|
||||
&& std::fs::symlink_metadata(&parent).is_ok_and(|m| m.is_dir() && m.uid() == 0)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// For the Finder view (macOS).
|
||||
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
|
||||
pub fn fs_stat(&self, id: &str, path: &str) -> io::Result<super::vmlink::FileInfo> {
|
||||
|
||||
@@ -428,9 +428,26 @@ pub fn run(_args: &[String]) -> io::Result<()> {
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[cfg(test)]
|
||||
fn admit_connection(gate: &Option<std::sync::Arc<access::Gate>>, conn: &UnixStream) -> Result<Option<access::Seat>, ()> {
|
||||
admit_connection_for(gate, conn, None, &None)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn admit_connection_for(
|
||||
gate: &Option<std::sync::Arc<access::Gate>>,
|
||||
conn: &UnixStream,
|
||||
pinned: Option<access::PinnedPeer>,
|
||||
container_engine: &Option<std::sync::Arc<engine::Engine>>,
|
||||
) -> Result<Option<access::Seat>, ()> {
|
||||
match gate {
|
||||
Some(gate) => gate.admit(conn).map(Some).ok_or(()),
|
||||
Some(gate) => {
|
||||
let seat = match container_engine {
|
||||
Some(eng) => gate.admit_container(conn, pinned, |cg| eng.has_running_container_cgroup(cg)),
|
||||
None => gate.admit(conn),
|
||||
};
|
||||
seat.map(Some).ok_or(())
|
||||
}
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
@@ -443,12 +460,16 @@ fn accept(
|
||||
who: caller::Caller,
|
||||
) {
|
||||
let cap = open_conns_for(&who);
|
||||
#[cfg(target_os = "linux")]
|
||||
let container_engine = matches!(who, caller::Caller::Container).then(|| engine.clone());
|
||||
let engine = engine.clone();
|
||||
serve_each_with(
|
||||
serve_each_inner(
|
||||
listener,
|
||||
cap,
|
||||
#[cfg(target_os = "linux")]
|
||||
gate,
|
||||
#[cfg(target_os = "linux")]
|
||||
container_engine,
|
||||
std::sync::Arc::new(move |conn| {
|
||||
let _ = api::serve(conn, engine.clone(), who.clone());
|
||||
}),
|
||||
@@ -582,6 +603,24 @@ fn serve_each_with(
|
||||
cap: &std::sync::Arc<ConnCap>,
|
||||
#[cfg(target_os = "linux")] gate: &Option<std::sync::Arc<access::Gate>>,
|
||||
serve: std::sync::Arc<dyn Fn(UnixStream) + Send + Sync>,
|
||||
) {
|
||||
serve_each_inner(
|
||||
listener,
|
||||
cap,
|
||||
#[cfg(target_os = "linux")]
|
||||
gate,
|
||||
#[cfg(target_os = "linux")]
|
||||
None,
|
||||
serve,
|
||||
);
|
||||
}
|
||||
|
||||
fn serve_each_inner(
|
||||
listener: &UnixListener,
|
||||
cap: &std::sync::Arc<ConnCap>,
|
||||
#[cfg(target_os = "linux")] gate: &Option<std::sync::Arc<access::Gate>>,
|
||||
#[cfg(target_os = "linux")] container_engine: Option<std::sync::Arc<engine::Engine>>,
|
||||
serve: std::sync::Arc<dyn Fn(UnixStream) + Send + Sync>,
|
||||
) {
|
||||
for conn in listener.incoming() {
|
||||
let Ok(conn) = conn else { continue };
|
||||
@@ -590,15 +629,26 @@ fn serve_each_with(
|
||||
drop(conn);
|
||||
continue;
|
||||
};
|
||||
// Capture `/proc/<pid>` credentials + cgroup synchronously at `accept()`
|
||||
// before spawning `kiri-api`, preventing short-lived client exit races
|
||||
// and PID-reuse TOCTOU (#127).
|
||||
#[cfg(target_os = "linux")]
|
||||
let pinned = if gate.is_some() && container_engine.is_some() {
|
||||
access::PinnedPeer::capture(&conn)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let serve = serve.clone();
|
||||
#[cfg(target_os = "linux")]
|
||||
let gate = gate.clone();
|
||||
#[cfg(target_os = "linux")]
|
||||
let container_engine = container_engine.clone();
|
||||
let spawned = std::thread::Builder::new().name("kiri-api".into()).spawn(move || {
|
||||
let _permit = permit;
|
||||
// Checked here, not in the accept loop: a slow user lookup holds up
|
||||
// this connection only.
|
||||
#[cfg(target_os = "linux")]
|
||||
let Ok(_seat) = admit_connection(&gate, &conn) else {
|
||||
let Ok(_seat) = admit_connection_for(&gate, &conn, pinned, &container_engine) else {
|
||||
return;
|
||||
};
|
||||
serve(conn);
|
||||
|
||||
@@ -331,12 +331,33 @@ fn names(installed: bool) -> Check {
|
||||
|
||||
/// Whether a docker host is this Kiri's socket: `Some(false)` only when
|
||||
/// both are local sockets and resolve to different files (another Kiri,
|
||||
/// such as the installed one next to Kiri Dev).
|
||||
/// such as the installed one next to Kiri Dev). On Linux, a root daemon
|
||||
/// without `KIRI_SOCKET` binds both `/run/kiri/docker.sock` and
|
||||
/// `~/.kiri/run/docker.sock`, so both belong to this Kiri.
|
||||
#[cfg(unix)]
|
||||
fn ours_unix(host: &str) -> Option<bool> {
|
||||
let theirs = std::fs::canonicalize(host.strip_prefix("unix://")?).ok()?;
|
||||
let raw = std::path::Path::new(host.strip_prefix("unix://")?);
|
||||
let theirs = std::fs::canonicalize(raw).ok()?;
|
||||
let ours = std::fs::canonicalize(crate::client::socket().ok()?).ok()?;
|
||||
Some(theirs == ours)
|
||||
if theirs == ours {
|
||||
return Some(true);
|
||||
}
|
||||
#[cfg(target_os = "linux")]
|
||||
if std::env::var_os("KIRI_SOCKET").is_none() {
|
||||
use std::os::unix::fs::{FileTypeExt, MetadataExt};
|
||||
if let Ok(home_sock) = crate::daemon::home_socket_path()
|
||||
&& let Ok(md) = std::fs::symlink_metadata(&home_sock)
|
||||
&& !md.file_type().is_symlink()
|
||||
&& md.file_type().is_socket()
|
||||
&& md.uid() == 0
|
||||
&& std::fs::symlink_metadata(crate::client::SERVICE_SOCKET)
|
||||
.is_ok_and(|smd| !smd.file_type().is_symlink() && smd.file_type().is_socket() && smd.uid() == 0)
|
||||
&& std::fs::canonicalize(&home_sock).ok().as_ref() == Some(&theirs)
|
||||
{
|
||||
return Some(true);
|
||||
}
|
||||
}
|
||||
Some(false)
|
||||
}
|
||||
|
||||
enum Reached {
|
||||
|
||||
Reference in new issue
Block a user