From 73fb8edf61ab80b296432a4c990ce9286814007b Mon Sep 17 00:00:00 2001 From: Weidong Cui Date: Fri, 13 Nov 2026 15:44:29 -0800 Subject: [PATCH 1/3] Keep Linux host names in the broker Make sethostname and setdomainname set the broker's host names, which uname reads, so a change is seen by every process in the caller's UTS namespace. CLONE_NEWUTS gives the child its own copy, and unshare(CLONE_NEWUTS) gives the caller one. The shim keeps Linux's rules: 64-byte names, EPERM before EINVAL before EFAULT, and root only. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: f5406de6-bab4-4f3b-b232-ae238032c2c2 --- litebox_common_linux/src/lib.rs | 18 +++ .../src/test_broker.rs | 3 +- litebox_runner_linux_userland/tests/run.rs | 3 +- litebox_shim_linux/src/lib.rs | 7 + litebox_shim_linux/src/syscalls/misc.rs | 92 ++++++++++++- litebox_shim_linux/src/syscalls/process.rs | 129 +++++++++++------- .../src/syscalls/test_broker.rs | 5 +- 7 files changed, 198 insertions(+), 59 deletions(-) diff --git a/litebox_common_linux/src/lib.rs b/litebox_common_linux/src/lib.rs index b125818b52..6a787a784b 100644 --- a/litebox_common_linux/src/lib.rs +++ b/litebox_common_linux/src/lib.rs @@ -1990,6 +1990,14 @@ pub struct TaskParams { pub execfn: Option, } +/// The longest host name or NIS domain name, in bytes, not counting a terminating NUL (Linux's +/// `__NEW_UTS_LEN`). +pub const UTS_NAME_LENGTH: usize = 64; + +// Every name Linux accepts fits in the broker's host names. +const _: () = + assert!(UTS_NAME_LENGTH <= litebox_broker_protocol::process::MAX_HOST_NAME_SIZE as usize); + #[repr(C)] #[derive(Clone, FromBytes, IntoBytes)] pub struct Utsname { @@ -3237,6 +3245,14 @@ pub enum SyscallRequest { Uname { buf: UserPtrMut, }, + Sethostname { + name: UserPtr, + len: i32, + }, + Setdomainname { + name: UserPtr, + len: i32, + }, Statfs { pathname: UserPtr, buf: UserPtrMut, @@ -3855,6 +3871,8 @@ impl SyscallRequest { Sysno::wait4 => sys_req!(Wait4 { pid, wstatus:*, options, rusage:* }), Sysno::waitid => sys_req!(Waitid { idtype, id, infop:*, options, rusage:* }), Sysno::uname => sys_req!(Uname { buf:* }), + Sysno::sethostname => sys_req!(Sethostname { name:*, len }), + Sysno::setdomainname => sys_req!(Setdomainname { name:*, len }), Sysno::statfs => sys_req!(Statfs { pathname:*, buf:* }), Sysno::fstatfs => sys_req!(Fstatfs { fd, buf:* }), Sysno::fcntl => { diff --git a/litebox_runner_linux_on_macos_userland/src/test_broker.rs b/litebox_runner_linux_on_macos_userland/src/test_broker.rs index f21b832416..cf85adcc3b 100644 --- a/litebox_runner_linux_on_macos_userland/src/test_broker.rs +++ b/litebox_runner_linux_on_macos_userland/src/test_broker.rs @@ -19,7 +19,7 @@ use litebox_broker_core::{ stdio::StdioOutputStream, test_support::{TestBrokerBuilder, TestStdioProvider}, }; -use litebox_broker_host::test_support::InProcessBrokerSetup; +use litebox_broker_host::{default_host_names, test_support::InProcessBrokerSetup}; use litebox_broker_local::BrokerLocal; use litebox_broker_protocol::fs::{FileMode, FileUser}; use litebox_platform_macos_userland::MacosUserland4K; @@ -110,6 +110,7 @@ pub(crate) fn setup( )) .with_random_provider(Arc::new(TestRandomProvider)) .with_file_service(Arc::new(Resolver::::new(fs))) + .with_host_names(default_host_names()) .build() .map_err(|error| anyhow!("test broker: {error:?}"))?; let root = broker diff --git a/litebox_runner_linux_userland/tests/run.rs b/litebox_runner_linux_userland/tests/run.rs index f4b5ac9f2b..011ca0bb25 100644 --- a/litebox_runner_linux_userland/tests/run.rs +++ b/litebox_runner_linux_userland/tests/run.rs @@ -2212,7 +2212,8 @@ fn spawn_test_broker_with_mode( &file_roots, std::sync::Arc::new(CapturingStdioProvider { stdout_tx }), limits.max_shared_files, - )); + )) + .with_host_names(litebox_broker_host::default_host_names()); if let Some(vsock) = &vsock { broker = broker.with_vsock_provider(vsock.provider()); } diff --git a/litebox_shim_linux/src/lib.rs b/litebox_shim_linux/src/lib.rs index ca815581cd..84158837d8 100644 --- a/litebox_shim_linux/src/lib.rs +++ b/litebox_shim_linux/src/lib.rs @@ -1024,6 +1024,9 @@ impl Task { | SyscallRequest::Setsid | SyscallRequest::Getsid { .. } | SyscallRequest::Unshare { .. } + | SyscallRequest::Uname { .. } + | SyscallRequest::Sethostname { .. } + | SyscallRequest::Setdomainname { .. } | SyscallRequest::Ioctl { arg: IoctlArg::TIOCSCTTY(_) | IoctlArg::TIOCSPGRP(_), .. @@ -1392,6 +1395,10 @@ impl Task { addrlen, } => syscall!(sys_getpeername(sockfd, addr, addrlen)), SyscallRequest::Uname { buf } => syscall!(sys_uname(buf)), + SyscallRequest::Sethostname { name, len } => syscall!(sys_sethostname(name, len)), + SyscallRequest::Setdomainname { name, len } => { + syscall!(sys_setdomainname(name, len)) + } SyscallRequest::Statfs { pathname, buf } => { pathname .to_cstring::() diff --git a/litebox_shim_linux/src/syscalls/misc.rs b/litebox_shim_linux/src/syscalls/misc.rs index 712d0a74d3..a00fe6f592 100644 --- a/litebox_shim_linux/src/syscalls/misc.rs +++ b/litebox_shim_linux/src/syscalls/misc.rs @@ -6,10 +6,13 @@ //! Examples of syscalls handled here include `getrandom`, `uname`, and similar operations. use crate::{ShimPlatform, Task, guest_buffer::GuestReadBuffer}; +use litebox::process::ProcessError; use litebox::random::FillRandomError; -use litebox::user_pointers::UserPtrMut; +use litebox::user_pointers::{UserPtr, UserPtrMut}; use litebox::utils::TruncateExt as _; -use litebox_common_linux::{IoReadVec, errno::Errno}; +use litebox_broker_protocol::ProcessId; +use litebox_broker_protocol::process::{HostName, HostNameKind}; +use litebox_common_linux::{IoReadVec, UTS_NAME_LENGTH, errno::Errno}; use litebox_platform::buffer::Buffer as _; use litebox_platform::time::Instant as _; @@ -79,16 +82,73 @@ const SYS_INFO: litebox_common_linux::Utsname = litebox_common_linux::Utsname { domainname: to_fixed_size_array::<65>(""), }; +/// Returns `name` as a `uname` field: its first [`UTS_NAME_LENGTH`] bytes, then zeros. +/// +/// No Linux process can set a longer name, but the broker allows one, as from the host's +/// configuration or another kind of guest. Like Linux with a long `hostname=` boot parameter, the +/// shim truncates it rather than failing every `uname`. +fn uts_field(name: &HostName) -> [u8; UTS_NAME_LENGTH + 1] { + let bytes = name.as_bytes(); + let bytes = &bytes[..bytes.len().min(UTS_NAME_LENGTH)]; + let mut field = [0; UTS_NAME_LENGTH + 1]; + field[..bytes.len()].copy_from_slice(bytes); + field +} + impl Task { /// Handle syscall `uname`. + /// + /// The host and NIS domain names are the broker's host names of this process, or of the + /// `vfork` child, which processes in one UTS namespace share. Without a process service, they + /// are `SYS_INFO`'s. pub(crate) fn sys_uname( &self, buf: UserPtrMut, ) -> Result<(), Errno> { - buf.write_at_offset::(0, SYS_INFO) + let mut info = SYS_INFO; + let process_id = ProcessId(self.own_pid_for_requests().cast_unsigned()); + match self.global.litebox.get_host_names(process_id) { + Ok(names) => { + info.nodename = uts_field(&names.host); + info.domainname = uts_field(&names.domain); + } + Err(ProcessError::Unavailable) => {} + Err(error) => return Err(error.into()), + } + buf.write_at_offset::(0, info) .ok_or(Errno::EFAULT) } + /// Handle syscall `sethostname`. + pub(crate) fn sys_sethostname(&self, name: UserPtr, len: i32) -> Result<(), Errno> { + self.set_host_name(HostNameKind::Host, name, len) + } + + /// Handle syscall `setdomainname`, which sets the NIS domain name. + pub(crate) fn sys_setdomainname(&self, name: UserPtr, len: i32) -> Result<(), Errno> { + self.set_host_name(HostNameKind::Domain, name, len) + } + + /// Sets the `kind` name of this process, or of the `vfork` child, to the `len` bytes at + /// `name`, for every process in its UTS namespace. + /// + /// Like Linux, this checks the permission (`EPERM`), then the length (`EINVAL`), then the + /// bytes (`EFAULT`), before changing anything. + fn set_host_name(&self, kind: HostNameKind, name: UserPtr, len: i32) -> Result<(), Errno> { + self.check_admin()?; + let len = usize::try_from(len) + .ok() + .filter(|&len| len <= UTS_NAME_LENGTH) + .ok_or(Errno::EINVAL)?; + let mut bytes = [0; UTS_NAME_LENGTH]; + name.copy_to_slice::(0, &mut bytes[..len]) + .ok_or(Errno::EFAULT)?; + let name = HostName::new(&bytes[..len]).expect("Linux names fit the broker's"); + let process_id = ProcessId(self.own_pid_for_requests().cast_unsigned()); + self.global.litebox.set_host_name(process_id, kind, &name)?; + Ok(()) + } + /// Handle syscall `sysinfo`. pub(crate) fn sys_sysinfo(&self) -> litebox_common_linux::Sysinfo { let now = self.global.platform.now(); @@ -203,4 +263,30 @@ mod tests { assert_eq!(buf[..buf.len() - 1], [random; 15]); assert_eq!(buf[buf.len() - 1], 0); } + + #[test] + fn uname_reports_the_first_64_bytes_of_a_longer_name() { + use litebox_broker_protocol::ProcessId; + use litebox_broker_protocol::process::{HostName, HostNameKind, MAX_HOST_NAME_SIZE}; + use zerocopy::FromZeros as _; + + let task = init_platform(); + // Longer than a Linux process can set, as another kind of guest could. + let name: [u8; MAX_HOST_NAME_SIZE as usize] = + core::array::from_fn(|i| b"0123456789"[i % 10]); + task.global + .litebox + .set_host_name( + ProcessId(task.pid.cast_unsigned()), + HostNameKind::Host, + &HostName::new(&name).unwrap(), + ) + .unwrap(); + + let mut utsname = litebox_common_linux::Utsname::new_zeroed(); + task.sys_uname(UserPtrMut::from_ptr(&raw mut utsname)) + .expect("uname failed"); + assert_eq!(utsname.nodename[..64], name[..64]); + assert_eq!(utsname.nodename[64], 0); + } } diff --git a/litebox_shim_linux/src/syscalls/process.rs b/litebox_shim_linux/src/syscalls/process.rs index 40261f54e8..e7f86e361c 100644 --- a/litebox_shim_linux/src/syscalls/process.rs +++ b/litebox_shim_linux/src/syscalls/process.rs @@ -300,10 +300,10 @@ pub(super) enum RestartBlock { /// process, which also adopts the orphans that no other ancestor in the namespace adopts. const GUEST_PID_NAMESPACE: PidNamespaceOptions = PidNamespaceOptions::new(true, true); -/// The namespace flags that need only the permission check. The host and domain names `uname` -/// reports are fixed and LiteBox has no IPC objects, so a new UTS or IPC namespace has nothing to -/// scope and is indistinguishable from its creator's. Settable names or IPC objects, if added, -/// must be kept per namespace. +/// The UTS and IPC namespace flags, which need the permission check. A new UTS namespace gets a +/// copy of its creator's host names (see `ChildRelation::new_host_names`). LiteBox has no IPC +/// objects, so a new IPC namespace has nothing to scope and is indistinguishable from its +/// creator's; IPC objects, if added, must be kept per namespace. const UTS_AND_IPC_NAMESPACE_FLAGS: CloneFlags = CloneFlags::NEWUTS.union(CloneFlags::NEWIPC); /// How a new child process relates to the process creating it. @@ -314,13 +314,18 @@ struct ChildRelation { new_pid_namespace: bool, /// Whether the child's parent is the creating process's parent. sibling: bool, + /// Whether the child is in a new UTS namespace, with its own copy of the creating process's + /// host names rather than sharing them. + new_host_names: bool, } impl ChildRelation { - /// A plain child, in the PID namespace for the creating process's children. + /// A plain child, in the PID namespace for the creating process's children, sharing its host + /// names. const CHILD: Self = Self { new_pid_namespace: false, sibling: false, + new_host_names: false, }; } @@ -1025,7 +1030,8 @@ impl Task { /// Allocates a pending child of this process, as `relation` describes. fn allocate_child_process(&self, relation: ChildRelation) -> Result { - self.global + let child = self + .global .litebox .allocate_child_process( relation.new_pid_namespace.then_some(GUEST_PID_NAMESPACE), @@ -1040,7 +1046,14 @@ impl Task { // limit, which the broker doesn't tell apart. ProcessError::ResourceExhausted if relation.new_pid_namespace => Errno::ENOSPC, error => error.into(), - }) + })?; + // On failure, dropping the child cancels it. + if relation.new_host_names { + self.global + .litebox + .copy_host_names(child.identity().process_id)?; + } + Ok(child) } /// Returns whether this process called `unshare(CLONE_NEWPID)` (see @@ -1057,7 +1070,7 @@ impl Task { /// /// Guest user IDs exist only in the shim today, so the broker doesn't enforce this; whether it /// should is not yet decided. - fn check_admin(&self) -> Result<(), Errno> { + pub(super) fn check_admin(&self) -> Result<(), Errno> { if self.credentials.euid != 0 { return Err(Errno::EPERM); } @@ -1092,7 +1105,9 @@ impl Task { /// /// Unlike Linux, `CLONE_NEWPID` fails in a `vfork` child, whose requests go to the broker as /// its parent's, and in a process with more than one thread, since LiteBox keeps the PID - /// namespace for a process's children per process rather than per thread. + /// namespace for a process's children per process rather than per thread. Likewise, since + /// LiteBox keeps host names per process, `CLONE_NEWUTS` moves the whole process, with all its + /// threads, to the new UTS namespace, not just the calling thread. pub(crate) fn sys_unshare(&self, flags: CloneFlags) -> Result { if flags.is_empty() { return Ok(0); @@ -1102,32 +1117,44 @@ impl Task { return Err(Errno::EINVAL); } self.check_admin()?; - if !flags.contains(CloneFlags::NEWPID) { - return Ok(0); - } - // A `vfork` child makes its requests as its parent, whose children this would change. - if self.vfork.borrow().is_some() { - log_unsupported!("unshare(CLONE_NEWPID) in a vfork child"); - return Err(Errno::EINVAL); + if flags.contains(CloneFlags::NEWPID) { + // A `vfork` child makes its requests as its parent, whose children this would change. + if self.vfork.borrow().is_some() { + log_unsupported!("unshare(CLONE_NEWPID) in a vfork child"); + return Err(Errno::EINVAL); + } + self.check_can_create_pid_namespace()?; + // As the only thread, the caller is the only one that could create threads or change + // this process's state, so nothing changes what was checked until this returns. + if self.thread.process.nr_threads() > 1 { + return Err(Errno::EINVAL); + } + self.global + .litebox + .create_children_pid_namespace(GUEST_PID_NAMESPACE) + .map_err(|error| match error { + // The namespace limits, like Linux's nesting and count limits. + ProcessError::ResourceExhausted => Errno::ENOSPC, + error => error.into(), + })?; + self.thread + .process + .pid_namespace_unshared + .store(true, Ordering::Relaxed); } - self.check_can_create_pid_namespace()?; - // As the only thread, the caller is the only one that could create threads or change - // this process's state, so nothing changes what was checked until this returns. - if self.thread.process.nr_threads() > 1 { - return Err(Errno::EINVAL); + // Last, so that a failure above leaves the host names shared. Without a process service, + // the names are fixed, so there is nothing to copy. Otherwise, only a failed broker + // association, after which the process can't go on, fails the copy. + if flags.contains(CloneFlags::NEWUTS) { + match self + .global + .litebox + .copy_host_names(ProcessId(self.own_pid_for_requests().cast_unsigned())) + { + Ok(()) | Err(ProcessError::Unavailable) => {} + Err(error) => return Err(error.into()), + } } - self.global - .litebox - .create_children_pid_namespace(GUEST_PID_NAMESPACE) - .map_err(|error| match error { - // The namespace limits, like Linux's nesting and count limits. - ProcessError::ResourceExhausted => Errno::ENOSPC, - error => error.into(), - })?; - self.thread - .process - .pid_namespace_unshared - .store(true, Ordering::Relaxed); Ok(0) } @@ -1772,7 +1799,7 @@ impl Task { /// Handles `vfork`; see [`Self::begin_vfork`]. pub(crate) fn sys_vfork(&self, ctx: &mut litebox_common_linux::PtRegs) -> Result { - self.begin_vfork(ctx, None, false, false) + self.begin_vfork(ctx, None, false, ChildRelation::CHILD) } /// Handle syscall `fork`. @@ -2045,8 +2072,8 @@ impl Task { /// /// The child continues from the syscall on `child_stack` if given, or else on the parent's /// stack. If `clear_signal_handlers` is set (`CLONE_CLEAR_SIGHAND`), the child's handled - /// signals start with their default action. If `new_pid_namespace` is set, the child is the - /// first process of a new PID namespace. + /// signals start with their default action. The child relates to this process as `relation` + /// describes. /// /// Only processes with default alarm state are admitted. The child gets its own copy of the /// parent's resource limits, working directory, umask, and `no_new_privs`, of its descriptor @@ -2066,21 +2093,19 @@ impl Task { ctx: &mut litebox_common_linux::PtRegs, child_stack: Option, clear_signal_handlers: bool, - new_pid_namespace: bool, + relation: ChildRelation, ) -> Result { if self.vfork.borrow().is_some() || !self.thread.process.has_default_alarm_state() { return Err(Errno::EAGAIN); } - let child = self.allocate_child_process(ChildRelation { - new_pid_namespace, - sibling: false, - })?; + let child = self.allocate_child_process(relation)?; let child_pid = i32::try_from(child.identity().process_id.0) .expect("broker process IDs must fit Linux pid_t"); - let child_own_pid = (new_pid_namespace || self.pid_namespace_unshared()).then(|| { - i32::try_from(child.identity().own_process_id.0) - .expect("broker process IDs must fit Linux pid_t") - }); + let child_own_pid = + (relation.new_pid_namespace || self.pid_namespace_unshared()).then(|| { + i32::try_from(child.identity().own_process_id.0) + .expect("broker process IDs must fit Linux pid_t") + }); let mut parent_context = ctx.clone(); #[cfg(target_arch = "x86_64")] { @@ -2229,6 +2254,7 @@ impl Task { let relation = ChildRelation { new_pid_namespace: self.clone_creates_pid_namespace(flags)?, sibling, + new_host_names: flags.contains(CloneFlags::NEWUTS), }; let child_tid: usize = child_tid.trunc(); let tid_if = |flag| if flags.contains(flag) { child_tid } else { 0 }; @@ -2266,13 +2292,12 @@ impl Task { if flags.intersects(UTS_AND_IPC_NAMESPACE_FLAGS) { self.check_admin()?; } - let new_pid_namespace = self.clone_creates_pid_namespace(flags)?; - return self.begin_vfork( - ctx, - sp, - flags.contains(CloneFlags::CLEAR_SIGHAND), - new_pid_namespace, - ); + let relation = ChildRelation { + new_pid_namespace: self.clone_creates_pid_namespace(flags)?, + sibling: false, + new_host_names: flags.contains(CloneFlags::NEWUTS), + }; + return self.begin_vfork(ctx, sp, flags.contains(CloneFlags::CLEAR_SIGHAND), relation); } // Like Linux, refuse a new thread with `CLONE_NEWPID` or after `unshare(CLONE_NEWPID)`. diff --git a/litebox_shim_linux/src/syscalls/test_broker.rs b/litebox_shim_linux/src/syscalls/test_broker.rs index 908171b27c..af848bd655 100644 --- a/litebox_shim_linux/src/syscalls/test_broker.rs +++ b/litebox_shim_linux/src/syscalls/test_broker.rs @@ -26,7 +26,7 @@ use litebox_broker_core::{ test_support::{self, FailingRandomProvider, TestBrokerBuilder, TestStdioProvider}, }; use litebox_broker_host::{ - BrokerHostError, + BrokerHostError, default_host_names, test_support::{InProcessBrokerChannel, InProcessBrokerSetup}, }; use litebox_broker_local::BrokerLocal; @@ -166,7 +166,8 @@ fn test_broker(limits: BrokerCoreLimits) -> &'static TestBroker { ) .with_limits(limits) .with_random_provider(Arc::new(FixedRandomProvider)) - .with_file_service(Arc::new(Resolver::::new(fs))); + .with_file_service(Arc::new(Resolver::::new(fs))) + .with_host_names(default_host_names()); #[cfg(any(target_os = "linux", all(windows, target_arch = "x86_64")))] let builder = builder.with_socket_provider(Arc::new(socket_provider)); let broker = builder From 4cf769b9a5561985ee874830dd9736b0c4ada978 Mon Sep 17 00:00:00 2001 From: Weidong Cui Date: Fri, 13 Nov 2026 15:49:17 -0800 Subject: [PATCH 2/3] Test host names shared in UTS namespaces Extend the UTS and IPC namespace test to set and read the host and domain names: their length and error rules, that the processes of a namespace, vfork children and exec'd programs included, share them, and that clone, clone3 and unshare give a new namespace a separate copy. Every check also holds on Linux. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: f5406de6-bab4-4f3b-b232-ae238032c2c2 --- .../tests/uts_ipc_namespace.c | 322 +++++++++++++++++- 1 file changed, 318 insertions(+), 4 deletions(-) diff --git a/litebox_runner_linux_userland/tests/uts_ipc_namespace.c b/litebox_runner_linux_userland/tests/uts_ipc_namespace.c index 62d757e7d3..ebcba78f17 100644 --- a/litebox_runner_linux_userland/tests/uts_ipc_namespace.c +++ b/litebox_runner_linux_userland/tests/uts_ipc_namespace.c @@ -1,11 +1,13 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -// Checks creating UTS and IPC namespaces with `clone`, `clone3`, and `unshare`. Runs as guest root, -// or, with the argument `unprivileged`, as another user, who can't create them. +// Checks creating UTS and IPC namespaces with `clone`, `clone3`, and `unshare`, and the host and +// NIS domain names a UTS namespace holds: setting and reading them, that the processes in a +// namespace share them, and that a new namespace starts with a copy. Runs as guest root, or, with +// the argument `unprivileged`, as another user, who can't create namespaces or set the names. // -// LiteBox's host and domain names are fixed and it has no IPC objects, so nothing tells a new UTS -// or IPC namespace apart from its creator's. These checks see only whether creating one succeeds. +// LiteBox has no IPC objects, so nothing tells a new IPC namespace apart from its creator's. Those +// checks see only whether creating one succeeds. #define _GNU_SOURCE #include @@ -16,15 +18,33 @@ #include #include #include +#include #include +#include #include #include // The code each new child exits with. #define CHILD_CODE 7 +// Names that the program and its children set. +#define HOST "parent-host" +#define DOMAIN "parent.domain" +#define CHILD_HOST "child-host" +#define CHILD_DOMAIN "child.domain" +#define OTHER_HOST "other-host" +#define OTHER_DOMAIN "other.domain" + +// The longest name, without a terminating NUL (Linux's `__NEW_UTS_LEN`). +#define NAME_MAX_LENGTH 64 + +extern char **environ; + static int failures; +// This program's path, which children exec. +static char *self_path; + #define CHECK(condition) \ do { \ if (!(condition)) { \ @@ -153,6 +173,284 @@ static void unshare_creates_namespaces(void) { CHECK(unshare_in_a_vfork_child(CLONE_NEWUTS | CLONE_NEWIPC) == 0); } +// Returns whether the `uname` field `field` holds the `length` bytes at `name`, then only zeros. +static int holds(const char *field, const char *name, size_t length) { + if (memcmp(field, name, length) != 0) { + return 0; + } + for (size_t i = length; i < sizeof ((struct utsname *)0)->nodename; i++) { + if (field[i] != 0) { + return 0; + } + } + return 1; +} + +// Returns whether `uname` reports host name `host` and domain name `domain`. +static int has_names(const char *host, const char *domain) { + struct utsname names; + return uname(&names) == 0 && holds(names.nodename, host, strlen(host)) && + holds(names.domainname, domain, strlen(domain)); +} + +// Sets the host and domain names, returning whether both succeeded. +static int set_names(const char *host, const char *domain) { + return sethostname(host, strlen(host)) == 0 && setdomainname(domain, strlen(domain)) == 0; +} + +// Returns an address no mapping covers, right after a mapped page, or NULL. +static char *unmapped_address(void) { + long size = sysconf(_SC_PAGESIZE); + char *pages = mmap(NULL, 2 * size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + if (pages == MAP_FAILED || munmap(pages + size, size) != 0) { + return NULL; + } + return pages + size; +} + +// The syscalls that set the host name and the domain name. +static const long setters[] = {SYS_sethostname, SYS_setdomainname}; + +// Returns whether the setter `number`, given `name` and `length`, fails with `error` and leaves the +// names `HOST` and `DOMAIN`. +static int fails_with(long number, const char *name, long length, int error) { + int failed = syscall(number, name, length) == -1 && errno == error; + return failed && has_names(HOST, DOMAIN); +} + +// `sethostname` and `setdomainname` take up to 64 bytes, kept as given, and zero the rest of the +// name, as `uname`, `gethostname`, and `getdomainname` report. They check the length before the +// bytes, and a failed call changes nothing. +static void set_and_read_names(void) { + char longest[NAME_MAX_LENGTH + 1]; + memset(longest, 'x', sizeof longest); + CHECK(sethostname(longest, NAME_MAX_LENGTH) == 0); + CHECK(setdomainname(longest, NAME_MAX_LENGTH) == 0); + struct utsname names; + CHECK(uname(&names) == 0 && holds(names.nodename, longest, NAME_MAX_LENGTH) && + holds(names.domainname, longest, NAME_MAX_LENGTH)); + char name[NAME_MAX_LENGTH + 1]; + CHECK(gethostname(name, sizeof name) == 0 && memcmp(name, longest, NAME_MAX_LENGTH) == 0 && + name[NAME_MAX_LENGTH] == 0); + CHECK(getdomainname(name, sizeof name) == 0 && memcmp(name, longest, NAME_MAX_LENGTH) == 0 && + name[NAME_MAX_LENGTH] == 0); + + // A shorter name clears the rest of a longer one, and an empty one clears it all. + CHECK(set_names(HOST, DOMAIN) && has_names(HOST, DOMAIN)); + CHECK(gethostname(name, sizeof name) == 0 && strcmp(name, HOST) == 0); + CHECK(getdomainname(name, sizeof name) == 0 && strcmp(name, DOMAIN) == 0); + CHECK(sethostname("", 0) == 0 && has_names("", DOMAIN)); + // The bytes are kept as given, zero bytes included. + CHECK(sethostname("a\0b", 3) == 0 && uname(&names) == 0 && holds(names.nodename, "a\0b", 3)); + + CHECK(set_names(HOST, DOMAIN)); + char *unmapped = unmapped_address(); + CHECK(unmapped != NULL); + for (size_t i = 0; unmapped != NULL && i < sizeof setters / sizeof setters[0]; i++) { + CHECK(fails_with(setters[i], longest, NAME_MAX_LENGTH + 1, EINVAL)); + CHECK(fails_with(setters[i], longest, -1, EINVAL)); + CHECK(fails_with(setters[i], unmapped, NAME_MAX_LENGTH + 1, EINVAL)); + CHECK(fails_with(setters[i], unmapped, 4, EFAULT)); + // A name that runs into the unmapped page. + CHECK(fails_with(setters[i], unmapped - 2, 4, EFAULT)); + } +} + +// The processes in a namespace share its names: a change by a child created by `fork`, by a +// vfork child, or by a program a child execs, reaches this program. +static void children_share_the_names(void) { + CHECK(set_names(HOST, DOMAIN)); + pid_t child = fork(); + if (child == 0) { + _exit(set_names(CHILD_HOST, CHILD_DOMAIN) ? 0 : 1); + } + CHECK(child > 0 && exited_with(child, 0)); + CHECK(has_names(CHILD_HOST, CHILD_DOMAIN)); + + // What the vfork child read before and after setting the host name, in memory it shares with + // this program. + static int read_before, read_after; + child = vfork(); + if (child == 0) { + read_before = has_names(CHILD_HOST, CHILD_DOMAIN); + read_after = sethostname(HOST, strlen(HOST)) == 0 && has_names(HOST, CHILD_DOMAIN); + _exit(CHILD_CODE); + } + CHECK(child > 0 && exited_with(child, CHILD_CODE) && read_before && read_after); + CHECK(has_names(HOST, CHILD_DOMAIN)); + + child = fork(); + if (child == 0) { + char *const argv[] = {self_path, "set", OTHER_HOST, NULL}; + execve(self_path, argv, environ); + _exit(2); + } + CHECK(child > 0 && exited_with(child, 0)); + CHECK(has_names(OTHER_HOST, CHILD_DOMAIN)); +} + +// Runs in a child in a new UTS namespace: checks that it starts with its parent's names, then, +// once its parent changed its own, which it doesn't see, sets its own names. +static int keep_names_apart(int ready, int changed) { + char byte; + if (!has_names(HOST, DOMAIN) || write(ready, "x", 1) != 1 || read(changed, &byte, 1) != 1) { + return 1; + } + return has_names(HOST, DOMAIN) && set_names(CHILD_HOST, CHILD_DOMAIN) && + has_names(CHILD_HOST, CHILD_DOMAIN) + ? 0 + : 2; +} + +// A child in a new UTS namespace, from `clone` or `clone3`, starts with a copy of its parent's +// names, and a change on either side doesn't reach the other. +static void new_namespaces_are_separate(void) { + for (int use_clone3 = 0; use_clone3 <= 1; use_clone3++) { + CHECK(set_names(HOST, DOMAIN)); + int ready[2], changed[2]; + if (pipe(ready) != 0 || pipe(changed) != 0) { + CHECK(0); + return; + } + pid_t child = use_clone3 ? clone3_child(CLONE_NEWUTS) : clone_child(CLONE_NEWUTS); + if (child == 0) { + // Each side keeps only the ends it uses, so it sees a pipe close if the other fails. + close(ready[0]); + close(changed[1]); + _exit(keep_names_apart(ready[1], changed[0])); + } + close(ready[1]); + close(changed[0]); + char byte; + CHECK(child > 0 && read(ready[0], &byte, 1) == 1); + CHECK(set_names(OTHER_HOST, OTHER_DOMAIN)); + CHECK(write(changed[1], "x", 1) == 1); + close(changed[1]); + CHECK(child > 0 && exited_with(child, 0)); + CHECK(has_names(OTHER_HOST, OTHER_DOMAIN)); + close(ready[0]); + } +} + +// Sets this process's names to `CHILD_HOST` and `CHILD_DOMAIN`, returning whether `uname` and +// `gethostname` then report them. +static int set_and_read_child_names(void) { + char name[NAME_MAX_LENGTH + 1]; + return set_names(CHILD_HOST, CHILD_DOMAIN) && has_names(CHILD_HOST, CHILD_DOMAIN) && + gethostname(name, sizeof name) == 0 && strcmp(name, CHILD_HOST) == 0; +} + +// Runs in a vfork child in a new UTS namespace: records at `read_back`, an `int`, whether it reads +// back the names it sets, then execs this program to check that it keeps them. +static int set_names_and_exec(void *read_back) { + *(int *)read_back = set_and_read_child_names(); + char *const argv[] = {self_path, "check", CHILD_HOST, CHILD_DOMAIN, NULL}; + execve(self_path, argv, environ); + _exit(2); +} + +// Runs in a vfork child: moves to a new UTS namespace, then records at `read_back`, an `int`, +// whether it reads back the names it sets. +static int unshare_and_set_names(void *read_back) { + *(int *)read_back = unshare(CLONE_NEWUTS) == 0 && set_and_read_child_names(); + _exit(CHILD_CODE); +} + +// A vfork child in a new UTS namespace, from `clone` or its own `unshare`, has its own names while +// it shares its parent's memory, and keeps them in the program it execs. Its parent's don't change. +static void vfork_children_have_their_own_names(void) { + CHECK(set_names(HOST, DOMAIN)); + int read_back = 0; + pid_t child = vfork_child(CLONE_NEWUTS, set_names_and_exec, &read_back); + CHECK(child > 0 && exited_with(child, 0) && read_back); + CHECK(has_names(HOST, DOMAIN)); + read_back = 0; + child = vfork_child(0, unshare_and_set_names, &read_back); + CHECK(child > 0 && exited_with(child, CHILD_CODE) && read_back); + CHECK(has_names(HOST, DOMAIN)); +} + +// Runs in a helper that has a child, `other`, waiting for a byte on `moved`: unshares a UTS +// namespace and sets its host name, which `other` doesn't see, then waits for `other` to set its +// own on `changed`, which the helper doesn't see. A child the helper creates afterwards shares the +// helper's names. +static int move_away_from_a_child(pid_t other, int moved, int changed) { + int moved_away = + unshare(CLONE_NEWUTS) == 0 && sethostname(CHILD_HOST, strlen(CHILD_HOST)) == 0; + // Without the byte, `other` sees the pipe close and fails rather than waiting. + int told = moved_away && write(moved, "x", 1) == 1; + close(moved); + char byte; + int heard = read(changed, &byte, 1) == 1; + if (!exited_with(other, 0) || !told || !heard) { + return 1; + } + if (!has_names(CHILD_HOST, DOMAIN)) { + return 2; + } + pid_t child = fork(); + if (child == 0) { + _exit(has_names(CHILD_HOST, DOMAIN) && + setdomainname(OTHER_DOMAIN, strlen(OTHER_DOMAIN)) == 0 + ? 0 + : 1); + } + return child > 0 && exited_with(child, 0) && has_names(CHILD_HOST, OTHER_DOMAIN) ? 0 : 3; +} + +// Runs in a helper's child, which stays in the helper's first UTS namespace: once the helper moved +// away, it still has the old names, and sets its own. +static int stay_behind(int moved, int changed) { + char byte; + return read(moved, &byte, 1) == 1 && has_names(HOST, DOMAIN) && + sethostname(OTHER_HOST, strlen(OTHER_HOST)) == 0 && write(changed, "x", 1) == 1 + ? 0 + : 1; +} + +// `unshare` moves only the calling process to a new UTS namespace: a helper unshares while its +// child stays in this program's namespace. +static int unshare_moves_the_caller(void) { + int moved[2], changed[2]; + if (pipe(moved) != 0 || pipe(changed) != 0) { + return 1; + } + pid_t other = fork(); + if (other == 0) { + // Each side keeps only the ends it uses, so it sees a pipe close if the other fails. + close(moved[1]); + close(changed[0]); + _exit(stay_behind(moved[0], changed[1])); + } + close(moved[0]); + close(changed[1]); + return other > 0 ? move_away_from_a_child(other, moved[1], changed[0]) : 1; +} + +// `unshare` creates a UTS namespace for the caller alone, with a copy of its names. +static void unshare_copies_the_names(void) { + CHECK(set_names(HOST, DOMAIN)); + CHECK(in_a_child(unshare_moves_the_caller)); + // The helper's child stayed in this program's namespace. + CHECK(has_names(OTHER_HOST, DOMAIN)); +} + +// Without root, the names can't be set, even with an invalid length or address. `uname` and +// `unshare` without namespaces still work. +static void unprivileged_changes_no_names(void) { + char longest[NAME_MAX_LENGTH + 1]; + memset(longest, 'x', sizeof longest); + char *unmapped = unmapped_address(); + CHECK(unmapped != NULL); + for (size_t i = 0; unmapped != NULL && i < sizeof setters / sizeof setters[0]; i++) { + CHECK(syscall(setters[i], longest, NAME_MAX_LENGTH + 1) == -1 && errno == EPERM); + CHECK(syscall(setters[i], unmapped, 4) == -1 && errno == EPERM); + } + struct utsname names; + CHECK(uname(&names) == 0); + CHECK(unshare(0) == 0); +} + // Without root, neither `unshare` nor `clone`, also vfork-style, creates a UTS or IPC namespace. static void unprivileged_creates_nothing(void) { const int flags[] = {CLONE_NEWUTS, CLONE_NEWIPC}; @@ -177,14 +475,30 @@ static void unprivileged_creates_nothing(void) { } int main(int argc, char **argv) { + // A program a child execs checks that it has the given names, or sets the given host name. + if (argc == 4 && strcmp(argv[1], "check") == 0) { + return has_names(argv[2], argv[3]) ? 0 : 1; + } + if (argc == 3 && strcmp(argv[1], "set") == 0) { + return sethostname(argv[2], strlen(argv[2])) == 0 ? 0 : 1; + } setvbuf(stdout, NULL, _IONBF, 0); if (argc > 1 && strcmp(argv[1], "unprivileged") == 0) { unprivileged_creates_nothing(); + unprivileged_changes_no_names(); printf("uts-ipc-namespace unprivileged failures=%d\n", failures); return failures != 0; } + self_path = argv[0]; + // A write to a pipe whose reader failed and exited fails rather than ending this program. + signal(SIGPIPE, SIG_IGN); clone_creates_namespaces(); unshare_creates_namespaces(); + set_and_read_names(); + children_share_the_names(); + new_namespaces_are_separate(); + vfork_children_have_their_own_names(); + unshare_copies_the_names(); printf("uts-ipc-namespace failures=%d\n", failures); return failures != 0; } From 794ae08ac95249e4a63b36e3399850be202f6a50 Mon Sep 17 00:00:00 2001 From: Weidong Cui Date: Sun, 15 Nov 2026 12:19:02 -0800 Subject: [PATCH 3/3] Describe host names in LiteBox terms in the shim The shim shouldn't assume how LiteBox supports host names, so its comments refer to LiteBox rather than the broker. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 2e5cd85d-5d69-4dcf-a36d-b00805c90d53 --- litebox_common_linux/src/lib.rs | 2 +- litebox_shim_linux/src/syscalls/misc.rs | 10 +++++----- litebox_shim_linux/src/syscalls/process.rs | 5 ++--- 3 files changed, 8 insertions(+), 9 deletions(-) diff --git a/litebox_common_linux/src/lib.rs b/litebox_common_linux/src/lib.rs index 6a787a784b..15e2c1858f 100644 --- a/litebox_common_linux/src/lib.rs +++ b/litebox_common_linux/src/lib.rs @@ -1994,7 +1994,7 @@ pub struct TaskParams { /// `__NEW_UTS_LEN`). pub const UTS_NAME_LENGTH: usize = 64; -// Every name Linux accepts fits in the broker's host names. +// Every name Linux accepts fits in LiteBox's host names. const _: () = assert!(UTS_NAME_LENGTH <= litebox_broker_protocol::process::MAX_HOST_NAME_SIZE as usize); diff --git a/litebox_shim_linux/src/syscalls/misc.rs b/litebox_shim_linux/src/syscalls/misc.rs index a00fe6f592..226626b22b 100644 --- a/litebox_shim_linux/src/syscalls/misc.rs +++ b/litebox_shim_linux/src/syscalls/misc.rs @@ -84,7 +84,7 @@ const SYS_INFO: litebox_common_linux::Utsname = litebox_common_linux::Utsname { /// Returns `name` as a `uname` field: its first [`UTS_NAME_LENGTH`] bytes, then zeros. /// -/// No Linux process can set a longer name, but the broker allows one, as from the host's +/// No Linux process can set a longer name, but LiteBox allows one, as from the host's /// configuration or another kind of guest. Like Linux with a long `hostname=` boot parameter, the /// shim truncates it rather than failing every `uname`. fn uts_field(name: &HostName) -> [u8; UTS_NAME_LENGTH + 1] { @@ -98,9 +98,9 @@ fn uts_field(name: &HostName) -> [u8; UTS_NAME_LENGTH + 1] { impl Task { /// Handle syscall `uname`. /// - /// The host and NIS domain names are the broker's host names of this process, or of the - /// `vfork` child, which processes in one UTS namespace share. Without a process service, they - /// are `SYS_INFO`'s. + /// The host and NIS domain names are LiteBox's host names of this process, or of the + /// `vfork` child, which processes in one UTS namespace share. If LiteBox can't keep host names + /// (`ProcessError::Unavailable`), they are `SYS_INFO`'s. pub(crate) fn sys_uname( &self, buf: UserPtrMut, @@ -143,7 +143,7 @@ impl Task { let mut bytes = [0; UTS_NAME_LENGTH]; name.copy_to_slice::(0, &mut bytes[..len]) .ok_or(Errno::EFAULT)?; - let name = HostName::new(&bytes[..len]).expect("Linux names fit the broker's"); + let name = HostName::new(&bytes[..len]).expect("Linux names fit LiteBox's"); let process_id = ProcessId(self.own_pid_for_requests().cast_unsigned()); self.global.litebox.set_host_name(process_id, kind, &name)?; Ok(()) diff --git a/litebox_shim_linux/src/syscalls/process.rs b/litebox_shim_linux/src/syscalls/process.rs index e7f86e361c..d478e2eb24 100644 --- a/litebox_shim_linux/src/syscalls/process.rs +++ b/litebox_shim_linux/src/syscalls/process.rs @@ -1142,9 +1142,8 @@ impl Task { .pid_namespace_unshared .store(true, Ordering::Relaxed); } - // Last, so that a failure above leaves the host names shared. Without a process service, - // the names are fixed, so there is nothing to copy. Otherwise, only a failed broker - // association, after which the process can't go on, fails the copy. + // Last, so that a failure above leaves the host names shared. If LiteBox can't change host + // names (`ProcessError::Unavailable`), they are fixed, so there is nothing to copy. if flags.contains(CloneFlags::NEWUTS) { match self .global