fix(ec2): give privileged systemd guests a private cgroup namespace (#7353)

Systemd guests ran with --cgroupns=host and the host's /sys/fs/cgroup bound
in, so every guest's systemd managed the same cgroup tree as the Docker
host and as each other. Two guests running Kubernetes nodes (kubelet with
the systemd cgroup driver, as Kubernetes The Hard Way configures it)
shared one kubepods.slice: both nodes saw the same inode, and each kubelet
tore down the other's pod sandboxes, so every pod restarted in a loop
(SandboxChanged, "network namespace for sandbox ... is closed").

A private namespace without the bind, as kind runs its nodes, gives each
guest's systemd its own writable subtree, because Docker mounts it
read-write for a privileged container. Measured on OrbStack (cgroup v2):
two guests boot to 'running', each with cgroup 0::/init.scope on a
distinct cgroupfs root.

A guest under security-group enforcement runs unprivileged, and Docker
mounts an unprivileged container's private cgroupfs read-only, where
systemd cannot create its slices. That guest keeps the host namespace and
the read-write bind, so it boots as before; the docs say its cgroups stay
shared.

fix(ec2): keep the IMDS proxy out of a systemd guest's root cgroup

A privileged systemd guest now has a private cgroup namespace, and a
docker exec lands in that namespace's root. Floci leaves its link-local
IMDS proxy (socat) running from such an exec, so the guest's root cgroup
held a process. cgroup v2 will not enable controllers in a cgroup's
subtree_control while it holds processes, so the root's stayed empty and
kubelet with the cgroupfs driver died creating kubepods.slice
("openat2 /sys/fs/cgroup/kubepods.slice/pids.max: no such file or
directory"). Whether a node hit it depended on whether anything else
enabled the controllers before the proxy started.

The proxy's install and start scripts now move their own shell into the
leaf /sys/fs/cgroup/floci first, so socat and everything else they start
stay out of the root. They do so only at the root of a cgroup v2
namespace whose cgroupfs is writable; a host-namespace container, a
cgroup v1 host and a read-only mount run as before. A plain directory
rather than systemd-run, because the proxy starts while the guest's
systemd may still be booting, and systemd neither reaps nor moves a
cgroup it did not create. EKS's pod-identity proxy shares the script.

The Docker integration test launches a privileged systemd guest through the real
container spec. It now also reads /proc/self/cgroup, which must be 0::/ at the
namespace root, and creates and removes a directory under /sys/fs/cgroup, so
native Linux CI fails if the guest falls back to the host cgroup namespace.

Rewrap the class javadoc, rename the test to cover both the modules and the
cgroup namespace, and comment what each cgroup probe does and does not prove.
This commit is contained in:
Allen Sanborn authored and GitHub committed 2026-11-12 11:28:20 -04:00
1 parent 14f01c80e8
commit 639fbe38d0
6 files changed
+138 -8

No files matched your search

+2
View File
@@ -9,6 +9,8 @@
!!! warning "Systemd guests can load modules into the host kernel"
An instance container runs privileged exactly when `FLOCI_NETWORK_SECURITY_GROUP_ENFORCEMENT_ENABLED` is off; with it on, the container joins a Floci-protected network namespace unprivileged, without Docker's `CAP_SYS_MODULE`, and a launch whose namespace cannot be created fails rather than falling back to privileged. A privileged systemd guest with the host's `/lib/modules/<KernelVersion>` mounted can `modprobe` any module that tree holds. The module loads into the **shared** kernel of the Docker host (or Docker Desktop / OrbStack VM), not into the guest. User data or an AMI that loads modules therefore changes the machine Floci runs on. Run systemd catalog images only with user data you would run on that host yourself, and prefer a disposable VM or CI runner for untrusted workloads.
A systemd guest gets a private cgroup namespace, as kind runs its nodes, so its systemd owns its own cgroup subtree and two guests running Kubernetes nodes do not share (and tear down) each other's `kubepods.slice`. Under security-group enforcement the guest runs unprivileged, and Docker mounts an unprivileged container's private cgroupfs read-only; there the guest keeps the host's cgroup namespace and a read-write bind of `/sys/fs/cgroup`, so it boots, but its cgroups are shared with the host and with other such guests. The private namespace was measured on OrbStack (cgroup v2); cgroup v1 hosts are untested. Floci's link-local IMDS proxy, which it starts in the guest with `docker exec`, moves itself into the leaf cgroup `/sys/fs/cgroup/floci` first: an exec'd process lands in the root of the guest's cgroup namespace, and cgroup v2 will not enable controllers in a cgroup that holds processes, so a proxy left there kept kubelet (cgroupfs driver) from creating `kubepods.slice`. Processes your own user data or SSM commands leave running in the background are not moved.
| EC2 state | Docker operation |
|---|---|
| `pending → running` | Container created and started |
@@ -758,11 +758,10 @@ public class Ec2ContainerManager {
specBuilder.withLabels(Map.of(ContainerStorageHelper.SECURITY_GROUP_WORKLOAD_LABEL, "true"));
}
if (image.systemd()) {
applySystemdCgroup(specBuilder, namespace == null);
specBuilder
.withCgroupnsMode("host")
.withMount(new Mount().withType(MountType.TMPFS).withTarget("/run"))
.withMount(new Mount().withType(MountType.TMPFS).withTarget("/run/lock"))
.withBind("/sys/fs/cgroup", "/sys/fs/cgroup");
.withMount(new Mount().withType(MountType.TMPFS).withTarget("/run/lock"));
// The guest shares the Docker host's kernel but ships none of its modules, so
// `modprobe br_netfilter` (Kubernetes node setup) fails with "not found" even
// when the module is built in. Only the running kernel's directory is bound: the
@@ -791,6 +790,25 @@ public class Ec2ContainerManager {
return null;
}
/**
* The cgroup setup a systemd guest boots with. A privileged guest gets a private cgroup namespace,
* as kind gives its nodes: Docker mounts that namespace's cgroupfs read-write for a privileged
* container, so the guest's systemd owns its own subtree. With the host namespace and the host's
* {@code /sys/fs/cgroup} bound in, every guest's systemd managed the same tree, so two Kubernetes
* nodes shared one {@code kubepods.slice} and each kubelet tore down the other's pod sandboxes.
*
* <p>A guest under security-group enforcement runs unprivileged, and Docker mounts an unprivileged
* container's private cgroupfs read-only, where systemd cannot create its slices. That guest keeps
* the host namespace and the read-write bind it booted with before, and with it the shared tree.
*/
static void applySystemdCgroup(ContainerBuilder.Builder spec, boolean privileged) {
if (privileged) {
spec.withCgroupnsMode("private");
} else {
spec.withCgroupnsMode("host").withBind("/sys/fs/cgroup", "/sys/fs/cgroup");
}
}
private void failLaunch(Instance instance) {
failLaunch(instance, instance.getPrivateIpAddress());
}
@@ -22,9 +22,30 @@ public final class Ec2MetadataProxy {
private Ec2MetadataProxy() {}
/**
* Moves the exec'd shell, and everything it starts, out of the container's root cgroup into the
* leaf {@code /sys/fs/cgroup/floci}. A {@code docker exec} lands in the root of the container's
* cgroup namespace, and a systemd guest runs with a private one. cgroup v2 will not enable
* controllers in a cgroup's {@code subtree_control} while that cgroup holds processes, so a
* long-lived socat left in the root kept it empty, and kubelet with the cgroupfs driver then
* failed to create {@code kubepods.slice} ("pids.max: no such file or directory").
*
* <p>Acts only when this shell sits at the root of a cgroup v2 namespace ({@code 0::/}) whose
* cgroupfs is writable. A host-namespace container reports its full path, cgroup v1 reports one
* line per hierarchy, and a read-only mount fails {@code -w} (access(2) reports EROFS, even for
* root); all three run as before. Any {@code mkdir} or write that still fails is swallowed.
* A plain directory rather than {@code systemd-run}, because the proxy starts while the guest's
* systemd may still be booting, and systemd neither reaps nor moves a cgroup it did not create.
*/
static final String LEAVE_ROOT_CGROUP =
"if [ \"$(cat /proc/self/cgroup 2>/dev/null)\" = 0::/ ] && [ -w /sys/fs/cgroup/cgroup.procs ]; then"
+ " { mkdir -p /sys/fs/cgroup/floci && echo $$ >/sys/fs/cgroup/floci/cgroup.procs; } 2>/dev/null || true;"
+ " fi";
public static String[] installCommand() {
return new String[]{"sh", "-c", String.join("\n",
"set -eu",
LEAVE_ROOT_CGROUP,
CLEAR_APPLICATION_PATHS,
"if command -v ip >/dev/null 2>&1 && command -v socat >/dev/null 2>&1 && command -v curl >/dev/null 2>&1; then exit 0; fi",
"if command -v apt-get >/dev/null 2>&1; then",
@@ -91,6 +112,7 @@ public final class Ec2MetadataProxy {
String logFile = "/tmp/floci-" + name + "-proxy.log";
return new String[]{"sh", "-c", String.join("\n",
"set -eu",
LEAVE_ROOT_CGROUP,
CLEAR_APPLICATION_PATHS,
"ip addr show dev lo | grep -q '" + bindIp + "/32' || ip addr add " + bindIp + "/32 dev lo",
// The pid file is on the container's writable layer, so it outlives a restart while
@@ -1754,8 +1754,8 @@ class Ec2ContainerManagerTest {
awaitUntil(() -> "running".equals(instance.getState().getName()), Duration.ofSeconds(2));
verify(harness.builder).withCmd(List.of("/sbin/init"));
verify(harness.builder).withCgroupnsMode("host");
verify(harness.builder).withBind("/sys/fs/cgroup", "/sys/fs/cgroup");
verify(harness.builder).withCgroupnsMode("private");
verify(harness.builder, never()).withBind("/sys/fs/cgroup", "/sys/fs/cgroup");
verify(harness.builder).withReadOnlyBind("/lib/modules/6.8.0-test", "/lib/modules/6.8.0-test");
verify(harness.builder, never()).withReadOnlyBind(eq("/lib/modules"), anyString());
// User data runs after the sshd step, so once it has started that step is settled.
@@ -1765,6 +1765,24 @@ class Ec2ContainerManagerTest {
verify(harness.lifecycleManager).create(any(ContainerSpec.class), eq("linux/arm64"));
}
@Test
void privilegedSystemdGuestGetsAPrivateCgroupNamespaceAndNoHostTree() {
ContainerBuilder.Builder spec = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
Ec2ContainerManager.applySystemdCgroup(spec, true);
verify(spec).withCgroupnsMode("private");
verify(spec, never()).withBind(anyString(), anyString());
}
@Test
void unprivilegedSystemdGuestUnderSecurityGroupEnforcementKeepsAWritableCgroupTree() {
// Docker mounts an unprivileged container's private cgroupfs read-only, and systemd
// cannot boot on it.
ContainerBuilder.Builder spec = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
Ec2ContainerManager.applySystemdCgroup(spec, false);
verify(spec).withCgroupnsMode("host");
verify(spec).withBind("/sys/fs/cgroup", "/sys/fs/cgroup");
}
@Test
void preferredMetadataSourceIpUsesConfiguredNetworkBeforeBridge() {
ContainerNetwork bridge = new ContainerNetwork();
@@ -28,6 +28,61 @@ import static org.junit.jupiter.api.Assumptions.assumeTrue;
class Ec2MetadataProxyTest {
@Test
void everyProxyCommandLeavesTheRootCgroupBeforeItStartsAnything() {
// A process left in the root of a systemd guest's private cgroup namespace keeps cgroup v2
// from enabling controllers there, and kubelet (cgroupfs driver) cannot create kubepods.
String prelude = Ec2MetadataProxy.LEAVE_ROOT_CGROUP;
assertTrue(prelude.startsWith("if [ \"$(cat /proc/self/cgroup 2>/dev/null)\" = 0::/ ]"
+ " && [ -w /sys/fs/cgroup/cgroup.procs ]; then"));
assertTrue(prelude.contains("mkdir -p /sys/fs/cgroup/floci && echo $$ >/sys/fs/cgroup/floci/cgroup.procs;"));
// Best effort: a read-only cgroupfs must not abort a script running under set -e.
assertTrue(prelude.contains("2>/dev/null || true;"));
for (String[] command : new String[][]{
Ec2MetadataProxy.installCommand(),
Ec2MetadataProxy.startCommand("10.0.0.1", 9169),
Ec2MetadataProxy.podIdentityStartCommand("10.0.0.1", 4566)}) {
assertTrue(command[2].startsWith("set -eu\n" + prelude + "\n"), command[2]);
}
}
@ParameterizedTest(name = "{0}")
@CsvSource(delimiter = '|', value = {
"private v2 namespace root | 0::/ | procs | true",
"host namespace (full path) | 0::/system.slice/docker-1.scope | procs | false",
"cgroup v1 hierarchy line | 4:pids:/ | procs | false",
"cgroupfs not writable | 0::/ | none | false",
"mkdir fails under set -e | 0::/ | block | false"})
void leaveRootCgroupMovesTheShellOnlyFromAWritableV2NamespaceRoot(String scenario, String selfCgroup,
String layout, boolean moved, @TempDir Path directory) throws Exception {
// Runs the real prelude with /proc/self/cgroup and /sys/fs/cgroup pointed at fakes.
Path proc = directory.resolve("self-cgroup");
Path root = Files.createDirectories(directory.resolve("cgroup"));
Files.writeString(proc, selfCgroup + "\n");
if (!layout.equals("none")) {
Files.writeString(root.resolve("cgroup.procs"), "");
}
if (layout.equals("block")) {
Files.writeString(root.resolve("floci"), ""); // a file, so mkdir -p fails even as root
}
String prelude = Ec2MetadataProxy.LEAVE_ROOT_CGROUP;
String faked = prelude.replace("/proc/self/cgroup", proc.toString())
.replace("/sys/fs/cgroup", root.toString());
assertTrue(prelude.contains("/proc/self/cgroup") && !faked.contains("/sys/fs/cgroup"), faked);
int exit = HelperShellFixture.run(new String[]{"sh", "-c", "set -eu\n" + faked + "\necho $$"},
directory, Map.of());
String output = HelperShellFixture.output(directory);
assertEquals(0, exit, scenario + ": " + output);
Path procs = root.resolve("floci/cgroup.procs");
if (moved) {
assertEquals(output, Files.readString(procs), "shell pid not written to the leaf cgroup");
} else {
assertTrue(Files.notExists(procs), scenario + ": shell moved out of " + selfCgroup);
}
}
@Test
void installCommandContainsSupportedPackageManagers() {
String[] command = Ec2MetadataProxy.installCommand();
@@ -38,8 +38,9 @@ import static org.junit.jupiter.api.Assumptions.assumeTrue;
import static org.mockito.Mockito.mock;
/**
* A systemd guest sees the Docker host's module tree, read-only. The launch goes through the real
* {@link Ec2ContainerManager} container spec and a real Docker daemon. The image is Alpine rather
* A systemd guest sees the Docker host's module tree, read-only, and runs in a private cgroup
* namespace. The launch goes through the real {@link Ec2ContainerManager} container spec and a
* real Docker daemon. The image is Alpine rather
* than a systemd cloud image, which is too heavy to pull in CI: the systemd runtime only decides
* the container's command and mounts, and Alpine's busybox {@code /sbin/init} stays up as PID 1.
*/
@@ -79,7 +80,7 @@ class Ec2SystemdGuestDockerIntegrationTest {
}
@Test
void systemdGuestSeesHostModulesReadOnly() {
void systemdGuestSeesHostModulesReadOnlyInPrivateCgroupNamespace() {
Ec2ContainerManager manager = new Ec2ContainerManager(containerBuilder, lifecycleManager,
mock(ContainerLogStreamer.class), mock(ContainerDetector.class), dockerHostResolver, docker,
portAllocator, config, mock(Ec2MetadataServer.class), mock(Ec2PortForwardManager.class),
@@ -115,6 +116,20 @@ class Ec2SystemdGuestDockerIntegrationTest {
new String[]{"sh", "-c", "touch /lib/modules/.floci-w && rm /lib/modules/.floci-w"}, 30);
assertEquals(0, writable.exitCode(),
"guest's /lib/modules outside " + modulesDir + " is not writable: " + writable.summary());
// A privileged guest gets its own cgroup namespace: it sits at the namespace root, and
// Docker mounts that cgroupfs read-write so the guest's systemd can create slices.
// Assumes cgroup v2: on v1/hybrid hosts there is no "0::" line.
ContainerExec.Result cgroup =ContainerExec.runMerged(docker, containerId,
new String[]{"cat", "/proc/self/cgroup"}, 30);
assertEquals(0, cgroup.exitCode(), "cannot read the guest's cgroup: " + cgroup.summary());
assertTrue(cgroup.stdout().lines().anyMatch("0::/"::equals),
"guest is not at the root of a private cgroup namespace: " + cgroup.stdout());
// Checks only that the cgroupfs is writable; the host namespace is writable too, so the
// "0::/" line above is what distinguishes a private namespace.
ContainerExec.Result cgroupfs =ContainerExec.runMerged(docker, containerId,
new String[]{"sh", "-c", "mkdir /sys/fs/cgroup/.floci-w && rmdir /sys/fs/cgroup/.floci-w"}, 30);
assertEquals(0, cgroupfs.exitCode(), "guest's cgroupfs is not writable: " + cgroupfs.summary());
} finally {
// terminate() removes the container and releases the SSH port in the shared allocator.
CountDownLatch torndown = new CountDownLatch(1);