fix(eks): answer IMDS on a node by NAT rules instead of a socat relay (#8856)

* fix(eks): answer IMDS on a node by NAT rules instead of a socat relay
* fix(eks): refuse a pod's IMDS request without the pod network, and probe the instance id
This commit is contained in:
mrfelek authored and GitHub committed 2026-11-18 18:10:38 -04:00
1 parent bbc80c9b51
commit 545006249b
6 files changed
+378 -365

No files matched your search

+10 -9
View File
@@ -856,7 +856,7 @@ services:
## Instance Metadata Service (IMDS)
The cluster container is registered as a synthesized EC2 instance node (image `ami-eks-k3s`) regardless of whether IMDS is enabled, making it visible to the EC2 service (`DescribeInstances`, `DescribeInstanceStatus`, volume attachments, tagging). Its instance type is the node group's type, which also sizes the container unless `floci.services.eks.node-instance-type` is set.
When IMDS is enabled (`FLOCI_SERVICES_EKS_IMDS=true`), each k3s cluster container exposes the AWS Instance Metadata Service on the link-local address `169.254.169.254:80`. Inside the container, Floci adds `169.254.169.254/32` to the loopback interface (`lo`) and runs a lightweight `socat` TCP relay forwarding metadata requests to Floci's IMDS server.
When IMDS is enabled (`FLOCI_SERVICES_EKS_IMDS=true`), each k3s cluster container exposes the AWS Instance Metadata Service on the link-local address `169.254.169.254:80`. Inside the container, NAT rules send metadata requests to Floci's IMDS server (see below).
Both IMDSv1 and IMDSv2 (`PUT /latest/api/token`) are supported. The cluster container is registered as a synthesized EC2 instance node associated with the cluster's IAM role:
@@ -872,23 +872,24 @@ curl -s -H "x-aws-ec2-metadata-token: $TOKEN" \
### Reachability and network namespaces
The link-local proxy attaches to the loopback interface of the k3s container network namespace (the node network namespace).
NAT rules in the k3s container's network namespace (the node network namespace) send `169.254.169.254:80` straight to Floci's metadata service, as they send the EKS Pod Identity address to its credentials endpoint. No relay process runs in the node, so nothing is installed there: a stock `rancher/k3s` image, which has `iptables` but no package manager, answers IMDS too.
- **Reachable from node network namespace:** Workloads configured with `hostNetwork: true` share the node network namespace and can reach `169.254.169.254:80`. This allows local testing of host-network security policies, intrusion-detection rules, and credential exfiltration defenses.
- **Default isolation for ordinary pods:** By default, pods running in separate pod network namespaces cannot reach `169.254.169.254`. CNI portmap rules on the node intercept local traffic, preserving node credential isolation for multi-tenant or untrusted workloads.
- **Opt-in pod network routing:** When `floci.services.eks.imds-pod-network=true` is set alongside `floci.services.eks.imds=true`, iptables DNAT rules are programmed in a custom `FLOCI-LINK-LOCAL` chain at the head of `PREROUTING`. Traffic originating from the pod CIDR (`10.42.0.0/16`) targeting `169.254.169.254:80` matches first and is routed directly to the local node listener, preempting CNI portmap rules. This enables standard AWS SDK credential resolution inside ordinary pods without requiring `hostNetwork: true`.
- **Reachable from node network namespace:** An `OUTPUT` rule takes the node's own requests. Workloads configured with `hostNetwork: true` share the node network namespace and can reach `169.254.169.254:80`. This allows local testing of host-network security policies, intrusion-detection rules, and credential exfiltration defenses.
- **Default isolation for ordinary pods:** By default, pods running in separate pod network namespaces cannot reach `169.254.169.254`: a `FORWARD` rule refuses their requests, so that they don't leave the node for the network the Docker host is on, where a Docker host on EC2 can answer them with its own metadata. This preserves node credential isolation for multi-tenant or untrusted workloads.
- **Opt-in pod network routing:** When `floci.services.eks.imds-pod-network=true` is set alongside `floci.services.eks.imds=true`, a `PREROUTING` rule at the head of the chain takes requests from the pod CIDR (`10.42.0.0/16`) for `169.254.169.254:80` too, and the node's masquerade rule (flannel's) carries the answers back. This enables standard AWS SDK credential resolution inside ordinary pods without requiring `hostNetwork: true`.
- **Nodes an older Floci set up:** the rules and the `socat` relay an older Floci left for the address, on the node's loopback, are removed when the node starts or is adopted.
### Configuration
IMDS proxy initialization is disabled by default (`floci.services.eks.imds=false`). Set `FLOCI_SERVICES_EKS_IMDS=true` to enable the proxy setup inside the k3s container.
IMDS is disabled by default (`floci.services.eks.imds=false`). Set `FLOCI_SERVICES_EKS_IMDS=true` to add the forward inside the k3s container.
Pod network reachability is also disabled by default (`floci.services.eks.imds-pod-network=false`) to maintain pod isolation. Set `FLOCI_SERVICES_EKS_IMDS_POD_NETWORK=true` together with `FLOCI_SERVICES_EKS_IMDS=true` to route pod traffic to the link-local proxy.
Pod network reachability is also disabled by default (`floci.services.eks.imds-pod-network=false`) to maintain pod isolation. Set `FLOCI_SERVICES_EKS_IMDS_POD_NETWORK=true` together with `FLOCI_SERVICES_EKS_IMDS=true` to forward pod traffic too.
A failure to configure the proxy (for example on custom minimal images lacking network utilities) logs a warning and allows cluster startup to continue.
A failure to configure the forward (for example on a custom image without `iptables`) logs a warning and allows cluster startup to continue.
### Hop limits
EC2 metadata options store `HttpPutResponseHopLimit`, but the userspace TCP proxy relay terminates the incoming connection and opens a new connection to Floci, regenerating the IP packet TTL. Hop limits are recorded on the instance metadata options model but are not enforced by the userspace proxy.
EC2 metadata options store `HttpPutResponseHopLimit`, but Floci's metadata service sets no TTL on the packets of its answers, so a hop limit is recorded on the instance metadata options model but not enforced.
## IRSA (IAM Roles for Service Accounts)
@@ -920,7 +920,9 @@ public class EksClusterManager
specBuilder.withEmbeddedDns();
}
if (config.services().eks().ecrRegistryMirror() && config.services().ecr().enabled()) {
// The IMDS forward resolves Floci's host in the node too (configureLinkLocalMetadataEndpoint).
if ((config.services().eks().ecrRegistryMirror() && config.services().ecr().enabled())
|| config.services().eks().imds()) {
specBuilder.withHostDockerInternalOnLinux();
}
@@ -2927,6 +2929,12 @@ public class EksClusterManager
}
}
/**
* With {@code imds}, registers the cluster's node with the metadata server and answers IMDS in the node: NAT rules
* send the node's requests, and with {@code imds-pod-network} its pods' too, straight to Floci's metadata service
* (see {@link EksPodNetworkRouting#buildImdsForwardCommand}). No relay process runs in the node, so nothing has
* to be installed there, which a stock {@code rancher/k3s} image could not do.
*/
void configureLinkLocalMetadataEndpoint(Cluster cluster, String containerId) {
if (!config.services().eks().imds()) {
return;
@@ -2949,29 +2957,16 @@ public class EksClusterManager
metadataServer.reconcileClusterNodeAddresses(containerIps.allIps(), nodeInstance);
}
ContainerExec.Result install = execInContainerForResult(containerId,
Ec2MetadataProxy.installCommand(), 180);
if (install.exitCode() != 0) {
LOG.warnv("Could not install IMDS proxy dependencies for EKS cluster {0}: {1}",
cluster.getName(), install.summary());
ContainerExec.Result forward = execInContainerForResult(containerId,
EksPodNetworkRouting.buildImdsForwardCommand(cluster.getPodCidr(),
config.services().eks().imdsPodNetwork(), dockerHostResolver.resolve(),
config.services().ec2().imdsPort()), 30);
if (forward.exitCode() != 0) {
LOG.warnv("Could not forward the link-local IMDS address for EKS cluster {0} to Floci: {1}",
cluster.getName(), forward.summary());
return;
}
String flociHost = dockerHostResolver.resolve();
int imdsPort = config.services().ec2().imdsPort();
ContainerExec.Result start = execInContainerForResult(containerId,
Ec2MetadataProxy.startCommand(flociHost, imdsPort), 30);
if (start.exitCode() != 0) {
LOG.warnv("Could not start link-local IMDS proxy for EKS cluster {0}: {1}",
cluster.getName(), start.summary());
return;
}
if (config.services().eks().imdsPodNetwork()) {
configurePodNetworkRouting(cluster, containerId);
}
LOG.infov("Configured link-local IMDS endpoint for EKS cluster {0}", cluster.getName());
} catch (Exception e) {
LOG.warnv("Could not configure link-local IMDS endpoint for EKS cluster {0}: {1}",
@@ -3080,26 +3075,6 @@ public class EksClusterManager
}
}
void configurePodNetworkRouting(Cluster cluster, String containerId) {
configurePodNetworkRouting(cluster, containerId, EksPodNetworkRouting.DEFAULT_ENDPOINTS);
}
void configurePodNetworkRouting(Cluster cluster, String containerId, List<LinkLocalEndpoint> endpoints) {
try {
String[] routingCmd = EksPodNetworkRouting.buildRoutingCommand(
EksPodNetworkRouting.DEFAULT_POD_CIDR,
endpoints);
ContainerExec.Result routing = execInContainerForResult(containerId, routingCmd, 15);
if (routing.exitCode() != 0) {
LOG.warnv("Could not configure link-local pod network routing for EKS cluster {0}: {1}",
cluster.getName(), routing.summary());
}
} catch (Exception e) {
LOG.warnv("Could not configure link-local pod network routing for EKS cluster {0}: {1}",
cluster.getName(), e.getMessage());
}
}
void configureVpcRoutes(Cluster cluster, String containerId) {
if (!config.services().eks().vpcRouteProgramming() || config.services().eks().mock()) {
return;
@@ -7,13 +7,11 @@ import java.util.List;
import java.util.regex.Pattern;
/**
* Generates iptables routing rules for link-local endpoints inside an EKS cluster container.
* <p>
* Programs DNAT rules in the node network namespace nat table so traffic originating
* from the cluster pod CIDR directed at a link-local address (such as IMDS 169.254.169.254:80)
* reaches Floci's node listener rather than being dropped by the Linux kernel or hijacked by CNI
* hostPort ingress rules. The EKS Pod Identity address, 169.254.170.23:80, is sent straight to
* Floci's credentials endpoint instead, by {@link #buildPodIdentityForwardCommand}.
* Generates the iptables rules that answer a link-local address inside an EKS cluster container: IMDS,
* {@code 169.254.169.254:80} ({@link #buildImdsForwardCommand}), and the EKS Pod Identity address,
* {@code 169.254.170.23:80} ({@link #buildPodIdentityForwardCommand}). NAT rules in the node send the address
* straight to Floci, so no relay process runs there and nothing has to be installed, which a stock
* {@code rancher/k3s} image, with {@code iptables} but no package manager, could not do.
*/
public final class EksPodNetworkRouting {
@@ -21,7 +19,9 @@ public final class EksPodNetworkRouting {
public static final String CHAIN_NAME = "FLOCI-LINK-LOCAL";
public static final LinkLocalEndpoint IMDS_ENDPOINT = new LinkLocalEndpoint("169.254.169.254", 80);
public static final LinkLocalEndpoint POD_IDENTITY_ENDPOINT = new LinkLocalEndpoint("169.254.170.23", 80);
public static final List<LinkLocalEndpoint> DEFAULT_ENDPOINTS = List.of(IMDS_ENDPOINT);
/** The names the relays an older Floci ran for the addresses went by ({@link Ec2MetadataProxy#stopRelayLines}). */
private static final String IMDS_RELAY = "imds";
private static final String POD_IDENTITY_RELAY = "pod-identity";
private static final String HOSTS_FILE = "/etc/hosts";
private static final Pattern IPV4_CIDR = Pattern.compile("\\d{1,3}(\\.\\d{1,3}){3}/\\d{1,2}");
/** A hostname or IPv4 address: nothing a shell or an iptables argument could read as more. */
@@ -32,34 +32,30 @@ public final class EksPodNetworkRouting {
private EksPodNetworkRouting() {}
/**
* Builds a POSIX sh command array that idempotently programs iptables DNAT rules
* in the node container nat table for the specified link-local endpoints.
* Builds a POSIX sh command array that sends IMDS ({@code 169.254.169.254:80}) straight to Floci's metadata
* service with NAT rules in the node, as {@link #buildPodIdentityForwardCommand} sends the Pod Identity address.
* An {@code OUTPUT} rule takes the node's own requests, which is where a {@code hostNetwork} pod's come from. With
* {@code podNetwork} a {@code PREROUTING} rule takes the pod network's too; without it, a {@code FORWARD} rule
* refuses them, so that they don't leave the node for the network the Docker host is on, where a host on EC2 can
* answer with its own metadata. The rules and the relay an older Floci set up for the address go first. The command
* ends once the node's instance id answers, or {@code 401} for an instance that requires tokens, which also proves
* that Floci knows the node by the address its requests come from.
*
* @param podCidr pod network CIDR (defaults to {@link #DEFAULT_POD_CIDR} if null or blank)
* @param endpoints link-local endpoints to route from the pod network
* @param podCidr pod network CIDR (defaults to {@link #DEFAULT_POD_CIDR} if null or blank)
* @param podNetwork whether pods outside the node's network namespace reach IMDS
* @param flociHost the address or hostname the node reaches Floci on
* @param imdsPort the port of Floci's metadata service
* @return command array suitable for container exec (["sh", "-c", "..."])
*/
public static String[] buildRoutingCommand(String podCidr, List<LinkLocalEndpoint> endpoints) {
String cidr = (podCidr != null && !podCidr.isBlank()) ? podCidr : DEFAULT_POD_CIDR;
if (endpoints == null || endpoints.isEmpty()) {
throw new IllegalArgumentException("endpoints cannot be null or empty");
}
public static String[] buildImdsForwardCommand(String podCidr, boolean podNetwork, String flociHost, int imdsPort) {
return buildImdsForwardCommand(podCidr, podNetwork, flociHost, imdsPort, HOSTS_FILE);
}
List<String> lines = iptablesLines(true);
lines.add("$IPTABLES -t nat -N " + CHAIN_NAME + " 2>/dev/null || true");
lines.add("$IPTABLES -t nat -C PREROUTING -j " + CHAIN_NAME + " 2>/dev/null || $IPTABLES -t nat -I PREROUTING 1 -j " + CHAIN_NAME);
for (LinkLocalEndpoint ep : endpoints) {
String check = String.format(
"$IPTABLES -t nat -C %s -s %s -d %s -p tcp --dport %d -j DNAT --to-destination %s:%d 2>/dev/null",
CHAIN_NAME, cidr, ep.ip(), ep.port(), ep.ip(), ep.port());
String add = String.format(
"$IPTABLES -t nat -A %s -s %s -d %s -p tcp --dport %d -j DNAT --to-destination %s:%d",
CHAIN_NAME, cidr, ep.ip(), ep.port(), ep.ip(), ep.port());
lines.add(check + " || " + add);
}
return new String[]{"sh", "-c", String.join("\n", lines)};
/** As above, reading host names from {@code hostsFile} rather than {@code /etc/hosts}. */
static String[] buildImdsForwardCommand(String podCidr, boolean podNetwork, String flociHost, int imdsPort,
String hostsFile) {
return buildForwardCommand(IMDS_ENDPOINT, IMDS_RELAY, podCidrOf(podCidr), podNetwork, flociHost, imdsPort,
hostsFile, imdsProbeCommand("http://" + IMDS_ENDPOINT.ip()));
}
/**
@@ -91,10 +87,28 @@ public final class EksPodNetworkRouting {
/** As above, reading host names from {@code hostsFile} rather than {@code /etc/hosts}. */
static String[] buildPodIdentityForwardCommand(String podCidr, String flociHost, int flociPort, String hostsFile) {
return buildForwardCommand(POD_IDENTITY_ENDPOINT, POD_IDENTITY_RELAY, podCidrOf(podCidr), true, flociHost,
flociPort, hostsFile, podIdentityProbeCommand("http://" + POD_IDENTITY_ENDPOINT.ip()));
}
/** {@code podCidr}, or {@link #DEFAULT_POD_CIDR} if null or blank, which must be an IPv4 CIDR. */
private static String podCidrOf(String podCidr) {
String cidr = (podCidr != null && !podCidr.isBlank()) ? podCidr.trim() : DEFAULT_POD_CIDR;
if (!IPV4_CIDR.matcher(cidr).matches()) {
throw new IllegalArgumentException("podCidr must be an IPv4 CIDR: " + podCidr);
}
return cidr;
}
/**
* The forward of {@code endpoint} to {@code flociHost:flociPort}: the {@code flociHost} name resolved inside the
* node, the rules and the relay named {@code relay} an earlier Floci set up for the address removed, a
* {@code PREROUTING} rule for {@code podCidr} if {@code podNetwork}, else a {@code FORWARD} rule refusing it, and
* an {@code OUTPUT} rule added, then {@code probe} until it ends the command, failing if Floci doesn't answer.
*/
private static String[] buildForwardCommand(LinkLocalEndpoint endpoint, String relay, String podCidr,
boolean podNetwork, String flociHost, int flociPort, String hostsFile,
String probe) {
if (flociHost == null || !HOST.matcher(flociHost).matches()) {
throw new IllegalArgumentException("flociHost must be an IPv4 address or a hostname: " + flociHost);
}
@@ -104,8 +118,8 @@ public final class EksPodNetworkRouting {
if (hostsFile == null || !ABSOLUTE_PATH.matcher(hostsFile).matches()) {
throw new IllegalArgumentException("hostsFile must be an absolute path: " + hostsFile);
}
String address = POD_IDENTITY_ENDPOINT.ip();
String match = "-d " + address + "/32 -p tcp --dport " + POD_IDENTITY_ENDPOINT.port();
String address = endpoint.ip();
String match = "-d " + address + "/32 -p tcp --dport " + endpoint.port();
List<String> lines = iptablesLines(true);
lines.add("HOST='" + flociHost + "'");
@@ -125,14 +139,20 @@ public final class EksPodNetworkRouting {
lines.add(" exit 1");
lines.add("fi");
lines.add("TARGET=\"$ADDR:" + flociPort + "\"");
addPodIdentityRuleRemoval(lines);
lines.add("$IPTABLES -t nat -I PREROUTING 1 -s " + cidr + " " + match + " -j DNAT --to-destination \"$TARGET\"");
addRuleRemoval(lines, endpoint, relay);
if (podNetwork) {
lines.add("$IPTABLES -t nat -I PREROUTING 1 -s " + podCidr + " " + match
+ " -j DNAT --to-destination \"$TARGET\"");
} else {
lines.add("$IPTABLES -t filter -I FORWARD 1 -s " + podCidr + " " + match
+ " -j REJECT --reject-with tcp-reset");
}
lines.add("$IPTABLES -t nat -I OUTPUT 1 " + match + " -j DNAT --to-destination \"$TARGET\"");
lines.add("for i in 1 2 3 4 5 6; do");
lines.add(" " + podIdentityProbeCommand("http://" + address));
lines.add(" " + probe);
lines.add(" sleep 1");
lines.add("done");
lines.add("echo \"nothing answers on " + address + " through $TARGET\" >&2");
lines.add("echo \"Floci does not answer on " + address + " through $TARGET\" >&2");
lines.add("exit 1");
return new String[]{"sh", "-c", String.join("\n", lines)};
}
@@ -147,25 +167,37 @@ public final class EksPodNetworkRouting {
*/
public static String[] buildPodIdentityRemoveCommand() {
List<String> lines = iptablesLines(false);
addPodIdentityRuleRemoval(lines);
addRuleRemoval(lines, POD_IDENTITY_ENDPOINT, POD_IDENTITY_RELAY);
return new String[]{"sh", "-c", String.join("\n", lines)};
}
/**
* Ready once the pod identity endpoint answers at all: without a pod's token Floci answers 400,
* which still proves the path reaches it. Any HTTP proxy the image configures is bypassed, since
* a proxy's own answer would pass the same check. Uses {@code curl} where there is one, else
* {@code wget}, as in a stock {@code rancher/k3s} node, which has BusyBox's and no {@code curl}:
* both print the status of an error answer, which is what is looked for.
*/
/** Ready once the pod identity endpoint answers at all: without a pod's token Floci answers 400. */
static String podIdentityProbeCommand(String endpoint) {
String url = endpoint + "/v1/credentials";
return statusProbeCommand(endpoint + "/v1/credentials", "[1-5][0-9][0-9]");
}
/**
* Ready once the node's instance id answers, or 401 for an instance that requires tokens: an instance Floci
* doesn't know by the caller's address gets 404, as does any path that isn't a metadata path.
*/
static String imdsProbeCommand(String endpoint) {
return statusProbeCommand(endpoint + "/latest/meta-data/instance-id", "200|401");
}
/**
* Ready once {@code url} answers with a status that {@code statuses}, a shell {@code case} pattern, matches. Any
* HTTP proxy the image configures is bypassed, since a proxy's own answer could pass the same check. Uses
* {@code curl} where there is one, else {@code wget}, as in a stock {@code rancher/k3s} node, which has BusyBox's
* and no {@code curl}: with {@code -S}, BusyBox's and GNU's both print the status line, indented, whatever the
* status, which is where it is read from.
*/
static String statusProbeCommand(String url, String statuses) {
return "if command -v curl >/dev/null 2>&1; then"
+ " [ \"$(curl -s --noproxy '*' -o /dev/null -w '%{http_code}' --max-time 1 " + url + ")\" != \"000\" ]"
+ " && exit 0;"
+ " else env -u http_proxy -u HTTP_PROXY wget -T 1 -O /dev/null " + url + " 2>&1"
+ " | grep -qE 'HTTP/1[.][01] [0-9]{3}|ERROR [0-9]{3}' && exit 0;"
+ " fi";
+ " STATUS=$(curl -s --noproxy '*' -o /dev/null -w '%{http_code}' --max-time 1 " + url + " || true);"
+ " else STATUS=$(env -u http_proxy -u HTTP_PROXY wget -S -T 1 -O /dev/null " + url + " 2>&1"
+ " | grep -oE '^ +HTTP/1[.][01] [0-9]{3}' | grep -oE '[0-9]{3}$' || true);"
+ " fi;"
+ " case \"$STATUS\" in " + statuses + ") exit 0 ;; esac";
}
/**
@@ -189,16 +221,18 @@ public final class EksPodNetworkRouting {
}
/**
* Deletes each rule for the Pod Identity address in {@code PREROUTING} and {@code OUTPUT}, and in
* {@link #CHAIN_NAME}, where an older Floci sent it to the relay it ran in the node, then retires that relay.
* The relay would otherwise answer again once the rules in front of it go.
* Deletes each rule for {@code endpoint}'s address in {@code PREROUTING} and {@code OUTPUT}, in
* {@link #CHAIN_NAME}, where an older Floci sent it to the relay it ran in the node, and in {@code FORWARD}, where
* it refused the pod network's requests, then retires that relay, named {@code relay}. The relay would otherwise
* answer again once the rules in front of it go.
*/
private static void addPodIdentityRuleRemoval(List<String> lines) {
lines.add("for CHAIN in PREROUTING OUTPUT " + CHAIN_NAME + "; do");
lines.add(" $IPTABLES -t nat -S \"$CHAIN\" 2>/dev/null | grep -F -- '-d " + POD_IDENTITY_ENDPOINT.ip() + "/32 '"
+ " | grep -F -- '--dport " + POD_IDENTITY_ENDPOINT.port() + " '"
+ " | sed 's/^-A /-D /' | while read -r rule; do $IPTABLES -t nat $rule; done");
private static void addRuleRemoval(List<String> lines, LinkLocalEndpoint endpoint, String relay) {
lines.add("for CHAIN in 'nat PREROUTING' 'nat OUTPUT' 'nat " + CHAIN_NAME + "' 'filter FORWARD'; do");
lines.add(" TABLE=${CHAIN% *}");
lines.add(" $IPTABLES -t \"$TABLE\" -S \"${CHAIN#* }\" 2>/dev/null | grep -F -- '-d " + endpoint.ip() + "/32 '"
+ " | grep -F -- '--dport " + endpoint.port() + " '"
+ " | sed 's/^-A /-D /' | while read -r rule; do $IPTABLES -t \"$TABLE\" $rule; done");
lines.add("done");
lines.addAll(Ec2MetadataProxy.stopRelayLines("pod-identity", POD_IDENTITY_ENDPOINT.ip()));
lines.addAll(Ec2MetadataProxy.stopRelayLines(relay, endpoint.ip()));
}
}
@@ -2106,13 +2106,10 @@ class EksClusterManagerTest {
manager.configureLinkLocalMetadataEndpoint(cluster, "container-42");
verify(metadataServer).reconcileClusterNodeAddresses(any(), any());
// imds=true, imdsPodNetwork=false (default): 2 commands (install probe, start proxy)
assertEquals(2, capturedCmds.size());
// First command: install probe
assertTrue(capturedCmds.get(0)[2].contains("command -v socat"));
// Second command: start command with 169.254.169.254
assertTrue(capturedCmds.get(1)[2].contains("169.254.169.254"));
assertTrue(capturedCmds.get(1)[2].contains("TCP:floci-host:9169"));
// imds=true, imdsPodNetwork=false (default): the node's requests alone go to the metadata service
assertEquals(1, capturedCmds.size());
assertArrayEquals(EksPodNetworkRouting.buildImdsForwardCommand(null, false, "floci-host", 9169),
capturedCmds.get(0));
assertNotNull(manager.getRegisteredClusterNodeInstance(cluster));
}
@@ -2127,18 +2124,10 @@ class EksClusterManagerTest {
manager.configureLinkLocalMetadataEndpoint(cluster, "container-42");
verify(metadataServer).reconcileClusterNodeAddresses(any(), any());
assertEquals(3, capturedCmds.size());
// First command: install probe
assertTrue(capturedCmds.get(0)[2].contains("command -v socat"));
// Second command: start command with 169.254.169.254
assertTrue(capturedCmds.get(1)[2].contains("169.254.169.254"));
assertTrue(capturedCmds.get(1)[2].contains("TCP:floci-host:9169"));
// Third command: pod network routing with iptables
assertTrue(capturedCmds.get(2)[2].contains("FLOCI-LINK-LOCAL"));
assertTrue(capturedCmds.get(2)[2].contains("10.42.0.0/16"));
assertTrue(capturedCmds.get(2)[2].contains("169.254.169.254"));
assertFalse(capturedCmds.get(2)[2].contains("169.254.170.23"),
"IMDS pod routing must not route Pod Identity traffic");
// The node's and the pod network's requests go to the metadata service, in one command
assertEquals(1, capturedCmds.size());
assertArrayEquals(EksPodNetworkRouting.buildImdsForwardCommand(null, true, "floci-host", 9169),
capturedCmds.get(0));
assertNotNull(manager.getRegisteredClusterNodeInstance(cluster));
}
@@ -2435,23 +2424,22 @@ class EksClusterManagerTest {
}
@Test
void podNetworkRoutingFailureLogsWarningAndDoesNotAbort() {
void aForwardThatFailsLogsAWarningAndDoesNotAbort() {
when(eks.imdsPodNetwork()).thenReturn(true);
InspectExecCmd inspectExec = Mockito.mock(InspectExecCmd.class);
InspectExecResponse inspectResponse = Mockito.mock(InspectExecResponse.class);
// Simulate install and start succeeding (0), but routing failing (1)
when(inspectResponse.getExitCodeLong()).thenReturn(0L, 0L, 1L);
when(inspectResponse.getExitCodeLong()).thenReturn(1L);
when(inspectExec.exec()).thenReturn(inspectResponse);
when(dockerClient.inspectExecCmd(anyString())).thenReturn(inspectExec);
Cluster cluster = new Cluster();
cluster.setName("test-cluster");
// Pod network routing failure logs warning and continues without throwing
// The forward's failure logs a warning and continues without throwing
manager.configureLinkLocalMetadataEndpoint(cluster, "container-42");
assertEquals(3, capturedCmds.size());
assertEquals(1, capturedCmds.size());
assertNotNull(manager.getRegisteredClusterNodeInstance(cluster));
}
@@ -3819,6 +3807,24 @@ class EksClusterManagerTest {
return host;
}
/**
* The IMDS forward resolves Floci's host in the node, which on a Linux host is {@code host.docker.internal}
* when Floci runs natively: the node is given that name whenever IMDS is on, as for the ECR mirror and the
* token webhook, which are both off here.
*/
@ParameterizedTest
@ValueSource(booleans = {true, false})
void aNodeWithImdsResolvesFlocisHostOnLinux(boolean imds) {
when(eks.imds()).thenReturn(imds);
stubDockerHost(16L * 1024 * 1024 * 1024, 8);
Cluster cluster = new Cluster();
cluster.setName("imds-host-cluster");
manager.startCluster(cluster);
verify(builder, imds ? Mockito.times(1) : never()).withHostDockerInternalOnLinux();
}
@Test
void hostTooSmallLeavesClusterUnboundedAndStarting() {
DockerClient dockerClient = Mockito.mock(DockerClient.class, Mockito.RETURNS_DEEP_STUBS);
@@ -1,15 +1,16 @@
package io.floci.aws.services.eks;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.dockerjava.api.DockerClient;
import io.floci.aws.config.EmulatorConfig;
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.core.common.docker.ContainerSpec;
import io.floci.aws.core.common.docker.DockerHostResolver;
import io.floci.aws.services.ec2.Ec2MetadataServer;
import io.floci.aws.services.ec2.model.Instance;
import io.floci.aws.services.eks.model.Cluster;
import io.floci.aws.testing.CloudFormationSettingsProfile;
import io.floci.aws.testing.DockerAvailability;
import io.floci.aws.testing.EksTestNode;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import jakarta.inject.Inject;
@@ -19,39 +20,32 @@ import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.time.Duration;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Configures the link-local IMDS endpoint on a stand-in cluster container and queries it from the
* node and from a pod network namespace. The settings come from
* {@link CloudFormationSettingsProfile}, which this class shares with
* {@code TimestreamInfluxDbDockerIntegrationTest}.
* IMDS answers on a stock {@code rancher/k3s} node, which has {@code iptables} but no {@code socat}, {@code curl} or
* package manager: the node itself, where a {@code hostNetwork} pod's requests come from, and an ordinary pod both
* read the node's instance from {@code 169.254.169.254}, and with the pod network off the node refuses the pod's
* requests rather than send them on. The settings come from
* {@link CloudFormationSettingsProfile}, which turns on IMDS for the node and its pod network; the node is started
* through {@link EksClusterManager} directly, which runs a k3s container while EKS is mocked too.
*/
@QuarkusTest
@TestProfile(CloudFormationSettingsProfile.class)
class EksImdsDockerIntegrationTest {
private static final Logger LOG = Logger.getLogger(EksImdsDockerIntegrationTest.class);
private static final String TEST_IMAGE = "alpine:3.21";
private static final String ACCOUNT = "000000000000";
private static final String POD = "imds-client";
private static final String IMDS = "http://169.254.169.254/latest/meta-data/";
@Inject
DockerClient dockerClient;
@Inject
ContainerBuilder containerBuilder;
@Inject
ContainerLifecycleManager lifecycleManager;
@Inject
EmulatorConfig config;
@Inject
Ec2MetadataServer metadataServer;
@@ -61,163 +55,80 @@ class EksImdsDockerIntegrationTest {
@Inject
DockerHostResolver dockerHostResolver;
private String containerId;
@Inject
EmulatorConfig config;
private Cluster cluster;
@BeforeEach
void requireDockerAndStartMetadataServer() {
boolean dockerAvailable = isDockerAvailable();
if (!dockerAvailable) {
LOG.warn("Docker daemon is not available; skipping EksImdsDockerIntegrationTest");
}
Assumptions.assumeTrue(dockerAvailable, "Docker daemon must be available for EKS IMDS integration test");
Assumptions.assumeTrue(DockerAvailability.answers(dockerClient),
"Docker daemon must be available for EKS IMDS integration test");
Assumptions.assumeTrue(dockerHostResolver.isLinuxHost(),
"Link-local IMDS container test requires a Linux host; on macOS/Windows, container-to-host proxy traffic arrives from 127.0.0.1 which collides across clusters");
"Link-local IMDS container test requires a Linux host; on macOS/Windows, container-to-host traffic"
+ " arrives from 127.0.0.1 which collides across clusters");
metadataServer.start().join();
}
@AfterEach
void tearDown() {
if (cluster != null) {
eksClusterManager.unregisterMetadataEndpoint(cluster);
}
if (containerId != null) {
try {
lifecycleManager.stopAndRemove(containerId, null);
} catch (Exception ignored) {
eksClusterManager.stopCluster(cluster);
} catch (Exception e) {
LOG.warnv(e, "Failed to stop test cluster {0}", cluster.getName());
}
}
}
@Test
void linkLocalImdsEndpointAnswersInsideClusterContainer() throws Exception {
String clusterName = "imds-it-" + UUID.randomUUID().toString().substring(0, 8);
cluster = new Cluster();
cluster.setName(clusterName);
cluster.setRoleArn("arn:aws:iam::000000000000:role/eks-it-role");
void theNodeAndAPodReadTheNodesInstanceFromImds() throws Exception {
cluster = EksTestNode.cluster(ACCOUNT, "imds-" + UUID.randomUUID().toString().substring(0, 8));
EksTestNode node = EksTestNode.start(dockerClient, eksClusterManager, cluster, Duration.ofSeconds(60));
Instance instance = eksClusterManager.getRegisteredClusterNodeInstance(cluster);
assertNotNull(instance, "the node must be registered with the metadata server");
ContainerSpec spec = containerBuilder.newContainer(TEST_IMAGE)
.withName("floci-eks-imds-test-" + clusterName)
.withPrivileged(true)
.withHostDockerInternalOnLinux()
// PID 1 gets no default SIGTERM handler, so a bare "sleep 300" sits out the
// whole stopAndRemove grace period when @AfterEach tears the container down.
.withCmd(List.of("sh", "-c", "trap 'exit 0' TERM; sleep 300 & wait"))
.build();
// The node's namespace, with BusyBox's wget: the stock image has no curl.
assertEquals(instance.getInstanceId(), node.execOutput("wget", "-q", "-O", "-", "-T", "3",
IMDS + "instance-id"));
containerId = lifecycleManager.createAndStart(spec).containerId();
assertNotNull(containerId, "Container ID must not be null");
node.apply("""
apiVersion: v1
kind: Pod
metadata:
name: %s
namespace: default
spec:
containers:
- name: client
image: alpine:3.21
command: ["sleep", "3600"]
""".formatted(POD));
node.awaitPodRunning(POD, Duration.ofSeconds(90));
// Ensure curl, iptables, and iproute2 dependencies are installed in the test fixture if absent
execInContainer(containerId, new String[]{"sh", "-c",
"command -v curl >/dev/null 2>&1 && command -v iptables >/dev/null 2>&1 && command -v ip >/dev/null 2>&1 || apk add --no-cache curl iptables iproute2"});
// An ordinary pod, from the pod network: the node's own instance and its instance profile.
assertEquals(instance.getInstanceId(), node.kubectlOutput("exec", POD, "--", "wget", "-q", "-O", "-",
"-T", "3", IMDS + "instance-id"));
String iamInfo = node.kubectlOutput("exec", POD, "--", "wget", "-q", "-O", "-", "-T", "3", IMDS + "iam/info");
assertEquals(instance.getIamInstanceProfileArn(),
new ObjectMapper().readTree(iamInfo).path("InstanceProfileArn").asText(), iamInfo);
eksClusterManager.configureLinkLocalMetadataEndpoint(cluster, containerId);
// Without the pod network the node refuses a pod's request, which would otherwise leave the node for the
// network the Docker host is on and time out here, and still answers its own; with it again, the pod reads
// IMDS once more. Each forward ends only once the node's instance id answers through it.
String flociHost = dockerHostResolver.resolve();
int imdsPort = config.services().ec2().imdsPort();
node.execOutput(EksPodNetworkRouting.buildImdsForwardCommand(cluster.getPodCidr(), false, flociHost, imdsPort));
ContainerExec.Result refused = node.kubectl("exec", POD, "--", "wget", "-q", "-O", "-", "-T", "3",
IMDS + "instance-id");
assertEquals(1, refused.exitCode(), refused.summary());
assertEquals("wget: can't connect to remote host (169.254.169.254): Connection refused\n"
+ "command terminated with exit code 1", refused.stderr().trim());
assertEquals(instance.getInstanceId(), node.execOutput("wget", "-q", "-O", "-", "-T", "3",
IMDS + "instance-id"));
// IMDSv2 token test
String tokenCmd = "curl -s -f -X PUT http://169.254.169.254/latest/api/token -H 'x-aws-ec2-metadata-token-ttl-seconds: 21600'";
String token = execInContainer(containerId, new String[]{"sh", "-c", tokenCmd});
assertNotNull(token, "IMDSv2 token response should not be null");
assertTrue(!token.isBlank(), "IMDSv2 token should not be blank");
// IMDSv2 instance-id metadata test
String instanceIdCmd = "curl -s -f -H 'x-aws-ec2-metadata-token: " + token.trim() + "' http://169.254.169.254/latest/meta-data/instance-id";
String instanceId = execInContainer(containerId, new String[]{"sh", "-c", instanceIdCmd});
assertNotNull(instanceId, "instance-id response should not be null");
assertTrue(instanceId.trim().startsWith("i-"), "Instance ID should start with 'i-': " + instanceId);
// IMDSv1 fallback test using wget (hostNetwork / node namespace regression test)
String imdsv1Cmd = "wget -q -O - http://169.254.169.254/latest/meta-data/instance-id";
String v1InstanceId = execInContainer(containerId, new String[]{"sh", "-c", imdsv1Cmd});
assertEquals(instanceId.trim(), v1InstanceId.trim(), "IMDSv1 and IMDSv2 instance IDs should match");
// Pod network namespace test: ordinary pods in their own network namespace reach link-local IMDS
// via the rules programmed for the pod CIDR (10.42.0.0/16).
String podNetworkSetupCmd = """
set -e
ip link add cni0 type bridge 2>/dev/null || true
ip addr add 10.42.0.1/24 dev cni0 2>/dev/null || true
ip link set cni0 up
ip netns add pod-test 2>/dev/null || true
ip link add veth-host type veth peer name eth0 netns pod-test 2>/dev/null || true
ip link set veth-host master cni0 up
ip netns exec pod-test ip link set lo up
ip netns exec pod-test ip addr add 10.42.0.15/24 dev eth0 2>/dev/null || true
ip netns exec pod-test ip link set eth0 up
ip netns exec pod-test ip route replace default via 10.42.0.1
# Stand-in CNI portmap rule: k3s/flannel installs CNI-HOSTPORT-DNAT matching dst-type LOCAL.
# Simulate a hostPort/ingress binding or redirect on port 80 that intercepts LOCAL traffic.
iptables -t nat -N CNI-HOSTPORT-DNAT 2>/dev/null || true
iptables -t nat -F CNI-HOSTPORT-DNAT 2>/dev/null || true
iptables -t nat -A CNI-HOSTPORT-DNAT -p tcp --dport 80 -j REDIRECT --to-ports 9999
iptables -t nat -D PREROUTING -m addrtype --dst-type LOCAL -j CNI-HOSTPORT-DNAT 2>/dev/null || true
iptables -t nat -A PREROUTING -m addrtype --dst-type LOCAL -j CNI-HOSTPORT-DNAT
""";
execInContainer(containerId, new String[]{"sh", "-c", podNetworkSetupCmd});
try {
// Ordinary pod querying instance-id with FLOCI-LINK-LOCAL preempting CNI-HOSTPORT-DNAT
String podInstanceIdCmd = "ip netns exec pod-test wget -q -O - -T 3 http://169.254.169.254/latest/meta-data/instance-id";
String podInstanceId = execInContainer(containerId, new String[]{"sh", "-c", podInstanceIdCmd});
assertNotNull(podInstanceId, "Pod instance ID response should not be null");
assertEquals(instanceId.trim(), podInstanceId.trim(),
"Pod should receive the same instance ID as the node namespace");
// Ordinary pod querying IAM info
String podIamInfoCmd = "ip netns exec pod-test wget -q -O - -T 3 http://169.254.169.254/latest/meta-data/iam/info";
String podIamInfo = execInContainer(containerId, new String[]{"sh", "-c", podIamInfoCmd});
assertNotNull(podIamInfo, "Pod IAM info response should not be null");
assertTrue(podIamInfo.contains(clusterName + "-node-profile"),
"Pod IAM info should contain instance profile: " + podIamInfo);
// Prove the FLOCI-LINK-LOCAL rule is strictly required:
// Temporarily detach FLOCI-LINK-LOCAL from PREROUTING. The pod request now hits CNI-HOSTPORT-DNAT
// and fails because port 80 is redirected to 9999.
execInContainer(containerId, new String[]{"sh", "-c",
"iptables -t nat -D PREROUTING -j FLOCI-LINK-LOCAL"});
ContainerExec.Result intercepted = execInContainerWithExitCode(containerId, new String[]{"sh", "-c",
"ip netns exec pod-test wget -q -O - -T 2 http://169.254.169.254/latest/meta-data/instance-id"});
assertNotEquals(0, intercepted.exitCode(),
"Without FLOCI-LINK-LOCAL chain, pod request should be intercepted by CNI-HOSTPORT-DNAT and fail");
// Re-insert FLOCI-LINK-LOCAL at rule 1: pod request succeeds again
execInContainer(containerId, new String[]{"sh", "-c",
"iptables -t nat -I PREROUTING 1 -j FLOCI-LINK-LOCAL"});
String restoredInstanceId = execInContainer(containerId, new String[]{"sh", "-c", podInstanceIdCmd});
assertEquals(instanceId.trim(), restoredInstanceId.trim(),
"Restoring FLOCI-LINK-LOCAL rule must restore pod reachability");
} finally {
execInContainerWithExitCode(containerId, new String[]{"sh", "-c", """
ip netns del pod-test 2>/dev/null || true
ip link del cni0 2>/dev/null || true
iptables -t nat -D PREROUTING -j FLOCI-LINK-LOCAL 2>/dev/null || true
iptables -t nat -D PREROUTING -m addrtype --dst-type LOCAL -j CNI-HOSTPORT-DNAT 2>/dev/null || true
iptables -t nat -F CNI-HOSTPORT-DNAT 2>/dev/null || true
iptables -t nat -X CNI-HOSTPORT-DNAT 2>/dev/null || true
"""});
}
}
private boolean isDockerAvailable() {
try {
dockerClient.pingCmd().exec();
return true;
} catch (Exception e) {
return false;
}
}
private ContainerExec.Result execInContainerWithExitCode(String containerId, String[] cmd) {
return ContainerExec.run(dockerClient, containerId, cmd, 30).throwIfTimedOut(containerId);
}
private String execInContainer(String containerId, String[] cmd) throws Exception {
ContainerExec.Result result = execInContainerWithExitCode(containerId, cmd);
if (result.exitCode() != 0) {
throw new RuntimeException("exec failed with code " + result.exitCode() + ": " + result.stderr());
}
return result.stdout();
node.execOutput(EksPodNetworkRouting.buildImdsForwardCommand(cluster.getPodCidr(), true, flociHost, imdsPort));
assertEquals(instance.getInstanceId(), node.kubectlOutput("exec", POD, "--", "wget", "-q", "-O", "-",
"-T", "3", IMDS + "instance-id"));
}
}
@@ -9,6 +9,7 @@ import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
@@ -21,13 +22,12 @@ 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.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class EksPodNetworkRoutingTest {
/** What the stand-in iptables is asked when it lists a rule for the address in each chain. */
/** What the stand-in iptables is asked when it lists the rules for the address in each chain, and deletes them. */
private static final List<String> EARLIER_RULES_REMOVED = List.of(
"-t nat -S PREROUTING",
"-t nat -D PREROUTING -s 10.42.0.0/16 -d 169.254.170.23/32 -p tcp -m tcp --dport 80 -j DNAT"
@@ -36,10 +36,27 @@ class EksPodNetworkRoutingTest {
"-t nat -D OUTPUT -d 169.254.170.23/32 -p tcp -m tcp --dport 80 -j DNAT --to-destination 172.18.0.9:4566",
"-t nat -S FLOCI-LINK-LOCAL",
"-t nat -D FLOCI-LINK-LOCAL -s 10.42.0.0/16 -d 169.254.170.23/32 -p tcp -m tcp --dport 80 -j DNAT"
+ " --to-destination 169.254.170.23:80");
+ " --to-destination 169.254.170.23:80",
"-t filter -S FORWARD");
/** As {@link #EARLIER_RULES_REMOVED}, for IMDS. */
private static final List<String> EARLIER_IMDS_RULES_REMOVED = List.of(
"-t nat -S PREROUTING",
"-t nat -D PREROUTING -s 10.42.0.0/16 -d 169.254.169.254/32 -p tcp -m tcp --dport 80 -j DNAT"
+ " --to-destination 172.18.0.9:9169",
"-t nat -S OUTPUT",
"-t nat -D OUTPUT -d 169.254.169.254/32 -p tcp -m tcp --dport 80 -j DNAT --to-destination 172.18.0.9:9169",
"-t nat -S FLOCI-LINK-LOCAL",
"-t nat -D FLOCI-LINK-LOCAL -s 10.42.0.0/16 -d 169.254.169.254/32 -p tcp -m tcp --dport 80 -j DNAT"
+ " --to-destination 169.254.169.254:80",
"-t filter -S FORWARD",
"-t filter -D FORWARD -s 10.42.0.0/16 -d 169.254.169.254/32 -p tcp -m tcp --dport 80 -j REJECT"
+ " --reject-with tcp-reset");
/** Where the relay an older Floci ran for the address kept its PID. */
private static final Path RELAY_PID_FILE = Path.of("/tmp/floci-pod-identity-proxy.pid");
/** As {@link #RELAY_PID_FILE}, for IMDS. */
private static final Path IMDS_RELAY_PID_FILE = Path.of("/tmp/floci-imds-proxy.pid");
@Test
void linkLocalEndpointValidatesInput() {
@@ -62,66 +79,6 @@ class EksPodNetworkRoutingTest {
assertEquals(80, ep.port());
}
@Test
void buildRoutingCommandRejectsNullOrEmptyEndpoints() {
assertThrows(IllegalArgumentException.class, () ->
EksPodNetworkRouting.buildRoutingCommand(null, null));
assertThrows(IllegalArgumentException.class, () ->
EksPodNetworkRouting.buildRoutingCommand("10.42.0.0/16", List.of()));
}
@Test
void buildRoutingCommandUsesDefaultPodCidrWhenNullOrBlank() {
String[] cmdNull = EksPodNetworkRouting.buildRoutingCommand(null, EksPodNetworkRouting.DEFAULT_ENDPOINTS);
assertEquals(3, cmdNull.length);
assertEquals("sh", cmdNull[0]);
assertEquals("-c", cmdNull[1]);
assertTrue(cmdNull[2].contains(EksPodNetworkRouting.DEFAULT_POD_CIDR));
String[] cmdBlank = EksPodNetworkRouting.buildRoutingCommand(" ", EksPodNetworkRouting.DEFAULT_ENDPOINTS);
assertTrue(cmdBlank[2].contains(EksPodNetworkRouting.DEFAULT_POD_CIDR));
}
@Test
void buildRoutingCommandGeneratesIdempotentChainAndRules() {
String[] cmd = EksPodNetworkRouting.buildRoutingCommand("10.42.0.0/16", List.of(
new LinkLocalEndpoint("169.254.169.254", 80),
new LinkLocalEndpoint("169.254.170.23", 80)
));
String script = cmd[2];
assertNotNull(script);
// Finds iptables binary across standard and k3s aux locations
assertTrue(script.contains("IPTABLES=$(command -v iptables 2>/dev/null || command -v /bin/aux/iptables 2>/dev/null || true)"));
assertTrue(script.contains("iptables not found in container"));
// Creates custom chain idempotently
assertTrue(script.contains("$IPTABLES -t nat -N FLOCI-LINK-LOCAL 2>/dev/null || true"));
// Inserts jump in PREROUTING only if not already present
assertTrue(script.contains("$IPTABLES -t nat -C PREROUTING -j FLOCI-LINK-LOCAL 2>/dev/null || $IPTABLES -t nat -I PREROUTING 1 -j FLOCI-LINK-LOCAL"));
// Adds rule for IMDS endpoint with check before append
String imdsCheck = "$IPTABLES -t nat -C FLOCI-LINK-LOCAL -s 10.42.0.0/16 -d 169.254.169.254 -p tcp --dport 80 -j DNAT --to-destination 169.254.169.254:80 2>/dev/null";
String imdsAdd = "$IPTABLES -t nat -A FLOCI-LINK-LOCAL -s 10.42.0.0/16 -d 169.254.169.254 -p tcp --dport 80 -j DNAT --to-destination 169.254.169.254:80";
assertTrue(script.contains(imdsCheck + " || " + imdsAdd));
// Adds rule for Pod Identity endpoint with check before append
String podIdCheck = "$IPTABLES -t nat -C FLOCI-LINK-LOCAL -s 10.42.0.0/16 -d 169.254.170.23 -p tcp --dport 80 -j DNAT --to-destination 169.254.170.23:80 2>/dev/null";
String podIdAdd = "$IPTABLES -t nat -A FLOCI-LINK-LOCAL -s 10.42.0.0/16 -d 169.254.170.23 -p tcp --dport 80 -j DNAT --to-destination 169.254.170.23:80";
assertTrue(script.contains(podIdCheck + " || " + podIdAdd));
}
@Test
void buildRoutingCommandSupportsCustomCidr() {
String customCidr = "192.168.0.0/16";
String[] cmd = EksPodNetworkRouting.buildRoutingCommand(customCidr, EksPodNetworkRouting.DEFAULT_ENDPOINTS);
String script = cmd[2];
assertTrue(script.contains("-s 192.168.0.0/16 -d 169.254.169.254"));
}
@ParameterizedTest
@ValueSource(strings = {"", "floci host", "floci;reboot", "$(id)", "floci`id`", "-floci", "floci-", "a'b"})
void podIdentityForwardRefusesAHostTheShellCouldReadAsMore(String host) {
@@ -148,9 +105,10 @@ class EksPodNetworkRoutingTest {
}
/**
* Runs the forward script against stand-ins for a stock k3s node's tools: iptables records what
* it is asked and lists the rules an earlier Floci left for the address, nslookup answers as
* BusyBox's does, and wget gets Floci's 400 for a request without a pod token. There is no curl.
* Runs the forward script against stand-ins for a stock k3s node's tools ({@link #fakeStockNode}):
* iptables records what it is asked and lists the rules an earlier Floci left for the address,
* nslookup answers as BusyBox's does, and wget gets Floci's 400 for a request without a pod token.
* There is no curl.
* The host is resolved from the hosts file first, through DNS when that has no entry, and an
* address is used as it is.
*/
@@ -179,6 +137,79 @@ class EksPodNetworkRoutingTest {
assertEquals(looksUp ? List.of(host) : List.of(), calls(dir.resolve("nslookup-calls")));
}
@Test
void imdsForwardRefusesABadHostOrPodCidr() {
assertThrows(IllegalArgumentException.class,
() -> EksPodNetworkRouting.buildImdsForwardCommand(null, true, "floci;reboot", 9169));
assertThrows(IllegalArgumentException.class,
() -> EksPodNetworkRouting.buildImdsForwardCommand("10.42.0.0/16; id", true, "floci", 9169));
assertThrows(IllegalArgumentException.class,
() -> EksPodNetworkRouting.buildImdsForwardCommand(null, true, "floci", 0));
}
/**
* IMDS goes to Floci's metadata service as the Pod Identity address goes to its credentials endpoint, once the
* rules an earlier Floci left for it are gone: from the node always, and from the pod network when asked. When not,
* the pod network's requests are refused, rather than sent on toward the network the Docker host is on.
*/
@ParameterizedTest
@ValueSource(booleans = {true, false})
void imdsForwardReplacesEarlierRulesAndTakesThePodNetworkOnlyWhenAsked(boolean podNetwork, @TempDir Path dir)
throws Exception {
Path bin = fakeStockNode(dir);
Path hosts = Files.writeString(dir.resolve("hosts"), "172.18.0.7 floci-under-test.internal\n");
int exit = HelperShellFixture.run(EksPodNetworkRouting.buildImdsForwardCommand(null, podNetwork,
"floci-under-test.internal", 9169, hosts.toString()), dir,
Map.of("PATH", bin.toString(), "http_proxy", "http://127.0.0.1:9"));
assertEquals(0, exit, HelperShellFixture.output(dir));
List<String> expected = new ArrayList<>(EARLIER_IMDS_RULES_REMOVED);
if (podNetwork) {
expected.add("-t nat -I PREROUTING 1 -s 10.42.0.0/16 -d 169.254.169.254/32 -p tcp --dport 80 -j DNAT"
+ " --to-destination 172.18.0.7:9169");
} else {
expected.add("-t filter -I FORWARD 1 -s 10.42.0.0/16 -d 169.254.169.254/32 -p tcp --dport 80 -j REJECT"
+ " --reject-with tcp-reset");
}
expected.add("-t nat -I OUTPUT 1 -d 169.254.169.254/32 -p tcp --dport 80 -j DNAT --to-destination"
+ " 172.18.0.7:9169");
assertEquals(expected, Files.readAllLines(dir.resolve("iptables-calls")));
}
/**
* The IMDS relay an older Floci ran on the node's loopback would keep the address local to the node, so the
* forward stops it, while its PID file still names it, and takes its address off the loopback. The forward runs
* traced, so the test sees the {@code kill} it sends.
*/
@Test
void imdsForwardRetiresTheRelayAnOlderFlociRan(@TempDir Path dir) throws Exception {
Path bin = fakeStockNode(dir);
HelperShellFixture.writeTool(bin, "ip", "echo \"$*\" >> '" + dir.resolve("ip-calls") + "'\n"
+ "if [ \"$*\" = 'addr show dev lo' ]; then\n"
+ " echo ' inet 127.0.0.1/8 scope host lo'\n"
+ " echo ' inet 169.254.169.254/32 scope global lo'\n"
+ "fi\n");
Process relay = startFakeRelay(bin, "169.254.169.254");
try {
Files.writeString(IMDS_RELAY_PID_FILE, relay.pid() + "\n");
int exit = HelperShellFixture.run(
traced(EksPodNetworkRouting.buildImdsForwardCommand(null, true, "172.18.0.7", 9169)), dir,
Map.of("PATH", bin.toString()));
assertEquals(0, exit, HelperShellFixture.output(dir));
assertEquals(List.of("kill " + relay.pid()), tracedKills(dir), HelperShellFixture.output(dir));
assertTrue(relay.waitFor(10, TimeUnit.SECONDS), "the relay is still running");
assertFalse(Files.exists(IMDS_RELAY_PID_FILE));
assertEquals(List.of("addr show dev lo", "addr del 169.254.169.254/32 dev lo"),
calls(dir.resolve("ip-calls")));
} finally {
relay.destroyForcibly();
Files.deleteIfExists(IMDS_RELAY_PID_FILE);
}
}
/** Without the add-on nothing answers on the address: every rule for it goes, the others stay. */
@Test
void podIdentityRemovalDeletesEveryRuleForTheAddressAndAddsNone(@TempDir Path dir) throws Exception {
@@ -265,8 +296,8 @@ class EksPodNetworkRoutingTest {
* Floci answers 400 without a pod token, which still proves the path reaches it. A proxy that
* answered in its place would look the same to the status check, so the probe must not go
* through one, whether it asks with curl or, on a stock {@code rancher/k3s} node, which has
* BusyBox's {@code wget} and no {@code curl}, with wget, reading the status from the error it
* prints.
* BusyBox's {@code wget} and no {@code curl}, with wget, reading the status from the status line
* {@code -S} prints.
*/
@ParameterizedTest
@ValueSource(strings = {"curl", "wget"})
@@ -286,8 +317,8 @@ class EksPodNetworkRoutingTest {
exchange.close();
});
floci.start();
String[] probe = {"sh", "-c",
EksPodNetworkRouting.podIdentityProbeCommand("http://127.0.0.1:" + floci.getAddress().getPort())};
String[] probe = probe(
EksPodNetworkRouting.podIdentityProbeCommand("http://127.0.0.1:" + floci.getAddress().getPort()));
Map<String, String> environment = new HashMap<>(HelperShellFixture.proxyEnvironment(proxy));
environment.put("PATH", bin.toString());
@@ -306,13 +337,51 @@ class EksPodNetworkRoutingTest {
}
}
/**
* The IMDS forward is ready once the node's instance id answers, or 401 for an instance that requires tokens:
* Floci's 404, for a caller it doesn't know by its address, or another server's error leaves it waiting. With
* curl, or with wget, whose status line {@code -S} prints: GNU's prints no status in its own message for a 401.
*/
@ParameterizedTest
@CsvSource({"curl, 200, 0", "curl, 401, 0", "curl, 404, 1", "curl, 500, 1",
"wget, 200, 0", "wget, 401, 0", "wget, 404, 1", "wget, 500, 1"})
void imdsProbeIsReadyOnceTheNodesInstanceIdAnswers(String client, int status, int expectedExit, @TempDir Path dir)
throws Exception {
Path bin = Files.createDirectory(dir.resolve("bin"));
HelperShellFixture.linkHostTools(bin, List.of(client, "env", "grep"));
List<String> asked = new CopyOnWriteArrayList<>();
HttpServer imds = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
try {
imds.createContext("/", exchange -> {
asked.add(exchange.getRequestURI().getPath());
byte[] body = "i-0123456789abcdef0".getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(status, body.length);
exchange.getResponseBody().write(body);
exchange.close();
});
imds.start();
int result = HelperShellFixture.run(
probe(EksPodNetworkRouting.imdsProbeCommand("http://127.0.0.1:" + imds.getAddress().getPort())),
dir, Map.of("PATH", bin.toString()));
assertEquals(expectedExit, result, HelperShellFixture.output(dir));
assertEquals(List.of("/latest/meta-data/instance-id"), asked);
} finally {
imds.stop(0);
}
}
/**
* A bin directory of stand-ins for a stock k3s node's tools, beside the host's awk, sed, grep,
* env, sleep, cat, tr and rm. iptables records its arguments in {@code iptables-calls} and lists,
* in {@code PREROUTING} and {@code OUTPUT}, a rule an earlier Floci on 172.18.0.9 left for the
* address and one rule of another's, and in {@code FLOCI-LINK-LOCAL} the rule an older Floci sent
* the address to its relay with, beside the IMDS one. nslookup records its arguments in
* {@code nslookup-calls} and answers as BusyBox's.
* in {@code PREROUTING} and {@code OUTPUT}, the rules an earlier Floci on 172.18.0.9 left for the
* Pod Identity address and for IMDS and one rule of another's, in {@code FORWARD} the rule an earlier
* Floci refused the pod network's IMDS requests with and one of another's, and in
* {@code FLOCI-LINK-LOCAL} the rules an older Floci sent each address to its relay with. nslookup
* records its arguments in {@code nslookup-calls} and answers as BusyBox's. wget prints the status
* line as BusyBox's does with {@code -S}: a 200 for the node's instance id from IMDS, and Floci's
* 400 for anything else, as for a Pod Identity request without a pod token.
*/
private static Path fakeStockNode(Path dir) throws Exception {
Path bin = Files.createDirectory(dir.resolve("bin"));
@@ -322,13 +391,22 @@ class EksPodNetworkRoutingTest {
+ " echo '-P PREROUTING ACCEPT'\n"
+ " echo '-A PREROUTING -s 10.42.0.0/16 -d 169.254.170.23/32 -p tcp -m tcp --dport 80 -j DNAT"
+ " --to-destination 172.18.0.9:4566'\n"
+ " echo '-A PREROUTING -s 10.42.0.0/16 -d 169.254.169.254/32 -p tcp -m tcp --dport 80 -j DNAT"
+ " --to-destination 172.18.0.9:9169'\n"
+ " echo '-A PREROUTING -j FLOCI-LINK-LOCAL'\n"
+ "fi\n"
+ "if [ \"$*\" = '-t nat -S OUTPUT' ]; then\n"
+ " echo '-P OUTPUT ACCEPT'\n"
+ " echo '-A OUTPUT -d 169.254.170.23/32 -p tcp -m tcp --dport 80 -j DNAT --to-destination 172.18.0.9:4566'\n"
+ " echo '-A OUTPUT -d 169.254.169.254/32 -p tcp -m tcp --dport 80 -j DNAT --to-destination 172.18.0.9:9169'\n"
+ " echo '-A OUTPUT -j KUBE-SERVICES'\n"
+ "fi\n"
+ "if [ \"$*\" = '-t filter -S FORWARD' ]; then\n"
+ " echo '-P FORWARD ACCEPT'\n"
+ " echo '-A FORWARD -s 10.42.0.0/16 -d 169.254.169.254/32 -p tcp -m tcp --dport 80 -j REJECT"
+ " --reject-with tcp-reset'\n"
+ " echo '-A FORWARD -j KUBE-ROUTER-FORWARD'\n"
+ "fi\n"
+ "if [ \"$*\" = '-t nat -S FLOCI-LINK-LOCAL' ]; then\n"
+ " echo '-N FLOCI-LINK-LOCAL'\n"
+ " echo '-A FLOCI-LINK-LOCAL -s 10.42.0.0/16 -d 169.254.169.254/32 -p tcp -m tcp --dport 80 -j DNAT"
@@ -341,6 +419,9 @@ class EksPodNetworkRoutingTest {
+ "printf 'Server:\\t\\t127.0.0.11\\nAddress:\\t127.0.0.11:53\\n\\nNon-authoritative answer:\\n"
+ "Name:\\tfloci-under-test.internal\\nAddress: 172.18.0.2\\n'\n");
HelperShellFixture.writeTool(bin, "wget", "[ -z \"${http_proxy:-}\" ] || exit 2\n"
+ "case \"$*\" in *' http://169.254.169.254/latest/meta-data/instance-id')\n"
+ " echo ' HTTP/1.1 200 OK' >&2\n exit 0 ;;\nesac\n"
+ "echo ' HTTP/1.1 400 Bad Request' >&2\n"
+ "echo 'wget: server returned error: HTTP/1.1 400 Bad Request' >&2\nexit 1\n");
return bin;
}
@@ -359,6 +440,11 @@ class EksPodNetworkRoutingTest {
"TCP:172.18.0.9:4566").start();
}
/** A probe run on its own: it ends the shell once ready, and otherwise the shell fails. */
private static String[] probe(String probeCommand) {
return new String[]{"sh", "-c", probeCommand + "\nexit 1"};
}
/** {@code command}, an {@code sh -c} one, run with each command it runs printed to its output ({@code sh -x}). */
private static String[] traced(String[] command) {
List<String> arguments = new ArrayList<>(List.of(command));