diff --git a/docs/services/sts.md b/docs/services/sts.md index 1d4c73966c..8e54ed1502 100644 --- a/docs/services/sts.md +++ b/docs/services/sts.md @@ -138,6 +138,8 @@ When `FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED=true`, `AssumeRole` also evaluates (`AssumeRolePolicyDocument`) against the caller and returns `AccessDenied` if it is not permitted. AWS principal forms are matched: `"*"`, an account id, an account-root ARN (`arn:aws:iam:::root`), and exact principal ARNs; and an explicit `Deny` always wins. Both `Action` and `NotAction` elements are honored when matching `sts:AssumeRole`. +The caller's own identity policy must allow `sts:AssumeRole` too, evaluated against the role's ARN, so a policy can +allow assuming one role and not another. Other STS actions are evaluated against `*`, whatever `RoleArn` they carry. The caller is the account that owns the request's credentials, whether they sign the `Authorization` header or a presigned query string: an IAM user's or a role session's access key @@ -157,9 +159,6 @@ when its condition matches. - **Session tags and source identity are not modelled.** `aws:RequestTag/*`, `aws:TagKeys`, `sts:TransitiveTagKeys` and `sts:SourceIdentity` are not in the request context, so a condition on them does not match, and `sts:TagSession` and `sts:SetSourceIdentity` are not checked. -- **The caller's own permission is checked against `*`.** The caller's identity policy must allow - `sts:AssumeRole`, but it is evaluated for resource `*` rather than the role's ARN, so a policy - that names the role in `Resource` does not grant it. ## Web Identity Validation (IRSA) 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 dc86e06493..a621af0cbc 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 @@ -1505,7 +1505,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter { } /** - * Logs and Secrets Manager targets depend on the serving operation and the request's partition; + * Logs and Secrets Manager targets depend on the serving operation and the request's partition, STS + * targets on the serving operation; * Scheduler and Pipes targets on the request's partition, which those services mint their ARNs in. */ private List targetResources(String credentialScope, String action, ContainerRequestContext ctx, @@ -1516,6 +1517,9 @@ public class IamEnforcementFilter implements ContainerRequestFilter { if ("secretsmanager".equals(credentialScope)) { return arnBuilder.buildSecretsManagerResources(action, ctx, region, accountId, requestPartition()); } + if ("sts".equals(credentialScope)) { + return arnBuilder.buildStsResources(action, ctx); + } if ("scheduler".equals(credentialScope) || "pipes".equals(credentialScope) || "dsql".equals(credentialScope)) { return arnBuilder.buildResources(credentialScope, ctx, region, accountId, requestPartition()); } diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/RequestBodyReader.java b/src/main/java/io/github/hectorvent/floci/services/iam/RequestBodyReader.java index e9ba62ec26..5bb2a317d6 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/RequestBodyReader.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/RequestBodyReader.java @@ -46,16 +46,21 @@ public final class RequestBodyReader { return body; } + static boolean isForm(ContainerRequestContext ctx) { + MediaType mt = ctx.getMediaType(); + return mt != null + && "application".equalsIgnoreCase(mt.getType()) + && "x-www-form-urlencoded".equalsIgnoreCase(mt.getSubtype()); + } + public static String formField(ContainerRequestContext ctx, String key) { if ("GET".equalsIgnoreCase(ctx.getMethod()) && IamActionRegistry.isQueryRequest(ctx)) { return ctx.getUriInfo().getQueryParameters().getFirst(key); } - MediaType mt = ctx.getMediaType(); - if (mt == null - || !"application".equalsIgnoreCase(mt.getType()) - || !"x-www-form-urlencoded".equalsIgnoreCase(mt.getSubtype())) { + if (!isForm(ctx)) { return null; } + MediaType mt = ctx.getMediaType(); byte[] body = buffer(ctx); if (body.length == 0) { return null; diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java b/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java index 9ac4371d9d..43b0ff4e3c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java @@ -1243,11 +1243,7 @@ public class ResourceArnBuilder { // ── SQS ───────────────────────────────────────────────────────────────────── private String buildSqsArn(ContainerRequestContext ctx, String region, String accountId) { - String queueUrl = ctx.getUriInfo().getQueryParameters().getFirst("QueueUrl"); - if (queueUrl == null) { - // Try form param for Query-protocol - queueUrl = firstFormParam(ctx, "QueueUrl"); - } + String queueUrl = firstFormParam(ctx, "QueueUrl"); if (queueUrl == null) { JsonNode json = readJsonBody(ctx); if (json != null && json.isObject()) { @@ -1586,9 +1582,37 @@ public class ResourceArnBuilder { return slash > 0 ? after.substring(0, slash) : after; } + // ── STS ───────────────────────────────────────────────────────────────────── + /** + * Uses the serving operation, as {@link #buildLogResources} does: {@code AssumeRole} is + * authorized against the role it names, so a policy can allow assuming one role and not another. + * Every other operation keeps {@code *}, so a {@code RoleArn} it never reads cannot choose its resource. + */ + public List buildStsResources(String action, ContainerRequestContext ctx) { + return List.of("sts:AssumeRole".equals(action) ? buildAssumeRoleArn(ctx) : "*"); + } + + private String buildAssumeRoleArn(ContainerRequestContext ctx) { + String roleArn = firstFormParam(ctx, "RoleArn"); + // Untrimmed: the handler assumes the role named by this exact string. + return roleArn == null || roleArn.isBlank() ? "*" : roleArn; + } + + /** + * A Query-protocol parameter, read from the same place the handler reads it. For a form POST + * that is the body alone: {@code AwsQueryController} dispatches on the form parameters and never + * sees the URL query, so authorizing a URL value would check one resource and act on another. + * A value with an invalid percent escape is read as absent, so the resource stays the default + * and the request goes on to be answered as it is without enforcement. + */ private String firstFormParam(ContainerRequestContext ctx, String name) { - // Form params are typically available as query params in REST-Assured / JAX-RS - String v = ctx.getUriInfo().getQueryParameters().getFirst(name); - return v; + if (RequestBodyReader.isForm(ctx)) { + try { + return RequestBodyReader.formField(ctx, name); + } catch (IllegalArgumentException malformed) { + return null; + } + } + return ctx.getUriInfo().getQueryParameters().getFirst(name); } } diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java index aee85c7515..6be9f06cab 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java @@ -767,6 +767,65 @@ class ResourceArnBuilderTest { } } + // ── STS ────────────────────────────────────────────────────────────────────── + + @Test + void stsAssumeRoleIsAuthorizedAgainstTheRoleItNames() { + setFormBody("Action=AssumeRole&Version=2011-06-15" + + "&RoleArn=arn%3Aaws%3Aiam%3A%3A729951873967%3Arole%2FAdmin&RoleSessionName=robin"); + String arn = sts("sts:AssumeRole"); + assertEquals("arn:aws:iam::729951873967:role/Admin", arn); + } + + @Test + void stsAssumeRoleIgnoresARoleArnInTheUrlOfAFormPost() { + // The handler acts on the body's RoleArn, so authorization must check that one, never a + // decoy in the query string. + queryParams.add("RoleArn", "arn:aws:iam::729951873967:role/Allowed"); + setFormBody("Action=AssumeRole&Version=2011-06-15" + + "&RoleArn=arn%3Aaws%3Aiam%3A%3A729951873967%3Arole%2FAdmin&RoleSessionName=robin"); + String arn = sts("sts:AssumeRole"); + assertEquals("arn:aws:iam::729951873967:role/Admin", arn); + } + + @Test + void stsReadsRoleArnOnlyForAssumeRole() { + // GetFederationToken never acts on a role, so a RoleArn added to it must not let a policy + // scoped to that role allow it. + setFormBody("Action=GetFederationToken&Version=2011-06-15&Name=robin" + + "&RoleArn=arn%3Aaws%3Aiam%3A%3A729951873967%3Arole%2FAdmin"); + assertEquals("*", sts("sts:GetFederationToken")); + } + + @Test + void stsMalformedRoleArnIsAuthorizedAsNoRole() { + // Read as absent, so the request reaches the form reader, which refuses it as it does today. + setFormBody("Action=AssumeRole&Version=2011-06-15&RoleArn=arn%3Aaws%ZZ&RoleSessionName=robin"); + assertEquals("*", sts("sts:AssumeRole")); + } + + @Test + void stsRoleArnIsCheckedAsTheHandlerReadsIt() { + // The handler does not trim, so neither does the check. + setFormBody("Action=AssumeRole&Version=2011-06-15" + + "&RoleArn=+arn%3Aaws%3Aiam%3A%3A729951873967%3Arole%2FAdmin&RoleSessionName=robin"); + assertEquals(" arn:aws:iam::729951873967:role/Admin", sts("sts:AssumeRole")); + } + + private String sts(String action) { + return builder.buildStsResources(action, ctx).getFirst(); + } + + @Test + void sqsBuildsArnFromFormBodyQueueUrl() { + // The handler acts on the body's QueueUrl, so a decoy in the query string must not be checked. + queryParams.add("QueueUrl", "http://localhost:4566/000000000000/allowed"); + setFormBody("Action=SendMessage&QueueUrl=http%3A%2F%2Flocalhost%3A4566%2F000000000000%2Forders&MessageBody=x"); + String arn = builder.build("sqs", ctx, "us-east-1", "000000000000"); + assertEquals("arn:aws:sqs:us-east-1:000000000000:orders", arn); + } + + // ── DynamoDB ───────────────────────────────────────────────────────────────── @Test @@ -1102,6 +1161,14 @@ class ResourceArnBuilderTest { // ── SNS ───────────────────────────────────────────────────────────────────── + @Test + void snsBuildsArnFromFormBodyTopicArn() { + queryParams.add("TopicArn", "arn:aws:sns:us-east-1:000000000000:allowed"); + setFormBody("Action=Publish&TopicArn=arn%3Aaws%3Asns%3Aus-east-1%3A000000000000%3Aalerts&Message=hi"); + String arn = builder.build("sns", ctx, "us-east-1", "000000000000"); + assertEquals("arn:aws:sns:us-east-1:000000000000:alerts", arn); + } + @Test void snsBuildsArnFromJsonTopicArn() { String topicArn = "arn:aws:sns:us-east-1:000000000000:alerts"; diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/StsAssumeRoleResourceEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/StsAssumeRoleResourceEnforcementIntegrationTest.java new file mode 100644 index 0000000000..231ed99eec --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/iam/StsAssumeRoleResourceEnforcementIntegrationTest.java @@ -0,0 +1,122 @@ +package io.github.hectorvent.floci.services.iam; + +import io.github.hectorvent.floci.testing.EnforcementFixtures; +import io.github.hectorvent.floci.testing.EnforcementFixtures.UserCredentials; +import io.github.hectorvent.floci.testing.IamEnforcementProfile; +import io.github.hectorvent.floci.testing.PartitionCleanup; +import io.quarkus.test.common.http.TestHTTPResource; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.restassured.response.Response; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import java.net.URI; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.UUID; + +import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth; +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.not; + +/** + * With {@code iam.enforcement-enabled=true}, {@code sts:AssumeRole} is authorized against the role it + * names, so an identity policy can allow assuming one role and not another (IAM User Guide, "Granting + * a user permissions to switch roles": the policy's Resource is the role's ARN). + */ +@QuarkusTest +@TestProfile(IamEnforcementProfile.class) +class StsAssumeRoleResourceEnforcementIntegrationTest { + + private static final String ACCOUNT = "111111111111"; + + @TestHTTPResource + URI baseUri; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @Test + void aPolicyNamingOneRoleAllowsAssumingThatRoleOnly() { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String allowedArn = createRole("assume-allowed-" + suffix); + String otherArn = createRole("assume-other-" + suffix); + String user = "assume-caller-" + suffix; + String iamAuth = auth(ACCOUNT, "iam"); + UserCredentials caller = EnforcementFixtures.createUser(cleanup, baseUri.getPort(), iamAuth, user); + EnforcementFixtures.putUserPolicy(baseUri.getPort(), iamAuth, user, "assume", """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":"sts:AssumeRole","Resource":"%s"}]}""".formatted(allowedArn)); + + assumeRole(caller, allowedArn).then().statusCode(200); + assumeRole(caller, otherArn).then().statusCode(403); + } + + @Test + void aPolicyNamingOneRoleDoesNotAllowOtherStsActionsThatCarryItsArn() { + // GetFederationToken never acts on a role, so adding the allowed role's ARN to it must not + // make a policy scoped to that role allow it. + String suffix = UUID.randomUUID().toString().substring(0, 8); + String allowedArn = createRole("federation-allowed-" + suffix); + String user = "federation-caller-" + suffix; + String iamAuth = auth(ACCOUNT, "iam"); + UserCredentials caller = EnforcementFixtures.createUser(cleanup, baseUri.getPort(), iamAuth, user); + EnforcementFixtures.putUserPolicy(baseUri.getPort(), iamAuth, user, "sts-all", """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":"sts:*","Resource":"%s"}]}""".formatted(allowedArn)); + + given().port(baseUri.getPort()) + .contentType("application/x-www-form-urlencoded") + .header("Authorization", auth(caller.accessKeyId(), "sts")) + .formParam("Action", "GetFederationToken") + .formParam("Name", "federated") + .formParam("RoleArn", allowedArn) + .when().post("/") + .then().statusCode(403); + assumeRole(caller, allowedArn).then().statusCode(200); + } + + @Test + void aMalformedRoleArnCannotDodgeADenyOnTheRoleItSpells() { + // A RoleArn with an invalid percent escape cannot be decoded, so it is authorized as * like + // a request naming no role, and the Deny on the role it spells does not match. The Allow on * + // lets it through, but the form reader behind the filter cannot decode the body either, so no + // role is assumed: the request fails exactly as it does without the resource check. This pins + // the outcome only; ResourceArnBuilderTest pins that the filter reads the value as absent. + String suffix = UUID.randomUUID().toString().substring(0, 8); + String deniedArn = createRole("malformed-denied-" + suffix); + String user = "malformed-caller-" + suffix; + String iamAuth = auth(ACCOUNT, "iam"); + UserCredentials caller = EnforcementFixtures.createUser(cleanup, baseUri.getPort(), iamAuth, user); + EnforcementFixtures.putUserPolicy(baseUri.getPort(), iamAuth, user, "assume", """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":"sts:AssumeRole","Resource":"*"}, + {"Effect":"Deny","Action":"sts:AssumeRole","Resource":"%s"}]}""".formatted(deniedArn)); + + given().port(baseUri.getPort()).urlEncodingEnabled(false) + .contentType("application/x-www-form-urlencoded") + .header("Authorization", auth(caller.accessKeyId(), "sts")) + .body("Action=AssumeRole&RoleSessionName=s&RoleArn=" + + URLEncoder.encode(deniedArn, StandardCharsets.UTF_8) + "%ZZ") + .when().post("/") + .then().statusCode(not(200)).body(not(containsString("AccessKeyId"))); + } + + private String createRole(String role) { + return EnforcementFixtures.createRole(cleanup, baseUri.getPort(), ACCOUNT, "/", role, """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":"iam:ListUsers","Resource":"*"}]}"""); + } + + private Response assumeRole(UserCredentials caller, String roleArn) { + return given().port(baseUri.getPort()) + .contentType("application/x-www-form-urlencoded") + .header("Authorization", auth(caller.accessKeyId(), "sts")) + .formParam("Action", "AssumeRole") + .formParam("RoleArn", roleArn) + .formParam("RoleSessionName", "s") + .when().post("/"); + } +}