diff --git a/docs/services/sts.md b/docs/services/sts.md index 2862bfe39a..9c95117a64 100644 --- a/docs/services/sts.md +++ b/docs/services/sts.md @@ -74,6 +74,8 @@ and is answered `ExpiredTradeInTokenException`, the refusal any token that canno where the check it replaces called it absent. Nothing published says what AWS answers an empty trade-in token, and the model is what is in hand, so the blank is read as the value it is. +SAML role sessions reject `DurationSeconds` above the target role maximum. Accepted requests retain the shorter assertion expiration. + ## Privileged Root Sessions `AssumeRoot` returns "short term credentials you can use to perform privileged tasks on a member diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java index 6311294d65..48860ebe40 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java @@ -373,10 +373,9 @@ public class StsQueryHandler { } } - if (durationSeconds > role.getMaxSessionDuration()) { - return AwsQueryResponse.error("ValidationError", - "The requested DurationSeconds exceeds the MaxSessionDuration set for this role.", - AwsNamespaces.STS, 400); + Response roleDurationError = validateMaxSessionDuration(durationSeconds, role); + if (roleDurationError != null) { + return roleDurationError; } String accessKeyId = "ASIA" + randomId(16); @@ -574,16 +573,17 @@ public class StsQueryHandler { throw new AwsException("AccessDenied", "Not authorized to perform sts:AssumeRoleWithSAML on resource: " + roleArn, 403); } + Response roleDurationError = validateMaxSessionDuration(durationSeconds, role); + if (roleDurationError != null) { + return roleDurationError; + } + String sessionName = verified.subject().replaceAll("[^A-Za-z0-9+=,.@_-]", "_"); if (sessionName.length() > 64) { sessionName = sessionName.substring(0, 64); } Instant requestedExpiration = clock.instant().plusSeconds(durationSeconds); - Instant roleExpiration = clock.instant().plusSeconds(role.getMaxSessionDuration()); Instant expiration = verified.expiration().isBefore(requestedExpiration) ? verified.expiration() : requestedExpiration; - if (roleExpiration.isBefore(expiration)) { - expiration = roleExpiration; - } String accessKeyId = "ASIA" + randomId(16); String secretKey = randomSecret(40); String sessionToken = randomSecret(200); @@ -847,6 +847,15 @@ public class StsQueryHandler { return Response.ok(AwsQueryResponse.envelope("DecodeAuthorizationMessage", AwsNamespaces.STS, result)).build(); } + private static Response validateMaxSessionDuration(int durationSeconds, IamRole role) { + if (durationSeconds > role.getMaxSessionDuration()) { + return AwsQueryResponse.error("ValidationError", + "The requested DurationSeconds exceeds the MaxSessionDuration set for this role.", + AwsNamespaces.STS, 400); + } + return null; + } + /** * The constraints the model declares for {@code action}, answered the way this handler answers * every other refusal: one {@code ValidationError} naming every violation it found, in the diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/AssumeRoleWithSamlValidationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/AssumeRoleWithSamlValidationIntegrationTest.java index db45b9f2b7..9d392c4bd4 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/AssumeRoleWithSamlValidationIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/AssumeRoleWithSamlValidationIntegrationTest.java @@ -1,9 +1,12 @@ package io.github.hectorvent.floci.services.iam; import io.github.hectorvent.floci.core.common.XmlParser; +import io.github.hectorvent.floci.testing.AwsTestClients; import io.github.hectorvent.floci.testing.SamlMetadata; +import io.quarkus.test.common.http.TestHTTPResource; import io.quarkus.test.junit.QuarkusTest; import io.restassured.response.ValidatableResponse; +import jakarta.inject.Inject; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.cert.X509CertificateHolder; import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; @@ -14,6 +17,13 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.w3c.dom.Document; import org.w3c.dom.Element; +import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.iam.IamClient; +import software.amazon.awssdk.services.iam.model.IamException; +import software.amazon.awssdk.services.sts.StsClient; +import software.amazon.awssdk.services.sts.model.AssumeRoleWithSamlResponse; +import software.amazon.awssdk.services.sts.model.StsException; import javax.xml.crypto.dsig.CanonicalizationMethod; import javax.xml.crypto.dsig.DigestMethod; @@ -35,22 +45,31 @@ import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import java.io.StringWriter; import java.math.BigInteger; +import java.net.URI; import java.nio.charset.StandardCharsets; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.Security; import java.security.cert.X509Certificate; import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; import java.util.Base64; import java.util.Date; import java.util.List; import java.util.UUID; +import java.util.function.Consumer; import java.util.function.Function; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.startsWith; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; @QuarkusTest class AssumeRoleWithSamlValidationIntegrationTest { @@ -60,6 +79,15 @@ class AssumeRoleWithSamlValidationIntegrationTest { private static final String PROVIDER = "arn:aws:iam::" + ACCOUNT + ":saml-provider/" + PROVIDER_NAME; private static final String AUDIENCE = "urn:amazon:webservices"; private static final String SAML_NS = "urn:oasis:names:tc:SAML:2.0:assertion"; + @TestHTTPResource + URI endpoint; + + @Inject + IamService iamService; + + @Inject + SAMLProviderService samlProviders; + private static KeyPair signingKeys; private static String certificateBase64; private static boolean providerRegistered; @@ -250,6 +278,165 @@ class AssumeRoleWithSamlValidationIntegrationTest { .body("GetCallerIdentityResponse.GetCallerIdentityResult.UserId", equalTo(assumedRoleId)); } + @Test + void samlDurationAboveRoleMaximumIsRejected() { + try (DurationFixture fixture = new DurationFixture(3600)) { + StsException error = assertThrows(StsException.class, + () -> fixture.assume(3601, Instant.now().plusSeconds(7200), true)); + assertEquals("ValidationError", error.awsErrorDetails().errorCode()); + assertEquals(400, error.statusCode()); + } + } + + @Test + void samlShortAssertionDoesNotBypassRoleMaximum() { + try (DurationFixture fixture = new DurationFixture(3600)) { + StsException error = assertThrows(StsException.class, + () -> fixture.assume(7200, Instant.now().plusSeconds(300), true)); + assertEquals("ValidationError", error.awsErrorDetails().errorCode()); + } + } + + @Test + void samlDurationAtRoleMaximumRetainsRequestedExpiration() { + try (DurationFixture fixture = new DurationFixture(7200)) { + Instant before = Instant.now().truncatedTo(ChronoUnit.MILLIS); + AssumeRoleWithSamlResponse result = fixture.assume(7200, before.plusSeconds(10000), true); + assertTrue(!result.credentials().expiration().isBefore(before.plusSeconds(7200))); + assertTrue(!result.credentials().expiration().isAfter(Instant.now().plusSeconds(7200))); + } + } + + @Test + void samlValidDurationStillUsesShorterAssertionExpiration() { + try (DurationFixture fixture = new DurationFixture(7200)) { + Instant expiry = Instant.now().plusSeconds(300).truncatedTo(ChronoUnit.MILLIS); + AssumeRoleWithSamlResponse result = fixture.assume(7200, expiry, true); + assertEquals(expiry, result.credentials().expiration()); + } + } + + @Test + void samlInvalidSignaturePrecedesRoleDurationValidation() { + try (DurationFixture fixture = new DurationFixture(3600)) { + StsException error = assertThrows(StsException.class, + () -> fixture.assume(7200, Instant.now().plusSeconds(300), false)); + assertEquals("InvalidIdentityToken", error.awsErrorDetails().errorCode()); + } + } + + @Test + void samlDurationFixtureCleansProviderAfterConstructionFailure() { + List providers = new ArrayList<>(); + IllegalStateException original = new IllegalStateException("before role creation"); + IllegalStateException caught = assertThrows(IllegalStateException.class, + () -> new DurationFixture(3600, provider -> { + providers.add(provider); + throw original; + })); + assertSame(original, caught); + assertEquals(0, caught.getSuppressed().length); + assertEquals(1, providers.size()); + assertTrue(samlProviders.find(providers.getFirst()).isEmpty()); + } + + @Test + void samlDurationFixturePreservesConstructionFailureWhenCleanupFails() { + List providers = new ArrayList<>(); + IllegalStateException original = new IllegalStateException("before role creation"); + IllegalStateException caught = assertThrows(IllegalStateException.class, + () -> new DurationFixture(3600, provider -> { + providers.add(provider); + samlProviders.delete(ACCOUNT, provider); + throw original; + })); + assertSame(original, caught); + assertEquals(1, caught.getSuppressed().length); + IamException cleanup = assertInstanceOf(IamException.class, caught.getSuppressed()[0]); + assertEquals("NoSuchEntity", cleanup.awsErrorDetails().errorCode()); + assertEquals(1, providers.size()); + assertTrue(samlProviders.find(providers.getFirst()).isEmpty()); + } + + private final class DurationFixture implements AutoCloseable { + private final IamClient client; + private final StsClient sts; + private final String name = "saml-duration-" + UUID.randomUUID(); + private final List sessions = new ArrayList<>(); + private String providerArn; + private String roleArn; + + private DurationFixture(int maximum) { + this(maximum, provider -> assertTrue(samlProviders.find(provider).isPresent())); + } + + private DurationFixture(int maximum, Consumer providerCreated) { + client = AwsTestClients.create(IamClient.builder(), ACCOUNT, Region.US_EAST_1, endpoint); + try { + sts = StsClient.builder().endpointOverride(endpoint).region(Region.US_EAST_1) + .credentialsProvider(AnonymousCredentialsProvider.create()).build(); + String metadata = SamlMetadata.forEntity(ISSUER, certificateBase64); + providerArn = client.createSAMLProvider(b -> b.name(name).samlMetadataDocument(metadata)) + .samlProviderArn(); + providerCreated.accept(providerArn); + String trust = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"," + + "\"Principal\":{\"Federated\":\"" + providerArn + + "\"},\"Action\":\"sts:AssumeRoleWithSAML\"}]}"; + roleArn = client.createRole(b -> b.roleName(name).assumeRolePolicyDocument(trust) + .maxSessionDuration(maximum)).role().arn(); + } catch (RuntimeException | Error failure) { + try { + close(); + } catch (RuntimeException | Error cleanup) { + if (cleanup != failure) { + failure.addSuppressed(cleanup); + } + } + throw failure; + } + } + + private AssumeRoleWithSamlResponse assume(int duration, Instant expiry, boolean sign) { + AssumeRoleWithSamlResponse response = sts.assumeRoleWithSAML(b -> b.roleArn(roleArn) + .principalArn(providerArn).durationSeconds(duration) + .samlAssertion(assertion(roleArn, providerArn, expiry, AUDIENCE, ISSUER, sign))); + sessions.add(response.credentials().accessKeyId()); + return response; + } + + @Override + public void close() { + try { + for (String key : sessions.reversed()) { + iamService.unregisterSession(ACCOUNT, key); + assertTrue(iamService.resolveCallerArns(key).isEmpty()); + } + } finally { + try { + if (roleArn != null) { + client.deleteRole(b -> b.roleName(name)); + assertTrue(iamService.findRole(ACCOUNT, name).isEmpty()); + } + } finally { + try { + if (providerArn != null) { + client.deleteSAMLProvider(b -> b.samlProviderArn(providerArn)); + assertTrue(samlProviders.find(providerArn).isEmpty()); + } + } finally { + try { + if (sts != null) { + sts.close(); + } + } finally { + client.close(); + } + } + } + } + } + } + private static void assertSignatureInvalid(Function> transforms) { String role = createRole(true); assume(role, assertion(role, PROVIDER, Instant.now().plusSeconds(300), AUDIENCE, ISSUER, true, false, transforms),