diff --git a/docs/services/ec2.md b/docs/services/ec2.md index 5a7896a3e2..6a04ce7979 100644 --- a/docs/services/ec2.md +++ b/docs/services/ec2.md @@ -39,6 +39,11 @@ so policies can scope release to that allocation or its stored tags. !!! 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. +Floci masks systemd's getty units to prevent accidental disruption of the Docker host's virtual consoles. +It also mounts `/dev/null` read-only over `/dev/console` and `/dev/tty0` through `/dev/tty63`. +Pseudo-terminals remain available for SSH. Privileged guest processes can undo the masks. +Docker applies the mounts when it creates the container. Recreate existing systemd instances to apply the change. + 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 | 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 715b5fd9b9..359ce460ed 100644 --- a/src/main/java/io/floci/aws/services/ec2/Ec2ContainerManager.java +++ b/src/main/java/io/floci/aws/services/ec2/Ec2ContainerManager.java @@ -86,6 +86,17 @@ public class Ec2ContainerManager { // Guest-created /tmp mounts hide files copied through Docker's archive API. private static final String USER_DATA_SCRIPT_PATH = UserDataPipeline.USER_DATA_SCRIPT_PATH; private static final List ALLOWED_SSHD_PATHS = List.of("/usr/sbin/sshd", "/usr/local/sbin/sshd", "/sbin/sshd"); + // Inside containers, systemd's generators read PID 1's arguments instead of /proc/cmdline, + // so these arguments apply runtime unit masks when container=docker is set. + // https://github.com/systemd/systemd/blob/v252/src/basic/proc-cmdline.c#L17-L36 + private static final List SYSTEMD_INIT_COMMAND = List.of( + "/sbin/init", + "systemd.mask=getty@.service", + "systemd.mask=autovt@.service", + "systemd.mask=console-getty.service", + "systemd.mask=container-getty@.service", + "systemd.mask=serial-getty@.service", + "systemd.mask=getty-static.service"); /** Exit code the sshd install probe uses for "sshd is present but scp is not". See startSshd. */ static final int SSH_CLIENT_MISSING_EXIT_CODE = 2; private static final int LAUNCH_CORE_THREADS = 4; @@ -759,7 +770,7 @@ public class Ec2ContainerManager { // EC2 instances expose IMDS on 169.254.169.254. Floci needs network administration // privileges in the local container to attach that link-local address. .withPrivileged(namespace == null) - .withCmd(image.systemd() ? List.of("/sbin/init") : List.of("tail", "-f", "/dev/null")); + .withCmd(image.systemd() ? SYSTEMD_INIT_COMMAND : List.of("tail", "-f", "/dev/null")); if (config.services().ec2().instanceResourceLimits() && instanceType != null && !instanceType.isBlank()) { Optional catalogType = instanceTypeCatalog.find(instanceType); if (catalogType.isPresent()) { @@ -780,8 +791,15 @@ public class Ec2ContainerManager { if (image.systemd()) { applySystemdCgroup(specBuilder, namespace == null); specBuilder + .withEnv("container", "docker") .withMount(new Mount().withType(MountType.TMPFS).withTarget("/run")) .withMount(new Mount().withType(MountType.TMPFS).withTarget("/run/lock")); + // Privileged guests can see the host's virtual consoles. Mask those device paths + // so a guest getty cannot hang up a host session, and leave pseudo-terminals available. + specBuilder.withReadOnlyBind("/dev/null", "/dev/console"); + for (int tty = 0; tty < 64; tty++) { + specBuilder.withReadOnlyBind("/dev/null", "/dev/tty" + tty); + } // 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 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 2ef96acdf8..c0a51b3ae3 100644 --- a/src/test/java/io/floci/aws/services/ec2/Ec2ContainerManagerTest.java +++ b/src/test/java/io/floci/aws/services/ec2/Ec2ContainerManagerTest.java @@ -17,6 +17,8 @@ import com.github.dockerjava.api.command.RemoveContainerCmd; import com.github.dockerjava.api.command.StartContainerCmd; import com.github.dockerjava.api.command.StopContainerCmd; import com.github.dockerjava.api.exception.DockerException; +import com.github.dockerjava.api.model.AccessMode; +import com.github.dockerjava.api.model.Bind; import com.github.dockerjava.api.model.Container; import com.github.dockerjava.api.model.ContainerConfig; import com.github.dockerjava.api.model.ContainerNetwork; @@ -67,6 +69,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Base64; import java.util.HashMap; +import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -99,6 +102,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anySet; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.after; import static org.mockito.Mockito.atLeastOnce; @@ -1892,7 +1896,7 @@ class Ec2ContainerManagerTest { "us-west-2"); awaitUntil(() -> "running".equals(instance.getState().getName()), Duration.ofSeconds(2)); - verify(harness.builder).withCmd(List.of("/sbin/init")); + verify(harness.builder).withCmd(argThat((List command) -> "/sbin/init".equals(command.getFirst()))); 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"); @@ -1904,6 +1908,72 @@ class Ec2ContainerManagerTest { verify(harness.lifecycleManager).create(any(ContainerSpec.class), eq("linux/arm64")); } + @Test + void systemdGuestMasksHostConsolesAndKeepsPseudoTerminals() throws Exception { + ContainerSpec spec = launchSpecForImage(new ResolvedAmiImage( + "floci/ami-ubuntu:24.04", ResolvedAmiImage.SYSTEMD_RUNTIME, false, null)); + + Set consolePaths = new HashSet<>(); + consolePaths.add("/dev/console"); + for (int tty = 0; tty < 64; tty++) { + consolePaths.add("/dev/tty" + tty); + } + Set maskedPaths = new HashSet<>(); + for (Bind bind : spec.binds()) { + String path = bind.getVolume().getPath(); + if (path.startsWith("/dev/")) { + assertEquals("/dev/null", bind.getPath(), path); + assertEquals(AccessMode.ro, bind.getAccessMode(), path); + maskedPaths.add(path); + } + } + assertEquals(consolePaths, maskedPaths); + assertTrue(spec.env().contains("container=docker")); + assertEquals(List.of("/sbin/init", "systemd.mask=getty@.service", "systemd.mask=autovt@.service", + "systemd.mask=console-getty.service", "systemd.mask=container-getty@.service", + "systemd.mask=serial-getty@.service", "systemd.mask=getty-static.service"), spec.cmd()); + } + + @Test + void nonSystemdGuestKeepsTheTailCommandWithoutConsoleMasks() throws Exception { + ContainerSpec spec = launchSpecForImage(ResolvedAmiImage.minimal("ubuntu:24.04")); + + assertEquals(List.of("tail", "-f", "/dev/null"), spec.cmd()); + assertTrue(spec.binds().isEmpty()); + assertFalse(spec.env().contains("container=docker")); + } + + private ContainerSpec launchSpecForImage(ResolvedAmiImage image) throws Exception { + Ec2ContainerManager.containerBridgeIpAttempts = 1; + Ec2ContainerManager.containerBridgeIpPollMillis = 1; + LaunchHarness harness = launchHarness(); + EmulatorConfig.DockerConfig docker = mock(EmulatorConfig.DockerConfig.class); + when(harness.config.docker()).thenReturn(docker); + when(docker.logMaxSize()).thenReturn("10m"); + when(docker.logMaxFile()).thenReturn("3"); + ContainerBuilder actualBuilder = new ContainerBuilder(harness.config, mock(DockerHostResolver.class), + mock(EmbeddedDnsServer.class)); + ContainerBuilder.Builder builder = actualBuilder.newContainer(image.dockerImage()); + when(harness.containerBuilder.newContainer(image.dockerImage())).thenReturn(builder); + InspectContainerCmd inspect = mock(InspectContainerCmd.class); + when(harness.dockerClient.inspectContainerCmd(TEST_CONTAINER_ID)).thenReturn(inspect); + InspectContainerResponse response = inspectResponse("172.18.0.11"); + when(inspect.exec()).thenReturn(response); + harness.stubSuccessfulExecs(new CountDownLatch(0), new CountDownLatch(0)); + Instance instance = instance("i-console-settings"); + + try { + harness.manager.launch(instance, image, null, "us-west-2"); + + awaitUntil(() -> "running".equals(instance.getState().getName()), Duration.ofSeconds(2)); + ArgumentCaptor spec = ArgumentCaptor.forClass(ContainerSpec.class); + verify(harness.lifecycleManager).create(spec.capture()); + return spec.getValue(); + } finally { + harness.manager.stop(); + } + } + @Test void privilegedSystemdGuestGetsAPrivateCgroupNamespaceAndNoHostTree() { ContainerBuilder.Builder spec = mock(ContainerBuilder.Builder.class, RETURNS_SELF); @@ -2652,7 +2722,7 @@ class Ec2ContainerManagerTest { executor, userDataTimeout); return new LaunchHarness(manager, lifecycleManager, dockerClient, streamingDockerClient, metadataServer, - logStreamer, builder, portAllocator, portForwardManager, config, vpcNetworkManager, + logStreamer, containerBuilder, builder, portAllocator, portForwardManager, config, vpcNetworkManager, new CopyOnWriteArrayList<>()); } @@ -3196,6 +3266,7 @@ class Ec2ContainerManagerTest { DockerClient streamingDockerClient, Ec2MetadataServer metadataServer, ContainerLogStreamer logStreamer, + ContainerBuilder containerBuilder, ContainerBuilder.Builder builder, PortAllocator portAllocator, Ec2PortForwardManager portForwardManager, diff --git a/src/test/java/io/floci/aws/services/ec2/Ec2SystemdGuestDockerIntegrationTest.java b/src/test/java/io/floci/aws/services/ec2/Ec2SystemdGuestDockerIntegrationTest.java index 6657307c7f..6bf171c48f 100644 --- a/src/test/java/io/floci/aws/services/ec2/Ec2SystemdGuestDockerIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/ec2/Ec2SystemdGuestDockerIntegrationTest.java @@ -1,7 +1,12 @@ package io.floci.aws.services.ec2; import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.async.ResultCallback; import com.github.dockerjava.api.command.InspectContainerResponse; +import com.github.dockerjava.api.exception.ConflictException; +import com.github.dockerjava.api.model.Frame; +import com.github.dockerjava.core.command.BuildImageResultCallback; +import com.github.dockerjava.core.command.ExecStartResultCallback; import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.docker.ContainerBuilder; @@ -22,8 +27,15 @@ import jakarta.inject.Inject; import org.jboss.logging.Logger; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; import java.time.Duration; +import java.util.Set; import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -71,6 +83,9 @@ class Ec2SystemdGuestDockerIntegrationTest { @Inject RegionResolver regionResolver; + @TempDir + Path imageContext; + @Inject ContainerReachableEndpoint reachableEndpoint; @@ -79,6 +94,115 @@ class Ec2SystemdGuestDockerIntegrationTest { assumeTrue(DockerAvailability.answers(docker), "Docker must be available for EC2 systemd guest tests"); } + @Test + void systemdLaunchMasksConsoleDevicesWithoutBreakingPseudoTerminals() throws Exception { + String imageId = buildConsoleGuardImage(); + 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-console" + UUID.randomUUID().toString().replace("-", "").substring(0, 8)); + instance.setRegion(REGION); + try { + manager.launch(instance, + new ResolvedAmiImage(imageId, ResolvedAmiImage.SYSTEMD_RUNTIME, false, null), null, REGION); + await().atMost(Duration.ofSeconds(60)).untilAsserted(() -> { + assertNotNull(instance.getDockerContainerId(), "EC2 must create the guarded guest"); + String containerId = instance.getDockerContainerId(); + ContainerExec.Result guard; + try { + guard = ContainerExec.runMerged(docker, containerId, + new String[]{"test", "-f", "/run/floci-console-guard-passed"}, 10); + } catch (ConflictException e) { + InspectContainerResponse.ContainerState state = docker.inspectContainerCmd(containerId).exec().getState(); + throw new IllegalStateException("console guard container exited with code " + state.getExitCodeLong() + + ": " + containerLogs(containerId), e); + } + assertEquals(0, guard.exitCode(), "console guard did not admit the launch: " + guard.summary()); + }); + + String execId = docker.execCreateCmd(instance.getDockerContainerId()).withTty(true) + .withAttachStdout(true).withAttachStderr(true) + .withCmd("sh", "-c", "test -t 0 && test -t 1 && tty").exec().getId(); + ByteArrayOutputStream output = new ByteArrayOutputStream(); + try (ExecStartResultCallback callback = new ExecStartResultCallback(output, output)) { + assertTrue(docker.execStartCmd(execId).withTty(true).exec(callback) + .awaitCompletion(10, TimeUnit.SECONDS), "PTY probe timed out"); + } + assertEquals(0L, docker.inspectExecCmd(execId).exec().getExitCodeLong()); + assertTrue(output.toString(StandardCharsets.UTF_8).contains("/dev/pts/"), + "guest must retain working pseudo-terminals: " + output.toString(StandardCharsets.UTF_8)); + } finally { + CountDownLatch tornDown = new CountDownLatch(1); + manager.terminate(instance, tornDown::countDown); + try { + assertTrue(tornDown.await(60, TimeUnit.SECONDS), "guarded guest cleanup timed out"); + } finally { + manager.stop(); + docker.removeImageCmd(imageId).exec(); + } + } + } + + @Test + void consoleGuardRejectsAnUnprotectedLaunch() throws Exception { + String imageId = buildConsoleGuardImage(); + String containerId = null; + try { + containerId = docker.createContainerCmd(imageId).withCmd("/sbin/init").exec().getId(); + docker.startContainerCmd(containerId).exec(); + String rejectedId = containerId; + await().atMost(Duration.ofSeconds(10)).untilAsserted(() -> { + InspectContainerResponse.ContainerState state = docker.inspectContainerCmd(rejectedId).exec().getState(); + assertFalse(state.getRunning(), "unprotected fixture must exit rather than boot an init"); + assertEquals(78L, state.getExitCodeLong()); + }); + } finally { + if (containerId != null) { + docker.removeContainerCmd(containerId).withForce(true).exec(); + } + docker.removeImageCmd(imageId).exec(); + } + } + + private String buildConsoleGuardImage() throws Exception { + // The guard checks the production launch settings but never runs systemd or a getty. + String dockerfile = """ + FROM %s + RUN rm /sbin/init + COPY systemd-console-guard.sh /sbin/init + RUN chmod 0755 /sbin/init + """.formatted(TestImages.PYTHON_ALPINE); + Files.writeString(imageContext.resolve("Dockerfile"), dockerfile); + try (InputStream guard = getClass().getResourceAsStream("/ec2/systemd-console-guard.sh")) { + assertNotNull(guard); + Files.copy(guard, imageContext.resolve("systemd-console-guard.sh")); + } + try (BuildImageResultCallback callback = new BuildImageResultCallback()) { + String imageId = docker.buildImageCmd(imageContext.toFile()) + .withTags(Set.of("floci-console-guard-test:" + UUID.randomUUID())) + .withRemove(true).exec(callback).awaitImageId(180, TimeUnit.SECONDS); + assertNotNull(imageId, "Docker must build the console guard fixture"); + return imageId; + } + } + + private String containerLogs(String containerId) throws Exception { + StringBuilder output = new StringBuilder(); + try (ResultCallback.Adapter callback = new ResultCallback.Adapter<>() { + @Override + public void onNext(Frame frame) { + output.append(new String(frame.getPayload(), StandardCharsets.UTF_8)); + } + }) { + assertTrue(docker.logContainerCmd(containerId).withStdOut(true).withStdErr(true) + .exec(callback).awaitCompletion(10, TimeUnit.SECONDS), "guard log retrieval timed out"); + } + return output.toString(); + } + @Test void systemdGuestSeesHostModulesReadOnlyInPrivateCgroupNamespace() { Ec2ContainerManager manager = new Ec2ContainerManager(containerBuilder, lifecycleManager, diff --git a/src/test/resources/ec2/systemd-console-guard.sh b/src/test/resources/ec2/systemd-console-guard.sh new file mode 100644 index 0000000000..f9ddb004d9 --- /dev/null +++ b/src/test/resources/ec2/systemd-console-guard.sh @@ -0,0 +1,27 @@ +#!/bin/sh +set -eu + +# Never start a getty: this fixture must remain safe when the launcher regresses. +reject() { + printf 'EC2 console guard rejected launch: %s\n' "$1" >&2 + exit 78 +} + +for path in /dev/console $(seq 0 63 | sed 's|^|/dev/tty|'); do + [ -c "$path" ] || reject "$path is not a character device" + number=$(stat -Lc '%t:%T' "$path") + [ "$number" = 1:3 ] || reject "$path is not /dev/null ($number)" + awk -v path="$path" '$5 == path && $6 ~ /(^|,)ro(,|$)/ { found=1 } END { exit !found }' \ + /proc/self/mountinfo || reject "$path is not mounted read-only" +done + +[ "${container:-}" = docker ] || reject 'container=docker is missing' +for unit in getty@.service autovt@.service console-getty.service container-getty@.service serial-getty@.service getty-static.service; do + case " $* " in + *" systemd.mask=$unit "*) ;; + *) reject "$unit is not masked" ;; + esac +done + +touch /run/floci-console-guard-passed +exec tail -f /dev/null