fix(apigatewayv2): pin the checked address and cover WebSocket HTTP integrations (#3978)

Connect http:// hostname targets to the address that was checked instead of resolving the name a second time, and apply the link-local and metadata check to the WebSocket HTTP and HTTP_PROXY integrations. The pinned socket path now returns an empty body for HEAD, 204, 304 and 1xx responses.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-09-20 09:13:50 -05:00
1 parent 2697868e86
commit 0e02d34c6b
5 files changed
+196 -18

No files matched your search

@@ -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);
@@ -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<String, List<String>> 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);
@@ -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();