Light, fluffy, and always free - The AWS Local Emulator alternative
fix(elbv2): block link-local and metadata targets (#4031)
Priamo Germosen9dab36197a4f
diff --git a/docs/services/elb.md b/docs/services/elb.mdindex d7b7b3d0a5..9b4b4c793f 100644--- a/docs/services/elb.md+++ b/docs/services/elb.md@@ -96,6 +96,7 @@ Floci supports Application Load Balancers (ALB) and Network Load Balancers (NLB)- `DescribeSSLPolicies` returns a pre-seeded list of standard AWS SSL policies (`ELBSecurityPolicy-*`).- `DescribeAccountLimits` returns standard default limits (e.g., 50 load balancers per region, 100 target groups, etc.).- `routing.http.preserve_host_header.enabled` (default `false`) controls whether the original client Host header is forwarded to targets unchanged, or replaced with the target's `host:port`.+- `RegisterTargets` rejects link-local and cloud instance-metadata addresses (`169.254.0.0/16`, `fe80::/10`, `fd00:ec2::254`) with `InvalidTarget`, and the load balancer and its health checks refuse to connect to them. Loopback and private addresses stay reachable so a load balancer can front a neighbouring container.## ARN Formatdiff --git a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2DataPlane.java b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2DataPlane.javaindex 09f63f90da..e4f864a965 100644--- a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2DataPlane.java+++ b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2DataPlane.java@@ -21,6 +21,7 @@ import io.vertx.core.http.HttpClient;import io.vertx.core.http.HttpClientOptions;import io.vertx.core.http.HttpServer;import io.vertx.core.http.HttpServerOptions;+import io.vertx.core.http.HttpServerRequest;import io.vertx.core.http.RequestOptions;import jakarta.annotation.PostConstruct;import jakarta.annotation.PreDestroy;@@ -29,6 +30,7 @@ import jakarta.inject.Inject;import org.jboss.logging.Logger;import java.io.ByteArrayOutputStream;+import java.io.IOException;import java.nio.charset.StandardCharsets;import java.util.ArrayList;import java.util.Base64;@@ -596,8 +598,29 @@ public class ElbV2DataPlane {private void proxyRequest(io.vertx.core.http.HttpServerRequest req, String host, int port,boolean preserveHostHeader) {req.pause();+ if (ElbV2TargetResolver.isIpLiteral(host)) {+ try {+ proxyRequestTo(req, ElbV2TargetResolver.resolveCheckedAddress(host), host, port, preserveHostHeader);+ } catch (IOException e) {+ rejectTarget(req, host, e);+ }+ return;+ }+ vertx.<String>executeBlocking(() -> ElbV2TargetResolver.resolveCheckedAddress(host))+ .onSuccess(address -> proxyRequestTo(req, address, host, port, preserveHostHeader))+ .onFailure(err -> rejectTarget(req, host, err));+ }++ private void rejectTarget(HttpServerRequest req, String host, Throwable err) {+ LOG.warnv("Refusing to proxy to target {0}: {1}", host, err.getMessage());+ req.resume();+ req.response().setStatusCode(503).end("Service unavailable");+ }++ private void proxyRequestTo(HttpServerRequest req, String address, String host, int port,+ boolean preserveHostHeader) {RequestOptions opts = new RequestOptions()- .setHost(host)+ .setHost(address).setPort(port).setURI(req.uri()).setMethod(req.method());diff --git a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2HealthChecker.java b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2HealthChecker.javaindex f8bc9d1f78..348981762f 100644--- a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2HealthChecker.java+++ b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2HealthChecker.java@@ -195,7 +195,7 @@ public class ElbV2HealthChecker implements Resettable {}private int probe(String host, int port, String path, int timeoutSeconds) throws IOException {- URL url = new URL("http", host, port, path);+ URL url = new URL("http", ElbV2TargetResolver.resolveCheckedAddress(host), port, path);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setConnectTimeout(timeoutSeconds * 1000);conn.setReadTimeout(timeoutSeconds * 1000);diff --git a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2Service.java b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2Service.javaindex 690f400ee1..3e5fa55ab2 100644--- a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2Service.java+++ b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2Service.java@@ -5,6 +5,7 @@ import io.github.hectorvent.floci.config.EmulatorConfig;import io.github.hectorvent.floci.core.common.AwsArnUtils;import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.core.common.SsrfProtection;import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer;import io.github.hectorvent.floci.core.storage.StorageBackedMap;import io.github.hectorvent.floci.core.storage.StorageFactory;@@ -15,6 +16,8 @@ import jakarta.annotation.PostConstruct;import jakarta.enterprise.context.ApplicationScoped;import jakarta.inject.Inject;+import java.io.IOException;+import java.net.InetAddress;import java.time.Instant;import java.util.*;import java.util.concurrent.ConcurrentHashMap;@@ -776,6 +779,11 @@ public class ElbV2Service implements ResourceProvider {public void registerTargets(String region, String tgArn, List<TargetDescription> targets) {TargetGroup tg = requireTargetGroup(region, tgArn);+ if (!"lambda".equals(tg.getTargetType())) {+ for (TargetDescription t : targets) {+ requireNotMetadataAddress(t.getId());+ }+ }List<TargetDescription> existing = tg.getTargets();for (TargetDescription t : targets) {// replace if same id+port already registered@@ -786,6 +794,18 @@ public class ElbV2Service implements ResourceProvider {healthChecker.addTargets(tgArn, targets, tg);}+ private static void requireNotMetadataAddress(String targetId) {+ if (!ElbV2TargetResolver.isIpLiteral(targetId)) {+ return;+ }+ try {+ SsrfProtection.rejectMetadataAddresses(InetAddress.getAllByName(targetId), targetId);+ } catch (IOException e) {+ throw new AwsException("InvalidTarget",+ "The IP address '" + targetId + "' is not a valid target", 400);+ }+ }+public void deregisterTargets(String region, String tgArn, List<TargetDescription> targets) {TargetGroup tg = requireTargetGroup(region, tgArn);for (TargetDescription t : targets) {diff --git a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2TargetResolver.java b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2TargetResolver.javaindex 375f977cb0..5c2044104c 100644--- a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2TargetResolver.java+++ b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2TargetResolver.java@@ -1,10 +1,14 @@package io.github.hectorvent.floci.services.elbv2;+import io.github.hectorvent.floci.core.common.SsrfProtection;import io.github.hectorvent.floci.services.ec2.Ec2Service;import io.github.hectorvent.floci.services.ec2.model.Instance;import io.github.hectorvent.floci.services.elbv2.model.TargetDescription;import io.github.hectorvent.floci.services.elbv2.model.TargetGroup;+import java.io.IOException;+import java.net.InetAddress;+final class ElbV2TargetResolver {private ElbV2TargetResolver() {}@@ -32,4 +36,14 @@ final class ElbV2TargetResolver {}return targetId;}++ /** Resolves once, rejects metadata addresses, and returns the address to connect to instead of the name. */+ static String resolveCheckedAddress(String host) throws IOException {+ InetAddress[] addresses = SsrfProtection.rejectMetadataAddresses(InetAddress.getAllByName(host), host);+ return addresses[0].getHostAddress();+ }++ static boolean isIpLiteral(String host) {+ return host != null && (host.contains(":") || host.matches("[0-9.]+"));+ }}diff --git a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2IntegrationTest.javaindex 14ce381129..0d690344f8 100644--- a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2IntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2IntegrationTest.java@@ -664,6 +664,33 @@ class ElbV2IntegrationTest {.statusCode(200);}+ @Test+ @Order(26)+ void registerTargetsRejectsMetadataAddress() {+ given()+ .formParam("Action", "RegisterTargets")+ .formParam("TargetGroupArn", tgArn)+ .formParam("Targets.member.1.Id", "169.254.169.254")+ .formParam("Targets.member.1.Port", "80")+ .header("Authorization", AUTH)+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("ErrorResponse.Error.Code", equalTo("InvalidTarget"));++ given()+ .formParam("Action", "DescribeTargetHealth")+ .formParam("TargetGroupArn", tgArn)+ .header("Authorization", AUTH)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("DescribeTargetHealthResponse.DescribeTargetHealthResult.TargetHealthDescriptions.member.Target.Id",+ not(hasItem("169.254.169.254")));+ }+@Test@Order(27)void describeTargetHealthReturnsInitial() {diff --git a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ServiceTest.javaindex 5d0ec31789..2041783118 100644--- a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ServiceTest.java@@ -287,6 +287,33 @@ class ElbV2ServiceTest {assertEquals("Target is not registered to the target group", health.getDescription());}+ @Test+ void registerTargetsRejectsLinkLocalAndMetadataAddresses() {+ String tgArn = createTargetGroup("metadata-tg");++ for (String address : List.of("169.254.169.254", "169.254.170.2", "fe80::1", "fd00:ec2::254")) {+ TargetDescription target = new TargetDescription();+ target.setId(address);+ AwsException ex = assertThrows(AwsException.class,+ () -> service.registerTargets(REGION, tgArn, List.of(target)), address);+ assertEquals("InvalidTarget", ex.getErrorCode());+ }+ assertTrue(service.describeTargetGroups(REGION, null, List.of(tgArn), null).getFirst().getTargets().isEmpty());+ verify(healthChecker, never()).addTargets(eq(tgArn), anyList(), any(TargetGroup.class));+ }++ @Test+ void registerTargetsStillAcceptsLoopbackAndPrivateAddresses() {+ String tgArn = createTargetGroup("local-tg");++ for (String address : List.of("127.0.0.1", "10.0.0.5", "172.17.0.2", "192.168.1.10")) {+ TargetDescription target = new TargetDescription();+ target.setId(address);+ service.registerTargets(REGION, tgArn, List.of(target));+ }+ assertEquals(4, service.describeTargetGroups(REGION, null, List.of(tgArn), null).getFirst().getTargets().size());+ }+private String createTargetGroup(String name) {return service.createTargetGroup(REGION, name, "HTTP", "HTTP1", 9999, "vpc-a", "instance",diff --git a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2TargetResolverTest.java b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2TargetResolverTest.javaindex cd3ddc65cf..f5ce289266 100644--- a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2TargetResolverTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2TargetResolverTest.java@@ -6,7 +6,12 @@ import io.github.hectorvent.floci.services.elbv2.model.TargetDescription;import io.github.hectorvent.floci.services.elbv2.model.TargetGroup;import org.junit.jupiter.api.Test;+import java.io.IOException;+import java.util.List;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;import static org.mockito.Mockito.mock;import static org.mockito.Mockito.when;@@ -38,4 +43,18 @@ class ElbV2TargetResolverTest {assertEquals("10.0.0.12", ElbV2TargetResolver.resolveHost(ec2Service, targetGroup, target));}++ @Test+ void checkedAddressReturnsAnIpLiteralForLoopbackAndPrivateTargets() throws IOException {+ assertEquals("127.0.0.1", ElbV2TargetResolver.resolveCheckedAddress("127.0.0.1"));+ assertEquals("10.0.0.12", ElbV2TargetResolver.resolveCheckedAddress("10.0.0.12"));+ }++ @Test+ void checkedAddressRejectsLinkLocalAndMetadataTargets() {+ for (String host : List.of("169.254.169.254", "169.254.170.2", "fe80::1", "fd00:ec2::254")) {+ IOException ex = assertThrows(IOException.class, () -> ElbV2TargetResolver.resolveCheckedAddress(host), host);+ assertTrue(ex.getMessage().contains("link-local or metadata address"), ex.getMessage());+ }+ }}