diff --git a/src/main/java/io/github/hectorvent/floci/core/common/SsrfProtection.java b/src/main/java/io/github/hectorvent/floci/core/common/SsrfProtection.java index da82428250..7f60e5f878 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/SsrfProtection.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/SsrfProtection.java @@ -1,5 +1,6 @@ package io.github.hectorvent.floci.core.common; +import java.io.IOException; import java.net.InetAddress; import java.util.Arrays; @@ -35,6 +36,21 @@ public final class SsrfProtection { return false; } + /** + * Returns {@code addresses} unchanged, or throws when any of them is a metadata address per + * {@link #isMetadataAddress}. Callers that connect to the returned addresses, instead of + * resolving {@code host} again, are not exposed to a hostname that answers differently the + * second time. + */ + public static InetAddress[] rejectMetadataAddresses(InetAddress[] addresses, String host) throws IOException { + for (InetAddress address : addresses) { + if (isMetadataAddress(address)) { + throw new IOException("integration URI resolves to a link-local or metadata address: " + host); + } + } + return addresses; + } + private static boolean isAwsIpv6Metadata(byte[] bytes) { byte[] metadata = {(byte) 0xfd, 0x00, 0x0e, (byte) 0xc2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x02, 0x54}; return Arrays.equals(bytes, metadata); diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/HttpProxyInvoker.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/HttpProxyInvoker.java index 048c3bdb38..eedfe3816a 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/HttpProxyInvoker.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/HttpProxyInvoker.java @@ -18,6 +18,7 @@ import java.net.InetSocketAddress; import java.net.Socket; import java.net.URI; import java.net.URLEncoder; +import java.net.UnknownHostException; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; @@ -273,6 +274,21 @@ public class HttpProxyInvoker { private final RequestParameterMapper mapper = new RequestParameterMapper(new ContextValueResolver()); + @FunctionalInterface + interface HostResolver { + InetAddress[] resolve(String host) throws UnknownHostException; + } + + private final HostResolver resolver; + + public HttpProxyInvoker() { + this(InetAddress::getAllByName); + } + + HttpProxyInvoker(HostResolver resolver) { + this.resolver = resolver; + } + public ProxyResult invoke(Integration integration, RequestContext ctx) { return invoke(integration, ctx, ProxyOptions.DEFAULTS); } @@ -310,9 +326,9 @@ public class HttpProxyInvoker { // 5. Build java.net.http.HttpRequest String finalUrl = buildFinalUrl(builder); - if (hasHeader(builder, "Host") && finalUrl.startsWith("http://")) { + if (finalUrl.startsWith("http://") && (hasHeader(builder, "Host") || isNamedHost(finalUrl))) { try { - return invokeHttpWithHostOverride(finalUrl, method, builder, options.timeout()); + return invokeHttpPinned(finalUrl, method, builder, options.timeout()); } catch (Exception e) { LOG.warnv("HTTP_PROXY backend call failed: {0}", e.getMessage()); return errorResult("Bad Gateway: " + e.getMessage()); @@ -363,17 +379,16 @@ public class HttpProxyInvoker { } } - private static InetAddress[] resolveNonMetadataTarget(String host) throws IOException { + private InetAddress[] resolveNonMetadataTarget(String host) throws IOException { if (host == null || host.isBlank()) { throw new IOException("integration URI has no host"); } - InetAddress[] addresses = InetAddress.getAllByName(host); - for (InetAddress address : addresses) { - if (SsrfProtection.isMetadataAddress(address)) { - throw new IOException("integration URI resolves to a link-local or metadata address: " + host); - } - } - return addresses; + return SsrfProtection.rejectMetadataAddresses(resolver.resolve(host), host); + } + + private static boolean isNamedHost(String url) { + String host = URI.create(url).getHost(); + return host != null && !host.startsWith("[") && !host.matches("[0-9.]+"); } private static boolean hasHeader(ProxyRequestBuilder builder, String headerName) { @@ -389,8 +404,8 @@ public class HttpProxyInvoker { return null; } - private static ProxyResult invokeHttpWithHostOverride(String finalUrl, String method, - ProxyRequestBuilder builder, Duration timeout) + private ProxyResult invokeHttpPinned(String finalUrl, String method, + ProxyRequestBuilder builder, Duration timeout) throws IOException { URI uri = URI.create(finalUrl); int port = uri.getPort() == -1 ? 80 : uri.getPort(); @@ -403,6 +418,10 @@ public class HttpProxyInvoker { } InetAddress[] targets = resolveNonMetadataTarget(uri.getHost()); + String hostHeader = firstHeader(builder, "Host"); + if (hostHeader == null) { + hostHeader = uri.getRawAuthority(); + } try (Socket socket = new Socket()) { socket.connect(new InetSocketAddress(targets[0], port), 10_000); socket.setSoTimeout((int) Math.min(timeout.toMillis(), Integer.MAX_VALUE)); @@ -411,7 +430,7 @@ public class HttpProxyInvoker { byte[] body = builder.body() == null ? new byte[0] : builder.body(); StringBuilder request = new StringBuilder() .append(method.toUpperCase(Locale.ROOT)).append(' ').append(path).append(" HTTP/1.1\r\n") - .append("Host: ").append(firstHeader(builder, "Host")).append("\r\n") + .append("Host: ").append(hostHeader).append("\r\n") .append("Connection: close\r\n"); for (Map.Entry> header : builder.headers().entrySet()) { String name = header.getKey(); @@ -431,11 +450,11 @@ public class HttpProxyInvoker { out.write(body); out.flush(); - return readRawHttpResponse(socket.getInputStream()); + return readRawHttpResponse(socket.getInputStream(), method); } } - private static ProxyResult readRawHttpResponse(InputStream input) throws IOException { + private static ProxyResult readRawHttpResponse(InputStream input, String method) throws IOException { ByteArrayOutputStream headerBytes = new ByteArrayOutputStream(); int previous3 = -1; int previous2 = -1; @@ -479,7 +498,11 @@ public class HttpProxyInvoker { headers.computeIfAbsent(name, k -> new java.util.ArrayList<>()).add(value); } } - byte[] body = transferEncoding != null && transferEncoding.toLowerCase(Locale.ROOT).contains("chunked") + boolean bodyless = "HEAD".equalsIgnoreCase(method) || statusCode == 204 || statusCode == 304 + || (statusCode >= 100 && statusCode < 200); + byte[] body = bodyless + ? new byte[0] + : transferEncoding != null && transferEncoding.toLowerCase(Locale.ROOT).contains("chunked") ? readChunkedBody(input) : contentLength >= 0 ? input.readNBytes(contentLength) : input.readAllBytes(); return new ProxyResult(statusCode, headers, body); diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketIntegrationInvoker.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketIntegrationInvoker.java index 7e9839cb60..7bdded4721 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketIntegrationInvoker.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketIntegrationInvoker.java @@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.apigatewayv2.websocket; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.core.common.SsrfProtection; import io.github.hectorvent.floci.services.apigateway.AwsServiceRouter; import io.github.hectorvent.floci.services.apigateway.VtlTemplateEngine; import io.github.hectorvent.floci.services.apigatewayv2.model.Integration; @@ -14,6 +15,7 @@ import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; +import java.net.InetAddress; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; @@ -241,8 +243,10 @@ public class WebSocketIntegrationInvoker { LOG.debugv("Forwarding event to HTTP_PROXY endpoint: {0}", uri); try { + URI target = URI.create(uri); + SsrfProtection.rejectMetadataAddresses(InetAddress.getAllByName(target.getHost()), target.getHost()); HttpRequest request = HttpRequest.newBuilder() - .uri(URI.create(uri)) + .uri(target) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(eventJson, StandardCharsets.UTF_8)) .build(); @@ -289,8 +293,10 @@ public class WebSocketIntegrationInvoker { LOG.debugv("Forwarding transformed event to HTTP endpoint: {0}", uri); try { + URI target = URI.create(uri); + SsrfProtection.rejectMetadataAddresses(InetAddress.getAllByName(target.getHost()), target.getHost()); HttpRequest request = HttpRequest.newBuilder() - .uri(URI.create(uri)) + .uri(target) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(transformedPayload, StandardCharsets.UTF_8)) .build(); diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/HttpProxyInvokerTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/HttpProxyInvokerTest.java index 719151946f..71dc49088a 100644 --- a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/HttpProxyInvokerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/HttpProxyInvokerTest.java @@ -8,16 +8,20 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; +import java.net.InetAddress; import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; +import java.time.Duration; import java.util.LinkedHashMap; import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; 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.assertNull; +import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; import static org.junit.jupiter.api.Assertions.assertTrue; /** @@ -294,4 +298,50 @@ class HttpProxyInvokerTest { assertEquals(200, result.statusCode()); assertNotNull(received.get(), "loopback backends must stay reachable"); } + + @Test + void connectsToTheAddressItCheckedInsteadOfResolvingTheNameAgain() throws Exception { + AtomicInteger lookups = new AtomicInteger(); + HttpProxyInvoker invoker = new HttpProxyInvoker(host -> { + if (lookups.incrementAndGet() == 1) { + return new InetAddress[] {InetAddress.getByName("127.0.0.1")}; + } + return new InetAddress[] {InetAddress.getByName("169.254.169.254")}; + }); + Integration integration = httpProxyIntegration("http://rebind.example.test:" + backendPort + "/ok", null); + RequestContext ctx = ctxFor("GET", "/wallet/x", "x", Map.of(), Map.of(), null, Map.of()); + + ProxyResult result = invoker.invoke(integration, ctx); + + assertEquals(200, result.statusCode()); + assertEquals(1, lookups.get(), "the name must be resolved once, then the checked address used"); + assertEquals("rebind.example.test:" + backendPort, received.get().headers().getFirst("Host")); + } + + @Test + void rejectsANameThatResolvesToAMetadataAddress() { + HttpProxyInvoker invoker = new HttpProxyInvoker( + host -> new InetAddress[] {InetAddress.getByAddress(new byte[] {(byte) 169, (byte) 254, (byte) 169, (byte) 254})}); + Integration integration = httpProxyIntegration("http://metadata.example.test/latest/", null); + RequestContext ctx = ctxFor("GET", "/wallet/x", "x", Map.of(), Map.of(), null, Map.of()); + + ProxyResult result = invoker.invoke(integration, ctx); + + assertEquals(502, result.statusCode()); + assertTrue(new String(result.body(), StandardCharsets.UTF_8).contains("link-local or metadata address")); + } + + @Test + void headRequestToANamedHostDoesNotWaitForABody() { + HttpProxyInvoker invoker = new HttpProxyInvoker( + host -> new InetAddress[] {InetAddress.getByAddress(new byte[] {127, 0, 0, 1})}); + Integration integration = httpProxyIntegration("http://named.example.test:" + backendPort + "/ok", null); + RequestContext ctx = ctxFor("HEAD", "/wallet/x", "x", Map.of(), Map.of(), null, Map.of()); + + ProxyResult result = assertTimeoutPreemptively( + Duration.ofSeconds(5), () -> invoker.invoke(integration, ctx)); + + assertEquals(200, result.statusCode()); + assertEquals(0, result.body().length); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketIntegrationInvokerHttpTargetTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketIntegrationInvokerHttpTargetTest.java new file mode 100644 index 0000000000..aba9d36781 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketIntegrationInvokerHttpTargetTest.java @@ -0,0 +1,83 @@ +package io.github.hectorvent.floci.services.apigatewayv2.websocket; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.sun.net.httpserver.HttpServer; +import io.github.hectorvent.floci.services.apigateway.AwsServiceRouter; +import io.github.hectorvent.floci.services.apigateway.VtlTemplateEngine; +import io.github.hectorvent.floci.services.apigatewayv2.model.Integration; +import io.github.hectorvent.floci.services.apigatewayv2.websocket.WebSocketIntegrationInvoker.IntegrationResult; +import io.github.hectorvent.floci.services.lambda.LambdaService; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; + +class WebSocketIntegrationInvokerHttpTargetTest { + + private WebSocketIntegrationInvoker invoker; + private HttpServer backend; + + @BeforeEach + void setUp() throws IOException { + invoker = new WebSocketIntegrationInvoker( + mock(LambdaService.class), + mock(AwsServiceRouter.class), + new ObjectMapper(), + mock(VtlTemplateEngine.class)); + backend = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + backend.createContext("/", exchange -> { + byte[] body = "ok".getBytes(StandardCharsets.UTF_8); + exchange.sendResponseHeaders(200, body.length); + exchange.getResponseBody().write(body); + exchange.close(); + }); + backend.start(); + } + + @AfterEach + void tearDown() { + backend.stop(0); + } + + private IntegrationResult invoke(String type, String uri) { + Integration integration = new Integration(); + integration.setIntegrationType(type); + integration.setIntegrationUri(uri); + return invoker.invoke("us-east-1", integration, "{}", Map.of(), Map.of(), Map.of()); + } + + @Test + void httpProxyRejectsMetadataTarget() { + IntegrationResult result = invoke("HTTP_PROXY", "http://169.254.169.254/latest/meta-data/"); + + assertEquals(500, result.statusCode()); + assertNotNull(result.functionError()); + assertTrue(result.functionError().contains("link-local or metadata address"), result.functionError()); + } + + @Test + void httpRejectsMetadataTarget() { + IntegrationResult result = invoke("HTTP", "http://169.254.169.254/latest/meta-data/"); + + assertEquals(500, result.statusCode()); + assertNotNull(result.functionError()); + assertTrue(result.functionError().contains("link-local or metadata address"), result.functionError()); + } + + @Test + void httpProxyStillReachesLoopbackBackend() { + IntegrationResult result = invoke("HTTP_PROXY", "http://127.0.0.1:" + backend.getAddress().getPort() + "/"); + + assertEquals(200, result.statusCode()); + assertEquals("ok", result.body()); + } +}