Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(iam): record a denied browser PostObject in CloudTrail (#6030)

Priamo Germosen37717537a4a7
diff --git a/docs/services/cloudtrail.md b/docs/services/cloudtrail.md
index 48701ca8f6..39cb1abfda 100644
--- a/docs/services/cloudtrail.md
+++ b/docs/services/cloudtrail.md
@@ -61,7 +61,8 @@ sub-resource, since `CreateMultipartUpload` and `CompleteMultipartUpload` are
both checked as `s3:PutObject` and `SelectObjectContent` as `s3:GetObject`. A request
refused for a permission it needs besides its own, such as
`s3:PutObjectTagging` for an upload that sets tags, is recorded as the
-operation.
+operation. A browser `POST` upload, whose credential is in its form fields, is
+recorded as `PostObject` when IAM refuses it.
## Configuration
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java
index 44156f0557..ab42819e15 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java
@@ -1146,6 +1146,36 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
String resource,
ResourcePolicyDecision resourcePolicyDecision,
String resourceOwnerAccountId) {
+ authorizeAdditionalResource(authorizationHeader, action, resource, resourcePolicyDecision,
+ resourceOwnerAccountId, null);
+ }
+
+ /**
+ * Authorizes a browser POST upload, a PostObject, as {@code s3:PutObject} on {@code resource}.
+ * Its credential is only in the form body, so {@link #filter} never sees it, and a denial is
+ * recorded in CloudTrail here, under {@code PostObject}, as the denials {@link #filter} refuses
+ * are recorded under their operation. AWS's S3 developer guide lists PostObject among "the
+ * object-level API actions that are logged as CloudTrail events". The denial is recorded in
+ * {@code region}, the one the form's credential names, as a presigned URL's is in the one its
+ * query credential names.
+ */
+ public void authorizePostObject(String authorizationHeader, String resource, String region) {
+ authorizeAdditionalResource(authorizationHeader, "s3:PutObject", resource, null, null,
+ new DeniedEvent("PostObject", region));
+ }
+
+ /** A CloudTrail record to write when IAM refuses a request: its event name and its Region. */
+ private record DeniedEvent(String name, String region) {
+ }
+
+ /** As the public overload; a denial is also recorded in CloudTrail when {@code deniedEvent} is given. */
+ private void authorizeAdditionalResource(
+ String authorizationHeader,
+ String action,
+ String resource,
+ ResourcePolicyDecision resourcePolicyDecision,
+ String resourceOwnerAccountId,
+ DeniedEvent deniedEvent) {
if (!config.services().iam().enforcementEnabled()) {
return;
}
@@ -1260,12 +1290,14 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
return;
}
LOG.infov("IAM enforcement DENY: akid={0} action={1} resource={2}", akid, action, resource);
- throw new AwsException("AccessDenied",
- "User: " + AwsArnUtils.Arn.global(requestPartition(), "iam", accountId, "user/" + akid)
- + " is not authorized to perform: " + action
- + " on resource: \"" + resource + "\""
- + " because no identity-based policy allows the " + action + " action",
- 403);
+ String denyMessage = "User: " + AwsArnUtils.Arn.global(requestPartition(), "iam", accountId, "user/" + akid)
+ + " is not authorized to perform: " + action
+ + " on resource: \"" + resource + "\""
+ + " because no identity-based policy allows the " + action + " action";
+ if (deniedEvent != null) {
+ emitS3Denial(akid, deniedEvent.name(), resource, deniedEvent.region(), denyMessage);
+ }
+ throw new AwsException("AccessDenied", denyMessage, 403);
} finally {
requestContext.setAccountId(previousAccountId);
}
@@ -1304,9 +1336,18 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
}
String eventName = mapS3ActionToEventName(action, ctx.getMethod(),
ctx.getUriInfo().getQueryParameters().keySet());
- if (eventName == null) {
- return;
+ if (eventName != null) {
+ emitS3Denial(akid, eventName, resource, region, denyMessage);
}
+ } catch (RuntimeException e) {
+ // The request is refused either way; a record that could not be written is logged, not raised.
+ LOG.warnv(e, "CloudTrail denial emission failed for {0} on {1}", action, resource);
+ }
+ }
+
+ /** Records an S3 request IAM refused as a CloudTrail data event named {@code eventName}. */
+ private void emitS3Denial(String akid, String eventName, String resource, String region, String denyMessage) {
+ try {
String[] bk = parseS3Resource(resource);
String bucket = bk[0];
String key = bk[1];
@@ -1329,7 +1370,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
}
}
} catch (Exception e) {
- LOG.tracev(e, "CloudTrail: could not extract request context for IAM denial {0} on {1}", action, resource);
+ LOG.tracev(e, "CloudTrail: could not extract request context for IAM denial {0} on {1}", eventName, resource);
}
cloudTrailService.emitS3DataEvent(CloudTrailService.S3EventInput.builder()
@@ -1345,7 +1386,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
.eventTimeMillis(System.currentTimeMillis())
.build());
} catch (RuntimeException e) {
- LOG.tracev(e, "CloudTrail denial emission failed for {0} on {1}", action, resource);
+ LOG.warnv(e, "CloudTrail denial emission failed for {0} on {1}", eventName, resource);
}
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java
index b294f388c5..09203b327f 100644
--- a/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java
+++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java
@@ -3918,15 +3918,15 @@ public class S3Controller {
* filter stage. Evaluate the signing principal's IAM identity policy here whenever a
* credential is present, independent of whether S3's own presigned-POST signature and
* condition checks (s3.enforce-auth) are enabled, so an IAM deny is not bypassed by
- * running S3 without its own presigned-POST enforcement. authorizeAdditionalResource
+ * running S3 without its own presigned-POST enforcement. authorizePostObject
* itself no-ops when IAM enforcement is disabled.
*/
String credential = lcFields.get("x-amz-credential");
rejectUnknownPostRegion(credential);
if (credential != null && !credential.isEmpty()) {
- iamEnforcementFilter.authorizeAdditionalResource(
- AccountResolver.SIGV4_SCHEME + " Credential=" + credential, "s3:PutObject",
- S3PublicAccessEvaluator.objectArn(s3Service.bucketPartition(bucket), bucket, key));
+ iamEnforcementFilter.authorizePostObject(AccountResolver.SIGV4_SCHEME + " Credential=" + credential,
+ S3PublicAccessEvaluator.objectArn(s3Service.bucketPartition(bucket), bucket, key),
+ regionResolver.resolveRegionFromPresignedCredential(credential));
}
if (s3Service.isAuthEnforced() || (config.auth().validateSignatures() && isSignedPost(lcFields))) {
diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3PresignedPostIamOnlyEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3PresignedPostIamOnlyEnforcementIntegrationTest.java
index bb6a593a92..97354ae34b 100644
--- a/src/test/java/io/github/hectorvent/floci/services/s3/S3PresignedPostIamOnlyEnforcementIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3PresignedPostIamOnlyEnforcementIntegrationTest.java
@@ -1,18 +1,32 @@
package io.github.hectorvent.floci.services.s3;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.services.cloudtrail.CloudTrailLogWriter;
import io.github.hectorvent.floci.testing.IamEnforcementProfile;
+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
+import jakarta.inject.Inject;
+import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
+import java.util.ArrayList;
+import java.util.List;
import java.util.UUID;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.zip.GZIPInputStream;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Regression coverage for the presigned POST gap in #3195/#3504: {@code S3Controller} only ran
@@ -35,6 +49,14 @@ class S3PresignedPostIamOnlyEnforcementIntegrationTest {
private static final DateTimeFormatter AMZ_DATE_FMT =
DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC);
+ @Inject
+ CloudTrailLogWriter trailWriter;
+
+ @BeforeAll
+ static void configureRestAssured() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
@Test
void presignedPostIsDeniedWhenIdentityPolicyDeniesPutObject() {
String suffix = UUID.randomUUID().toString().substring(0, 8);
@@ -186,6 +208,96 @@ class S3PresignedPostIamOnlyEnforcementIntegrationTest {
.statusCode(204);
}
+ /**
+ * A browser POST is refused outside the filter that records IAM denials, since its credential is
+ * only in the form, so it left no CloudTrail record at all. It is now recorded as PostObject, the
+ * name AWS's S3 developer guide gives it among the object-level actions CloudTrail logs, in the
+ * Region its credential names: a trail that logs only that Region, not the default one, gets it.
+ */
+ @Test
+ void aDeniedPresignedPostIsRecordedInCloudTrailAsPostObject() throws IOException {
+ String region = "eu-west-1";
+ String suffix = UUID.randomUUID().toString().substring(0, 8);
+ String bucket = "presigned-post-trail-" + suffix;
+ String logBucket = "presigned-post-trail-logs-" + suffix;
+ String trail = "presigned-post-trail-" + suffix;
+ String userName = "presigned-post-trail-user-" + suffix;
+ createBucketAsRoot(bucket, region);
+ createBucketAsRoot(logBucket, region);
+ cloudTrail(region, "CreateTrail", "{\"Name\":\"" + trail + "\",\"S3BucketName\":\"" + logBucket + "\"}");
+ cloudTrail(region, "PutEventSelectors", """
+ {"TrailName":"%s","EventSelectors":[{"ReadWriteType":"All","IncludeManagementEvents":false,
+ "DataResources":[{"Type":"AWS::S3::Object","Values":["arn:aws:s3:::%s/"]}]}]}"""
+ .formatted(trail, bucket));
+ cloudTrail(region, "StartLogging", "{\"Name\":\"" + trail + "\"}");
+ String accessKeyId = createUser(userName);
+ putUserPolicy(userName, "DenyPutObject", """
+ {"Version":"2012-10-17","Statement":[
+ {"Effect":"Deny","Action":"s3:PutObject","Resource":"*"}
+ ]}""");
+
+ try {
+ given()
+ .multiPart("key", "trailed.txt")
+ .multiPart("x-amz-credential", presignedCredential(accessKeyId, region))
+ .multiPart("file", "trailed.txt",
+ "should not be stored".getBytes(StandardCharsets.UTF_8), "text/plain")
+ .when()
+ .post("/" + bucket)
+ .then()
+ .statusCode(403)
+ .body("Error.Code", equalTo("AccessDenied"));
+ trailWriter.flushNow();
+
+ List<JsonNode> records = trailRecords(logBucket);
+ assertTrue(records.stream().anyMatch(record -> "PostObject".equals(record.path("eventName").asText())
+ && "AccessDenied".equals(record.path("errorCode").asText())
+ && bucket.equals(record.path("requestParameters").path("bucketName").asText())
+ && "trailed.txt".equals(record.path("requestParameters").path("key").asText())),
+ "Expected a PostObject AccessDenied record for " + bucket + "/trailed.txt: " + records);
+ } finally {
+ cloudTrail(region, "DeleteTrail", "{\"Name\":\"" + trail + "\"}");
+ }
+ }
+
+ private static void cloudTrail(String region, String operation, String body) {
+ given()
+ .header("Authorization", auth("test", "cloudtrail", region))
+ .header("X-Amz-Target", "CloudTrail_20131101." + operation)
+ .contentType("application/x-amz-json-1.1")
+ .body(body)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+ }
+
+ /** Every record in the log files the trail delivered to {@code logBucket}. */
+ private static List<JsonNode> trailRecords(String logBucket) throws IOException {
+ String listing = given()
+ .header("Authorization", auth("test", "s3"))
+ .when()
+ .get("/" + logBucket + "?list-type=2")
+ .then()
+ .statusCode(200)
+ .extract().asString();
+ List<JsonNode> records = new ArrayList<>();
+ Matcher key = Pattern.compile("<Key>([^<]+\\.json\\.gz)</Key>").matcher(listing);
+ while (key.find()) {
+ byte[] compressed = given()
+ .header("Authorization", auth("test", "s3"))
+ .when()
+ .get("/" + logBucket + "/" + key.group(1))
+ .then()
+ .statusCode(200)
+ .extract().asByteArray();
+ try (GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(compressed))) {
+ new ObjectMapper().readTree(in.readAllBytes()).path("Records").forEach(records::add);
+ }
+ }
+ return records;
+ }
+
private static void putBucketPolicy(String bucket, String policyDocument) {
given()
.header("Authorization", auth("test", "s3"))
@@ -198,9 +310,13 @@ class S3PresignedPostIamOnlyEnforcementIntegrationTest {
}
private static String presignedCredential(String accessKeyId) {
+ return presignedCredential(accessKeyId, REGION);
+ }
+
+ private static String presignedCredential(String accessKeyId, String region) {
String amzDate = AMZ_DATE_FMT.format(Instant.now());
String dateStamp = amzDate.substring(0, 8);
- return accessKeyId + "/" + dateStamp + "/" + REGION + "/s3/aws4_request";
+ return accessKeyId + "/" + dateStamp + "/" + region + "/s3/aws4_request";
}
private static void createBucketAsRoot(String bucket) {
@@ -212,6 +328,17 @@ class S3PresignedPostIamOnlyEnforcementIntegrationTest {
.statusCode(200);
}
+ private static void createBucketAsRoot(String bucket, String region) {
+ given()
+ .header("Authorization", auth("test", "s3", region))
+ .body("<CreateBucketConfiguration><LocationConstraint>" + region
+ + "</LocationConstraint></CreateBucketConfiguration>")
+ .when()
+ .put("/" + bucket)
+ .then()
+ .statusCode(200);
+ }
+
private static String createUser(String userName) {
return createUser(userName, null);
}
@@ -259,8 +386,12 @@ class S3PresignedPostIamOnlyEnforcementIntegrationTest {
}
private static String auth(String accessKeyId, String service) {
+ return auth(accessKeyId, service, REGION);
+ }
+
+ private static String auth(String accessKeyId, String service, String region) {
String amzDate = AMZ_DATE_FMT.format(Instant.now()).substring(0, 8);
- return "AWS4-HMAC-SHA256 Credential=" + accessKeyId + "/" + amzDate + "/" + REGION + "/" + service
+ return "AWS4-HMAC-SHA256 Credential=" + accessKeyId + "/" + amzDate + "/" + region + "/" + service
+ "/aws4_request, SignedHeaders=host, Signature=abc";
}
}