Skip to content

armgit / floci

Public Imported from GitHub
0

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

fix(s3): answer an expired session with ExpiredToken when verifying signatures (#5435)

Priamo Germosen013a9214b50d
diff --git a/docs/services/s3.md b/docs/services/s3.md
index 886611b29b..bdc0f71fa2 100644
--- a/docs/services/s3.md
+++ b/docs/services/s3.md
@@ -271,6 +271,7 @@ For a signed request, verification rebuilds the canonical request from the wire
- a signature that does not verify, or one computed for another key or method, with `403 SignatureDoesNotMatch`
- an access key that is neither `test` nor registered in Floci IAM (`CreateAccessKey` keys, and STS keys with their session token), with `403 InvalidAccessKeyId`. Under `FLOCI_AUTH_VALIDATE_SIGNATURES` alone, a presigned URL from such a key falls back to the older `FLOCI_AUTH_PRESIGN_SECRET` check instead, which an SDK-made URL fails with `403 SignatureDoesNotMatch`
+- temporary credentials past their expiry, sent with their own session token, with `400 ExpiredToken`, whichever placement carries the signature. Once Floci has removed an expired session it no longer knows the key, and answers as for one that is not registered
- a header-signed request more than 15 minutes from server time, with `403 RequestTimeTooSkewed`
- a body that does not match a declared `x-amz-content-sha256` digest, with `400 XAmzContentSHA256Mismatch`
- an `Authorization` header whose algorithm is not `AWS4-HMAC-SHA256`, with `400 AuthorizationHeaderMalformed`. This includes SigV4A (`AWS4-ECDSA-P256-SHA256`), which AWS accepts, for example on multi-region access points: Floci does not verify ECDSA signatures yet, so it refuses the request instead of serving it unverified
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java
index 2deb40c9b4..c73ed63c72 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java
@@ -4002,6 +4002,19 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
.map(SessionCredential::getSecretAccessKey));
}
+ /**
+ * Whether this temporary access key and session token are those of a session that has expired
+ * on the injected clock but is still stored, which {@link #findSecretKey(String, String)} finds
+ * no secret for. AWS answers such a credential as expired, not as a key it does not know. The
+ * token has to match, so a caller that does not hold the credential learns nothing about it.
+ */
+ public boolean isExpiredSessionToken(String accessKeyId, String sessionToken) {
+ return findSessionAnyAccount(accessKeyId)
+ .filter(session -> isExpired(session, clock.instant()))
+ .filter(session -> hasMatchingSessionToken(session, sessionToken))
+ .isPresent();
+ }
+
/**
* The session token issued alongside a temporary credential, for callers that must tell a
* missing token apart from one that does not match.
diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/PreSignedUrlFilter.java b/src/main/java/io/github/hectorvent/floci/services/s3/PreSignedUrlFilter.java
index 0d2f06498a..c3c68f6f4e 100644
--- a/src/main/java/io/github/hectorvent/floci/services/s3/PreSignedUrlFilter.java
+++ b/src/main/java/io/github/hectorvent/floci/services/s3/PreSignedUrlFilter.java
@@ -186,7 +186,13 @@ public class PreSignedUrlFilter implements ContainerRequestFilter {
}
} else {
String accessKeyId = credParts[0];
- String secretKey = resolveSecretKey(accessKeyId, queryParams.getFirst("X-Amz-Security-Token"));
+ String sessionToken = queryParams.getFirst("X-Amz-Security-Token");
+ String secretKey = resolveSecretKey(accessKeyId, sessionToken);
+ if (secretKey == null && S3PostPolicySigner.isExpiredSession(iamService, accessKeyId, sessionToken)) {
+ requestContext.abortWith(errorResponse(400, "ExpiredToken",
+ S3PostPolicySigner.EXPIRED_TOKEN_MESSAGE));
+ return;
+ }
if (secretKey != null) {
if (!verifySigV4Signature(requestContext, signature, secretKey)) {
requestContext.abortWith(errorResponse(403, "SignatureDoesNotMatch",
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 6abf8373b7..fa451e8aba 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
@@ -3665,8 +3665,11 @@ public class S3Controller {
}
String accessKeyId = credential.split("/", 2)[0];
- Optional<String> secretKey = S3PostPolicySigner.resolveSecretKey(
- iamService, accessKeyId, fields.get("x-amz-security-token"));
+ String sessionToken = fields.get("x-amz-security-token");
+ Optional<String> secretKey = S3PostPolicySigner.resolveSecretKey(iamService, accessKeyId, sessionToken);
+ if (secretKey.isEmpty() && S3PostPolicySigner.isExpiredSession(iamService, accessKeyId, sessionToken)) {
+ throw new AwsException("ExpiredToken", S3PostPolicySigner.EXPIRED_TOKEN_MESSAGE, 400);
+ }
if (secretKey.isEmpty()
|| !S3PostPolicySigner.verifySignature(policy, credential, signature, secretKey.get())) {
throw new AwsException("SignatureDoesNotMatch",
@@ -3677,7 +3680,7 @@ public class S3Controller {
// Route through the same bucket-policy/ACL check every other S3 write path uses, so this
// path automatically inherits any future strengthening there too.
s3Service.authorizeObjectWrite(bucket, key, "s3:PutObject",
- new S3Service.RequestAuthorization(true, accessKeyId, fields.get("x-amz-security-token")));
+ new S3Service.RequestAuthorization(true, accessKeyId, sessionToken));
validatePolicyExpiration(policy);
validatePolicyConditions(policy, bucket, fields, contentLength);
diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3HeaderSignatureFilter.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3HeaderSignatureFilter.java
index 96eee2587f..7e759a7b6b 100644
--- a/src/main/java/io/github/hectorvent/floci/services/s3/S3HeaderSignatureFilter.java
+++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3HeaderSignatureFilter.java
@@ -43,7 +43,8 @@ import java.util.Optional;
* <p>Error codes, statuses and ordering follow real S3: a structurally bad header is
* {@code 400 AuthorizationHeaderMalformed}; a request with no date is {@code 403 AccessDenied};
* a missing {@code x-amz-content-sha256} is {@code 400 InvalidRequest}; an unregistered key is
- * {@code 403 InvalidAccessKeyId}; a request more than fifteen minutes from server time is
+ * {@code 403 InvalidAccessKeyId}, and a session past its expiry, sent with its own token,
+ * {@code 400 ExpiredToken}; a request more than fifteen minutes from server time is
* {@code 403 RequestTimeTooSkewed}; a signature that does not verify is
* {@code 403 SignatureDoesNotMatch}; and a body that does not match its declared hash is
* {@code 400 XAmzContentSHA256Mismatch}.
@@ -169,9 +170,13 @@ public class S3HeaderSignatureFilter implements ContainerRequestFilter {
}
declaredHash = declaredHash.trim();
- Optional<String> secretKey = S3PostPolicySigner.resolveSecretKey(
- iamService, accessKeyId, ctx.getHeaderString("X-Amz-Security-Token"));
+ String sessionToken = ctx.getHeaderString("X-Amz-Security-Token");
+ Optional<String> secretKey = S3PostPolicySigner.resolveSecretKey(iamService, accessKeyId, sessionToken);
if (secretKey.isEmpty()) {
+ if (S3PostPolicySigner.isExpiredSession(iamService, accessKeyId, sessionToken)) {
+ abort(ctx, 400, "ExpiredToken", S3PostPolicySigner.EXPIRED_TOKEN_MESSAGE);
+ return;
+ }
abort(ctx, 403, "InvalidAccessKeyId",
"The AWS Access Key Id you provided does not exist in our records.");
return;
diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3PostPolicySigner.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3PostPolicySigner.java
index 87f5478780..c96f21235d 100644
--- a/src/main/java/io/github/hectorvent/floci/services/s3/S3PostPolicySigner.java
+++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3PostPolicySigner.java
@@ -22,6 +22,9 @@ final class S3PostPolicySigner {
static final String LEGACY_ACCESS_KEY_ID = "test";
static final String LEGACY_SECRET_KEY = "test";
+ /** S3's error list: {@code ExpiredToken}, 400 Bad Request. */
+ static final String EXPIRED_TOKEN_MESSAGE = "The provided token has expired.";
+
private S3PostPolicySigner() {
}
@@ -35,6 +38,15 @@ final class S3PostPolicySigner {
return Optional.empty();
}
+ /**
+ * Whether a credential {@link #resolveSecretKey} found no secret for is a session past its
+ * expiry, sent with its own token. S3 answers it with {@code 400 ExpiredToken}
+ * ({@link #EXPIRED_TOKEN_MESSAGE}), not as a key it does not know.
+ */
+ static boolean isExpiredSession(IamService iamService, String accessKeyId, String sessionToken) {
+ return iamService != null && iamService.isExpiredSessionToken(accessKeyId, sessionToken);
+ }
+
/**
* Verifies that {@code credential} is a well-formed S3 SigV4 credential scope:
* exactly {@code accessKeyId/date/region/s3/aws4_request}, with the service and
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java
index fbf150c85d..46ec1e3660 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java
@@ -287,6 +287,7 @@ class IamServiceTest {
expired.put("caller ARNs", (service, key) -> service.resolveCallerArns(key).isEmpty());
expired.put("user ID", (service, key) -> service.resolveCallerUserId(key, "token").isEmpty());
expired.put("enforcement", (service, key) -> service.isExpiredSession(key, expiration));
+ expired.put("expired token", (service, key) -> service.isExpiredSessionToken(key, "token"));
expired.put("sweep", (service, key) -> service.sweepExpiredSessions() == 1);
for (Map.Entry<String, BiPredicate<IamService, String>> check : expired.entrySet()) {
@@ -323,6 +324,27 @@ class IamServiceTest {
assertEquals(1, service.sweepExpiredSessions());
}
+ @Test
+ void anExpiredSessionIsToldApartOnlyWithItsOwnToken() {
+ // Signature validation asks once the secret-key lookup has found nothing, to answer a session
+ // past its expiry as expired rather than as a key that exists nowhere.
+ MutableClock clock = new MutableClock();
+ IamService service = new IamService(new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
+ new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
+ new RegionResolver("us-east-1", "000000000000"), false, clock);
+ service.registerSession("ASIACLOCKSESSION", "secret", "token", "arn:aws:iam::000000000000:role/ClockRole",
+ clock.instant().plusSeconds(60), null, "000000000000", "s", "AROACLOCKROLE:s");
+
+ assertFalse(service.isExpiredSessionToken("ASIACLOCKSESSION", "token"), "a live session");
+ clock.advance(Duration.ofSeconds(61));
+ assertTrue(service.findSecretKey("ASIACLOCKSESSION", "token").isEmpty());
+ assertTrue(service.isExpiredSessionToken("ASIACLOCKSESSION", "token"), "an expired session");
+ // Without its token the session stays as unknown as a key that exists nowhere.
+ assertFalse(service.isExpiredSessionToken("ASIACLOCKSESSION", "another-token"), "another token");
+ assertFalse(service.isExpiredSessionToken("ASIACLOCKSESSION", null), "no token");
+ assertFalse(service.isExpiredSessionToken("ASIANOSUCHSESSION", "token"), "a key that exists nowhere");
+ }
+
private static final String READ_S3 = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:GetObject","Resource":"*"}]}""";
private static final String ALL_S3 = """
diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3ValidateSignaturesIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3ValidateSignaturesIntegrationTest.java
index 62b6b5aa7b..2d3ab21773 100644
--- a/src/test/java/io/github/hectorvent/floci/services/s3/S3ValidateSignaturesIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3ValidateSignaturesIntegrationTest.java
@@ -7,6 +7,7 @@ import io.github.hectorvent.floci.testutil.AwsRequestSigner;
import io.github.hectorvent.floci.testutil.S3RequestSigner;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
+import io.restassured.RestAssured;
import io.restassured.path.xml.XmlPath;
import io.restassured.response.Response;
import jakarta.inject.Inject;
@@ -318,8 +319,7 @@ class S3ValidateSignaturesIntegrationTest {
void headerSignedRequestsWithSigninCredentialsAreAcceptedUntilTheyExpire() throws Exception {
// Sign-In stamps its access token's expiry from the injected clock, so IAM measures it on the same one.
Response token = signIn();
- S3RequestSigner signinSigner = S3RequestSigner.signedAs(token.path("accessToken.accessKeyId"),
- token.path("accessToken.secretAccessKey"), token.path("accessToken.sessionToken"));
+ S3RequestSigner signinSigner = signinSigner(token);
given()
.filter(signinSigner)
.when()
@@ -327,19 +327,101 @@ class S3ValidateSignaturesIntegrationTest {
.then()
.statusCode(200);
- clock.advance(Duration.ofSeconds(token.<Integer>path("expiresIn") + 1L));
- // A known gap from AWS, not the intended answer: S3 lists 400 ExpiredToken for a session past
- // its expiry, which only IAM enforcement gives today. Signature validation still answers it
- // as a key it does not know.
+ advancePastExpiry(token);
given()
.filter(signinSigner)
.when()
.get("/" + BUCKET + "/" + KEY)
+ .then()
+ .statusCode(400)
+ .body("Error.Code", equalTo("ExpiredToken"))
+ .body("Error.Message", equalTo("The provided token has expired."));
+ }
+
+ @Test
+ @Order(35)
+ void presignedUrlsWithSigninCredentialsAreAcceptedUntilTheyExpire() throws Exception {
+ Response token = signIn();
+ S3RequestSigner signinSigner = signinSigner(token);
+ String path = "/" + BUCKET + "/" + KEY;
+ URI uri = URI.create("http://localhost:" + RestAssured.port + path);
+ given()
+ .urlEncodingEnabled(false)
+ .when()
+ .get(path + "?" + signinSigner.presignedQuery("GET", uri, 3600))
+ .then()
+ .statusCode(200)
+ .body(equalTo("signed body"));
+
+ advancePastExpiry(token);
+ given()
+ .urlEncodingEnabled(false)
+ .when()
+ .get(path + "?" + signinSigner.presignedQuery("GET", uri, 3600))
+ .then()
+ .statusCode(400)
+ .body("Error.Code", equalTo("ExpiredToken"))
+ .body("Error.Message", equalTo("The provided token has expired."));
+ }
+
+ @Test
+ @Order(36)
+ void presignedPostsWithSigninCredentialsAreAcceptedUntilTheyExpire() throws Exception {
+ Response token = signIn();
+ postWithSigninCredentials(token, "post-signin-live.txt").then().statusCode(204);
+
+ advancePastExpiry(token);
+ postWithSigninCredentials(token, "post-signin-expired.txt")
+ .then()
+ .statusCode(400)
+ .body("Error.Code", equalTo("ExpiredToken"))
+ .body("Error.Message", equalTo("The provided token has expired."));
+ given().filter(LOCAL_SIGNER).when().get("/" + BUCKET + "/post-signin-expired.txt").then().statusCode(404);
+ }
+
+ @Test
+ @Order(37)
+ void anExpiredSessionSentWithAnotherTokenIsStillAnUnknownKey() throws Exception {
+ // Only the session's own token tells an expired session apart from a key that exists nowhere.
+ Response token = signIn();
+ advancePastExpiry(token);
+ given()
+ .filter(S3RequestSigner.signedAs(token.path("accessToken.accessKeyId"),
+ token.path("accessToken.secretAccessKey"), "another-token"))
+ .when()
+ .get("/" + BUCKET + "/" + KEY)
.then()
.statusCode(403)
.body("Error.Code", equalTo("InvalidAccessKeyId"));
}
+ private static S3RequestSigner signinSigner(Response token) {
+ return S3RequestSigner.signedAs(token.path("accessToken.accessKeyId"),
+ token.path("accessToken.secretAccessKey"), token.path("accessToken.sessionToken"));
+ }
+
+ private void advancePastExpiry(Response token) {
+ clock.advance(Duration.ofSeconds(token.<Integer>path("expiresIn") + 1L));
+ }
+
+ /** A presigned POST of {@code key} signed with the Sign-In session, its token listed in the policy as S3 requires. */
+ private static Response postWithSigninCredentials(Response token, String key) {
+ String sessionToken = token.path("accessToken.sessionToken");
+ String policy = postPolicy(key, sessionToken);
+ return given()
+ .multiPart("key", key)
+ .multiPart("policy", policy)
+ .multiPart("x-amz-algorithm", "AWS4-HMAC-SHA256")
+ .multiPart("x-amz-credential", token.path("accessToken.accessKeyId") + "/" + CREDENTIAL_DATE
+ + "/us-east-1/s3/aws4_request")
+ .multiPart("x-amz-date", AMZ_DATE)
+ .multiPart("x-amz-security-token", sessionToken)
+ .multiPart("x-amz-signature", signPolicy(policy, token.path("accessToken.secretAccessKey")))
+ .multiPart("file", key, "posted".getBytes(StandardCharsets.UTF_8), "text/plain")
+ .when()
+ .post("/" + BUCKET);
+ }
+
/** Runs the AWS Sign-In authorization-code flow through its consent page and returns the token response. */
private static Response signIn() throws Exception {
byte[] digest = MessageDigest.getInstance("SHA-256")
@@ -418,11 +500,21 @@ class S3ValidateSignaturesIntegrationTest {
}
private static String postPolicy(String key) {
+ return encodePolicy("""
+ [{"bucket": "%s"}, {"key": "%s"}]""".formatted(BUCKET, key));
+ }
+
+ private static String postPolicy(String key, String sessionToken) {
+ return encodePolicy("""
+ [{"bucket": "%s"}, {"key": "%s"}, {"x-amz-security-token": "%s"}]""".formatted(BUCKET, key, sessionToken));
+ }
+
+ private static String encodePolicy(String conditions) {
String expiration = DateTimeFormatter.ISO_INSTANT.format(
Instant.now().plusSeconds(3600).atZone(ZoneOffset.UTC));
String policy = """
- {"expiration": "%s", "conditions": [{"bucket": "%s"}, {"key": "%s"}]}
- """.formatted(expiration, BUCKET, key);
+ {"expiration": "%s", "conditions": %s}
+ """.formatted(expiration, conditions);
return Base64.getEncoder().encodeToString(policy.getBytes(StandardCharsets.UTF_8));
}
diff --git a/src/test/java/io/github/hectorvent/floci/testutil/S3RequestSigner.java b/src/test/java/io/github/hectorvent/floci/testutil/S3RequestSigner.java
index bacee90f73..bb8c98cd0a 100644
--- a/src/test/java/io/github/hectorvent/floci/testutil/S3RequestSigner.java
+++ b/src/test/java/io/github/hectorvent/floci/testutil/S3RequestSigner.java
@@ -33,6 +33,7 @@ import java.util.stream.Collectors;
* session token is given, {@code x-amz-security-token}; the content hash is the SHA-256 of the
* body the request carries. The {@code with*} methods return a copy that deliberately deviates
* (a stale timestamp, a forged signature, a wrong content hash) for the rejection cases.
+ * {@link #presignedQuery} signs the same credential into a presigned URL's query string instead.
*/
public final class S3RequestSigner implements Filter {
@@ -132,13 +133,10 @@ public final class S3RequestSigner implements Filter {
String contentSha256 = contentSha256Override != null
? contentSha256Override
: sha256Hex(body);
- String host = uri.getPort() > 0 && uri.getPort() != 80 && uri.getPort() != 443
- ? uri.getHost() + ":" + uri.getPort()
- : uri.getHost();
List<String[]> headers = new ArrayList<>();
if (signHost) {
- headers.add(new String[]{"host", host});
+ headers.add(new String[]{"host", host(uri)});
}
headers.add(new String[]{"x-amz-content-sha256", contentSha256});
headers.add(new String[]{"x-amz-date", amzDate});
@@ -179,6 +177,55 @@ public final class S3RequestSigner implements Filter {
return result;
}
+ /**
+ * The query string of a presigned URL for {@code method} on {@code uri}, written the way an AWS
+ * SDK presigner writes it: the {@code X-Amz-*} parameters, {@code X-Amz-Security-Token} when a
+ * session token is given, {@code host} as the only signed header, an unsigned payload, and the
+ * signature last. Send it with URL encoding off, since it is already encoded.
+ */
+ public String presignedQuery(String method, URI uri, int expiresSeconds) throws Exception {
+ Instant at = signedAt != null ? signedAt : Instant.now();
+ String amzDate = AMZ_DATE.format(at);
+ String scopeDate = amzDate.substring(0, 8);
+ String credentialScope = scopeDate + "/" + region + "/" + SERVICE + "/aws4_request";
+
+ Map<String, String> params = new LinkedHashMap<>();
+ params.put("X-Amz-Algorithm", ALGORITHM);
+ params.put("X-Amz-Credential", accessKeyId + "/" + credentialScope);
+ params.put("X-Amz-Date", amzDate);
+ params.put("X-Amz-Expires", Integer.toString(expiresSeconds));
+ if (sessionToken != null) {
+ params.put("X-Amz-Security-Token", sessionToken);
+ }
+ params.put("X-Amz-SignedHeaders", "host");
+ String query = params.entrySet().stream()
+ .map(param -> uriEncode(param.getKey()) + "=" + uriEncode(param.getValue()))
+ .collect(Collectors.joining("&"));
+
+ String rawPath = uri.getRawPath() == null || uri.getRawPath().isEmpty() ? "/" : uri.getRawPath();
+ String canonicalRequest = method + "\n"
+ + rawPath + "\n"
+ + canonicalQueryString(query) + "\n"
+ + "host:" + host(uri) + "\n"
+ + "\n"
+ + "host" + "\n"
+ + "UNSIGNED-PAYLOAD";
+ String stringToSign = ALGORITHM + "\n"
+ + amzDate + "\n"
+ + credentialScope + "\n"
+ + sha256Hex(canonicalRequest.getBytes(StandardCharsets.UTF_8));
+ String signature = signatureOverride != null
+ ? signatureOverride
+ : hexEncode(hmacSha256(signingKey(scopeDate), stringToSign));
+ return query + "&X-Amz-Signature=" + signature;
+ }
+
+ private static String host(URI uri) {
+ return uri.getPort() > 0 && uri.getPort() != 80 && uri.getPort() != 443
+ ? uri.getHost() + ":" + uri.getPort()
+ : uri.getHost();
+ }
+
private byte[] signingKey(String scopeDate) throws Exception {
byte[] kDate = hmacSha256(("AWS4" + secretKey).getBytes(StandardCharsets.UTF_8), scopeDate);
byte[] kRegion = hmacSha256(kDate, region);