diff --git a/docs/services/cloudtrail.md b/docs/services/cloudtrail.md index d9a380fc40..d2271203dc 100644 --- a/docs/services/cloudtrail.md +++ b/docs/services/cloudtrail.md @@ -40,6 +40,28 @@ and `AWS::S3::Object` data resource ARNs in any of these forms: - `arn:aws:s3:::bucket/prefix` — keys with the given prefix - `arn:aws:s3:::bucket/prefix/key` — exact key match +## Source address + +`sourceIPAddress` is "the IP address that the request was made from" +([CloudTrail record contents](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-event-reference-record-contents.html)): +the address of the connection Floci received the request on. An `X-Forwarded-For` header is not read on its own, +since any client can send one. Behind a reverse proxy, Quarkus's own proxy settings make the address it forwards +the source address, from the proxies they name only: + +```bash +QUARKUS_HTTP_PROXY_PROXY_ADDRESS_FORWARDING=true +QUARKUS_HTTP_PROXY_ALLOW_X_FORWARDED=true +QUARKUS_HTTP_PROXY_TRUSTED_PROXIES=10.0.0.5 # the proxy's address or range +``` + +Quarkus takes the first address in `X-Forwarded-For`, so the proxy must set the header to the address its own +connection came from, replacing any the client sent (nginx's `proxy_set_header X-Forwarded-For $remote_addr`). A +proxy that appends to the client's header (nginx's `$proxy_add_x_forwarded_for`) leaves the client's choice first, +and that is what gets recorded. + +With `floci.tls.enabled`, Floci's own TCP proxy relays every connection to Quarkus, so the source address is the +loopback address. + ## Encryption and CloudWatch Logs settings `CreateTrail` and `UpdateTrail` record `KmsKeyId`, `CloudWatchLogsLogGroupArn` and `CloudWatchLogsRoleArn`, and `DescribeTrails` returns them, so a Terraform `aws_cloudtrail` with encryption or log delivery reads back what it declared. `UpdateTrail` with an empty value clears one, as on AWS. A log group without a role is refused with `InvalidCloudWatchLogsRoleArnException`, and a role without a log group with `InvalidCloudWatchLogsLogGroupArnException`. The settings are recorded only: log files are not encrypted, events are not delivered to the log group, and `KmsKeyId` is stored as sent (an alias is not resolved to the key ARN, and an unknown key is not refused). diff --git a/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java b/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java index 4100339500..0ba5a59633 100644 --- a/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java +++ b/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java @@ -1711,13 +1711,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter { var req = rc.request(); if (req != null) { userAgent = req.getHeader("User-Agent"); - String fwd = req.getHeader("X-Forwarded-For"); - if (fwd != null && !fwd.isBlank()) { - int comma = fwd.indexOf(','); - sourceIp = (comma > 0 ? fwd.substring(0, comma) : fwd).trim(); - } else if (req.remoteAddress() != null) { - sourceIp = req.remoteAddress().host(); - } + sourceIp = RequestSourceAddress.of(req); } } } catch (Exception e) { diff --git a/src/main/java/io/floci/aws/core/common/RequestSourceAddress.java b/src/main/java/io/floci/aws/core/common/RequestSourceAddress.java new file mode 100644 index 0000000000..94df517633 --- /dev/null +++ b/src/main/java/io/floci/aws/core/common/RequestSourceAddress.java @@ -0,0 +1,22 @@ +package io.floci.aws.core.common; + +import io.vertx.core.http.HttpServerRequest; +import io.vertx.core.net.SocketAddress; + +/** + * The address a request was made from, as CloudTrail's {@code sourceIPAddress} names it: the address of the + * connection the request arrived on. An {@code X-Forwarded-For} header is not read on its own, since any client can + * send one. Behind a proxy that Quarkus's own proxy settings trust, Quarkus gives the request the address that proxy + * forwards as its remote address. + */ +public final class RequestSourceAddress { + + private RequestSourceAddress() { + } + + /** The request's remote host, or null when the connection names none. */ + public static String of(HttpServerRequest request) { + SocketAddress remote = request.remoteAddress(); + return remote != null ? remote.host() : null; + } +} diff --git a/src/main/java/io/floci/aws/services/s3/S3Controller.java b/src/main/java/io/floci/aws/services/s3/S3Controller.java index 1ab473dceb..0add7b8470 100644 --- a/src/main/java/io/floci/aws/services/s3/S3Controller.java +++ b/src/main/java/io/floci/aws/services/s3/S3Controller.java @@ -16,6 +16,7 @@ import io.floci.aws.core.common.PaginatedResult; import io.floci.aws.core.common.Pagination; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.RequestContext; +import io.floci.aws.core.common.RequestSourceAddress; import io.floci.aws.core.common.ResteasyRequests; import io.floci.aws.core.common.StreamingResponses; import io.floci.aws.core.common.UuidShapes; @@ -197,13 +198,7 @@ public class S3Controller { if (req != null) { authHeader = req.getHeader("Authorization"); userAgent = req.getHeader("User-Agent"); - String fwd = req.getHeader("X-Forwarded-For"); - if (fwd != null && !fwd.isBlank()) { - int comma = fwd.indexOf(','); - sourceIp = (comma > 0 ? fwd.substring(0, comma) : fwd).trim(); - } else if (req.remoteAddress() != null) { - sourceIp = req.remoteAddress().host(); - } + sourceIp = RequestSourceAddress.of(req); } } } catch (Exception e) { diff --git a/src/test/java/io/floci/aws/core/common/RequestSourceAddressTest.java b/src/test/java/io/floci/aws/core/common/RequestSourceAddressTest.java new file mode 100644 index 0000000000..c594b04425 --- /dev/null +++ b/src/test/java/io/floci/aws/core/common/RequestSourceAddressTest.java @@ -0,0 +1,36 @@ +package io.floci.aws.core.common; + +import io.vertx.core.http.HttpServerRequest; +import io.vertx.core.net.SocketAddress; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class RequestSourceAddressTest { + + @Test + void aClientSentForwardedForIsNotTheSourceAddress() { + HttpServerRequest request = mock(HttpServerRequest.class); + when(request.remoteAddress()).thenReturn(SocketAddress.inetSocketAddress(54321, "127.0.0.1")); + when(request.getHeader("X-Forwarded-For")).thenReturn("203.0.113.7"); + + assertEquals("127.0.0.1", RequestSourceAddress.of(request)); + } + + /** Behind a proxy Quarkus trusts, Quarkus makes the forwarded address the request's remote address. */ + @Test + void theRemoteAddressQuarkusGivesTheRequestIsTheSourceAddress() { + HttpServerRequest request = mock(HttpServerRequest.class); + when(request.remoteAddress()).thenReturn(SocketAddress.inetSocketAddress(443, "203.0.113.7")); + + assertEquals("203.0.113.7", RequestSourceAddress.of(request)); + } + + @Test + void aConnectionWithoutAnAddressNamesNone() { + assertNull(RequestSourceAddress.of(mock(HttpServerRequest.class))); + } +} diff --git a/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailAdvancedSelectorsIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailAdvancedSelectorsIntegrationTest.java index 94c67c5793..d4087000fd 100644 --- a/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailAdvancedSelectorsIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailAdvancedSelectorsIntegrationTest.java @@ -2,7 +2,6 @@ package io.floci.aws.services.cloudtrail; import io.floci.aws.testing.RestAssuredJsonUtils; import io.quarkus.test.junit.QuarkusTest; -import io.restassured.response.Response; import jakarta.inject.Inject; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -11,6 +10,7 @@ import java.io.ByteArrayInputStream; import java.util.UUID; import java.util.zip.GZIPInputStream; +import static io.floci.aws.services.cloudtrail.CloudTrailRequests.invokeCloudTrail; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.containsString; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -31,9 +31,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue; @QuarkusTest class CloudTrailAdvancedSelectorsIntegrationTest { - private static final String CT_TARGET = "CloudTrail_20131101."; - private static final String JSON11 = "application/x-amz-json-1.1"; - @Inject CloudTrailLogWriter writer; @@ -161,14 +158,6 @@ class CloudTrailAdvancedSelectorsIntegrationTest { // --- Helpers --- - private static Response invokeCloudTrail(String action, String body) { - return given() - .header("X-Amz-Target", CT_TARGET + action) - .contentType(JSON11) - .body(body) - .when().post("/"); - } - private static void createBucket(String name) { given().when().put("/" + name).then().statusCode(200); } diff --git a/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailIntegrationTest.java index f6e25463df..3a351118d8 100644 --- a/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailIntegrationTest.java @@ -13,6 +13,7 @@ import java.io.ByteArrayInputStream; import java.util.UUID; import java.util.zip.GZIPInputStream; +import static io.floci.aws.services.cloudtrail.CloudTrailRequests.invokeCloudTrail; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; @@ -620,14 +621,6 @@ class CloudTrailIntegrationTest { .when().post("/"); } - private static Response invokeCloudTrail(String action, String body) { - return given() - .header("X-Amz-Target", CT_TARGET + action) - .contentType(JSON11) - .body(body) - .when().post("/"); - } - private static void createBucket(String name) { given().when().put("/" + name).then().statusCode(200); } diff --git a/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailListingAndTagsIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailListingAndTagsIntegrationTest.java index 0816bc77e1..d08b2a480d 100644 --- a/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailListingAndTagsIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailListingAndTagsIntegrationTest.java @@ -2,12 +2,12 @@ package io.floci.aws.services.cloudtrail; import io.floci.aws.testing.RestAssuredJsonUtils; import io.quarkus.test.junit.QuarkusTest; -import io.restassured.response.Response; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import java.util.UUID; +import static io.floci.aws.services.cloudtrail.CloudTrailRequests.invokeCloudTrail; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.containsString; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -19,9 +19,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue; @QuarkusTest class CloudTrailListingAndTagsIntegrationTest { - private static final String CT_TARGET = "CloudTrail_20131101."; - private static final String JSON11 = "application/x-amz-json-1.1"; - @BeforeAll static void configureRestAssured() { RestAssuredJsonUtils.configureAwsContentTypes(); @@ -155,14 +152,6 @@ class CloudTrailListingAndTagsIntegrationTest { // --- Helpers --- - private static Response invokeCloudTrail(String action, String body) { - return given() - .header("X-Amz-Target", CT_TARGET + action) - .contentType(JSON11) - .body(body) - .when().post("/"); - } - private static void createBucket(String name) { given().when().put("/" + name).then().statusCode(200); } diff --git a/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailLogFiles.java b/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailLogFiles.java new file mode 100644 index 0000000000..0843dc60d1 --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailLogFiles.java @@ -0,0 +1,51 @@ +package io.floci.aws.services.cloudtrail; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.restassured.path.xml.XmlPath; +import io.restassured.specification.RequestSpecification; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.zip.GZIPInputStream; + +import static io.restassured.RestAssured.given; + +/** Reads the records a trail delivered to its S3 bucket, through the S3 API, as a client of the trail would. */ +final class CloudTrailLogFiles { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private CloudTrailLogFiles() { + } + + /** Every record of every log file in {@code bucket}, in key order, across every page of the listing. */ + static List records(String bucket) throws IOException { + List records = new ArrayList<>(); + for (String key : keys(bucket)) { + byte[] gz = given().when().get("/" + bucket + "/" + key).then().statusCode(200).extract().asByteArray(); + try (GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(gz))) { + MAPPER.readTree(in).path("Records").forEach(records::add); + } + } + return records; + } + + private static List keys(String bucket) { + List keys = new ArrayList<>(); + String token = null; + do { + RequestSpecification listing = given().queryParam("list-type", "2"); + if (token != null) { + listing = listing.queryParam("continuation-token", token); + } + XmlPath page = listing.when().get("/" + bucket).then().statusCode(200).extract().xmlPath(); + keys.addAll(page.getList("ListBucketResult.Contents.Key")); + token = "true".equals(page.getString("ListBucketResult.IsTruncated")) + ? page.getString("ListBucketResult.NextContinuationToken") : null; + } while (token != null); + return keys; + } +} diff --git a/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailLogWriterBoundedRetryIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailLogWriterBoundedRetryIntegrationTest.java index 80611f9252..5818792043 100644 --- a/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailLogWriterBoundedRetryIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailLogWriterBoundedRetryIntegrationTest.java @@ -6,7 +6,6 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import io.floci.aws.core.common.XmlParser; import io.floci.aws.testing.RestAssuredJsonUtils; import io.quarkus.test.junit.QuarkusTest; -import io.restassured.response.Response; import jakarta.inject.Inject; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -22,6 +21,7 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.GZIPInputStream; +import static io.floci.aws.services.cloudtrail.CloudTrailRequests.invokeCloudTrail; import static io.restassured.RestAssured.given; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -30,8 +30,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue; @QuarkusTest class CloudTrailLogWriterBoundedRetryIntegrationTest { - private static final String CT_TARGET = "CloudTrail_20131101."; - private static final String JSON11 = "application/x-amz-json-1.1"; private static final int RETRY_RECORD_LIMIT = 1024; private static final int PRODUCED_EVENTS = RETRY_RECORD_LIMIT + 80; @@ -271,14 +269,6 @@ class CloudTrailLogWriterBoundedRetryIntegrationTest { return new ObjectMapper().readTree(body); } - private static Response invokeCloudTrail(String action, String body) { - return given() - .header("X-Amz-Target", CT_TARGET + action) - .contentType(JSON11) - .body(body) - .when().post("/"); - } - private static void createBucket(String name) { given().when().put("/" + name).then().statusCode(200); } diff --git a/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailRequests.java b/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailRequests.java new file mode 100644 index 0000000000..a88e6d3350 --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailRequests.java @@ -0,0 +1,20 @@ +package io.floci.aws.services.cloudtrail; + +import io.restassured.response.Response; + +import static io.restassured.RestAssured.given; + +/** CloudTrail's JSON 1.1 calls, as the integration tests send them: the action in {@code X-Amz-Target}. */ +final class CloudTrailRequests { + + private CloudTrailRequests() { + } + + static Response invokeCloudTrail(String action, String body) { + return given() + .header("X-Amz-Target", "CloudTrail_20131101." + action) + .contentType("application/x-amz-json-1.1") + .body(body) + .when().post("/"); + } +} diff --git a/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailSourceAddressIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailSourceAddressIntegrationTest.java new file mode 100644 index 0000000000..1f909d4232 --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailSourceAddressIntegrationTest.java @@ -0,0 +1,62 @@ +package io.floci.aws.services.cloudtrail; + +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.util.UUID; + +import static io.floci.aws.services.cloudtrail.CloudTrailRequests.invokeCloudTrail; +import static io.restassured.RestAssured.given; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; + +/** + * {@code sourceIPAddress} is "the IP address that the request was made from" + * (https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-event-reference-record-contents.html): + * the connection's, not an {@code X-Forwarded-For} any client can send. + */ +@QuarkusTest +class CloudTrailSourceAddressIntegrationTest { + + @Inject + CloudTrailLogWriter writer; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void aClientSentForwardedForIsNotTheSourceAddress() throws IOException { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String bucket = "ct-src-" + suffix; + String logs = "ct-src-logs-" + suffix; + String trail = "ct-src-" + suffix; + given().when().put("/" + bucket).then().statusCode(200); + given().when().put("/" + logs).then().statusCode(200); + cloudTrail("CreateTrail", "{\"Name\":\"" + trail + "\",\"S3BucketName\":\"" + logs + "\"}"); + cloudTrail("PutEventSelectors", "{\"TrailName\":\"" + trail + "\",\"EventSelectors\":[{\"ReadWriteType\":" + + "\"All\",\"IncludeManagementEvents\":false,\"DataResources\":[{\"Type\":\"AWS::S3::Object\"," + + "\"Values\":[\"arn:aws:s3:::" + bucket + "/\"]}]}]}"); + cloudTrail("StartLogging", "{\"Name\":\"" + trail + "\"}"); + + given().header("X-Forwarded-For", "203.0.113.7").body("x") + .when().put("/" + bucket + "/forwarded.txt").then().statusCode(200); + writer.flushNow(); + + String recorded = CloudTrailLogFiles.records(logs).stream() + .filter(r -> "forwarded.txt".equals(r.path("requestParameters").path("key").asText())) + .map(r -> r.path("sourceIPAddress").asText()) + .findFirst() + .orElseThrow(() -> new AssertionError("no record of the forwarded write in " + logs)); + assertThat(recorded, equalTo("127.0.0.1")); + } + + private static void cloudTrail(String action, String body) { + invokeCloudTrail(action, body).then().statusCode(200); + } +}