mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(ec2): bind the host's /lib/modules read-only into systemd guests (#7354)
A systemd guest shares the Docker host's kernel but ships none of its modules, so `modprobe br_netfilter` (Kubernetes node setup, e.g. Kubernetes The Hard Way lab 9) fails with "Module not found in directory /lib/modules/<kver>" even when the module is built in. kind binds the host's tree the same way. Docker creates a missing bind source as an empty directory, so hosts without /lib/modules still launch. Privileged systemd guests can now load any module in that tree into the shared host (or Docker Desktop / OrbStack VM) kernel, so docs/services/ec2.md carries a warning saying so. test(ec2): prove a systemd guest gets /lib/modules read-only on a real daemon Ec2SystemdGuestDockerIntegrationTest launches through the real Ec2ContainerManager container spec against Docker, with an Alpine image standing in for a systemd cloud image (its busybox /sbin/init stays up as PID 1), and checks the mount both from the daemon's inspect and from the guest's /proc/mounts. It is skipped when Docker is unavailable. docs/services/ec2.md now says that on Docker Desktop or OrbStack the tree is the VM's and may not match its running kernel, and states exactly when an instance runs privileged: only with security-group enforcement off. With enforcement on, the guest joins the protected namespace unprivileged, and a namespace that cannot be created fails the launch. docs(ec2): say the read-only modules mount does not bind a privileged guest; keep test cleanup from masking failures The read-only bind keeps an unprivileged guest from changing the tree, but a privileged guest can remount it read-write, so the first paragraph no longer claims the guest cannot load a module the host kernel lacks. The systemd guest test now logs a failed container removal instead of throwing it over the assertion error it is reporting. fix(ec2): bind only the running kernel's /lib/modules dir into systemd guests; tear down the integration test via terminate() test(ec2): pin that the guest's /lib/modules outside the bound kernel dir stays writable; document missing-dir and linux-modules caveats
This commit is contained in:
1 parent
42b28be218
commit
0de5566d22
4 files changed
+166
-1
No files matched your search
@@ -4,7 +4,10 @@
|
||||
|
||||
## Instance Execution Model
|
||||
|
||||
`RunInstances` launches a **real Docker container** for each instance. By default, the container is kept alive with `tail -f /dev/null` so any base image works regardless of its default CMD. Catalog entries that opt into the `systemd` guest runtime start `/sbin/init` instead, with the Docker mounts needed for a systemd-based cloud-image guest.
|
||||
`RunInstances` launches a **real Docker container** for each instance. By default, the container is kept alive with `tail -f /dev/null` so any base image works regardless of its default CMD. Catalog entries that opt into the `systemd` guest runtime start `/sbin/init` instead, with the Docker mounts needed for a systemd-based cloud-image guest. Those guests also get the Docker host's `/lib/modules/<KernelVersion>` (the running kernel's directory only, so the guest's own package manager keeps a writable `/lib/modules`) read-only, so `modprobe` finds modules the shared kernel already has (for example `br_netfilter`, which Kubernetes node setup loads). The mount is read-only, but it is not a boundary for a privileged guest: one can remount that directory read-write and load any module built for the shared kernel (see the warning below). On Docker Desktop or OrbStack, that directory is the Linux VM's, which may not hold modules matching the kernel that VM is running. If `/lib/modules/<KernelVersion>` does not exist on the Docker daemon's host, Docker creates an empty root-owned directory there and `modprobe` still fails. The bind is read-only, so a guest that installs the `linux-modules` package for the host's exact kernel version cannot write into it.
|
||||
|
||||
!!! 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.
|
||||
|
||||
| EC2 state | Docker operation |
|
||||
|---|---|
|
||||
|
||||
@@ -761,10 +761,34 @@ public class Ec2ContainerManager {
|
||||
.withMount(new Mount().withType(MountType.TMPFS).withTarget("/run"))
|
||||
.withMount(new Mount().withType(MountType.TMPFS).withTarget("/run/lock"))
|
||||
.withBind("/sys/fs/cgroup", "/sys/fs/cgroup");
|
||||
// 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
|
||||
// guest's dpkg owns the rest of /lib/modules, and a read-only bind of the whole
|
||||
// tree breaks apt-get upgrade, DKMS and linux-modules-extra.
|
||||
String kernelVersion = hostKernelVersion();
|
||||
if (kernelVersion != null) {
|
||||
String modules = "/lib/modules/" + kernelVersion;
|
||||
specBuilder.withReadOnlyBind(modules, modules);
|
||||
}
|
||||
}
|
||||
return specBuilder.build();
|
||||
}
|
||||
|
||||
/** The Docker daemon's kernel version, or null when it cannot be read (the modules bind is then skipped). */
|
||||
private String hostKernelVersion() {
|
||||
try {
|
||||
String version = dockerClient.infoCmd().exec().getKernelVersion();
|
||||
if (version != null && !version.isBlank()) {
|
||||
return version;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.debugv("Could not read the Docker host's kernel version: {0}", e.getMessage());
|
||||
}
|
||||
LOG.warn("Docker host kernel version unknown; systemd guest launches without /lib/modules");
|
||||
return null;
|
||||
}
|
||||
|
||||
private void failLaunch(Instance instance) {
|
||||
failLaunch(instance, instance.getPrivateIpAddress());
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import com.github.dockerjava.api.command.CopyArchiveToContainerCmd;
|
||||
import com.github.dockerjava.api.command.ExecCreateCmd;
|
||||
import com.github.dockerjava.api.command.ExecCreateCmdResponse;
|
||||
import com.github.dockerjava.api.command.ExecStartCmd;
|
||||
import com.github.dockerjava.api.command.InfoCmd;
|
||||
import com.github.dockerjava.api.command.InspectContainerCmd;
|
||||
import com.github.dockerjava.api.command.InspectContainerResponse;
|
||||
import com.github.dockerjava.api.command.InspectExecCmd;
|
||||
@@ -21,6 +22,7 @@ import com.github.dockerjava.api.model.ContainerConfig;
|
||||
import com.github.dockerjava.api.model.ContainerNetwork;
|
||||
import com.github.dockerjava.api.model.Frame;
|
||||
import com.github.dockerjava.api.model.HostConfig;
|
||||
import com.github.dockerjava.api.model.Info;
|
||||
import com.github.dockerjava.api.model.NetworkSettings;
|
||||
import com.github.dockerjava.api.model.StreamType;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
@@ -1728,6 +1730,11 @@ class Ec2ContainerManagerTest {
|
||||
Ec2ContainerManager.containerBridgeIpAttempts = 1;
|
||||
Ec2ContainerManager.containerBridgeIpPollMillis = 1;
|
||||
LaunchHarness harness = launchHarness();
|
||||
InfoCmd infoCmd = mock(InfoCmd.class);
|
||||
Info info = mock(Info.class);
|
||||
when(harness.dockerClient.infoCmd()).thenReturn(infoCmd);
|
||||
when(infoCmd.exec()).thenReturn(info);
|
||||
when(info.getKernelVersion()).thenReturn("6.8.0-test");
|
||||
when(harness.lifecycleManager.create(any(ContainerSpec.class), eq("linux/arm64")))
|
||||
.thenReturn(TEST_CONTAINER_ID);
|
||||
InspectContainerCmd inspect = mock(InspectContainerCmd.class);
|
||||
@@ -1748,6 +1755,8 @@ class Ec2ContainerManagerTest {
|
||||
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).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.
|
||||
awaitUntil(() -> commandIndex(harness.executedCommands, "/var/lib/user-data.sh") >= 0, Duration.ofSeconds(2));
|
||||
assertEquals(-1, commandIndex(harness.executedCommands, "/usr/sbin/sshd"),
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
package io.floci.aws.services.ec2;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.command.InspectContainerResponse;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.docker.ContainerBuilder;
|
||||
import io.floci.aws.core.common.docker.ContainerDetector;
|
||||
import io.floci.aws.core.common.docker.ContainerExec;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
|
||||
import io.floci.aws.core.common.docker.ContainerLogStreamer;
|
||||
import io.floci.aws.core.common.docker.ContainerReachableEndpoint;
|
||||
import io.floci.aws.core.common.docker.DockerHostResolver;
|
||||
import io.floci.aws.core.common.docker.PortAllocator;
|
||||
import io.floci.aws.services.ec2.model.Instance;
|
||||
import io.floci.aws.services.ec2.net.VpcNetworkManager;
|
||||
import io.floci.aws.services.ec2.portforward.Ec2PortForwardManager;
|
||||
import io.floci.aws.testing.DockerAvailability;
|
||||
import io.floci.aws.testing.TestImages;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
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
|
||||
* 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.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class Ec2SystemdGuestDockerIntegrationTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final Logger LOG = Logger.getLogger(Ec2SystemdGuestDockerIntegrationTest.class);
|
||||
|
||||
@Inject
|
||||
DockerClient docker;
|
||||
|
||||
@Inject
|
||||
ContainerBuilder containerBuilder;
|
||||
|
||||
@Inject
|
||||
ContainerLifecycleManager lifecycleManager;
|
||||
|
||||
@Inject
|
||||
DockerHostResolver dockerHostResolver;
|
||||
|
||||
@Inject
|
||||
PortAllocator portAllocator;
|
||||
|
||||
@Inject
|
||||
EmulatorConfig config;
|
||||
|
||||
@Inject
|
||||
RegionResolver regionResolver;
|
||||
|
||||
@Inject
|
||||
ContainerReachableEndpoint reachableEndpoint;
|
||||
|
||||
@BeforeEach
|
||||
void requireDocker() {
|
||||
assumeTrue(DockerAvailability.answers(docker), "Docker must be available for EC2 systemd guest tests");
|
||||
}
|
||||
|
||||
@Test
|
||||
void systemdGuestSeesHostModulesReadOnly() {
|
||||
Ec2ContainerManager manager = new Ec2ContainerManager(containerBuilder, lifecycleManager,
|
||||
mock(ContainerLogStreamer.class), mock(ContainerDetector.class), dockerHostResolver, docker,
|
||||
portAllocator, config, mock(Ec2MetadataServer.class), mock(Ec2PortForwardManager.class),
|
||||
regionResolver, mock(ContainerNetworkReachability.class), mock(VpcNetworkManager.class),
|
||||
reachableEndpoint);
|
||||
Instance instance = new Instance();
|
||||
instance.setInstanceId("i-systemd" + UUID.randomUUID().toString().replace("-", "").substring(0, 8));
|
||||
instance.setRegion(REGION);
|
||||
String modulesDir = "/lib/modules/" + docker.infoCmd().exec().getKernelVersion();
|
||||
try {
|
||||
manager.launch(instance,
|
||||
new ResolvedAmiImage(TestImages.PYTHON_ALPINE, ResolvedAmiImage.SYSTEMD_RUNTIME, false, null),
|
||||
null, REGION);
|
||||
await().atMost(Duration.ofSeconds(60)).until(() -> instance.getDockerContainerId() != null
|
||||
&& lifecycleManager.isContainerRunning(instance.getDockerContainerId()));
|
||||
String containerId = instance.getDockerContainerId();
|
||||
|
||||
InspectContainerResponse.Mount modules = docker.inspectContainerCmd(containerId).exec().getMounts()
|
||||
.stream().filter(m -> m.getDestination() != null
|
||||
&& modulesDir.equals(m.getDestination().getPath()))
|
||||
.findFirst().orElse(null);
|
||||
assertNotNull(modules, "systemd guest has no " + modulesDir + " mount");
|
||||
assertFalse(modules.getRW(), modulesDir + " must be mounted read-only");
|
||||
|
||||
ContainerExec.Result inside = ContainerExec.runMerged(docker, containerId,
|
||||
new String[]{"sh", "-c", "grep ' " + modulesDir + " ' /proc/mounts"}, 30);
|
||||
assertEquals(0, inside.exitCode(), "guest cannot see " + modulesDir + ": " + inside.summary());
|
||||
assertTrue(inside.stdout().matches("(?s).* " + Pattern.quote(modulesDir) + " \\S+ ro[, ].*"),
|
||||
"guest's " + modulesDir + " is not read-only: " + inside.stdout());
|
||||
|
||||
// The rest of the guest's /lib/modules must stay writable (package managers own it).
|
||||
ContainerExec.Result writable = ContainerExec.runMerged(docker, containerId,
|
||||
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());
|
||||
} finally {
|
||||
// terminate() removes the container and releases the SSH port in the shared allocator.
|
||||
CountDownLatch torndown = new CountDownLatch(1);
|
||||
manager.terminate(instance, torndown::countDown);
|
||||
try {
|
||||
torndown.await(60, TimeUnit.SECONDS);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user