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
This commit is contained in:
Jimmy Liu Jia authored and GitHub committed 2026-11-14 15:23:23 -04:00
1 parent 63607e899d
commit 045ecc4eeb
9 files changed
+777 -60

No files matched your search

@@ -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);
}
@@ -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<String> 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<String> 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<String> preferredMetadataSourceIp(Map<String, ContainerNetwork> networks) {
@@ -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<String> addresses, Instance instance) {
for (String address : addresses) {