Light, fluffy, and always free - The AWS Local Emulator alternative
fix(ec2): validate and expire IMDSv2 session tokens (#4303)
Niels Kootstra06ec4b563a17
diff --git a/docs/services/ec2.md b/docs/services/ec2.mdindex 3bf0bf836e..3a95f1bfcf 100644--- a/docs/services/ec2.md+++ b/docs/services/ec2.md@@ -128,6 +128,8 @@ curl -s -H "x-aws-ec2-metadata-token: $TOKEN" \http://169.254.169.254/latest/meta-data/instance-id```+As on AWS, the token TTL must be an integer from 1 to 21600 seconds, or the `PUT` returns `400`. A metadata request that presents an unknown or expired token returns `401`, which tells the SDK to fetch a new token. A token is valid only on the instance that requested it: presenting it from another instance returns `401`. A request without a token header still uses IMDSv1; Floci does not enforce `HttpTokens=required`.+### Supported IMDS endpoints| Endpoint | Returns |diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2MetadataServer.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2MetadataServer.javaindex d7b63cf787..9a44995783 100644--- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2MetadataServer.java+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2MetadataServer.java@@ -17,10 +17,12 @@ import org.jboss.logging.Logger;import java.net.URLDecoder;import java.nio.charset.StandardCharsets;+import java.time.Clock;import java.time.Instant;import java.time.ZoneOffset;import java.time.format.DateTimeFormatter;import java.util.Map;+import java.util.Objects;import java.util.Optional;import java.util.Set;import java.util.UUID;@@ -41,14 +43,17 @@ public class Ec2MetadataServer {private static final Logger LOG = Logger.getLogger(Ec2MetadataServer.class);private static final DateTimeFormatter ISO = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'").withZone(ZoneOffset.UTC);+ /** IMDSv2 tokens live from one second up to six hours. */+ private static final int MAX_TOKEN_TTL_SECONDS = 21_600;private static final String INSTANCE_TAGS_PREFIX = "/latest/meta-data/tags/instance/";private final Vertx vertx;private final EmulatorConfig config;private final Ec2InstanceCredentials credentials;+ private final Clock clock;/** IMDSv2: token value → Instance */- private final Map<String, Instance> tokenToInstance = new ConcurrentHashMap<>();+ private final Map<String, SessionToken> tokens = new ConcurrentHashMap<>();/** IMDSv1 fallback: container bridge IP → Instance */private final Map<String, Instance> containerIpToInstance = new ConcurrentHashMap<>();@@ -56,9 +61,14 @@ public class Ec2MetadataServer {@Injectpublic Ec2MetadataServer(Vertx vertx, EmulatorConfig config, IamService iamService) {+ this(vertx, config, iamService, Clock.systemUTC());+ }++ Ec2MetadataServer(Vertx vertx, EmulatorConfig config, IamService iamService, Clock clock) {this.vertx = vertx;this.config = config;this.credentials = new Ec2InstanceCredentials(iamService);+ this.clock = clock;}/** Called by Ec2ContainerManager after a container starts to register its IP. */@@ -89,7 +99,7 @@ public class Ec2MetadataServer {public void unregisterInstance(Instance instance) {if (instance != null) {credentials.unregister(instance);- tokenToInstance.entrySet().removeIf(entry -> entry.getValue() == instance);+ tokens.values().removeIf(token -> token.instance() == instance);containerIpToInstance.entrySet().removeIf(entry -> entry.getValue() == instance);}}@@ -149,7 +159,7 @@ public class Ec2MetadataServer {public synchronized void stop() {credentials.clear();- tokenToInstance.clear();+ tokens.clear();containerIpToInstance.clear();if (httpServer != null) {httpServer.close();@@ -161,15 +171,19 @@ public class Ec2MetadataServer {private void handleToken(RoutingContext ctx) {String ttlHeader = ctx.request().getHeader("x-aws-ec2-metadata-token-ttl-seconds");- if (ttlHeader == null) {- ctx.response().setStatusCode(400).end("Missing x-aws-ec2-metadata-token-ttl-seconds");+ Integer ttlSeconds = parseTokenTtl(ttlHeader);+ if (ttlSeconds == null) {+ ctx.response().setStatusCode(400).end(+ "x-aws-ec2-metadata-token-ttl-seconds must be an integer from 1 to " + MAX_TOKEN_TTL_SECONDS);return;}Instance inst = resolveInstanceByIp(ctx);String token = UUID.randomUUID().toString().replace("-", "");if (inst != null) {- tokenToInstance.put(token, inst);+ Instant now = clock.instant();+ tokens.values().removeIf(existing -> existing.isExpiredAt(now));+ tokens.put(token, new SessionToken(inst, now.plusSeconds(ttlSeconds)));}else {LOG.debugv("IMDS: token requested from {0}, which is not a registered EC2 container; "@@ -182,6 +196,25 @@ public class Ec2MetadataServer {.end(token);}+ /** Returns the TTL in seconds, or null when the header is missing or outside 1..21600. */+ private static Integer parseTokenTtl(String ttlHeader) {+ if (ttlHeader == null) {+ return null;+ }+ try {+ int ttl = Integer.parseInt(ttlHeader.trim());+ return ttl >= 1 && ttl <= MAX_TOKEN_TTL_SECONDS ? ttl : null;+ } catch (NumberFormatException e) {+ return null;+ }+ }++ private record SessionToken(Instance instance, Instant expiresAt) {+ boolean isExpiredAt(Instant now) {+ return !now.isBefore(expiresAt);+ }+ }+// ── Metadata helpers ──────────────────────────────────────────────────────@FunctionalInterface@@ -368,18 +401,32 @@ public class Ec2MetadataServer {}private Instance resolveInstance(RoutingContext ctx) {- // Try IMDSv2 token first+ String remoteIp = ctx.request().remoteAddress().host();+ Instance inst = containerIpToInstance.get(remoteIp);++ // 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.String token = ctx.request().getHeader("x-aws-ec2-metadata-token");if (token != null && !token.isBlank()) {- Instance inst = tokenToInstance.get(token);+ SessionToken session = tokens.get(token);+ if (session != null && !session.isExpiredAt(clock.instant())) {+ if (inst != null && !Objects.equals(inst.getInstanceId(), session.instance().getInstanceId())) {+ ctx.response().setStatusCode(401).end();+ return null;+ }+ return session.instance();+ }+ if (session != null) {+ tokens.remove(token, session);+ }if (inst != null) {- return inst;+ ctx.response().setStatusCode(401).end();+ return null;}}- // Fall back to source IP (IMDSv1)- String remoteIp = ctx.request().remoteAddress().host();- Instance inst = containerIpToInstance.get(remoteIp);if (inst == null) {String message = unregisteredContainerMessage(remoteIp);LOG.warnv("IMDS: {0}", message);diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2MetadataTokenTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2MetadataTokenTest.javanew file mode 100644index 0000000000..484dc743b9--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2MetadataTokenTest.java@@ -0,0 +1,152 @@+package io.github.hectorvent.floci.services.ec2;++import io.github.hectorvent.floci.config.EmulatorConfig;+import io.github.hectorvent.floci.services.ec2.model.Instance;+import io.github.hectorvent.floci.testing.MutableClock;+import io.vertx.core.Vertx;+import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.ValueSource;++import java.net.ServerSocket;+import java.net.URI;+import java.net.http.HttpClient;+import java.net.http.HttpRequest;+import java.net.http.HttpResponse;+import java.time.Duration;+import java.util.concurrent.TimeUnit;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.mockito.Mockito.RETURNS_DEEP_STUBS;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.when;++/**+ * IMDSv2 session tokens, as documented in the EC2 User Guide: the PUT must carry a TTL between+ * 1 and 21,600 seconds (otherwise 400), and a GET that presents an invalid or expired token gets+ * 401 so the caller fetches a new token. A token is not valid on other instances.+ */+class Ec2MetadataTokenTest {++ private static final String TTL_HEADER = "X-aws-ec2-metadata-token-ttl-seconds";+ private static final String TOKEN_HEADER = "X-aws-ec2-metadata-token";+ private static final String CALLER_IP = "127.0.0.1";++ private final MutableClock clock = new MutableClock();+ private final HttpClient client = HttpClient.newHttpClient();+ private Vertx vertx;+ private Instance instance;+ private Ec2MetadataServer server;+ private String endpoint;++ @BeforeEach+ void startServer() throws Exception {+ int port;+ try (ServerSocket socket = new ServerSocket(0)) {+ port = socket.getLocalPort();+ }+ EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);+ when(config.services().ec2().imdsPort()).thenReturn(port);+ vertx = Vertx.vertx();+ server = new Ec2MetadataServer(vertx, config, null, clock);+ server.start().get(10, TimeUnit.SECONDS);+ endpoint = "http://127.0.0.1:" + port;++ instance = instance("i-0123456789abcdef0");+ server.registerContainer(CALLER_IP, instance.getInstanceId(), instance);+ }++ @AfterEach+ void stopServer() throws Exception {+ server.stop();+ vertx.close().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);+ }++ @ParameterizedTest+ @ValueSource(strings = {"0", "21601", "-1", "sixty", ""})+ void tokenRequestWithTtlOutsideOneToSixHoursIsRejected(String ttl) throws Exception {+ assertEquals(400, putToken(ttl).statusCode());+ }++ @Test+ void tokenWithTheMaximumTtlIsIssued() throws Exception {+ HttpResponse<String> token = putToken("21600");++ assertEquals(200, token.statusCode());+ assertEquals("21600", token.headers().firstValue(TTL_HEADER).orElseThrow());+ }++ @Test+ void tokenIsAcceptedUntilItsTtlElapses() throws Exception {+ String token = putToken("60").body();+ clock.advance(Duration.ofSeconds(59));++ HttpResponse<String> response = getInstanceId(token);++ assertEquals(200, response.statusCode());+ assertEquals("i-0123456789abcdef0", response.body());+ }++ @Test+ void expiredTokenIsRejectedAsUnauthorized() throws Exception {+ String token = putToken("60").body();+ clock.advance(Duration.ofSeconds(60));++ assertEquals(401, getInstanceId(token).statusCode());+ }++ @Test+ void unknownTokenIsRejectedAsUnauthorized() throws Exception {+ assertEquals(401, getInstanceId("not-a-token").statusCode());+ }++ @Test+ void tokenPresentedFromAnotherInstanceIsRejectedAsUnauthorized() throws Exception {+ String token = putToken("60").body();+ Instance other = instance("i-0fedcba9876543210");+ server.unregisterContainer(CALLER_IP, instance);+ server.registerContainer(CALLER_IP, other.getInstanceId(), other);++ assertEquals(401, getInstanceId(token).statusCode());+ }++ @Test+ void tokenIdentifiesItsInstanceWhenTheCallerIpIsNotRegistered() throws Exception {+ String token = putToken("60").body();+ server.unregisterContainer(CALLER_IP, instance);++ HttpResponse<String> response = getInstanceId(token);++ assertEquals(200, response.statusCode());+ assertEquals("i-0123456789abcdef0", response.body());+ }++ @Test+ void requestWithoutTokenStillUsesImdsV1() throws Exception {+ HttpResponse<String> response = client.send(+ HttpRequest.newBuilder(URI.create(endpoint + "/latest/meta-data/instance-id")).GET().build(),+ HttpResponse.BodyHandlers.ofString());++ assertEquals(200, response.statusCode());+ }++ private static Instance instance(String instanceId) {+ Instance instance = new Instance();+ instance.setInstanceId(instanceId);+ return instance;+ }++ private HttpResponse<String> putToken(String ttl) throws Exception {+ return client.send(HttpRequest.newBuilder(URI.create(endpoint + "/latest/api/token"))+ .header(TTL_HEADER, ttl).PUT(HttpRequest.BodyPublishers.noBody()).build(),+ HttpResponse.BodyHandlers.ofString());+ }++ private HttpResponse<String> getInstanceId(String token) throws Exception {+ return client.send(HttpRequest.newBuilder(URI.create(endpoint + "/latest/meta-data/instance-id"))+ .header(TOKEN_HEADER, token).GET().build(),+ HttpResponse.BodyHandlers.ofString());+ }+}