mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
fix(ec2): require IMDSv2 tokens when HttpTokens is required (#5966)
* fix(ec2): probe IMDS proxy readiness with an IMDSv2 token The proxy start script checked readiness with a tokenless read of the instance ID. Once IMDS enforces HttpTokens=required, that read gets 401 and the proxy reports a failed start after twelve attempts. The probe now fetches a 60-second token and reads with it; a refused or empty token fails the attempt rather than falling back to a tokenless read. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): refuse tokenless metadata reads when HttpTokens is required IMDS answered every request without a token through IMDSv1, whatever the instance's HttpTokens said. On AWS, when token usage is required, requests without a valid token get 401 Unauthorized. Floci now does the same for every metadata endpoint, before it looks up the data, using the options the instance was launched with or last modified to. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): clear application library paths in IMDS helper shells docker exec gives the proxy's install and start shells the image's environment. An application image that sets LD_LIBRARY_PATH, PYTHONPATH or PYTHONHOME can then make the package manager, socat and curl load its libraries or Python instead of the system's. Both shells now unset those three first; only the helper shell changes, so the container's configuration and the application's processes keep them. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): refuse metadata option changes on EKS cluster nodes IMDS serves a cluster node from the instance its EKS cluster registered, while EC2 hands out a copy of it. ModifyInstanceMetadataOptions changed and stored that copy, so DescribeInstances reported HttpTokens=required while the node's IMDS kept answering tokenless reads, and the stored copy no longer counted as a cluster node. The action now answers OperationNotPermitted for cluster nodes, as their stop, start, reboot and terminate actions do. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): publish metadata option changes to the IMDS event loop IMDS now reads an instance's metadata options on its Vert.x event loop, while ModifyInstanceMetadataOptions replaces them from a request thread. Without a happens-before edge the event loop could keep serving the old options, or see the new object before its fields. The field is now volatile, as the instance's state already is. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): keep the IMDS readiness probe off HTTP proxies The probe's curl calls honored an image's http_proxy or ALL_PROXY, so a proxy configured for the application received the link-local requests, every attempt failed and the start reported a failure although socat was running. Both calls now pass --noproxy '*'. The helper-shell test support moves to a shared HelperShellFixture, and a new test runs the real token probe inside the generated start script, whose set -eu loop must retry after a refused token. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): clear application library paths in the sshd install probe The sshd install probe runs dnf, yum or apt-get through docker exec with the image's environment, the failure the IMDS helper shells now avoid: with an application's PYTHONHOME or LD_LIBRARY_PATH, dnf could not start, so sshd was never installed. The probe now unsets the same three variables first, through the IMDS proxy's shared constant. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): keep refusing cluster nodes once EC2 has stored a copy The cluster-node check counted an instance as a node only while EC2's own store had no record of it, but ModifyInstanceAttribute, monitoring and other actions store EC2's copy of a node. After one of them, ModifyInstanceMetadataOptions was accepted without reaching the node's IMDS, and TerminateInstances and StopInstances were no longer refused. A node is now recognized by its cluster's provider alone. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): keep the pod identity relay probe off HTTP proxies The EKS pod identity relay's readiness probe shares the IMDS proxy's start script and environment, but its curl still honored the image's http_proxy: a proxy that answered passed the probe whether or not socat relayed, and an unreachable one failed the start. It now passes --noproxy '*' like the IMDS probe, from a podIdentityProbeCommand the test runs. The shared unset's Javadoc now names the shells that run it. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): refuse tokenless reads of every path when tokens are required The HttpTokens=required check ran inside the handlers of the paths IMDS serves, so a tokenless read of any other path, such as the /latest/meta-data/ listing that IMDSv1 detection probes, answered 404 where AWS answers 401. The check now runs ahead of every GET route; with a token, or on an instance that allows IMDSv1, such a path is still 404. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): keep IMDS answers for methods it does not serve The required-token check was registered as a GET route for every path, and Vert.x answers 405 to any other method on a path some route matches, so POST /latest/meta-data/ began to answer 405 instead of 404, and a tokenless HEAD on a required-token instance got 405 instead of 401. The check is now a route for every method that acts on GET and HEAD only. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * test(ec2): check that the pod identity probe reaches its relay The probe treats any answer but 000 as ready, so the test passed even when curl was missing and nothing reached the relay. It now counts the relay's requests, and both stand-in servers start inside its try. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * docs(ec2): say that IMDS refuses a tokenless HEAD but serves none The required-token check's Javadoc called HEAD a read, but no IMDS route serves HEAD, so one with a token still gets the router's 405. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * docs(ec2): say what IMDS answers a HEAD that has a token No route serves HEAD, so the router answers 405 on a path a GET route serves and 404 elsewhere. A test pins both. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * test(ec2): check IMDS refuses tokenless reads on Fleet and Auto Scaling launches Since #5964, Auto Scaling launches carry a launch template's MetadataOptions and CreateFleet forwards them. The test of template options on Fleet and Auto Scaling launches now also checks that IMDS refuses the launched instance a tokenless read and serves it with a token. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * docs(ec2): say where HttpTokens comes from and what IMDS refuses The IMDS notes said HttpTokens could be set "at launch". They now name its sources: RunInstances, directly or through a launch template, EC2 Fleet and Auto Scaling launches, and ModifyInstanceMetadataOptions. They say that a tokenless GET or HEAD is refused on every path, and that EKS cluster nodes refuse the change, in the notes, the EKS lifecycle-protection list and the action table. They also say that the readiness probe bypasses the image's HTTP proxy, that the helper shells keep an application's library search path and Python installation from the system tools rather than promising more, and that the sshd install shell clears them too. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> --------- Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>
This commit is contained in:
1 parent
2f6f3a8f86
commit
7504d71e76
14 files changed
+755
-16
No files matched your search
@@ -1600,6 +1600,9 @@ public class Ec2ContainerManager {
|
||||
*/
|
||||
static String[] sshdInstallProbeCommand() {
|
||||
return new String[]{"sh", "-c",
|
||||
// dnf and yum are Python programs: an image's PYTHONHOME or LD_LIBRARY_PATH made them
|
||||
// fail to start, so sshd was never installed.
|
||||
Ec2MetadataProxy.CLEAR_APPLICATION_PATHS + ";" +
|
||||
"if ! command -v sshd >/dev/null 2>&1 || ! command -v scp >/dev/null 2>&1; then" +
|
||||
" if command -v dnf >/dev/null 2>&1; then dnf install -y openssh-server openssh-clients >/dev/null 2>&1;" +
|
||||
// yum is probed after dnf, and the order is load-bearing: Amazon Linux
|
||||
|
||||
@@ -11,11 +11,21 @@ import java.util.Optional;
|
||||
*/
|
||||
public final class Ec2MetadataProxy {
|
||||
|
||||
/**
|
||||
* 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
|
||||
* search path or Python installation would otherwise be what the package manager, {@code socat}
|
||||
* and {@code curl} load. Only the helper shell changes; the container's configured environment
|
||||
* and its processes keep these variables.
|
||||
*/
|
||||
static final String CLEAR_APPLICATION_PATHS = "unset LD_LIBRARY_PATH PYTHONPATH PYTHONHOME";
|
||||
|
||||
private Ec2MetadataProxy() {}
|
||||
|
||||
public static String[] installCommand() {
|
||||
return new String[]{"sh", "-c", String.join("\n",
|
||||
"set -eu",
|
||||
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 apt-get >/dev/null 2>&1; then",
|
||||
" apt-get update -qq >/dev/null",
|
||||
@@ -43,12 +53,36 @@ public final class Ec2MetadataProxy {
|
||||
|
||||
public static String[] startCommand(String flociHost, int imdsPort) {
|
||||
return startCommand("imds", "169.254.169.254", 80, flociHost, imdsPort,
|
||||
"curl -fsS --max-time 1 http://169.254.169.254/latest/meta-data/instance-id >/dev/null && exit 0");
|
||||
imdsProbeCommand("http://169.254.169.254"));
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* a tokenless read, which an empty token header would otherwise become. Both requests bypass
|
||||
* any HTTP proxy the image configures: the check is of the link-local path itself.
|
||||
*/
|
||||
static String imdsProbeCommand(String endpoint) {
|
||||
return "token=$(curl -fsS --noproxy '*' --max-time 1 -X PUT "
|
||||
+ "-H 'X-aws-ec2-metadata-token-ttl-seconds: 60' " + endpoint + "/latest/api/token)"
|
||||
+ " && [ -n \"$token\" ]"
|
||||
+ " && curl -fsS --noproxy '*' --max-time 1 -H \"X-aws-ec2-metadata-token: $token\" "
|
||||
+ 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,
|
||||
"[ \"$(curl -s -o /dev/null -w '%{http_code}' --max-time 1 http://169.254.170.23/v1/credentials)\" != \"000\" ] && exit 0");
|
||||
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,
|
||||
@@ -57,6 +91,7 @@ public final class Ec2MetadataProxy {
|
||||
String logFile = "/tmp/floci-" + name + "-proxy.log";
|
||||
return new String[]{"sh", "-c", String.join("\n",
|
||||
"set -eu",
|
||||
CLEAR_APPLICATION_PATHS,
|
||||
"ip addr show dev lo | grep -q '" + bindIp + "/32' || ip addr add " + bindIp + "/32 dev lo",
|
||||
"if [ -f " + pidFile + " ] && kill -0 \"$(cat " + pidFile + ")\" 2>/dev/null; then",
|
||||
" exit 0",
|
||||
|
||||
@@ -10,6 +10,7 @@ import io.github.hectorvent.floci.services.iam.model.InstanceProfile;
|
||||
import io.github.hectorvent.floci.services.iam.model.SessionCredential;
|
||||
import io.vertx.core.Vertx;
|
||||
import io.vertx.core.buffer.Buffer;
|
||||
import io.vertx.core.http.HttpMethod;
|
||||
import io.vertx.core.http.HttpServer;
|
||||
import io.vertx.core.json.JsonObject;
|
||||
import io.vertx.ext.web.Router;
|
||||
@@ -136,6 +137,10 @@ public class Ec2MetadataServer {
|
||||
|
||||
Router router = Router.router(vertx);
|
||||
router.route().handler(BodyHandler.create());
|
||||
// Ahead of every route, so a path IMDS does not serve also answers 401 when the instance
|
||||
// requires tokens, as on AWS. A method-free route, so methods IMDS does not serve keep the
|
||||
// router's own answers rather than all becoming 405.
|
||||
router.route().handler(this::refuseTokenlessReadsWhenTokensAreRequired);
|
||||
|
||||
// IMDSv2 token endpoint
|
||||
router.put("/latest/api/token").handler(this::handleToken);
|
||||
@@ -496,6 +501,24 @@ public class Ec2MetadataServer {
|
||||
return containerIpToInstance.get(remoteIp);
|
||||
}
|
||||
|
||||
/**
|
||||
* An instance whose HttpTokens is required refuses IMDSv1: as AWS does, a GET or HEAD without a
|
||||
* token gets 401 before any data is looked up, whatever the path. (No route serves HEAD, so one
|
||||
* with a token gets the router's answer: 405 on a path a GET route serves, 404 elsewhere.)
|
||||
*/
|
||||
private void refuseTokenlessReadsWhenTokensAreRequired(RoutingContext ctx) {
|
||||
HttpMethod method = ctx.request().method();
|
||||
String token = ctx.request().getHeader("x-aws-ec2-metadata-token");
|
||||
if ((HttpMethod.GET.equals(method) || HttpMethod.HEAD.equals(method)) && (token == null || token.isBlank())) {
|
||||
Instance inst = resolveInstanceByIp(ctx);
|
||||
if (inst != null && "required".equals(inst.effectiveMetadataOptions().getHttpTokens())) {
|
||||
ctx.response().setStatusCode(401).end();
|
||||
return;
|
||||
}
|
||||
}
|
||||
ctx.next();
|
||||
}
|
||||
|
||||
private Instance resolveInstance(RoutingContext ctx) {
|
||||
String remoteIp = ctx.request().remoteAddress().host();
|
||||
Instance inst = containerIpToInstance.get(remoteIp);
|
||||
@@ -503,7 +526,8 @@ public class Ec2MetadataServer {
|
||||
// IMDSv2: a presented token must be valid; an invalid or expired one gets 401 so the
|
||||
// caller fetches a new token. A token is not valid on another instance, so a caller whose
|
||||
// IP maps to a different instance also gets 401; an unregistered IP defers to the token.
|
||||
// Requests without a token fall back to IMDSv1.
|
||||
// Requests without a token fall back to IMDSv1; one whose instance requires tokens has
|
||||
// already been refused before routing.
|
||||
String token = ctx.request().getHeader("x-aws-ec2-metadata-token");
|
||||
if (token != null && !token.isBlank()) {
|
||||
SessionToken session = tokens.get(token);
|
||||
|
||||
@@ -4971,12 +4971,21 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
/**
|
||||
* ModifyInstanceMetadataOptions changes only the fields the caller names, as on AWS, so a
|
||||
* call that sets HttpTokens alone leaves HttpEndpoint and the hop limit as they were.
|
||||
*
|
||||
* <p>A cluster node is refused, as its lifecycle actions are: IMDS serves the instance its
|
||||
* cluster registered, and EC2 holds only a copy of it, so a change made here would be reported
|
||||
* by DescribeInstances but never enforced.
|
||||
*/
|
||||
public Instance modifyInstanceMetadataOptions(String region, String instanceId,
|
||||
LaunchTemplateData.MetadataOptions request) {
|
||||
ensureDefaultResources(region);
|
||||
validateMetadataOptions(request);
|
||||
Instance inst = getRequiredInstance(region, instanceId);
|
||||
if (isExternalInstance(region, instanceId)) {
|
||||
throw new AwsException("OperationNotPermitted",
|
||||
"The instance '" + instanceId + "' is a cluster node and its metadata options cannot be"
|
||||
+ " modified through EC2", 400);
|
||||
}
|
||||
inst.setMetadataOptions(LaunchTemplateData.MetadataOptions.merge(inst.effectiveMetadataOptions(), request));
|
||||
instances.put(key(region, instanceId), inst);
|
||||
return inst;
|
||||
@@ -5149,9 +5158,12 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a cluster's provider serves this instance. It stays a cluster node after an action has
|
||||
* stored EC2's copy of it, because IMDS and the cluster keep serving the provider's record.
|
||||
*/
|
||||
private boolean isExternalInstance(String region, String instanceId) {
|
||||
return instances.get(key(region, instanceId)).isEmpty()
|
||||
&& findExternalInstance(callerAccountId(), region, instanceId).isPresent();
|
||||
return findExternalInstance(callerAccountId(), region, instanceId).isPresent();
|
||||
}
|
||||
|
||||
private Instance getRequiredInstance(String region, String instanceId) {
|
||||
|
||||
@@ -63,8 +63,9 @@ public class Instance {
|
||||
private boolean disableApiTermination = false;
|
||||
|
||||
// Null for an instance persisted before metadata options were stored; reads fall back to
|
||||
// AWS's launch defaults through effectiveMetadataOptions().
|
||||
private LaunchTemplateData.MetadataOptions metadataOptions;
|
||||
// AWS's launch defaults through effectiveMetadataOptions(). Volatile because IMDS reads it on
|
||||
// its event loop while ModifyInstanceMetadataOptions replaces it from a request thread.
|
||||
private volatile LaunchTemplateData.MetadataOptions metadataOptions;
|
||||
|
||||
// The credit option this instance acquired, at launch from the request or from its burstable
|
||||
// family's default, or at a resize onto a burstable type. Stored rather than derived from the
|
||||
|
||||
Reference in new issue
Block a user