From 045ecc4eeb82e75dfc1eaa4162731acebc0e18e5 Mon Sep 17 00:00:00 2001 From: Jimmy Liu Jia <91264074+JimmyLiuJia@users.noreply.github.com> Date: Sun, 15 Nov 2026 03:23:23 +0800 Subject: [PATCH] fix(ec2): keep guest port 80 available with IMDS (#8225) The in-guest IMDS relay listened on 169.254.169.254:80, so Apache and other wildcard port-80 listeners could not start in an EC2 guest. The relay now listens on its own port, 42169, and an iptables or nft NAT rule routes local link-local port-80 traffic to it. The guest's own nft rules are kept, and only Floci's relay rule is added or removed. With no working NAT backend, the older port-80 listener keeps IMDS available. A protected instance's restart retires a retained older listener before the workload starts, and a failed start rolls back the IMDS registration it made. The network helper image now includes iptables. Closes #7937 --- docs/services/ec2.md | 8 +- .../aws/services/ec2/Ec2ContainerManager.java | 42 ++- .../aws/services/ec2/Ec2MetadataProxy.java | 245 ++++++++++++++++-- .../aws/services/ec2/Ec2MetadataServer.java | 8 + .../docker/network-helper.Dockerfile | 2 +- .../services/ec2/Ec2ContainerManagerTest.java | 158 ++++++++++- .../services/ec2/Ec2MetadataProxyTest.java | 204 ++++++++++++++- .../Ec2StartRequestScopeIntegrationTest.java | 2 +- ...ityGroupFirewallDockerIntegrationTest.java | 168 ++++++++++++ 9 files changed, 777 insertions(+), 60 deletions(-) diff --git a/docs/services/ec2.md b/docs/services/ec2.md index 258fb1469c..4a5108f159 100644 --- a/docs/services/ec2.md +++ b/docs/services/ec2.md @@ -254,6 +254,12 @@ instance ID. The check bypasses any HTTP proxy the image configures, a failed or response does not fall back to a tokenless request, and the check passes on an instance that requires tokens. +For EC2 guests, a working `iptables` or `nft` NAT backend routes link-local port `80` to the IMDS +relay on port `42169`, leaving the guest's wildcard port `80` available. If no NAT backend works +(for example, an offline image without firewall tools), Floci uses the older link-local port `80` +listener to preserve IMDS access. That fallback can still conflict with a guest server binding +`0.0.0.0:80`. + `iam/info` returns the ARN and ID that IAM holds for the attached profile, and 404 when that profile is missing, has no role or does not match the attached ARN. An EKS cluster node, whose profile Floci synthesizes, reports the synthesized ARN and a stable ID instead while IAM holds no @@ -309,7 +315,7 @@ Guests with an instance profile receive endpoint and region settings without Flo ### IMDS and SSM managed instances -IMDS only knows about containers that Floci itself launched through `RunInstances`. That launch is what installs the link-local `169.254.169.254` proxy inside the container and maps the container's IP to its instance record. A restarted container (`StopInstances` then `StartInstances`) has a new network namespace, so once the instance is `running` `StartInstances` sets the proxy up again; an instance under security-group enforcement keeps its helper container's namespace, and the proxy with it. +IMDS only knows about containers that Floci itself launched through `RunInstances`. That launch is what installs the link-local `169.254.169.254` proxy inside the container and maps the container's IP to its instance record. A restarted container (`StopInstances` then `StartInstances`) has a new network namespace, so once the instance is `running` `StartInstances` sets the proxy up again. An instance under security-group enforcement keeps its helper container's namespace; `StartInstances` attempts to migrate an older TCP/80 listener before starting the workload. Registering a container with SSM is independent of this: an SSM agent that calls `UpdateInstanceInformation` becomes a managed instance, but that does not create an EC2 instance record, does not install the IMDS proxy, and does not register the container with IMDS. From such a container, `curl http://169.254.169.254/...` fails outright (no proxy), and a request sent straight to the host IMDS port returns `404` with a message explaining that no EC2 instance is registered for the source IP. Floci also logs a warning when an SSM agent registers from a container that is not backed by a Floci EC2 instance. 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 3b9e4a477a..46a27c3381 100644 --- a/src/main/java/io/floci/aws/services/ec2/Ec2ContainerManager.java +++ b/src/main/java/io/floci/aws/services/ec2/Ec2ContainerManager.java @@ -1089,7 +1089,21 @@ public class Ec2ContainerManager { instance.setState(pending); submitLifecycleOperation(containerId, () -> RequestScopes.runAs(accountId, instance.getRegion(), () -> { boolean setUpMetadataEndpoint = false; + String protectedMetadataAddress = null; + boolean retainedMetadataRegistration = false; try { + String instanceId = instance.getInstanceId(); + ProtectedNamespace namespace = protectedNamespace(instance); + if (namespace != null) { + // The helper survives a workload stop. Migrate its old TCP/80 listener before + // a restarted guest can bind a wildcard HTTP server during boot. + protectedMetadataAddress = namespace.transportAddress(); + retainedMetadataRegistration = metadataServer.registeredContainer(protectedMetadataAddress) + .filter(registered -> registered == instance).isPresent(); + metadataServer.registerContainer(protectedMetadataAddress, instanceId, instance); + configureLinkLocalMetadataEndpoint(namespace.helperId(), instanceId, + dockerHostResolver.resolve(), config.services().ec2().imdsPort()); + } dockerClient.startContainerCmd(containerId).exec(); boolean running = false; for (int i = 0; i < 20 && !running; i++) { @@ -1098,11 +1112,9 @@ public class Ec2ContainerManager { Thread.sleep(500); } } - String instanceId = instance.getInstanceId(); // A protected workload shares the helper's namespace, so it has no Docker network // attachment of its own to rediscover: the helper keeps the transport address // across the workload's stop/start, exactly as launch used it. - ProtectedNamespace namespace = protectedNamespace(instance); String containerIp = namespace == null ? waitForContainerBridgeIp(containerId, instanceId) : namespace.transportAddress(); @@ -1120,26 +1132,29 @@ public class Ec2ContainerManager { if (instance.getPublicIpAddress() != null || AutomaticPublicAddress.isDue(instance, true)) { exposeReachablePublicAddress(instance); } - metadataServer.registerContainer(containerIp, instanceId, instance); + if (namespace == null) { + metadataServer.registerContainer(containerIp, instanceId, instance); + } refreshImdsSourceRegistration(instance, containerId, containerIp); refreshMetadataAddresses(instance, containerId); - // A restarted container has a new network namespace: the link-local IMDS - // address launch configured is gone, and without it the guest cannot reach - // 169.254.169.254 (instance credentials, user data, EC2 Instance Connect keys). - // A protected instance's helper kept its namespace, and the address with it. + // A plain restart loses its link-local address; a protected helper was + // prepared before starting the workload. setUpMetadataEndpoint = namespace == null; } } catch (InterruptedException e) { - Thread.currentThread().interrupt(); instance.compareAndSetState(pending, InstanceState.stopped()); + rollbackProtectedMetadataRegistration(instance, protectedMetadataAddress, retainedMetadataRegistration); + Thread.currentThread().interrupt(); return; } catch (Exception e) { LOG.warnv("Error starting EC2 container {0}: {1}", containerId, e.getMessage()); instance.compareAndSetState(pending, InstanceState.stopped()); + rollbackProtectedMetadataRegistration(instance, protectedMetadataAddress, retainedMetadataRegistration); return; } InstanceState running = InstanceState.running(); if (!instance.compareAndSetState(pending, running)) { + rollbackProtectedMetadataRegistration(instance, protectedMetadataAddress, retainedMetadataRegistration); return; } if (postStart != null) { @@ -1156,6 +1171,13 @@ public class Ec2ContainerManager { })); } + private void rollbackProtectedMetadataRegistration(Instance instance, String address, boolean retained) { + if (address == null || retained) { + return; + } + metadataServer.rollbackContainerRegistration(address, instance); + } + /** * Best effort with its own bounded commands, as at launch, and off the container's lifecycle * queue: a slow setup holds neither the instance pending nor a stop queued behind this start. @@ -1946,11 +1968,11 @@ public class Ec2ContainerManager { } static String[] metadataProxyInstallCommand() { - return Ec2MetadataProxy.installCommand(); + return Ec2MetadataProxy.installEc2Command(); } static String[] metadataProxyStartCommand(String flociHost, int imdsPort) { - return Ec2MetadataProxy.startCommand(flociHost, imdsPort); + return Ec2MetadataProxy.startEc2Command(flociHost, imdsPort); } diff --git a/src/main/java/io/floci/aws/services/ec2/Ec2MetadataProxy.java b/src/main/java/io/floci/aws/services/ec2/Ec2MetadataProxy.java index 2448f4c752..77cb4ed56c 100644 --- a/src/main/java/io/floci/aws/services/ec2/Ec2MetadataProxy.java +++ b/src/main/java/io/floci/aws/services/ec2/Ec2MetadataProxy.java @@ -2,15 +2,18 @@ package io.floci.aws.services.ec2; import com.github.dockerjava.api.model.ContainerNetwork; +import java.util.ArrayList; +import java.util.List; import java.util.Map; import java.util.Optional; /** - * Shared commands and network resolution helpers for installing and starting - * the link-local IMDS proxy (169.254.169.254:80) inside containers. + * Shared commands and network resolution helpers for link-local metadata proxies. */ public final class Ec2MetadataProxy { + private static final int EC2_IMDS_RELAY_PORT = 42169; + /** * Run first in the shells that install and start these proxies and in the sshd install probe. * {@code docker exec} hands the shell the image's environment, so an application's library @@ -43,14 +46,24 @@ public final class Ec2MetadataProxy { + " fi"; public static String[] installCommand() { - return new String[]{"sh", "-c", String.join("\n", + return installCommand(false); + } + + static String[] installEc2Command() { + return installCommand(true); + } + + private static String[] installCommand(boolean requireIptables) { + List lines = new ArrayList<>(List.of( "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 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", " apt-get update -qq >/dev/null", - " DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends iproute2 socat curl ca-certificates >/dev/null", + " DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends" + + " iproute2 socat curl ca-certificates >/dev/null", "elif command -v dnf >/dev/null 2>&1; then", // --allowerasing lets dnf swap the curl-minimal that // public.ecr.aws/amazonlinux/amazonlinux:2023 ships by default for the full @@ -69,7 +82,24 @@ public final class Ec2MetadataProxy { "else", " echo 'No supported package manager found for IMDS proxy dependencies' >&2", " exit 1", - "fi")}; + "fi")); + if (requireIptables) { + // A guest without a NAT tool can still use the pre-upgrade TCP/80 relay. + lines.add("if ! command -v iptables >/dev/null 2>&1 && ! command -v nft >/dev/null 2>&1; then"); + lines.add(" if command -v apt-get >/dev/null 2>&1; then"); + lines.add(" { apt-get update -qq >/dev/null" + + " && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends" + + " iptables >/dev/null; } || true"); + lines.add(" elif command -v dnf >/dev/null 2>&1; then"); + lines.add(" dnf install -y --allowerasing iptables-nft >/dev/null || true"); + lines.add(" elif command -v yum >/dev/null 2>&1; then"); + lines.add(" yum install -y iptables >/dev/null || true"); + lines.add(" elif command -v apk >/dev/null 2>&1; then"); + lines.add(" apk add --no-cache iptables >/dev/null || true"); + lines.add(" fi"); + lines.add("fi"); + } + return new String[]{"sh", "-c", String.join("\n", lines)}; } public static String[] startCommand(String flociHost, int imdsPort) { @@ -77,6 +107,11 @@ public final class Ec2MetadataProxy { imdsProbeCommand("http://169.254.169.254")); } + static String[] startEc2Command(String flociHost, int imdsPort) { + return startCommand("imds", "169.254.169.254", EC2_IMDS_RELAY_PORT, flociHost, imdsPort, + imdsProbeCommand("http://169.254.169.254"), true); + } + /** * Ready once an IMDSv2 token reads the instance ID, which also holds on an instance whose * HttpTokens is required. A refused or empty token ends the attempt rather than falling back to @@ -108,32 +143,186 @@ public final class Ec2MetadataProxy { public static String[] startCommand(String name, String bindIp, int bindPort, String targetHost, int targetPort, String probeCommand) { - String pidFile = "/tmp/floci-" + name + "-proxy.pid"; + return startCommand(name, bindIp, bindPort, targetHost, targetPort, probeCommand, false); + } + + private static String[] startCommand(String name, String bindIp, int bindPort, + String targetHost, int targetPort, String probeCommand, + boolean routeImdsPort) { + String legacyPidFile = "/tmp/floci-" + name + "-proxy.pid"; + String pidFile = routeImdsPort ? "/tmp/floci-" + name + "-proxy-" + bindPort + ".pid" : legacyPidFile; String logFile = "/tmp/floci-" + name + "-proxy.log"; - return new String[]{"sh", "-c", String.join("\n", + String listener = "TCP-LISTEN:" + bindPort + ",bind=" + bindIp + ","; + String ruleMatch = "-d " + bindIp + "/32 -p tcp --dport 80 -j DNAT --to-destination " + + bindIp + ":" + bindPort; + String nftRuleMarker = "floci-imds-relay-" + bindPort; + List lines = new ArrayList<>(List.of( "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 - // the PID namespace does not: only a pid that is still this socat listener counts. - // The command name matters as well as the arguments: the shell running this script - // carries the listener string in its own command line. - "if [ -f " + pidFile + " ] && pid=\"$(cat " + pidFile + ")\"" - + " && [ \"$(cat \"/proc/$pid/comm\" 2>/dev/null)\" = socat ]" - + " && tr '\\0' ' ' 2>/dev/null <\"/proc/$pid/cmdline\"" - + " | grep -q 'TCP-LISTEN:" + bindPort + ",bind=" + bindIp + ",'; then", - " exit 0", - "fi", - "nohup socat TCP-LISTEN:" + bindPort + ",bind=" + bindIp + ",fork,reuseaddr TCP:" - + targetHost + ":" + targetPort + " >" + logFile + " 2>&1 &", - "echo $! > " + pidFile, - "for i in 1 2 3 4 5 6 7 8 9 10 11 12; do", - " " + probeCommand, - " sleep 1", - "done", - "cat " + logFile + " >&2 || true", - "exit 1")}; + "ip addr show dev lo | grep -q '" + bindIp + "/32' || ip addr add " + bindIp + "/32 dev lo")); + lines.add("is_socat_listener() {"); + lines.add(" [ \"$(cat \"/proc/$1/comm\" 2>/dev/null)\" = socat ]" + + " && tr '\\0' ' ' 2>/dev/null <\"/proc/$1/cmdline\" | grep -Fq \"$2\""); + lines.add("}"); + + // The writable-layer PID file survives a container restart, so verify the process name and + // listener arguments before reusing it or retiring a pre-upgrade TCP/80 listener. + if (routeImdsPort) { + lines.add("legacy_pid="); + lines.add(socatPidCheck(legacyPidFile, "TCP-LISTEN:80,bind=" + bindIp + ",")); + lines.add(" legacy_pid=$pid"); + lines.add("fi"); + lines.add("proxy_running=0"); + lines.add("new_pid="); + lines.add("rule_added=0"); + lines.add("rule_backend="); + lines.add("nft_chain_created=0"); + lines.add("nft_rule_marker=" + nftRuleMarker + "-$$"); + lines.add("legacy_new_pid="); + lines.add("fallback_legacy=0"); + lines.add("remove_nft_rule() {"); + lines.add(" nft -a list chain ip floci_imds output 2>/dev/null" + + " | grep -F \"comment \\\"$1\\\"\" | while IFS= read -r rule; do"); + lines.add(" case \"$rule\" in"); + lines.add(" *'# handle '*) nft delete rule ip floci_imds output" + + " handle \"${rule##*# handle }\" 2>/dev/null || true ;;"); + lines.add(" esac"); + lines.add(" done"); + lines.add("}"); + lines.add("cleanup_new_proxy() {"); + lines.add(" if [ -n \"$new_pid\" ]; then"); + lines.add(" if is_socat_listener \"$new_pid\" '" + listener + "'; then"); + lines.add(" kill \"$new_pid\" 2>/dev/null || true"); + lines.add(" fi"); + lines.add(" if [ \"$(cat " + pidFile + " 2>/dev/null)\" = \"$new_pid\" ]; then"); + lines.add(" rm -f " + pidFile); + lines.add(" fi"); + lines.add(" fi"); + lines.add(" if [ \"$rule_added\" -eq 1 ]; then"); + lines.add(" if [ \"$rule_backend\" = nft ]; then"); + lines.add(" remove_nft_rule \"$nft_rule_marker\" || true"); + lines.add(" else"); + lines.add(" iptables -t nat -D OUTPUT " + ruleMatch + " 2>/dev/null || true"); + lines.add(" fi"); + lines.add(" fi"); + lines.add(" if [ \"$nft_chain_created\" -eq 1 ]; then"); + lines.add(" nft delete chain ip floci_imds output 2>/dev/null || true"); + lines.add(" fi"); + lines.add(" if [ -n \"$legacy_new_pid\" ]; then"); + lines.add(" if is_socat_listener \"$legacy_new_pid\" 'TCP-LISTEN:80,bind=" + bindIp + ",'; then"); + lines.add(" kill \"$legacy_new_pid\" 2>/dev/null || true"); + lines.add(" fi"); + lines.add(" if [ \"$(cat " + legacyPidFile + " 2>/dev/null)\" = \"$legacy_new_pid\" ]; then"); + lines.add(" rm -f " + legacyPidFile); + lines.add(" fi"); + lines.add(" fi"); + lines.add("}"); + } + lines.add(socatPidCheck(pidFile, listener)); + if (routeImdsPort) { + lines.add(" proxy_running=1"); + lines.add("fi"); + lines.add("if [ \"$proxy_running\" -eq 0 ]; then"); + } else { + lines.add(" exit 0"); + lines.add("fi"); + } + lines.add((routeImdsPort ? " " : "") + "nohup socat " + listener + "fork,reuseaddr TCP:" + + targetHost + ":" + targetPort + " >" + logFile + " 2>&1 &"); + if (routeImdsPort) { + lines.add(" new_pid=$!"); + lines.add(" echo \"$new_pid\" > " + pidFile); + } else { + lines.add("echo $! > " + pidFile); + } + if (routeImdsPort) { + lines.add("fi"); + lines.add("if command -v nft >/dev/null 2>&1" + + " && nft list chain ip floci_imds output 2>/dev/null" + + " | grep -F 'comment \"" + nftRuleMarker + "'" + + " | grep -Fq 'ip daddr " + bindIp + " tcp dport 80 dnat to " + + bindIp + ":" + bindPort + "'; then"); + lines.add(" rule_backend=nft"); + lines.add("fi"); + lines.add("if [ -z \"$rule_backend\" ] && command -v iptables >/dev/null 2>&1; then"); + lines.add(" if iptables -t nat -C OUTPUT " + ruleMatch + " 2>/dev/null; then"); + lines.add(" rule_backend=iptables"); + lines.add(" elif ! { command -v nft >/dev/null 2>&1" + + " && nft list table ip floci_imds >/dev/null 2>&1; }" + + " && iptables -t nat -I OUTPUT 1 " + ruleMatch + "; then"); + lines.add(" rule_backend=iptables"); + lines.add(" rule_added=1"); + lines.add(" fi"); + lines.add("fi"); + lines.add("if [ -z \"$rule_backend\" ] && command -v nft >/dev/null 2>&1; then"); + lines.add(" nft_ready=1"); + lines.add(" if ! nft list table ip floci_imds >/dev/null 2>&1; then"); + lines.add(" nft add table ip floci_imds || nft_ready=0"); + lines.add(" fi"); + lines.add(" if [ \"$nft_ready\" -eq 1 ]" + + " && ! nft list chain ip floci_imds output >/dev/null 2>&1; then"); + lines.add(" if printf '%s\\n'" + + " 'add chain ip floci_imds output { type nat hook output priority -100; policy accept; }'" + + " | nft -f -; then"); + lines.add(" nft_chain_created=1"); + lines.add(" else"); + lines.add(" nft_ready=0"); + lines.add(" fi"); + lines.add(" fi"); + lines.add(" if [ \"$nft_ready\" -eq 1 ]; then"); + lines.add(" if printf '%s\\n' \"insert rule ip floci_imds output ip daddr " + bindIp + + " tcp dport 80 dnat to " + bindIp + ":" + bindPort + + " comment \\\"$nft_rule_marker\\\"\" | nft -f -; then"); + lines.add(" rule_backend=nft"); + lines.add(" rule_added=1"); + lines.add(" fi"); + lines.add(" fi"); + lines.add("fi"); + lines.add("if [ -z \"$rule_backend\" ] && command -v iptables >/dev/null 2>&1" + + " && iptables -t nat -I OUTPUT 1 " + ruleMatch + "; then"); + lines.add(" rule_backend=iptables"); + lines.add(" rule_added=1"); + lines.add("fi"); + lines.add("if [ -z \"$rule_backend\" ]; then"); + lines.add(" cleanup_new_proxy"); + lines.add(" fallback_legacy=1"); + lines.add(" if [ -z \"$legacy_pid\" ]; then"); + lines.add(" nohup socat TCP-LISTEN:80,bind=" + bindIp + ",fork,reuseaddr TCP:" + + targetHost + ":" + targetPort + " >" + logFile + " 2>&1 &"); + lines.add(" legacy_new_pid=$!"); + lines.add(" echo \"$legacy_new_pid\" > " + legacyPidFile); + lines.add(" fi"); + lines.add("fi"); + } + lines.add("for i in 1 2 3 4 5 6 7 8 9 10 11 12; do"); + if (routeImdsPort) { + lines.add(" if (" + probeCommand + "); then"); + lines.add(" if [ \"$fallback_legacy\" -eq 0 ] && [ -n \"$legacy_pid\" ]" + + " && is_socat_listener \"$legacy_pid\" 'TCP-LISTEN:80,bind=" + bindIp + ",'; then"); + lines.add(" kill \"$legacy_pid\" 2>/dev/null || true"); + lines.add(" if [ \"$(cat " + legacyPidFile + " 2>/dev/null)\" = \"$legacy_pid\" ]; then"); + lines.add(" rm -f " + legacyPidFile); + lines.add(" fi"); + lines.add(" fi"); + lines.add(" exit 0"); + lines.add(" fi"); + } else { + lines.add(" " + probeCommand); + } + lines.add(" sleep 1"); + lines.add("done"); + if (routeImdsPort) { + lines.add("cleanup_new_proxy"); + } + lines.add("cat " + logFile + " >&2 || true"); + lines.add("exit 1"); + return new String[]{"sh", "-c", String.join("\n", lines)}; + } + + private static String socatPidCheck(String pidFile, String listener) { + return "if [ -f " + pidFile + " ] && pid=\"$(cat " + pidFile + ")\"" + + " && is_socat_listener \"$pid\" '" + listener + "'; then"; } public static Optional preferredMetadataSourceIp(Map networks) { diff --git a/src/main/java/io/floci/aws/services/ec2/Ec2MetadataServer.java b/src/main/java/io/floci/aws/services/ec2/Ec2MetadataServer.java index ce2148d26f..b58d3411da 100644 --- a/src/main/java/io/floci/aws/services/ec2/Ec2MetadataServer.java +++ b/src/main/java/io/floci/aws/services/ec2/Ec2MetadataServer.java @@ -112,6 +112,14 @@ public class Ec2MetadataServer { } } + void rollbackContainerRegistration(String containerIp, Instance instance) { + containerIpToInstance.remove(containerIp, instance); + if (!containerIpToInstance.containsValue(instance)) { + credentials.unregister(instance); + tokens.values().removeIf(token -> token.instance() == instance); + } + } + /** Reconcile every Docker attachment without retaining stale addresses after restart. */ public void reconcileContainerAddresses(Set addresses, Instance instance) { for (String address : addresses) { diff --git a/src/main/resources/docker/network-helper.Dockerfile b/src/main/resources/docker/network-helper.Dockerfile index 239b5ca125..909a811d84 100644 --- a/src/main/resources/docker/network-helper.Dockerfile +++ b/src/main/resources/docker/network-helper.Dockerfile @@ -1,3 +1,3 @@ FROM alpine:3.21 -RUN apk add --no-cache nftables iproute2 socat curl +RUN apk add --no-cache nftables iproute2 socat curl iptables CMD ["sleep", "2147483647"] 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 da82d82a8c..000d923188 100644 --- a/src/test/java/io/floci/aws/services/ec2/Ec2ContainerManagerTest.java +++ b/src/test/java/io/floci/aws/services/ec2/Ec2ContainerManagerTest.java @@ -79,6 +79,7 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.BooleanSupplier; +import java.util.function.Consumer; import java.util.zip.GZIPOutputStream; import static org.junit.jupiter.api.Assertions.assertArrayEquals; @@ -592,19 +593,119 @@ class Ec2ContainerManagerTest { } @Test - void startOfAProtectedInstanceDoesNotSetTheImdsEndpointUpAgain() throws Exception { - // The helper container kept its network namespace across the stop, and the address with it. + void startOfAProtectedInstanceMigratesTheImdsEndpointInItsHelper() throws Exception { + // The helper and its old TCP/80 listener survive a workload stop and an emulator upgrade. DockerClient dockerClient = mock(DockerClient.class); - List execs = recordExecs(dockerClient); + List events = new CopyOnWriteArrayList<>(); + List execs = recordExecs(dockerClient, "helper-1", () -> events.add("helper setup")); Instance instance = startProtectedInstance(mock(Ec2MetadataServer.class), Map.of( "floci.security-group-helper", "true", "io.floci.service", "ec2", "io.floci.resource-id", "i-protected", - "floci_owner_port", "4566"), dockerClient); + "floci_owner_port", "4566"), dockerClient, () -> events.add("workload start")); awaitUntil(() -> "running".equals(instance.getState().getName()), Duration.ofSeconds(5)); - assertTrue(execs.stream().noneMatch(cmd -> Arrays.equals(cmd, - Ec2ContainerManager.metadataProxyInstallCommand())), "no IMDS setup exec for a protected start"); + awaitUntil(() -> execs.stream().anyMatch(cmd -> Arrays.equals(cmd, + Ec2ContainerManager.metadataProxyInstallCommand())), Duration.ofSeconds(5)); + assertEquals(List.of("helper setup", "workload start"), events, + "the retained TCP/80 listener must be migrated before the workload can bind port 80"); + verify(dockerClient, never()).execCreateCmd(TEST_CONTAINER_ID); + } + + @Test + void failedProtectedStartRemovesNewMetadataRegistration() throws Exception { + Ec2MetadataServer metadataServer = new Ec2MetadataServer(null, null, null, (InstanceConnectKeys) null); + Instance instance = startProtectedInstance(metadataServer, Map.of( + "floci.security-group-helper", "true", + "io.floci.service", "ec2", + "io.floci.resource-id", "i-protected", + "floci_owner_port", "4566"), mock(DockerClient.class), + () -> { + throw new IllegalStateException("Docker start failed"); + }); + + awaitUntil(() -> "stopped".equals(instance.getState().getName()) + && metadataServer.registeredContainer("172.17.0.7").isEmpty(), Duration.ofSeconds(5)); + assertTrue(metadataServer.registeredContainer("172.17.0.7").isEmpty(), + "a failed Docker start must not leave a new IMDS mapping to a stopped workload"); + } + + @Test + void failedProtectedStartKeepsExistingMetadataRegistration() throws Exception { + Ec2MetadataServer metadataServer = new Ec2MetadataServer(null, null, null, (InstanceConnectKeys) null); + Instance instance = startProtectedInstance(metadataServer, Map.of( + "floci.security-group-helper", "true", + "io.floci.service", "ec2", + "io.floci.resource-id", "i-protected", + "floci_owner_port", "4566"), mock(DockerClient.class), + () -> { + throw new IllegalStateException("Docker start failed"); + }, + existing -> metadataServer.registerContainer("172.17.0.7", "i-protected", existing)); + + awaitUntil(() -> "stopped".equals(instance.getState().getName()), Duration.ofSeconds(5)); + assertEquals(instance, metadataServer.registeredContainer("172.17.0.7").orElseThrow(), + "a failed restart must retain the mapping left by an earlier successful run"); + } + + @Test + void failedProtectedStartDoesNotRestorePreviousInstanceAtReusedHelperAddress() throws Exception { + Ec2MetadataServer metadataServer = new Ec2MetadataServer(null, null, null, (InstanceConnectKeys) null); + Instance previous = new Instance(); + previous.setInstanceId("i-old-helper-owner"); + Instance instance = startProtectedInstance(metadataServer, Map.of( + "floci.security-group-helper", "true", + "io.floci.service", "ec2", + "io.floci.resource-id", "i-protected", + "floci_owner_port", "4566"), mock(DockerClient.class), + () -> { + throw new IllegalStateException("Docker start failed"); + }, + ignored -> metadataServer.registerContainer("172.17.0.7", previous.getInstanceId(), previous)); + + awaitUntil(() -> "stopped".equals(instance.getState().getName()) + && metadataServer.registeredContainer("172.17.0.7").isEmpty(), Duration.ofSeconds(5)); + assertTrue(metadataServer.registeredContainer("172.17.0.7").isEmpty(), + "rollback must not resurrect a previous instance after Docker reuses its helper address"); + } + + @Test + void failedProtectedStartKeepsOtherMetadataAddressesForTheInstance() throws Exception { + Ec2MetadataServer metadataServer = new Ec2MetadataServer(null, null, null, (InstanceConnectKeys) null); + Instance instance = startProtectedInstance(metadataServer, Map.of( + "floci.security-group-helper", "true", + "io.floci.service", "ec2", + "io.floci.resource-id", "i-protected", + "floci_owner_port", "4566"), mock(DockerClient.class), + () -> { + throw new IllegalStateException("Docker start failed"); + }, + existing -> metadataServer.registerContainer("172.17.0.8", "i-protected", existing)); + + awaitUntil(() -> "stopped".equals(instance.getState().getName()) + && metadataServer.registeredContainer("172.17.0.7").isEmpty(), Duration.ofSeconds(5)); + assertEquals(instance, metadataServer.registeredContainer("172.17.0.8").orElseThrow(), + "rolling back the new helper address must preserve other retained addresses"); + } + + @Test + void cancelledProtectedStartRemovesNewMetadataRegistration() throws Exception { + Ec2MetadataServer metadataServer = new Ec2MetadataServer(null, null, null, (InstanceConnectKeys) null); + AtomicReference startingInstance = new AtomicReference<>(); + CountDownLatch dockerStarted = new CountDownLatch(1); + Instance instance = startProtectedInstance(metadataServer, Map.of( + "floci.security-group-helper", "true", + "io.floci.service", "ec2", + "io.floci.resource-id", "i-protected", + "floci_owner_port", "4566"), mock(DockerClient.class), + () -> { + startingInstance.get().setState(InstanceState.stopping()); + dockerStarted.countDown(); + }, startingInstance::set); + + assertTrue(dockerStarted.await(5, TimeUnit.SECONDS)); + awaitUntil(() -> metadataServer.registeredContainer("172.17.0.7").isEmpty(), Duration.ofSeconds(5)); + assertEquals("stopping", instance.getState().getName()); } @Test @@ -661,14 +762,22 @@ class Ec2ContainerManagerTest { /** Records every command exec'd in the test container; each exec then fails, which start tolerates. */ private static List recordExecs(DockerClient dockerClient) { - return recordExecs(dockerClient, () -> { }); + return recordExecs(dockerClient, TEST_CONTAINER_ID, () -> { }); + } + + private static List recordExecs(DockerClient dockerClient, String containerId) { + return recordExecs(dockerClient, containerId, () -> { }); } /** As {@link #recordExecs(DockerClient)}, running {@code onExec} as each exec is created. */ private static List recordExecs(DockerClient dockerClient, Runnable onExec) { + return recordExecs(dockerClient, TEST_CONTAINER_ID, onExec); + } + + private static List recordExecs(DockerClient dockerClient, String containerId, Runnable onExec) { List execs = new CopyOnWriteArrayList<>(); ExecCreateCmd execCreate = mock(ExecCreateCmd.class, withSettings().defaultAnswer(RETURNS_SELF)); - when(dockerClient.execCreateCmd(TEST_CONTAINER_ID)).thenReturn(execCreate); + when(dockerClient.execCreateCmd(containerId)).thenReturn(execCreate); when(execCreate.withCmd(any(String[].class))).thenAnswer(invocation -> { Object[] args = invocation.getArguments(); execs.add(args.length == 1 && args[0] instanceof String[] cmd @@ -780,11 +889,25 @@ class Ec2ContainerManagerTest { private Instance startProtectedInstance(Ec2MetadataServer metadataServer, Map helperLabels, DockerClient dockerClient) { + return startProtectedInstance(metadataServer, helperLabels, dockerClient, () -> { }); + } + + private Instance startProtectedInstance(Ec2MetadataServer metadataServer, Map helperLabels, + DockerClient dockerClient, Runnable onStart) { + return startProtectedInstance(metadataServer, helperLabels, dockerClient, onStart, ignored -> { }); + } + + private Instance startProtectedInstance(Ec2MetadataServer metadataServer, Map helperLabels, + DockerClient dockerClient, Runnable onStart, Consumer beforeStart) { ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class); when(lifecycleManager.isContainerRunning(TEST_CONTAINER_ID)).thenReturn(true); - when(dockerClient.startContainerCmd(TEST_CONTAINER_ID)) - .thenReturn(mock(StartContainerCmd.class, RETURNS_SELF)); + StartContainerCmd start = mock(StartContainerCmd.class, RETURNS_SELF); + when(dockerClient.startContainerCmd(TEST_CONTAINER_ID)).thenReturn(start); + doAnswer(invocation -> { + onStart.run(); + return null; + }).when(start).exec(); // A workload in the helper's namespace has no Docker attachment of its own, so there is // no bridge address on it to rediscover after the restart. InspectContainerResponse workload = mock(InspectContainerResponse.class); @@ -832,6 +955,7 @@ class Ec2ContainerManagerTest { instance.setInstanceId("i-protected"); instance.setDockerContainerId(TEST_CONTAINER_ID); + beforeStart.accept(instance); manager.start(instance); return instance; } @@ -1568,6 +1692,7 @@ class Ec2ContainerManagerTest { assertTrue(command[2].contains("iproute2")); assertTrue(command[2].contains("socat")); assertTrue(command[2].contains("curl")); + assertTrue(command[2].contains("iptables")); } @Test @@ -1645,6 +1770,7 @@ class Ec2ContainerManagerTest { assertTrue(script.contains("command -v yum"), script); assertTrue(script.contains("yum install -y iproute socat curl ca-certificates"), script); + assertTrue(script.contains("yum install -y iptables >/dev/null || true"), script); } @Test @@ -1659,17 +1785,21 @@ class Ec2ContainerManagerTest { // instance was left with no link-local IMDS endpoint. String script = Ec2ContainerManager.metadataProxyInstallCommand()[2]; - assertTrue(script.contains("dnf install -y --allowerasing iproute socat curl ca-certificates"), - script); + assertTrue(script.contains("dnf install -y --allowerasing iproute socat curl ca-certificates"), script); + assertTrue(script.contains("dnf install -y --allowerasing iptables-nft >/dev/null || true"), script); } @Test - void metadataProxyStartCommandBindsAwsLinkLocalMetadataAddress() { + void metadataProxyStartCommandRoutesAwsLinkLocalMetadataWithoutReservingPort80() { String[] command = Ec2ContainerManager.metadataProxyStartCommand("floci", 9169); assertEquals("sh", command[0]); assertTrue(command[2].contains("169.254.169.254/32")); - assertTrue(command[2].contains("TCP-LISTEN:80,bind=169.254.169.254")); + assertTrue(command[2].contains("TCP-LISTEN:42169,bind=169.254.169.254")); + assertTrue(command[2].contains("-d 169.254.169.254/32 -p tcp --dport 80 -j DNAT" + + " --to-destination 169.254.169.254:42169")); + assertTrue(command[2].contains("if [ -z \"$rule_backend\" ]; then")); + assertTrue(command[2].contains("nohup socat TCP-LISTEN:80,bind=169.254.169.254")); assertTrue(command[2].contains("TCP:floci:9169")); assertTrue(command[2].contains("http://169.254.169.254/latest/meta-data/instance-id")); } diff --git a/src/test/java/io/floci/aws/services/ec2/Ec2MetadataProxyTest.java b/src/test/java/io/floci/aws/services/ec2/Ec2MetadataProxyTest.java index 6ced6a3f45..68bffed6e1 100644 --- a/src/test/java/io/floci/aws/services/ec2/Ec2MetadataProxyTest.java +++ b/src/test/java/io/floci/aws/services/ec2/Ec2MetadataProxyTest.java @@ -22,6 +22,7 @@ import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicInteger; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assumptions.assumeTrue; @@ -40,7 +41,9 @@ class Ec2MetadataProxyTest { assertTrue(prelude.contains("2>/dev/null || true;")); for (String[] command : new String[][]{ Ec2MetadataProxy.installCommand(), + Ec2MetadataProxy.installEc2Command(), Ec2MetadataProxy.startCommand("10.0.0.1", 9169), + Ec2MetadataProxy.startEc2Command("10.0.0.1", 9169), Ec2MetadataProxy.podIdentityStartCommand("10.0.0.1", 4566)}) { assertTrue(command[2].startsWith("set -eu\n" + prelude + "\n"), command[2]); } @@ -91,11 +94,13 @@ class Ec2MetadataProxyTest { assertEquals("-c", command[1]); String script = command[2]; - assertTrue(script.contains("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")); + assertTrue(script.contains("command -v curl >/dev/null 2>&1; then exit 0; fi")); + assertFalse(script.contains("command -v iptables")); assertTrue(script.contains("apt-get install -y --no-install-recommends iproute2 socat curl ca-certificates")); assertTrue(script.contains("dnf install -y --allowerasing iproute socat curl ca-certificates")); assertTrue(script.contains("yum install -y iproute socat curl ca-certificates")); assertTrue(script.contains("apk add --no-cache iproute2 socat curl ca-certificates")); + assertFalse(script.contains("iptables-nft")); } @Test @@ -109,8 +114,9 @@ class Ec2MetadataProxyTest { // Attaches address if missing assertTrue(script.contains("ip addr show dev lo | grep -q '169.254.169.254/32' || ip addr add 169.254.169.254/32 dev lo")); // Idempotent when pid file exists and process is alive - assertTrue(script.contains("if [ -f /tmp/floci-imds-proxy.pid ] && pid=\"$(cat /tmp/floci-imds-proxy.pid)\" && [ \"$(cat \"/proc/$pid/comm\" 2>/dev/null)\" = socat ]" - + " && tr '\\0' ' ' 2>/dev/null <\"/proc/$pid/cmdline\" | grep -q 'TCP-LISTEN:80,bind=169.254.169.254,'; then\n exit 0\nfi")); + assertTrue(script.contains("is_socat_listener() {"), script); + assertTrue(script.contains("is_socat_listener \"$pid\" 'TCP-LISTEN:80,bind=169.254.169.254,'; then" + + "\n exit 0\nfi"), script); // Targets configured Floci host and IMDS port assertTrue(script.contains("nohup socat TCP-LISTEN:80,bind=169.254.169.254,fork,reuseaddr TCP:10.0.0.1:9169 >/tmp/floci-imds-proxy.log 2>&1 &")); // Verifies through an IMDSv2 token even when tokenless access is refused. @@ -119,6 +125,33 @@ class Ec2MetadataProxyTest { assertTrue(script.contains("-H \"X-aws-ec2-metadata-token: $token\" http://169.254.169.254/latest/meta-data/instance-id")); } + @Test + void imdsStartPrefersRoutedRelay() { + String script = Ec2ContainerManager.metadataProxyStartCommand("10.0.0.1", 9169)[2]; + + assertTrue(script.contains("if [ -z \"$rule_backend\" ]; then"), script); + assertTrue(script.contains("nohup socat TCP-LISTEN:42169,bind=169.254.169.254,fork,reuseaddr" + + " TCP:10.0.0.1:9169"), script); + assertTrue(script.contains("iptables -t nat -C OUTPUT -d 169.254.169.254/32 -p tcp --dport 80" + + " -j DNAT --to-destination 169.254.169.254:42169"), script); + assertTrue(script.contains("iptables -t nat -I OUTPUT 1 -d 169.254.169.254/32 -p tcp --dport 80" + + " -j DNAT --to-destination 169.254.169.254:42169"), script); + assertTrue(script.contains("/tmp/floci-imds-proxy-42169.pid"), script); + assertTrue(script.contains("cleanup_new_proxy"), script); + } + + @Test + void imdsStartUsesOneSocatListenerCheckAndNoObsoleteRuleCleanup() { + String script = Ec2ContainerManager.metadataProxyStartCommand("10.0.0.1", 9169)[2]; + + assertTrue(script.contains("is_socat_listener() {"), script); + assertEquals(1L, script.lines().filter(line -> line.contains("/comm")).count(), script); + assertEquals(1L, script.lines().filter(line -> line.contains("/cmdline")).count(), script); + assertEquals(5L, script.lines().filter(line -> line.contains("is_socat_listener ")).count(), script); + assertTrue(script.contains("remove_nft_rule \"$nft_rule_marker\" || true"), script); + assertFalse(script.contains("remove_nft_rule floci-imds-relay-42169"), script); + } + @Test void podIdentityStartCommandAttachesAddressIdempotentlyAndTargetsHostAndPort() { String[] command = Ec2MetadataProxy.podIdentityStartCommand("10.0.0.1", 4566); @@ -128,8 +161,8 @@ class Ec2MetadataProxyTest { String script = command[2]; assertTrue(script.contains("ip addr show dev lo | grep -q '169.254.170.23/32' || ip addr add 169.254.170.23/32 dev lo")); - assertTrue(script.contains("if [ -f /tmp/floci-pod-identity-proxy.pid ] && pid=\"$(cat /tmp/floci-pod-identity-proxy.pid)\" && [ \"$(cat \"/proc/$pid/comm\" 2>/dev/null)\" = socat ]" - + " && tr '\\0' ' ' 2>/dev/null <\"/proc/$pid/cmdline\" | grep -q 'TCP-LISTEN:80,bind=169.254.170.23,'; then\n exit 0\nfi")); + assertTrue(script.contains("is_socat_listener \"$pid\" 'TCP-LISTEN:80,bind=169.254.170.23,'; then" + + "\n exit 0\nfi"), script); assertTrue(script.contains("nohup socat TCP-LISTEN:80,bind=169.254.170.23,fork,reuseaddr TCP:10.0.0.1:4566 >/tmp/floci-pod-identity-proxy.log 2>&1 &")); assertTrue(script.contains("http://169.254.170.23/v1/credentials")); } @@ -181,6 +214,167 @@ class Ec2MetadataProxyTest { Files.readString(arguments)); } + @Test + void ec2InstallUsesExistingNftWithoutNetworkOrPackageManager(@TempDir Path directory) throws Exception { + Path bin = Files.createDirectory(directory.resolve("bin")); + for (String tool : List.of("ip", "socat", "curl", "nft")) { + HelperShellFixture.writeTool(bin, tool, "exit 0\n"); + } + + assertEquals(0, HelperShellFixture.run(Ec2MetadataProxy.installEc2Command(), directory, + Map.of("PATH", bin.toString())), HelperShellFixture.output(directory)); + } + + @Test + void ec2InstallKeepsExistingImdsToolsWhenOfflineAndNoNatBackend(@TempDir Path directory) throws Exception { + Path bin = Files.createDirectory(directory.resolve("bin")); + Path packageCalls = directory.resolve("package-calls"); + for (String tool : List.of("ip", "socat", "curl")) { + HelperShellFixture.writeTool(bin, tool, "exit 0\n"); + } + HelperShellFixture.writeTool(bin, "apk", "printf '%s\\n' apk >> \"$TEST_RECORD\"\nexit 1\n"); + + assertEquals(0, HelperShellFixture.run(Ec2MetadataProxy.installEc2Command(), directory, + Map.of("PATH", bin.toString(), "TEST_RECORD", packageCalls.toString())), + HelperShellFixture.output(directory)); + assertFalse(Files.exists(packageCalls), "a guest with core IMDS tools must not wait on a package repository"); + } + + @Test + void ec2StartTriesNftWhenIptablesCannotInsertNatRule(@TempDir Path directory) throws Exception { + Path bin = Files.createDirectory(directory.resolve("bin")); + Path record = directory.resolve("nft-commands"); + writeEc2StartTools(bin); + HelperShellFixture.writeTool(bin, "iptables", "exit 1\n"); + HelperShellFixture.writeTool(bin, "nft", "printf '%s\\n' \"$*\" >> \"$TEST_RECORD\"\n" + + "case \"$*\" in\n" + + " '-f -') cat >> \"$TEST_RECORD\" ;;\n" + + " 'list table ip floci_imds') exit 1 ;;\n" + + "esac\n"); + + try { + assertEquals(0, HelperShellFixture.run(Ec2MetadataProxy.startEc2Command("127.0.0.1", 9169), + directory, Map.of("PATH", bin + ":/usr/bin:/bin", "TEST_RECORD", record.toString())), + HelperShellFixture.output(directory)); + assertTrue(Files.readString(record).contains("insert rule ip floci_imds output")); + } finally { + deleteEc2ProxyFiles(); + } + } + + @Test + void ec2StartReusesIptablesRuleDespiteEmptyNftTable(@TempDir Path directory) throws Exception { + Path bin = Files.createDirectory(directory.resolve("bin")); + Path record = directory.resolve("iptables-commands"); + writeEc2StartTools(bin); + HelperShellFixture.writeTool(bin, "iptables", "printf '%s\\n' \"$*\" >> \"$TEST_RECORD\"\n" + + "case \"$*\" in\n" + + " *' -C OUTPUT '*) exit 0 ;;\n" + + " *) exit 1 ;;\n" + + "esac\n"); + HelperShellFixture.writeTool(bin, "nft", "case \"$*\" in\n" + + " 'list table ip floci_imds') exit 0 ;;\n" + + " *) exit 1 ;;\n" + + "esac\n"); + + try { + assertEquals(0, HelperShellFixture.run(Ec2MetadataProxy.startEc2Command("127.0.0.1", 9169), + directory, Map.of("PATH", bin + ":/usr/bin:/bin", "TEST_RECORD", record.toString())), + HelperShellFixture.output(directory)); + String commands = Files.readString(record); + assertTrue(commands.contains("-C OUTPUT"), commands); + assertFalse(commands.contains("-I OUTPUT"), commands); + } finally { + deleteEc2ProxyFiles(); + } + } + + @Test + void ec2StartTriesIptablesWhenNftCannotCreateChain(@TempDir Path directory) throws Exception { + Path bin = Files.createDirectory(directory.resolve("bin")); + Path record = directory.resolve("iptables-commands"); + writeEc2StartTools(bin); + HelperShellFixture.writeTool(bin, "iptables", "printf '%s\\n' \"$*\" >> \"$TEST_RECORD\"\n" + + "case \"$*\" in\n" + + " *' -C OUTPUT '*) exit 1 ;;\n" + + " *' -I OUTPUT '*) exit 0 ;;\n" + + "esac\n"); + HelperShellFixture.writeTool(bin, "nft", "case \"$*\" in\n" + + " 'list table ip floci_imds') exit 0 ;;\n" + + " *) exit 1 ;;\n" + + "esac\n"); + + try { + assertEquals(0, HelperShellFixture.run(Ec2MetadataProxy.startEc2Command("127.0.0.1", 9169), + directory, Map.of("PATH", bin + ":/usr/bin:/bin", "TEST_RECORD", record.toString())), + HelperShellFixture.output(directory)); + assertTrue(Files.readString(record).contains("-I OUTPUT")); + } finally { + deleteEc2ProxyFiles(); + } + } + + @Test + void ec2StartPreservesOtherRulesInExistingNftTable(@TempDir Path directory) throws Exception { + Path bin = Files.createDirectory(directory.resolve("bin")); + Path record = directory.resolve("nft-commands"); + writeEc2StartTools(bin); + HelperShellFixture.writeTool(bin, "nft", "printf '%s\\n' \"$*\" >> \"$TEST_RECORD\"\n" + + "case \"$*\" in\n" + + " 'list chain ip floci_imds output') printf '%s\\n'" + + " 'ip daddr 192.0.2.1 accept comment \"guest-rule\" # handle 7' ;;\n" + + " '-f -') cat >> \"$TEST_RECORD\" ;;\n" + + "esac\n"); + + try { + assertEquals(0, HelperShellFixture.run(Ec2MetadataProxy.startEc2Command("127.0.0.1", 9169), + directory, Map.of("PATH", bin + ":/usr/bin:/bin", "TEST_RECORD", record.toString())), + HelperShellFixture.output(directory)); + String commands = Files.readString(record); + assertFalse(commands.contains("delete table ip floci_imds"), commands); + assertTrue(commands.contains("insert rule ip floci_imds output"), commands); + } finally { + deleteEc2ProxyFiles(); + } + } + + @Test + void ec2StartFallsBackToLegacyListenerWhenNoNatBackendExists(@TempDir Path directory) throws Exception { + Path bin = Files.createDirectory(directory.resolve("bin")); + Path record = directory.resolve("listeners"); + writeEc2StartTools(bin); + HelperShellFixture.writeTool(bin, "socat", "printf '%s\\n' \"$*\" >> \"$TEST_RECORD\"\n"); + HelperShellFixture.writeTool(bin, "curl", "grep -q 'TCP-LISTEN:80' \"$TEST_RECORD\" || exit 1\n" + + "case \"$*\" in\n" + + " *'/latest/api/token') printf '%s' fixture-token ;;\n" + + " *'/latest/meta-data/instance-id') printf '%s' i-fixture ;;\n" + + "esac\n"); + + try { + assertEquals(0, HelperShellFixture.run(Ec2MetadataProxy.startEc2Command("127.0.0.1", 9169), + directory, Map.of("PATH", bin + ":/usr/bin:/bin", "TEST_RECORD", record.toString())), + HelperShellFixture.output(directory)); + assertTrue(Files.readString(record).contains("TCP-LISTEN:80,bind=169.254.169.254")); + } finally { + deleteEc2ProxyFiles(); + } + } + + private static void writeEc2StartTools(Path bin) throws Exception { + HelperShellFixture.writeTool(bin, "ip", "printf '%s\\n' 'inet 169.254.169.254/32'\n"); + HelperShellFixture.writeTool(bin, "socat", "exit 0\n"); + HelperShellFixture.writeTool(bin, "curl", "case \"$*\" in\n" + + " *'/latest/api/token') printf '%s' fixture-token ;;\n" + + " *'/latest/meta-data/instance-id') printf '%s' i-fixture ;;\n" + + "esac\n"); + } + + private static void deleteEc2ProxyFiles() throws Exception { + Files.deleteIfExists(Path.of("/tmp/floci-imds-proxy.pid")); + Files.deleteIfExists(Path.of("/tmp/floci-imds-proxy-42169.pid")); + Files.deleteIfExists(Path.of("/tmp/floci-imds-proxy.log")); + } + @Test void startCommandClearsApplicationPathsBeforeAddressProxyAndProbeTools(@TempDir Path directory) throws Exception { diff --git a/src/test/java/io/floci/aws/services/ec2/Ec2StartRequestScopeIntegrationTest.java b/src/test/java/io/floci/aws/services/ec2/Ec2StartRequestScopeIntegrationTest.java index 8e8e99760b..869e61b90d 100644 --- a/src/test/java/io/floci/aws/services/ec2/Ec2StartRequestScopeIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/ec2/Ec2StartRequestScopeIntegrationTest.java @@ -45,7 +45,7 @@ class Ec2StartRequestScopeIntegrationTest { void backgroundStartUsesOwnerOrCallerAndClearsItsScopeAfterFailure(boolean ownerless) throws Exception { try (ExecutorService worker = Executors.newSingleThreadExecutor(); ExecutorService retries = Executors.newSingleThreadExecutor()) { - DockerClient docker = mock(DockerClient.class); + DockerClient docker = mock(DockerClient.class, RETURNS_DEEP_STUBS); Ec2ContainerManager manager = manager(docker, mock(ContainerLifecycleManager.class), worker, retries); Scope caller = new Scope("999900001111", "ap-southeast-1", "aws"); for (Scope owner : List.of(new Scope("111122223333", "eu-west-1", "aws"), diff --git a/src/test/java/io/floci/aws/services/ec2/SecurityGroupFirewallDockerIntegrationTest.java b/src/test/java/io/floci/aws/services/ec2/SecurityGroupFirewallDockerIntegrationTest.java index 476c1a67f6..f4433e91dc 100644 --- a/src/test/java/io/floci/aws/services/ec2/SecurityGroupFirewallDockerIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/ec2/SecurityGroupFirewallDockerIntegrationTest.java @@ -4,10 +4,12 @@ import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.async.ResultCallback; import com.github.dockerjava.api.model.Frame; import io.floci.aws.core.common.docker.ContainerBuilder; +import io.floci.aws.core.common.docker.ContainerExec; import io.floci.aws.core.common.docker.ContainerLifecycleManager; import io.floci.aws.services.ec2.model.IpPermission; import io.floci.aws.services.ec2.model.IpRange; import io.floci.aws.services.ec2.model.SecurityGroup; +import io.floci.aws.testing.TestImages; import io.quarkus.test.junit.QuarkusTest; import jakarta.inject.Inject; import org.junit.jupiter.api.Assumptions; @@ -24,10 +26,59 @@ import java.util.concurrent.TimeUnit; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; @QuarkusTest class SecurityGroupFirewallDockerIntegrationTest { + private static final String METADATA_AND_WEB_SERVERS = """ + from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + from sys import argv + + class Handler(BaseHTTPRequestHandler): + def respond(self, body): + payload = body.encode() + self.send_response(200) + self.send_header("Content-Length", str(len(payload))) + self.end_headers() + self.wfile.write(payload) + + def do_PUT(self): + if self.path == "/latest/api/token" and self.headers.get( + "X-aws-ec2-metadata-token-ttl-seconds"): + self.respond("fixture-token") + else: + self.send_error(400) + + def do_GET(self): + if self.server.server_port == 80: + self.respond("web-ok") + elif self.path == "/latest/meta-data/instance-id" and self.headers.get( + "X-aws-ec2-metadata-token") == "fixture-token": + self.respond("i-fixture") + else: + self.send_error(401) + + def log_message(self, format, *args): + pass + + if argv[1] == "metadata": + ThreadingHTTPServer(("127.0.0.1", 9169), Handler).serve_forever() + else: + ThreadingHTTPServer(("0.0.0.0", 80), Handler).serve_forever() + """; + private static final String IMDS_CLIENT = """ + from urllib.request import ProxyHandler, Request, build_opener + opener = build_opener(ProxyHandler({})) + endpoint = "http://169.254.169.254" + token = opener.open(Request(endpoint + "/latest/api/token", method="PUT", + headers={"X-aws-ec2-metadata-token-ttl-seconds": "60"}), timeout=2).read().decode() + instance = opener.open(Request(endpoint + "/latest/meta-data/instance-id", + headers={"X-aws-ec2-metadata-token": token}), timeout=2).read().decode() + print(token) + print(instance) + """; + // A denied connection is dropped without a reply, so it only ends when nc's timeout expires; // a permitted one connects in tens of milliseconds, so one second is ample to call it denied. private static final int PERMITTED_TIMEOUT_SECONDS = 2; @@ -38,6 +89,123 @@ class SecurityGroupFirewallDockerIntegrationTest { @Inject ContainerBuilder builder; @Inject DockerClient docker; + @Test + void legacyImdsRelayMigratesOfflineAndLeavesWildcardHttpPortAvailable() throws Exception { + Assumptions.assumeTrue(firewall.enabled()); + try { + Assumptions.assumeTrue("linux".equalsIgnoreCase(docker.infoCmd().exec().getOsType())); + } catch (Exception e) { + Assumptions.abort("Docker daemon is unavailable"); + } + + String suffix = UUID.randomUUID().toString().substring(0, 8); + String eniId = "eni-imds-" + suffix; + SecurityGroupFirewallManager.Namespace namespace = null; + String fixtureContainer = null; + String worker = null; + try { + namespace = firewall.createNamespace("ec2", "imds-" + suffix, "000000000000", + "us-east-1", Optional.empty(), Map.of()); + SecurityGroup group = group("sg-imds-" + suffix, false, "0.0.0.0/0"); + firewall.register(endpoint(eniId, "10.0.0.2", namespace, group), namespace.helperId(), Map.of()); + fixtureContainer = lifecycle.createAndStart(builder.newContainer(TestImages.PYTHON_ALPINE) + .withName("floci-imds-fixture-" + suffix) + .withNetworkMode("container:" + namespace.helperId()) + .withEntrypoint(List.of("python", "-c")) + .withCmd(List.of(METADATA_AND_WEB_SERVERS, "metadata")) + .build()).containerId(); + + ContainerExec.Result fixture = pollCurl(docker, namespace.helperId(), "--noproxy", "*", + "-fsS", "--max-time", "1", "-X", "PUT", "-H", + "X-aws-ec2-metadata-token-ttl-seconds: 60", + "http://127.0.0.1:9169/latest/api/token"); + assertEquals(0, fixture.exitCode(), "IMDS fixture did not start: " + fixture.summary()); + assertEquals("fixture-token", fixture.stdout().trim()); + + ContainerExec.Result legacy = ContainerExec.runMerged(docker, namespace.helperId(), + Ec2MetadataProxy.startCommand("127.0.0.1", 9169), 30); + assertEquals(0, legacy.exitCode(), "Old IMDS proxy did not start: " + legacy.summary()); + + ContainerExec.Result removed = ContainerExec.runMerged(docker, namespace.helperId(), + new String[]{"apk", "del", "iptables"}, 10); + assertEquals(0, removed.exitCode(), "Could not simulate the old helper image: " + removed.summary()); + ContainerExec.Result missing = ContainerExec.runMerged(docker, namespace.helperId(), + new String[]{"sh", "-c", "! command -v iptables && command -v nft"}, 5); + assertEquals(0, missing.exitCode(), "Old helper tool state is wrong: " + missing.summary()); + + ContainerExec.Result install = ContainerExec.runMerged(docker, namespace.helperId(), + Ec2ContainerManager.metadataProxyInstallCommand(), 20); + assertEquals(0, install.exitCode(), "Offline IMDS dependencies are unavailable: " + install.summary()); + String[] start = Ec2ContainerManager.metadataProxyStartCommand("127.0.0.1", 9169); + ContainerExec.Result proxy = ContainerExec.runMerged(docker, namespace.helperId(), start, 30); + assertEquals(0, proxy.exitCode(), "IMDS proxy did not start: " + proxy.summary()); + + worker = lifecycle.createAndStart(builder.newContainer(TestImages.PYTHON_ALPINE) + .withName("floci-imds-web-test-" + suffix) + .withNetworkMode("container:" + namespace.helperId()) + .withEntrypoint(List.of("python", "-c")) + .withCmd(List.of(METADATA_AND_WEB_SERVERS, "web")) + .build()).containerId(); + ContainerExec.Result web = pollCurl(docker, namespace.helperId(), "--noproxy", "*", + "-fsS", "--max-time", "1", "http://127.0.0.1:80/"); + assertEquals(0, web.exitCode(), "Wildcard port 80 did not serve HTTP: " + web.summary()); + assertEquals("web-ok", web.stdout().trim()); + + ContainerExec.Result imds = ContainerExec.runMerged(docker, worker, + new String[]{"python", "-c", IMDS_CLIENT}, 10); + assertEquals(0, imds.exitCode(), "Workload could not reach IMDSv2: " + imds.summary()); + assertEquals("fixture-token\ni-fixture", imds.stdout().trim().replace("\r", "")); + + ContainerExec.Result reapplied = ContainerExec.runMerged(docker, namespace.helperId(), start, 30); + assertEquals(0, reapplied.exitCode(), reapplied.summary()); + ContainerExec.Result stale = ContainerExec.runMerged(docker, namespace.helperId(), + new String[]{"nft", "flush", "chain", "ip", "floci_imds", "output"}, 5); + assertEquals(0, stale.exitCode(), stale.summary()); + ContainerExec.Result otherRule = ContainerExec.runMerged(docker, namespace.helperId(), + new String[]{"sh", "-c", "printf '%s\\n'" + + " 'add rule ip floci_imds output ip daddr 192.0.2.1 counter" + + " comment \"guest-preserved\"' | nft -f -"}, 5); + assertEquals(0, otherRule.exitCode(), otherRule.summary()); + ContainerExec.Result repaired = ContainerExec.runMerged(docker, namespace.helperId(), start, 30); + assertEquals(0, repaired.exitCode(), "A stale nft table was not repaired: " + repaired.summary()); + ContainerExec.Result rules = ContainerExec.runMerged(docker, namespace.helperId(), + new String[]{"nft", "list", "chain", "ip", "floci_imds", "output"}, 5); + assertEquals(0, rules.exitCode(), rules.summary()); + assertEquals(1L, rules.stdout().lines() + .filter(line -> line.contains("floci-imds-relay-42169") + && line.contains("169.254.169.254:42169")).count()); + assertTrue(rules.stdout().contains("guest-preserved"), rules.summary()); + assertTrue(Boolean.TRUE.equals(docker.inspectContainerCmd(worker).exec().getState().getRunning())); + } finally { + if (worker != null) { + lifecycle.removeIfExists(worker); + } + if (fixtureContainer != null) { + lifecycle.removeIfExists(fixtureContainer); + } + firewall.unregister(eniId); + if (namespace != null) { + lifecycle.removeIfExists(namespace.helperId()); + } + } + } + + private static ContainerExec.Result pollCurl(DockerClient docker, String helperId, String... curlArgs) + throws Exception { + String[] command = new String[curlArgs.length + 1]; + command[0] = "curl"; + System.arraycopy(curlArgs, 0, command, 1, curlArgs.length); + ContainerExec.Result result = null; + for (int attempt = 0; attempt < 30; attempt++) { + result = ContainerExec.runMerged(docker, helperId, command, 3); + if (result.exitCode() == 0) { + break; + } + Thread.sleep(100); + } + return result; + } + @Test void deniedLogicalCidrBlocksManagedPeerThenRuleUpdatePermitsIt() throws Exception { Assumptions.assumeTrue(firewall.enabled());