mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix: protect host consoles from systemd EC2 guests (#9355)
A privileged systemd EC2 guest could hang up the Docker host's virtual-console sessions. Systemd guests now start /sbin/init with systemd.mask= arguments for the getty units, which systemd reads from PID 1's command line once container=docker marks the guest as a container, and get /dev/null mounted read-only over /dev/console and /dev/tty0 through /dev/tty63. Pseudo-terminals stay available for SSH. Docker applies the mounts when it creates the container, so existing systemd instances need recreating. Closes #9342
This commit is contained in:
1 parent
19d0955c7c
commit
65dbaac26a
5 files changed
+248
-3
No files matched your search
@@ -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<String> 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<String> consolePaths = new HashSet<>();
|
||||
consolePaths.add("/dev/console");
|
||||
for (int tty = 0; tty < 64; tty++) {
|
||||
consolePaths.add("/dev/tty" + tty);
|
||||
}
|
||||
Set<String> 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<ContainerSpec> 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,
|
||||
|
||||
@@ -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<Frame> 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,
|
||||
|
||||
Reference in new issue
Block a user