context,deb: run the rules as a nested-namespace build identity

Rootless builds handed the staged tree to the build user with a
recursive chown; through the overlay staging every lower-layer file
the chown touched copy-ups — the full data movement of the tree, 19%
of a kernel build's wall clock.

The rules steps are now flagged and the unshare driver enters the
chroot by pivot_root instead of chroot(2), then creates a nested user
namespace mapping the context's root onto a fixed build id: the
chroot's files are the invoking user's host-side and the context maps
that user to uid 0, so the staged tree is owned by the build identity
by construction — no chown, no data movement. The kernel refuses user
namespace creation to chrooted processes, hence the pivot, and the
bind is recursive and taken inside the namespace: a plain bind of the
chroot's host-made submounts fails EINVAL on locked children, while
the rbind carries them across the pivot, and a fresh /proc is mounted
before the old root is shed (umount resolves through /proc/mounts).

fakeroot's chown wrappers attempt the real chown and swallow only
EPERM; as the mapped identity, root targets are unmapped and fail
EINVAL, so mapped builds export FAKEROOTDONTTRYCHOWN — fakeroot's own
knob — and the fake ownership is still recorded. Files the build
writes come out as the invoking user host-side, which also fixes the
silently missing .buildinfo/.changes of rootless builds: the host-side
rewrite of debian/files hit a subuid-owned file with EACCES.

The wrapper is probed per build; when nested namespaces are
unavailable (old util-linux, userns disabled), the previous setpriv
plus selective parallel chown handover runs unchanged. A setpriv-era
staged tree is handed to the invoking user once, host-side and
metadata-only, before the overlay mounts it — afterwards overlayfs
serves stale owners from its attribute cache.
This commit is contained in:
vhaudiquet committed 2026-10-03 13:00:26 +02:00
1 parent 5544873107
commit 2729f9d9e7
6 files changed
+526 -58

No files matched your search

+298 -39
View File
@@ -7,6 +7,7 @@ use crate::report::BuildView;
use log::warn;
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::error::Error;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::Arc;
@@ -96,17 +97,105 @@ pub(crate) fn apply_ccache_env(env: &mut HashMap<String, String>, enabled: bool,
/// (ssh, schroot) keep running the rules as their own user.
pub const BUILD_USER: &str = "pkh-build";
/// How the rules steps run as an unprivileged build identity.
enum RulesIdentity {
/// A nested user namespace maps the chroot's root ownership onto
/// [`crate::context::MAPPED_BUILD_ID`]: the whole staged tree — the
/// chroot's files are the invoking user's host-side, and the context
/// namespace maps that user to uid 0 — shows as already owned by the
/// build identity, so nothing is chowned and no data moves. Files the
/// build writes come out as the invoking user's own host-side.
MappedNamespace,
/// Fallback when the nested namespace is unavailable: `setpriv` drops
/// to an ordinary chroot user, and the tree is handed over with a
/// selective parallel chown. Carries the (uid, gid).
Setpriv(String, String),
}
/// Whether the build context can establish the nested build-identity
/// namespace: kernel user namespaces reachable, a new enough util-linux
/// (`--map-user`), the pivot wrapper working, and the mapping actually
/// taken. The probe runs the real wrapper over a `sh` test, so a failure
/// here means the fallback would fail the same way.
fn probe_mapped_namespace(ctx: &Arc<Context>) -> Result<(), String> {
let mut cmd = ctx.command("sh");
cmd.env(crate::context::MAPPED_IDENTITY_ENV, "1")
.arg("-c")
.arg(format!(
"test \"$(id -u)\" = {} && test \"$(id -g)\" = {}",
crate::context::MAPPED_BUILD_ID,
crate::context::MAPPED_BUILD_ID
));
match cmd.output() {
Ok(out) if out.status.success() => Ok(()),
Ok(out) => {
let stderr = String::from_utf8_lossy(&out.stderr);
Err(if stderr.trim().is_empty() {
format!("exit status {}", out.status)
} else {
stderr.trim().to_string()
})
}
Err(e) => Err(e.to_string()),
}
}
/// Ensure [`BUILD_USER`] exists in the build context and owns everything
/// the rules must write: the staged tree (whose parent is where
/// dh_builddeb drops the .debs), the scratch HOME and the shared ccache
/// directory. Returns the (uid, gid) for the setpriv invocation. Ownership
/// is re-applied on every build: a resumed build stages the tree fresh
/// from the host, where everything is root-owned again.
/// directory. Returns how the rules drop privileges.
///
/// The mapped namespace is the ownership by construction: the chroot's
/// files are the invoking user's host-side and the context maps that user
/// to uid 0, so a namespace nested inside the context's, mapping uid 0
/// onto [`crate::context::MAPPED_BUILD_ID`], makes the build identity the
/// owner of everything without moving a byte. The fallback creates an
/// ordinary chroot user and hands the tree over with a chown — through
/// the overlay staging every chowned lower-layer file copy-ups, which on
/// a kernel tree costs minutes (see [`hand_over_script`]).
fn ensure_build_user(
ctx: &Arc<Context>,
workroot: &Path,
session: Option<&session::Session>,
build_resume: bool,
ccache_dir: Option<&str>,
) -> Result<(String, String), Box<dyn Error>> {
ccache_host_dir: Option<&Path>,
) -> Result<RulesIdentity, Box<dyn Error>> {
let mut mapped = match probe_mapped_namespace(ctx) {
Ok(()) => true,
Err(reason) => {
log::info!(
"Nested user namespaces are unavailable in the build \
context ({reason}); falling back to the chown handover"
);
false
}
};
// A setpriv-era upperdir must already have been handed over by the
// pre-staging migration (`migrate_upper_ownership`, called before the
// overlay mounts): chowning it now, behind the live mount, would leave
// stale-owned entries behind the overlay's attribute cache. If it is
// still foreign-owned the migration failed — take the chown fallback,
// whose in-chroot chown needs no host escalation.
if mapped
&& let Some(upper) = resumed_upper_dir(session, build_resume)
&& has_foreign_owner(&upper)
{
log::warn!(
"the staged tree carries setpriv-era ownership the pre-staging \
migration could not hand over; falling back to the chown \
handover"
);
mapped = false;
}
if mapped {
if let Some(dir) = ccache_host_dir.filter(|dir| dir.is_dir()) {
migrate_ccache_ownership(dir);
}
write_build_user_entries(ctx, crate::context::MAPPED_BUILD_ID)?;
return Ok(RulesIdentity::MappedNamespace);
}
// Through sh with the stderr dropped: a missing user is the expected
// state in a fresh chroot, not a message the build log needs.
let id_of = |ctx: &Arc<Context>, what: &str| {
@@ -145,7 +234,162 @@ fn ensure_build_user(
if let Some(dir) = ccache_dir {
let _ = hand_over(ctx, Path::new(dir), &ids);
}
Ok(ids)
Ok(RulesIdentity::Setpriv(ids.0, ids.1))
}
/// Append the passwd and group entries naming [`BUILD_USER`] at `id` —
/// the identity of the mapped namespace (and of the setpriv fallback when
/// the chroot carries no useradd). Minimal mmdebstrap chroots carry no
/// passwd package, so the entries are appended directly, as sbuild's
/// build-user setup does.
fn write_build_user_entries(ctx: &Arc<Context>, id: u32) -> Result<(), Box<dyn Error>> {
// Through sh with the stderr dropped: a missing entry is the expected
// state in a fresh chroot, not a message the build log needs.
let known = ctx
.command("sh")
.arg("-c")
.arg(format!("id -u {BUILD_USER} 2>/dev/null"))
.output()
.is_ok_and(|out| out.status.success());
if known {
return Ok(());
}
for (file, entry) in [
("/etc/group", format!("{BUILD_USER}:x:{id}:")),
(
"/etc/passwd",
format!("{BUILD_USER}:x:{id}:{id}:/tmp/pkh-home:/usr/sbin/nologin"),
),
] {
let status = ctx
.command("sh")
.arg("-c")
.arg(format!("echo {} >> {file}", shlex_quote(&entry)))
.status()
.map_err(|e| format!("cannot append to {file}: {e}"))?;
if !status.success() {
return Err(format!("cannot append the {BUILD_USER} entry to {file}").into());
}
}
Ok(())
}
/// The host-side path of the staged tree's persistent overlay upperdir,
/// when this build resumes over one carrying setpriv-era files. Any other
/// staging mounts a fresh (empty) upper or a plain copy, and the merge
/// shows the host tree's own (invoking-user) files.
fn resumed_upper_dir(session: Option<&session::Session>, build_resume: bool) -> Option<PathBuf> {
build_resume
.then_some(session)
.flatten()
.map(|s| s.upper_dir())
.filter(|dir| dir.is_dir())
}
/// Whether any entry under `root` is not owned by the invoking user
/// host-side — the mark of a setpriv-era build (the old identity was a
/// chroot-local uid, host-side a subuid). The metadata is hot when the
/// resume sync just walked the same tree.
fn has_foreign_owner(root: &Path) -> bool {
use std::os::unix::fs::MetadataExt;
let euid = unsafe { libc::geteuid() };
let mut stack = vec![root.to_path_buf()];
while let Some(dir) = stack.pop() {
let Ok(entries) = fs::read_dir(&dir) else {
continue;
};
for entry in entries.flatten() {
let Ok(meta) = fs::symlink_metadata(entry.path()) else {
continue;
};
if meta.uid() != euid {
return true;
}
if meta.is_dir() {
stack.push(entry.path());
}
}
}
false
}
/// Hand a setpriv-era staged tree to the invoking user (one recursive,
/// host-side, metadata-only chown): the ownership the mapped-namespace
/// build identity writes with.
///
/// This MUST run before the overlay staging mounts the upperdir. Overlayfs
/// snapshots the owner into its overlay inode at first lookup, and its
/// permission checks consult that snapshot — a chown applied behind a live
/// mount leaves every previously-looked-up entry stale-owned, and the
/// rules (running as the mapped identity) fail with EACCES on files the
/// host side swears they own. On the unmounted upperdir the same chown is
/// a plain metadata pass, never a data copy.
pub(crate) fn migrate_upper_ownership(session: &session::Session) -> Result<(), Box<dyn Error>> {
let Some(upper) = session.upper_dir().is_dir().then_some(session.upper_dir()) else {
return Ok(());
};
if !has_foreign_owner(&upper) {
return Ok(());
}
let is_root = crate::utils::root::is_root().unwrap_or(false);
log::info!(
"Handing '{}' to the invoking user once (setpriv-era ownership, \
metadata only)",
upper.display()
);
let owner = format!("{}:{}", unsafe { libc::geteuid() }, unsafe {
libc::getegid()
});
let status = crate::deb::ephemeral::privileged_command("chown", is_root)
.arg("-R")
.arg(owner)
.arg(&upper)
.status()
.map_err(|e| format!("cannot hand over '{}': {e}", upper.display()))?;
if !status.success() {
return Err(format!(
"cannot hand over '{}' (ownership escalation failed)",
upper.display()
)
.into());
}
Ok(())
}
/// One-time migration of the shared ccache to the invoking user's
/// host-side ownership, keyed on a marker inside the cache so its walk
/// runs once per cache, not once per build. The ccache is bind-mounted
/// (no overlay attribute caching), so this is safe at any point of the
/// build.
fn migrate_ccache_ownership(ccache_host_dir: &Path) {
let marker = ccache_host_dir.join(".pkh-ownership");
if marker.is_file() || !has_foreign_owner(ccache_host_dir) {
return;
}
let is_root = crate::utils::root::is_root().unwrap_or(false);
log::info!(
"Handing the shared ccache '{}' to the invoking user once \
(setpriv-era ownership, metadata only)",
ccache_host_dir.display()
);
let owner = format!("{}:{}", unsafe { libc::geteuid() }, unsafe {
libc::getegid()
});
let status = crate::deb::ephemeral::privileged_command("chown", is_root)
.arg("-R")
.arg(owner)
.arg(ccache_host_dir)
.status();
if status.is_ok_and(|s| s.success()) {
let _ = fs::write(&marker, "mapped\n");
} else {
log::warn!(
"cannot hand the shared ccache '{}' over; its shard \
directories stay unwritable and compiles fall back to \
running without cache hits",
ccache_host_dir.display()
);
}
}
/// The shell pipeline handing `dir` to the build identity: chown only the
@@ -183,9 +427,9 @@ fn hand_over(ctx: &Arc<Context>, dir: &Path, ids: &(String, String)) -> Result<(
Ok(())
}
/// Create [`BUILD_USER`] in the build context. Minimal mmdebstrap chroots
/// carry no passwd package (no useradd), so the passwd and group entries
/// are appended directly when needed, as sbuild's build-user setup does.
/// Create [`BUILD_USER`] in the build context (the setpriv fallback).
/// Chroots carrying the passwd package take the useradd path; minimal
/// mmdebstrap ones append the entries directly at a fixed, free id.
fn create_build_user(ctx: &Arc<Context>) -> Result<(), Box<dyn Error>> {
let have_useradd = ctx
.command("sh")
@@ -224,24 +468,7 @@ fn create_build_user(ctx: &Arc<Context>) -> Result<(), Box<dyn Error>> {
let uid = (64500..=65500)
.find(|id| !used(&passwd, *id) && !used(&group, *id))
.ok_or("no free uid for the build user")?;
for (file, entry) in [
("/etc/group", format!("{BUILD_USER}:x:{uid}:")),
(
"/etc/passwd",
format!("{BUILD_USER}:x:{uid}:{uid}:/tmp/pkh-home:/usr/sbin/nologin"),
),
] {
let status = ctx
.command("sh")
.arg("-c")
.arg(format!("echo {} >> {file}", shlex_quote(&entry)))
.status()
.map_err(|e| format!("cannot append to {file}: {e}"))?;
if !status.success() {
return Err(format!("cannot append the {BUILD_USER} entry to {file}").into());
}
}
Ok(())
write_build_user_entries(ctx, uid)
}
/// Single-quote a string for /bin/sh.
@@ -249,17 +476,26 @@ fn shlex_quote(value: &str) -> String {
format!("'{}'", value.replace('\'', r"'\''"))
}
/// The rules command for the given user: `setpriv` drops to the build user
/// without touching the environment (a login shell would reset it), so the
/// dpkg architecture variables and DEB_BUILD_OPTIONS survive the
/// transition; without a user the rules run as the context's own.
/// The rules command for the given build identity. Under the mapped
/// namespace the command is flagged for the unshare driver, which pivots
/// into the chroot and creates the nested namespace: the process simply
/// IS the build identity, no setpriv needed. The fallback `setpriv`
/// drops to the build user without touching the environment (a login
/// shell would reset it), so the dpkg architecture variables and
/// DEB_BUILD_OPTIONS survive the transition. Without an identity the
/// rules run as the context's own.
fn rules_command<'a>(
ctx: &'a Arc<Context>,
user: Option<&(String, String)>,
identity: Option<&RulesIdentity>,
program: &str,
) -> ContextCommand<'a> {
match user {
Some((uid, gid)) => {
match identity {
Some(RulesIdentity::MappedNamespace) => {
let mut cmd = ctx.command(program);
cmd.env(crate::context::MAPPED_IDENTITY_ENV, "1");
cmd
}
Some(RulesIdentity::Setpriv(uid, gid)) => {
let mut cmd = ctx.command("setpriv");
cmd.arg(format!("--reuid={uid}"))
.arg(format!("--regid={gid}"))
@@ -713,24 +949,47 @@ pub async fn build(
// LTO/make -j process flood), and a rules chown that fails for the
// build user is cosmetic — the .deb is assembled in the binary step's
// own fakeroot session, where files unknown to its database are
// recorded as root-owned anyway. Handing the tree over is a selective,
// parallel chown (through the overlay staging each chown copy-ups the
// file it touches), and it is a phase of its own in the status bar and
// the profile.
// recorded as root-owned anyway. The mapped-namespace identity owns
// the tree by construction (no chown at all); the setpriv fallback
// hands it over with a selective, parallel chown, and it is a phase
// of its own in the status bar and the profile.
if build_user.is_some() {
enter_phase(view, Phase::PreparingBuildUser, profiler);
}
let ccache_host_dir = ccache.then(|| {
session::ccache_dir(&session::SessionIdentity {
package: package.to_string(),
series: series.to_string(),
arch: arch.to_string(),
cross,
})
});
let rule_ids = match build_user {
Some(_) => {
let workroot = Path::new(package_dir_str)
.parent()
.ok_or("cannot find the staged tree's parent directory")?
.to_path_buf();
let ccache_dir = env.get("CCACHE_DIR").cloned();
Some(ensure_build_user(&ctx, &workroot, ccache_dir.as_deref())?)
Some(ensure_build_user(
&ctx,
&workroot,
session,
build_resume,
env.get("CCACHE_DIR").map(String::as_str),
ccache_host_dir.as_deref(),
)?)
}
None => None,
};
if matches!(rule_ids, Some(RulesIdentity::MappedNamespace)) {
// fakeroot's chown wrappers attempt the real chown and swallow only
// EPERM; as the mapped identity, targets like root:root resolve to
// nothing in the nested namespace and fail with EINVAL, which
// propagates (dh_fixperms chowns to root:root). This env is
// fakeroot's own knob to skip the real attempt — the fake
// ownership is still recorded, which is all the binary step needs.
env.insert("FAKEROOTDONTTRYCHOWN".to_string(), "1".to_string());
}
// Run the build step
log::debug!("Building (debian/rules build) package...");
+14 -2
View File
@@ -46,8 +46,10 @@ pub enum Phase {
/// Drop the resumed tree's input-untracked stamp caches (quirk:
/// `resume_clear`)
ClearingResumeCaches,
/// Create the unprivileged build user and hand the staged tree to
/// it (rootless builds)
/// Establish the unprivileged build identity for the rules steps
/// (rootless builds): a nested user namespace mapping the chroot's
/// root ownership onto the identity — the tree needs no chown — or,
/// when unavailable, a build user with a chown tree handover
PreparingBuildUser,
/// debian/rules build
Building,
@@ -642,6 +644,16 @@ async fn build_binary_package_impl(
log::info!(
"Reusing the build artifacts of the previous attempt (incremental build)"
);
// Before the overlay mounts (see the function's doc): a
// setpriv-era tree handed over here lets the mapped
// build identity run the rules; a failed handover makes
// the identity setup fall back to the chown handover.
if let Err(e) = local::migrate_upper_ownership(s) {
log::warn!(
"cannot hand the staged tree to the invoking user \
({e}); falling back to the chown handover"
);
}
}
}
let staged_path = if let Some(s) = &session {
+5 -3
View File
@@ -2136,9 +2136,11 @@ pub(crate) fn plan_upper_sync(
///
/// Removals go through the privileged path: the upperdir's entries were
/// copy-up'd by whoever wrote them during the build — in a rootless build
/// the unprivileged build user (a subuid of the invoking user host-side) —
/// so a plain removal by the invoking user fails with EPERM exactly when a
/// host-modified file's stale upper copy must go.
/// the unprivileged build identity, whose files are the invoking user's
/// own host-side under the mapped namespace (a subuid of theirs with the
/// setpriv fallback, or of earlier builds) — so a plain removal by the
/// invoking user fails with EPERM exactly when a host-modified file's
/// stale upper copy must go.
pub(crate) fn apply_upper_sync(upper_root: &Path, ops: &[UpperOp]) -> io::Result<usize> {
let mut removed_prefixes: Vec<String> = Vec::new();
let mut removed = 0;