diff --git a/docs/services/cloudfront.md b/docs/services/cloudfront.md index 35022f6cab..096a223e13 100644 --- a/docs/services/cloudfront.md +++ b/docs/services/cloudfront.md @@ -265,6 +265,14 @@ PUT, PATCH and DELETE). keeps a connection to the origin after the last packet of a response. An origin that does not answer in time is answered 504, "The origin didn't respond before the request expired", as on AWS. - Custom origins that resolve to loopback, private, link-local, carrier-grade NAT, or other non-routable addresses are rejected by default. Development-only private origins must be explicitly allowlisted by exact hostname. + A refused origin is logged with the host and the setting that allows it. +- A custom origin that names this Floci itself, as `localhost`, `127.0.0.1`, `::1` or the configured + `floci.hostname`, on a port Floci listens on (its own port, or `floci.tls.aws-https-port` with TLS on) + for the protocol the request uses, is served by Floci itself, so neither DNS nor the private address check applies. This is the usual local setup for a + single-page app: a path-style S3 bucket as the origin path, fronted by the distribution's custom error + responses. The request reaches Floci with the origin's domain as its `Host`, and dot segments cannot + leave the origin path. A forwarded viewer `Host` is a 502, since it would route the request back to the + distribution. The same hosts on any other port are still refused unless allowlisted. - A custom origin whose domain is an execute-api endpoint (`{apiId}.execute-api.{region}.amazonaws.com`) of an HTTP or REST API that exists in this Floci is served by Floci itself, at the address the viewer reached, through the same host routing as a direct call. The origin path names the stage, as on AWS. Neither DNS nor diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontOriginHttpClient.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontOriginHttpClient.java index 46834c2a7b..78d0133505 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontOriginHttpClient.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontOriginHttpClient.java @@ -674,6 +674,14 @@ final class CloudFrontOriginHttpClient implements AutoCloseable { client.close(); } + /** The origin host resolves to an address the private-address guard refuses. */ + static final class BlockedOriginHostException extends UnknownHostException { + + BlockedOriginHostException(String host) { + super("CloudFront origin host resolves to a blocked address: " + host); + } + } + private record ValidatingDnsResolver(DnsResolver delegate, Set allowedHosts) implements DnsResolver { @@ -687,8 +695,7 @@ final class CloudFrontOriginHttpClient implements AutoCloseable { if (!allowedHosts.contains(normalizedHost)) { for (InetAddress address : addresses) { if (SsrfProtection.isBlockedAddress(address)) { - throw new UnknownHostException( - "CloudFront origin host resolves to a blocked address: " + normalizedHost); + throw new BlockedOriginHostException(normalizedHost); } } } diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServingController.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServingController.java index e3ccffc651..8660161582 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServingController.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServingController.java @@ -1,6 +1,7 @@ package io.github.hectorvent.floci.services.cloudfront; import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.config.TlsProxyServer; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RequestHost; import io.github.hectorvent.floci.services.apigateway.ApiGatewayExecuteApiHostFilter; @@ -118,9 +119,11 @@ public class CloudFrontServingController { private final ApiGatewayV2Service apiGatewayV2Service; private final ApiGatewayExecuteApiHostFilter executeApiHostFilter; private final String flociHostname; + private final int flociPort; private final LambdaWebIamAuth lambdaWebIamAuth; private final CurrentVertxRequest currentVertxRequest; private final HttpServer httpServer; + private final TlsProxyServer tlsProxyServer; private final CloudFrontOriginHttpClient httpClient; private final CloudFrontOriginHttpClient flociClient = CloudFrontOriginHttpClient.toFloci(); @@ -130,7 +133,7 @@ public class CloudFrontServingController { ApiGatewayService apiGatewayService, ApiGatewayV2Service apiGatewayV2Service, ApiGatewayExecuteApiHostFilter executeApiHostFilter, EmulatorConfig emulatorConfig, CurrentVertxRequest currentVertxRequest, - HttpServer httpServer) { + HttpServer httpServer, TlsProxyServer tlsProxyServer) { this.service = service; this.s3Service = s3Service; this.lambdaWebService = lambdaWebService; @@ -138,9 +141,11 @@ public class CloudFrontServingController { this.apiGatewayV2Service = apiGatewayV2Service; this.executeApiHostFilter = executeApiHostFilter; this.flociHostname = emulatorConfig.hostname().orElse("localhost"); + this.flociPort = emulatorConfig.port(); this.lambdaWebIamAuth = lambdaWebIamAuth; this.currentVertxRequest = currentVertxRequest; this.httpServer = httpServer; + this.tlsProxyServer = tlsProxyServer; this.httpClient = new CloudFrontOriginHttpClient( emulatorConfig.services().cloudfront().allowedPrivateOriginHosts().orElse(List.of())); } @@ -787,16 +792,18 @@ public class CloudFrontServingController { // Floci serves its own Web Function and execute-api endpoints, whatever port and protocol the origin names. String webEndpoint = webFunctionEndpoint(origin); String executeApiHost = webEndpoint == null ? executeApiHost(origin) : null; - boolean inProcess = webEndpoint != null || executeApiHost != null; + String selfHost = webEndpoint == null && executeApiHost == null ? selfHost(origin, viewerScheme) : null; + boolean inProcess = webEndpoint != null || executeApiHost != null || selfHost != null; if (inProcess && originRequest.headers().stream() .anyMatch(header -> "Host".equalsIgnoreCase(header.name()))) { - // CloudFront checks the endpoint's certificate against the forwarded viewer Host, which it never names. + // CloudFront checks the endpoint's certificate against the forwarded viewer Host, which it never + // names, and a self origin would route the distribution's own Host back to the distribution. LOG.debugv("CloudFront forwards the viewer Host to in-process origin {0}", origin.getId()); return OriginResponse.error(502, "Bad Gateway."); } // Dot segments would be resolved after the host filter's check and escape the API's stage. - String originPath = executeApiHost != null - ? CloudFrontRequestRouter.normalizePath(rawPath(forwardUri)) : forwardUri; + String originPath = executeApiHost != null ? CloudFrontRequestRouter.normalizePath(rawPath(forwardUri)) + : selfHost != null ? selfOriginPath(origin, rawPath(forwardUri)) : forwardUri; if (executeApiHost != null && !executeApiHostFilter.routes(executeApiHost, originPath)) { byte[] notFound = ApiGatewayExecuteApiHostFilter.NOT_FOUND_BODY.getBytes(StandardCharsets.UTF_8); return new OriginResponse(404, MediaType.APPLICATION_JSON, notFound, notFound.length, Map.of()); @@ -823,6 +830,9 @@ public class CloudFrontServingController { if (executeApiHost != null) { originHeaders.put("Host", executeApiHost); } + if (selfHost != null) { + originHeaders.put("Host", selfHost); + } if (webEndpoint != null) { originHeaders.put("Host", webEndpoint); if (alwaysAmzAuth(origin)) { @@ -852,6 +862,11 @@ public class CloudFrontServingController { } catch (CloudFrontOriginTimeoutException e) { LOG.warnv("CloudFront custom origin timed out for host {0}", safeOriginName(origin)); return OriginResponse.error(504, ORIGIN_TIMEOUT_MESSAGE); + } catch (CloudFrontOriginHttpClient.BlockedOriginHostException e) { + LOG.warnv("CloudFront custom origin host {0} resolves to a private or reserved address;" + + " list it in floci.services.cloudfront.allowed-private-origin-hosts to allow it", + safeOriginName(origin)); + return OriginResponse.error(502, "Bad Gateway."); } catch (Exception e) { // Do not log the target URI: forwarded query strings can contain credentials or tokens. LOG.warnv("CloudFront custom origin fetch failed for host {0}: {1}", @@ -875,6 +890,42 @@ public class CloudFrontServingController { } } + /** + * The origin's host when it names this Floci: its hostname, {@code localhost} or a loopback + * address, on the port Floci listens on for the protocol the request would use. Such an origin, + * typically a path-style S3 bucket, is served in-process, so the private-address guard that + * protects the other custom origins does not refuse it. + */ + private String selfHost(Origin origin, String viewerScheme) { + String host; + try { + host = normalizeOriginHost(origin.getDomainName()); + } catch (IllegalArgumentException ignored) { + // An invalid domain cannot name Floci; the normal origin fetch rejects it. + return null; + } + boolean flociHost = host.equalsIgnoreCase(flociHostname) || host.equalsIgnoreCase("localhost") + || host.equals("127.0.0.1") || host.equals("::1"); + if (!flociHost) { + return null; + } + int port = buildCustomOriginUri(origin, viewerScheme, "/", null).getPort(); + return port == flociPort || port == httpServer.getPort() || tlsProxyServer.reservesPort(port) + ? origin.getDomainName().trim() : null; + } + + /** + * The path a self origin is asked for. CloudFront sends the viewer's path to the origin as it + * came, but Floci's listener resolves dot segments, so they would climb out of the bucket the + * origin path names. Resolving them within the viewer's part first keeps the request inside it. + */ + private static String selfOriginPath(Origin origin, String forwardPath) { + String prefix = CloudFrontRequestRouter.joinPath(origin.getOriginPath(), ""); + prefix = prefix.substring(0, prefix.length() - 1); + String viewerPath = forwardPath.substring(prefix.length()); + return CloudFrontRequestRouter.normalizePath(prefix + CloudFrontRequestRouter.normalizePath(viewerPath)); + } + /** * The origin's host when it is an execute-api endpoint of an HTTP or REST API that exists in this * Floci, which the execute-api host filter then routes, and null otherwise. diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontSelfOriginServingTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontSelfOriginServingTest.java new file mode 100644 index 0000000000..55acf628ee --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontSelfOriginServingTest.java @@ -0,0 +1,205 @@ +package io.github.hectorvent.floci.services.cloudfront; + +import com.sun.net.httpserver.HttpServer; +import io.github.hectorvent.floci.config.TlsProxyServer; +import io.github.hectorvent.floci.services.cloudfront.model.DefaultCacheBehavior; +import io.github.hectorvent.floci.services.cloudfront.model.Distribution; +import io.github.hectorvent.floci.services.cloudfront.model.DistributionConfig; +import io.github.hectorvent.floci.services.cloudfront.model.Origin; +import io.github.hectorvent.floci.services.s3.S3Service; +import io.github.hectorvent.floci.testing.PartitionCleanup; +import io.quarkus.test.InjectMock; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.RestAssured; +import jakarta.inject.Inject; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.Mockito.when; + +/** + * Distributions whose custom origin is this Floci itself, addressed as {@code localhost} or a + * loopback address on Floci's own port: a path-style S3 bucket fronted by CloudFront, the usual + * local setup for a single-page app. No private origin host is allowed here. + */ +@QuarkusTest +class CloudFrontSelfOriginServingTest { + + private static final String CACHING_DISABLED = "4135ea2d-6df8-44a3-9df3-4b5a84be39ad"; + private static final String REGION = "us-east-1"; + + @Inject + CloudFrontService cloudFrontService; + + @Inject + S3Service s3Service; + + @InjectMock + TlsProxyServer tlsProxyServer; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + private String bucket; + private String otherBucket; + private HttpServer backend; + + @BeforeEach + void createSite() { + bucket = "self-origin-" + UUID.randomUUID().toString().substring(0, 8); + s3Service.createBucket(bucket, REGION); + s3Service.putObject(bucket, "index.html", "

spa

".getBytes(StandardCharsets.UTF_8), + "text/html", Map.of()); + cleanup.register(() -> { + s3Service.deleteObject(bucket, "index.html"); + s3Service.deleteBucket(bucket); + }); + otherBucket = "self-origin-other-" + UUID.randomUUID().toString().substring(0, 8); + s3Service.createBucket(otherBucket, REGION); + s3Service.putObject(otherBucket, "secret.txt", "secret".getBytes(StandardCharsets.UTF_8), + "text/plain", Map.of()); + cleanup.register(() -> { + s3Service.deleteObject(otherBucket, "secret.txt"); + s3Service.deleteBucket(otherBucket); + }); + } + + @AfterEach + void stopBackend() { + if (backend != null) { + backend.stop(0); + } + } + + @Test + void aLocalhostOriginOnFlociPortServesThePathStyleBucket() { + Distribution created = createDistribution("localhost", "/" + bucket, RestAssured.port, + CloudFrontService.MANAGED_ALL_VIEWER_EXCEPT_HOST_HEADER_ORIGIN_REQUEST_POLICY_ID); + + given().header("Host", created.getDomainName()) + .when().get("/index.html") + .then().statusCode(200) + .body(equalTo("

spa

")); + } + + @Test + void aLoopbackAddressOriginOnFlociPortServesThePathStyleBucket() { + Distribution created = createDistribution("127.0.0.1", "/" + bucket, RestAssured.port, + CloudFrontService.MANAGED_ALL_VIEWER_EXCEPT_HOST_HEADER_ORIGIN_REQUEST_POLICY_ID); + + given().header("Host", created.getDomainName()) + .when().get("/index.html") + .then().statusCode(200) + .body(equalTo("

spa

")); + } + + @Test + void dotSegmentsDoNotLeaveTheOriginPath() { + Distribution created = createDistribution("localhost", "/" + bucket, RestAssured.port, + CloudFrontService.MANAGED_ALL_VIEWER_EXCEPT_HOST_HEADER_ORIGIN_REQUEST_POLICY_ID); + + given().header("Host", created.getDomainName()).urlEncodingEnabled(false) + .when().get("/x/../index.html") + .then().statusCode(200) + .body(equalTo("

spa

")); + } + + @Test + void dotSegmentsCannotClimbOutOfTheOriginPathIntoAnotherBucket() { + Distribution created = createDistribution("localhost", "/" + bucket, RestAssured.port, + CloudFrontService.MANAGED_ALL_VIEWER_EXCEPT_HOST_HEADER_ORIGIN_REQUEST_POLICY_ID); + + given().header("Host", created.getDomainName()).urlEncodingEnabled(false) + .when().get("/x/../../" + otherBucket + "/secret.txt") + .then().statusCode(404); + // Floci's listener refuses encoded dot segments outright. + given().header("Host", created.getDomainName()).urlEncodingEnabled(false) + .when().get("/x/%2e%2e/%2e%2e/" + otherBucket + "/secret.txt") + .then().statusCode(400); + } + + @Test + void anHttpsOriginOnTheTlsProxyAwsPortServesThePathStyleBucket() { + when(tlsProxyServer.reservesPort(8443)).thenReturn(true); + Distribution created = createDistribution("localhost", "/" + bucket, 80, 8443, "https-only", + CloudFrontService.MANAGED_ALL_VIEWER_EXCEPT_HOST_HEADER_ORIGIN_REQUEST_POLICY_ID); + + given().header("Host", created.getDomainName()) + .when().get("/index.html") + .then().statusCode(200) + .body(equalTo("

spa

")); + } + + @Test + void forwardingTheViewerHostToASelfOriginIsABadGateway() { + Distribution created = createDistribution("localhost", "/" + bucket, RestAssured.port, + CloudFrontService.MANAGED_ALL_VIEWER_ORIGIN_REQUEST_POLICY_ID); + + given().header("Host", created.getDomainName()) + .when().get("/index.html") + .then().statusCode(502); + } + + @Test + void aLocalhostOriginOnAnotherPortIsStillRefused() throws IOException { + backend = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + backend.createContext("/", exchange -> { + byte[] body = "private".getBytes(StandardCharsets.UTF_8); + exchange.sendResponseHeaders(200, body.length); + exchange.getResponseBody().write(body); + exchange.close(); + }); + backend.start(); + Distribution created = createDistribution("localhost", "", backend.getAddress().getPort(), + CloudFrontService.MANAGED_ALL_VIEWER_EXCEPT_HOST_HEADER_ORIGIN_REQUEST_POLICY_ID); + + given().header("Host", created.getDomainName()) + .when().get("/index.html") + .then().statusCode(502); + } + + private Distribution createDistribution(String domain, String originPath, int originPort, + String originRequestPolicyId) { + return createDistribution(domain, originPath, originPort, 443, "http-only", originRequestPolicyId); + } + + private Distribution createDistribution(String domain, String originPath, int httpPort, int httpsPort, + String protocolPolicy, String originRequestPolicyId) { + Origin origin = new Origin(); + origin.setId("self"); + origin.setDomainName(domain); + origin.setOriginPath(originPath); + Map customOriginConfig = new LinkedHashMap<>(); + customOriginConfig.put("HTTPPort", String.valueOf(httpPort)); + customOriginConfig.put("HTTPSPort", String.valueOf(httpsPort)); + customOriginConfig.put("OriginProtocolPolicy", protocolPolicy); + origin.setCustomOriginConfig(customOriginConfig); + DefaultCacheBehavior behavior = new DefaultCacheBehavior(); + behavior.setTargetOriginId("self"); + behavior.setViewerProtocolPolicy("allow-all"); + behavior.setAllowedMethods(List.of("GET", "HEAD")); + behavior.setCachePolicyId(CACHING_DISABLED); + behavior.setOriginRequestPolicyId(originRequestPolicyId); + DistributionConfig config = new DistributionConfig(); + config.setEnabled(true); + config.setOrigins(List.of(origin)); + config.setDefaultCacheBehavior(behavior); + Distribution distribution = new Distribution(); + distribution.setConfig(config); + Distribution created = cloudFrontService.createDistribution(distribution, Map.of()); + cleanup.register(() -> cloudFrontService.removeDistribution(created.getId())); + return created; + } +}