fix(eks): forward the Pod Identity address to Floci with NAT rules while its add-on is installed (#8736)

A stock rancher/k3s node has no package manager, so the socat relay Floci installed for the EKS Pod Identity address, 169.254.170.23, never started, and every pod's credentials request timed out. The address is now sent straight to Floci's credentials endpoint with iptables NAT rules, a PREROUTING rule for the pod network and an OUTPUT rule for the node and hostNetwork pods, and what an older Floci set up for the address, its relay included, is removed. The rules follow the eks-pod-identity-agent add-on: CreateAddon adds them, DeleteAddon removes them unless preserve is set, and a node start or a restart's adoption sets them from the stored add-on, under a lock of the cluster. The Pod Identity webhook reads the same stored add-on.

Closes #5629
This commit is contained in:
mrfelek authored and GitHub committed 2026-11-17 21:50:25 -04:00
1 parent 11a16946b6
commit f06695cf08
21 files changed
+1435 -310

No files matched your search

@@ -14,6 +14,13 @@ public final class Ec2MetadataProxy {
private static final int EC2_IMDS_RELAY_PORT = 42169;
/** A shell function: whether process {@code $1} is a socat whose arguments hold {@code $2}. */
private static final List<String> IS_SOCAT_LISTENER = List.of(
"is_socat_listener() {",
" [ \"$(cat \"/proc/$1/comm\" 2>/dev/null)\" = socat ]"
+ " && tr '\\0' ' ' 2>/dev/null <\"/proc/$1/cmdline\" | grep -Fq \"$2\"",
"}");
/**
* 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
@@ -126,21 +133,6 @@ public final class Ec2MetadataProxy {
+ endpoint + "/latest/meta-data/instance-id >/dev/null && exit 0";
}
public static String[] podIdentityStartCommand(String flociHost, int flociPort) {
return startCommand("pod-identity", "169.254.170.23", 80, flociHost, flociPort,
podIdentityProbeCommand("http://169.254.170.23"));
}
/**
* Ready once the relay answers at all: without a pod's token Floci answers 400, which still
* proves socat relays. Any HTTP proxy the image configures is bypassed, since a proxy's own
* answer would pass the same check.
*/
static String podIdentityProbeCommand(String endpoint) {
return "[ \"$(curl -s --noproxy '*' -o /dev/null -w '%{http_code}' --max-time 1 " + endpoint
+ "/v1/credentials)\" != \"000\" ] && exit 0";
}
public static String[] startCommand(String name, String bindIp, int bindPort,
String targetHost, int targetPort, String probeCommand) {
return startCommand(name, bindIp, bindPort, targetHost, targetPort, probeCommand, false);
@@ -149,7 +141,7 @@ public final class Ec2MetadataProxy {
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 legacyPidFile = relayPidFile(name);
String pidFile = routeImdsPort ? "/tmp/floci-" + name + "-proxy-" + bindPort + ".pid" : legacyPidFile;
String logFile = "/tmp/floci-" + name + "-proxy.log";
String listener = "TCP-LISTEN:" + bindPort + ",bind=" + bindIp + ",";
@@ -161,10 +153,7 @@ public final class Ec2MetadataProxy {
LEAVE_ROOT_CGROUP,
CLEAR_APPLICATION_PATHS,
"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("}");
lines.addAll(IS_SOCAT_LISTENER);
// 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.
@@ -320,6 +309,29 @@ public final class Ec2MetadataProxy {
return new String[]{"sh", "-c", String.join("\n", lines)};
}
/**
* Shell lines that retire the relay {@link #startCommand(String, String, int, String, int, String)} started as
* {@code name} on {@code bindIp}, port 80: the socat its PID file names, while that is still the relay, then the
* PID file and the loopback address the relay was given. A node without the relay, or without {@code ip}, is
* left as it is.
*/
public static List<String> stopRelayLines(String name, String bindIp) {
String pidFile = relayPidFile(name);
List<String> lines = new ArrayList<>(IS_SOCAT_LISTENER);
lines.add(socatPidCheck(pidFile, "TCP-LISTEN:80,bind=" + bindIp + ","));
lines.add(" kill \"$pid\" 2>/dev/null || true");
lines.add("fi");
lines.add("rm -f " + pidFile);
lines.add("if command -v ip >/dev/null 2>&1 && ip addr show dev lo | grep -q '" + bindIp + "/32'; then");
lines.add(" ip addr del " + bindIp + "/32 dev lo");
lines.add("fi");
return lines;
}
private static String relayPidFile(String name) {
return "/tmp/floci-" + name + "-proxy.pid";
}
private static String socatPidCheck(String pidFile, String listener) {
return "if [ -f " + pidFile + " ] && pid=\"$(cat " + pidFile + ")\""
+ " && is_socat_listener \"$pid\" '" + listener + "'; then";
@@ -8,6 +8,7 @@ import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.EpochSeconds;
import io.floci.aws.core.common.PaginatedResult;
import io.floci.aws.core.common.Pagination;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.StorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.eks.model.Addon;
@@ -182,6 +183,19 @@ public class EksAddonService {
return stored.addon();
}
/**
* Whether {@code cluster} has the add-on stored, whatever the cluster's status: what its node
* acts on when it starts or is adopted, which can happen while the cluster is not ACTIVE.
*/
public boolean isInstalled(Cluster cluster, String addonName) {
if (cluster == null || addonName == null || addonName.isBlank()) {
return false;
}
// Read in the cluster's account, not the request's: restoring a cluster at startup asks with no request.
return AccountAwareStorageBackend.getInAccount(storage, AwsArnUtils.parse(cluster.getArn()).accountId(),
prefix(cluster) + addonName.trim().toLowerCase(Locale.ROOT)).isPresent();
}
public AddonNamesPage list(Cluster cluster, Integer maxResults, String nextToken) {
requireActiveCluster(cluster);
String p = prefix(cluster);
@@ -13,6 +13,7 @@ import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.AwsRegions;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.StripedLocks;
import io.floci.aws.core.common.dns.DnsAnswer;
import io.floci.aws.core.common.dns.DnsClientVpcSource;
import io.floci.aws.core.common.dns.DnsClientVpcSource.ClientVpc;
@@ -193,9 +194,14 @@ public class EksClusterManager
@Inject
jakarta.enterprise.inject.Instance<Ec2Service> ec2ServiceInstance;
private Ec2Service ec2Service;
/** Looked up on use, as {@link #ec2ServiceInstance} is, since the add-ons are read only then. */
@Inject
jakarta.enterprise.inject.Instance<EksAddonService> addonServiceInstance;
private EksAddonService addonService;
private final StorageBackend<String, Nodegroup> nodeGroupStorage;
private final Map<String, Set<String>> programmedClusterRoutes = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, Object> clusterRouteLocks = new ConcurrentHashMap<>();
private final StripedLocks podIdentityForwardLocks = new StripedLocks(256);
private record VpcLease(String accountId, String region, String vpcId, String subnetId, String address) {}
private record ClusterVpcSubnet(String vpcId, String subnetId) {}
private final Map<String, VpcLease> clusterVpcLeases = new ConcurrentHashMap<>();
@@ -309,6 +315,20 @@ public class EksClusterManager
}
}
void setAddonService(EksAddonService addonService) {
this.addonService = addonService;
}
private EksAddonService addonService() {
if (addonService != null) {
return addonService;
}
if (addonServiceInstance != null && !addonServiceInstance.isUnsatisfied()) {
return addonServiceInstance.get();
}
return null;
}
public void addNodeRegistrationListener(Consumer<Instance> listener) {
this.nodeRegistrationListeners.add(listener);
}
@@ -1006,7 +1026,7 @@ public class EksClusterManager
applyEndpoints(cluster, containerName, hostPort, info, endpointHost);
registerClusterNodeInstance(cluster, containerId);
configureLinkLocalMetadataEndpoint(cluster, containerId);
configurePodIdentityRelay(cluster, containerId);
configurePodIdentityForward(cluster, containerId);
activeClusters.put(clusterResourceName(cluster), cluster);
configureVpcRoutes(cluster, containerId);
attachClusterLogs(cluster);
@@ -1115,7 +1135,7 @@ public class EksClusterManager
}
registerClusterNodeInstance(cluster, info.containerId());
configureLinkLocalMetadataEndpoint(cluster, info.containerId());
configurePodIdentityRelay(cluster, info.containerId());
configurePodIdentityForward(cluster, info.containerId());
activeClusters.put(clusterResourceName(cluster), cluster);
configureVpcRoutes(cluster, info.containerId());
attachClusterLogsFromNow(cluster);
@@ -2778,35 +2798,100 @@ public class EksClusterManager
}
}
void configurePodIdentityRelay(Cluster cluster, String containerId) {
if (!config.services().eks().podIdentityWebhook() || !config.tls().enabled()) {
return;
/**
* Makes the EKS Pod Identity address, {@code 169.254.170.23:80}, answer in the node while the
* {@code eks-pod-identity-agent} add-on is stored, as the agent's DaemonSet answers it on EKS
* while the add-on is installed, and removes the forward otherwise, including one an earlier
* Floci left. Runs whenever the node starts or is adopted, so a restart forwards only while the
* add-on is stored: one deleted with {@code preserve}, whose agent EKS would leave running,
* keeps its forward until then.
*
* <p>NAT rules send pod and node requests for the address straight to Floci's credentials
* endpoint (see {@link EksPodNetworkRouting#buildPodIdentityForwardCommand}). 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 configurePodIdentityForward(Cluster cluster, String containerId) {
if (podIdentityForwardEnabled()) {
reconcilePodIdentityForward(cluster, containerId);
}
}
/**
* CreateAddon stored, or DeleteAddon without {@code preserve} removed, the
* {@code eks-pod-identity-agent} add-on of {@code cluster}: its node answers on the Pod Identity
* address while the add-on is stored. A cluster without a node, as when EKS is mocked, is left
* alone.
*/
public void podIdentityAgentChanged(Cluster cluster) {
if (podIdentityForwardEnabled() && cluster.getContainerId() != null) {
reconcilePodIdentityForward(cluster, cluster.getContainerId());
}
}
/**
* Forwards the address while the add-on is stored and removes the forward otherwise, reading the
* store under the cluster's lock: of a CreateAddon and a DeleteAddon racing, or of either and a
* restart's adoption, the later waits for the earlier's exec and then reads the store, so the node
* ends as the store does. A store that can't be read leaves the node as it is.
*/
private void reconcilePodIdentityForward(Cluster cluster, String containerId) {
synchronized (podIdentityForwardLocks.lockFor(clusterResourceName(cluster))) {
boolean installed;
try {
installed = podIdentityAgentInstalled(cluster);
} catch (RuntimeException e) {
LOG.warnv("Could not read the {0} add-on of EKS cluster {1}, leaving its Pod Identity address as it is: {2}",
EksPodIdentityWebhook.POD_IDENTITY_ADDON, cluster.getName(), e.getMessage());
return;
}
if (installed) {
forwardPodIdentityAddress(cluster, containerId);
} else {
removePodIdentityForward(cluster, containerId);
}
}
}
/** Pods only get the Pod Identity credentials URL through the webhook, which needs TLS. */
private boolean podIdentityForwardEnabled() {
return config.services().eks().podIdentityWebhook() && config.tls().enabled();
}
private boolean podIdentityAgentInstalled(Cluster cluster) {
EksAddonService addons = addonService();
return addons != null && addons.isInstalled(cluster, EksPodIdentityWebhook.POD_IDENTITY_ADDON);
}
private void forwardPodIdentityAddress(Cluster cluster, String containerId) {
try {
ContainerExec.Result install = execInContainerForResult(containerId,
Ec2MetadataProxy.installCommand(), 180);
if (install.exitCode() != 0) {
LOG.warnv("Could not install Pod Identity relay dependencies for EKS cluster {0}: {1}",
cluster.getName(), install.summary());
ContainerExec.Result forward = execInContainerForResult(containerId,
EksPodNetworkRouting.buildPodIdentityForwardCommand(cluster.getPodCidr(),
dockerHostResolver.resolve(), config.port()), 30);
if (forward.exitCode() != 0) {
LOG.warnv("Could not forward the Pod Identity address for EKS cluster {0} to Floci: {1}",
cluster.getName(), forward.summary());
return;
}
String flociHost = dockerHostResolver.resolve();
int flociPort = config.port();
ContainerExec.Result start = execInContainerForResult(containerId,
Ec2MetadataProxy.podIdentityStartCommand(flociHost, flociPort), 30);
if (start.exitCode() != 0) {
LOG.warnv("Could not start link-local Pod Identity relay for EKS cluster {0}: {1}",
cluster.getName(), start.summary());
return;
}
configurePodNetworkRouting(cluster, containerId, List.of(EksPodNetworkRouting.POD_IDENTITY_ENDPOINT));
LOG.infov("Configured link-local Pod Identity relay for EKS cluster {0}", cluster.getName());
LOG.infov("Forwarding the Pod Identity address {0}:{1,number,#} to Floci for EKS cluster {2}",
EksPodNetworkRouting.POD_IDENTITY_ENDPOINT.ip(), EksPodNetworkRouting.POD_IDENTITY_ENDPOINT.port(),
cluster.getName());
} catch (Exception e) {
LOG.warnv("Could not configure link-local Pod Identity relay for EKS cluster {0}: {1}",
LOG.warnv("Could not forward the Pod Identity address for EKS cluster {0} to Floci: {1}",
cluster.getName(), e.getMessage());
}
}
private void removePodIdentityForward(Cluster cluster, String containerId) {
try {
ContainerExec.Result removal = execInContainerForResult(containerId,
EksPodNetworkRouting.buildPodIdentityRemoveCommand(), 15);
if (removal.exitCode() != 0) {
LOG.warnv("Could not remove the Pod Identity forward for EKS cluster {0}: {1}",
cluster.getName(), removal.summary());
}
} catch (Exception e) {
LOG.warnv("Could not remove the Pod Identity forward for EKS cluster {0}: {1}",
cluster.getName(), e.getMessage());
}
}
@@ -64,16 +64,18 @@ public class EksController {
private final EksPodIdentityAssociationService podIdentityAssociations;
private final EksAddonService addons;
private final ObjectMapper objectMapper;
private final EksClusterManager clusterManager;
@Inject
public EksController(EksService eksService, EksAccessEntryService accessEntries,
EksPodIdentityAssociationService podIdentityAssociations,
EksAddonService addons, ObjectMapper objectMapper) {
EksAddonService addons, ObjectMapper objectMapper, EksClusterManager clusterManager) {
this.eksService = eksService;
this.accessEntries = accessEntries;
this.podIdentityAssociations = podIdentityAssociations;
this.addons = addons;
this.objectMapper = objectMapper;
this.clusterManager = clusterManager;
}
/**
@@ -302,6 +304,10 @@ public class EksController {
public Response createAddon(@PathParam("name") String name, CreateAddonRequest request) {
Cluster cluster = eksService.requireClusterInRequestRegion(name);
Addon addon = addons.create(cluster, request);
// After the add-on is stored and outside the add-on service's lock: the node is changed by an exec.
if (isPodIdentityAgent(addon)) {
clusterManager.podIdentityAgentChanged(cluster);
}
return Response.ok(Map.of("addon", addon)).build();
}
@@ -355,6 +361,10 @@ public class EksController {
@QueryParam("preserve") Boolean preserve) {
Cluster cluster = eksService.requireClusterInRequestRegion(name);
Addon addon = addons.delete(cluster, addonName, Boolean.TRUE.equals(preserve));
// With preserve, EKS leaves the add-on's software running on the cluster, and so its answers.
if (isPodIdentityAgent(addon) && !Boolean.TRUE.equals(preserve)) {
clusterManager.podIdentityAgentChanged(cluster);
}
return Response.ok(Map.of("addon", addon)).build();
}
@@ -439,4 +449,8 @@ public class EksController {
PodIdentityAssociation association = podIdentityAssociations.delete(cluster, associationId);
return Response.ok(Map.of("association", association)).build();
}
private static boolean isPodIdentityAgent(Addon addon) {
return EksPodIdentityWebhook.POD_IDENTITY_ADDON.equalsIgnoreCase(addon.addonName());
}
}
@@ -30,8 +30,9 @@ import java.util.function.Supplier;
* SDK at Floci with {@code AWS_ENDPOINT_URL} and {@code AWS_ENDPOINT_URL_STS}, as it does for every
* container it launches itself: otherwise the pod's calls, signed with Floci credentials, go to AWS.
*
* <p>Nothing answers {@link #CREDENTIALS_FULL_URI} yet: this class injects the plumbing only, so an
* injected pod still cannot obtain credentials.
* <p>This class injects the plumbing only. {@link #CREDENTIALS_FULL_URI} answers while the addon is
* installed: {@link EksClusterManager} forwards its address in the node to
* {@link EksPodIdentityCredentialsController}, which hands the pod its association's credentials.
*
* <p>Every path here admits the pod. A cluster that is gone, an addon that is not installed, a
* malformed review and an internal error all return {@code allowed: true} with no patch, which is
@@ -165,14 +166,12 @@ public class EksPodIdentityWebhook {
}
private boolean podIdentityAgentInstalled(Cluster cluster) {
try {
addons.describe(cluster, POD_IDENTITY_ADDON);
if (addons.isInstalled(cluster, POD_IDENTITY_ADDON)) {
return true;
} catch (AwsException e) {
LOG.debugv("EKS pod-identity-webhook: cluster {0} has no {1} addon, admitting pods unchanged ({2})",
cluster.getName(), POD_IDENTITY_ADDON, e.getMessage());
return false;
}
LOG.debugv("EKS pod-identity-webhook: cluster {0} has no {1} addon, admitting pods unchanged",
cluster.getName(), POD_IDENTITY_ADDON);
return false;
}
private boolean hasAssociation(Cluster cluster, String namespace, String serviceAccount) {
@@ -1,15 +1,19 @@
package io.floci.aws.services.eks;
import io.floci.aws.services.ec2.Ec2MetadataProxy;
import java.util.ArrayList;
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 link-local addresses (such as IMDS 169.254.169.254:80
* and EKS Pod Identity 169.254.170.23:80) reaches Floci's node listener rather than being
* dropped by the Linux kernel or hijacked by CNI hostPort ingress rules.
* 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}.
*/
public final class EksPodNetworkRouting {
@@ -18,6 +22,12 @@ public final class EksPodNetworkRouting {
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);
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. */
private static final Pattern HOST = Pattern.compile("[A-Za-z0-9]([A-Za-z0-9._-]{0,251}[A-Za-z0-9])?");
/** A path a single-quoted shell word can hold as it is. */
private static final Pattern ABSOLUTE_PATH = Pattern.compile("/[A-Za-z0-9._/-]*");
private EksPodNetworkRouting() {}
@@ -35,13 +45,7 @@ public final class EksPodNetworkRouting {
throw new IllegalArgumentException("endpoints cannot be null or empty");
}
List<String> lines = new ArrayList<>();
lines.add("set -eu");
lines.add("IPTABLES=$(command -v iptables 2>/dev/null || command -v /bin/aux/iptables 2>/dev/null || true)");
lines.add("if [ -z \"$IPTABLES\" ]; then");
lines.add(" echo 'iptables not found in container' >&2");
lines.add(" exit 1");
lines.add("fi");
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);
@@ -57,4 +61,144 @@ public final class EksPodNetworkRouting {
return new String[]{"sh", "-c", String.join("\n", lines)};
}
/**
* Builds a POSIX sh command array that sends the EKS Pod Identity address
* ({@code 169.254.170.23:80}) straight to Floci's credentials endpoint with NAT rules in the
* node, so no relay process has to run there. The stock {@code rancher/k3s} image has
* {@code iptables} (under {@code /bin/aux}) but neither {@code socat}, {@code curl} nor a
* package manager to install them.
*
* <p>A {@code PREROUTING} rule takes the pod network's requests and an {@code OUTPUT} rule
* those of the node itself, which is where a {@code hostNetwork} pod's come from. The node's
* own masquerade rule (flannel's) carries the answers back. What an earlier Floci set up for the
* address is removed first, as {@link #buildPodIdentityRemoveCommand} removes it, so a Floci that
* comes back on another address leaves no rule behind, and a node an older Floci gave a relay ends
* as a new node does.
*
* <p>iptables needs an address, so a {@code flociHost} name is resolved inside the node, as
* its pods resolve it: from {@code /etc/hosts} (where {@code host.docker.internal} lives on
* Linux), else through DNS. The command ends with a probe and fails if nothing answers.
*
* @param podCidr pod network CIDR (defaults to {@link #DEFAULT_POD_CIDR} if null or blank)
* @param flociHost the address or hostname the node reaches Floci on
* @param flociPort Floci's port
* @return command array suitable for container exec (["sh", "-c", "..."])
*/
public static String[] buildPodIdentityForwardCommand(String podCidr, String flociHost, int flociPort) {
return buildPodIdentityForwardCommand(podCidr, flociHost, flociPort, HOSTS_FILE);
}
/** As above, reading host names from {@code hostsFile} rather than {@code /etc/hosts}. */
static String[] buildPodIdentityForwardCommand(String podCidr, String flociHost, int flociPort, String hostsFile) {
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);
}
if (flociHost == null || !HOST.matcher(flociHost).matches()) {
throw new IllegalArgumentException("flociHost must be an IPv4 address or a hostname: " + flociHost);
}
if (flociPort <= 0 || flociPort > 65535) {
throw new IllegalArgumentException("flociPort must be between 1 and 65535");
}
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();
List<String> lines = iptablesLines(true);
lines.add("HOST='" + flociHost + "'");
lines.add("ADDR=");
lines.add("case \"$HOST\" in");
lines.add(" *[!0-9.]*)");
lines.add(" ADDR=$(awk -v h=\"$HOST\" '!/^[[:space:]]*#/ { for (i = 2; i <= NF; i++) if ($i == h) { print $1; exit } }'"
+ " '" + hostsFile + "' 2>/dev/null || true)");
lines.add(" case \"$ADDR\" in");
lines.add(" ''|*[!0-9.]*) ADDR=$(nslookup \"$HOST\" 2>/dev/null"
+ " | awk '/^Address/ && $NF ~ /^[0-9]+[.][0-9]+[.][0-9]+[.][0-9]+$/ { a = $NF } END { print a }' || true) ;;");
lines.add(" esac ;;");
lines.add(" *) ADDR=$HOST ;;");
lines.add("esac");
lines.add("if [ -z \"$ADDR\" ]; then");
lines.add(" echo \"cannot resolve $HOST to an IPv4 address\" >&2");
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\"");
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(" sleep 1");
lines.add("done");
lines.add("echo \"nothing answers on " + address + " through $TARGET\" >&2");
lines.add("exit 1");
return new String[]{"sh", "-c", String.join("\n", lines)};
}
/**
* Builds a POSIX sh command array that removes the rules {@link #buildPodIdentityForwardCommand}
* adds, any an earlier Floci added for the address, and the relay an older Floci ran for it, so
* that nothing answers on it, as on an EKS node without the Pod Identity agent. A node without
* {@code iptables} has no such rules, so the command succeeds there.
*
* @return command array suitable for container exec (["sh", "-c", "..."])
*/
public static String[] buildPodIdentityRemoveCommand() {
List<String> lines = iptablesLines(false);
addPodIdentityRuleRemoval(lines);
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.
*/
static String podIdentityProbeCommand(String endpoint) {
String url = endpoint + "/v1/credentials";
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";
}
/**
* The start of every command here: strict mode and {@code IPTABLES}, found on the path or
* where a stock {@code rancher/k3s} image keeps it. Without one, the command fails when it
* has rules to add, and ends successfully when it only removes them.
*/
private static List<String> iptablesLines(boolean required) {
List<String> lines = new ArrayList<>();
lines.add("set -eu");
lines.add("IPTABLES=$(command -v iptables 2>/dev/null || command -v /bin/aux/iptables 2>/dev/null || true)");
lines.add("if [ -z \"$IPTABLES\" ]; then");
if (required) {
lines.add(" echo 'iptables not found in container' >&2");
lines.add(" exit 1");
} else {
lines.add(" exit 0");
}
lines.add("fi");
return lines;
}
/**
* 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.
*/
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");
lines.add("done");
lines.addAll(Ec2MetadataProxy.stopRelayLines("pod-identity", POD_IDENTITY_ENDPOINT.ip()));
}
}