diff --git a/docs/services/ec2.md b/docs/services/ec2.md index 839430f986..6f06dba058 100644 --- a/docs/services/ec2.md +++ b/docs/services/ec2.md @@ -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/` (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/` 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/` 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 | |---|---| diff --git a/src/main/java/io/floci/aws/services/ec2/Ec2ContainerManager.java b/src/main/java/io/floci/aws/services/ec2/Ec2ContainerManager.java index ef130e69ad..bd509252fb 100644 --- a/src/main/java/io/floci/aws/services/ec2/Ec2ContainerManager.java +++ b/src/main/java/io/floci/aws/services/ec2/Ec2ContainerManager.java @@ -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()); } diff --git a/src/test/java/io/floci/aws/services/ec2/Ec2ContainerManagerTest.java b/src/test/java/io/floci/aws/services/ec2/Ec2ContainerManagerTest.java index 4c6e5a4639..8982e518bf 100644 --- a/src/test/java/io/floci/aws/services/ec2/Ec2ContainerManagerTest.java +++ b/src/test/java/io/floci/aws/services/ec2/Ec2ContainerManagerTest.java @@ -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"), diff --git a/src/test/java/io/floci/aws/services/ec2/Ec2SystemdGuestDockerIntegrationTest.java b/src/test/java/io/floci/aws/services/ec2/Ec2SystemdGuestDockerIntegrationTest.java new file mode 100644 index 0000000000..ecd39df0f8 --- /dev/null +++ b/src/test/java/io/floci/aws/services/ec2/Ec2SystemdGuestDockerIntegrationTest.java @@ -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(); + } + } + } +}