diff --git a/docs/services/iam.md b/docs/services/iam.md index 37fcad765b..b3beca6687 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -787,9 +787,27 @@ that has never set one. | EnableOrganizationsRootSessions | Enables the `RootSessions` feature. | | DisableOrganizationsRootSessions | Disables the `RootSessions` feature. | -Only the set of enabled features is stored, and enabling a feature twice is idempotent. Floci does not -model root credentials or root sessions themselves, so the flags change what `ListOrganizationsFeatures` -returns and nothing else. +Only the set of enabled features is stored, and enabling a feature twice is idempotent. Floci does +not model root credentials themselves, so `RootCredentialsManagement` changes what +`ListOrganizationsFeatures` returns and nothing else; `RootSessions` is what STS `AssumeRoot` reads +before opening a privileged session. + +All five answer for one organization, so all five check the caller, each refusal being a shape the +reference models on them and on nothing else. In the order they are asked: no organization at all +is `OrganizationNotFoundException`, an organization without All features is +`OrganizationNotInAllFeaturesModeException`, one without trusted access for IAM in Organizations is +`ServiceAccessNotEnabledException`, and a caller that is neither the management account nor a +delegated administrator for IAM is `AccountNotManagementOrDelegatedAdministratorException`. The two +enable operations add `CallerIsNotManagementAccountException`, which is modeled on them alone, so a +delegated administrator may read the features and turn them off but not on. Each is 400 and carries +the shape name as its code: botocore declares no `error.code` for any of the five. + +The feature set belongs to the organization rather than to whoever asked for it, so it is read and +written in the management account's scope and a delegated administrator sees what the management +account enabled. The order is chosen rather than read, and so is the account the record lives in; a +toggle set before this moved sat in the calling account's scope and is set again once. The +`OrganizationId` the model declares beside `EnabledFeatures` is answered now that the organization +is known either way. ### Server Certificates diff --git a/docs/services/index.md b/docs/services/index.md index e932309b35..57b35500f5 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -24,7 +24,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [API Gateway v1](api-gateway.md) | `/restapis/...` | REST JSON | 80 | | [API Gateway v2](api-gateway.md#v2) | `/v2/apis/...` | REST JSON | 53 + data-plane | | [IAM](iam.md) | `POST /` with `Action=` param | Query | 176 | -| [STS](sts.md) | `POST /` with `Action=` param | Query | 9 | +| [STS](sts.md) | `POST /` with `Action=` param | Query | 10 | | [AWS Sign-In](iam.md#aws-sign-in-login-credentials) | `/v1/authorize`, `/v1/token` | REST JSON | 2 | | [Organizations](organizations.md) | `POST /` + `X-Amz-Target: AWSOrganizationsV20161128.*` | JSON 1.1 | 56 | | [Cognito](cognito.md) | `POST /` + `X-Amz-Target: AWSCognitoIdentityProviderService.*` | JSON 1.1 | 90 | diff --git a/docs/services/sts.md b/docs/services/sts.md index 783d0206ef..1d4c73966c 100644 --- a/docs/services/sts.md +++ b/docs/services/sts.md @@ -15,6 +15,50 @@ | `DecodeAuthorizationMessage` | Decode an encoded authorization failure message | | `GetDelegatedAccessToken` | Exchange a delegation request's trade-in token for temporary credentials | | `GetAccessKeyInfo` | Returns the account an access key ID belongs to | +| `AssumeRoot` | Opens a privileged session on a member account of the organization | + +## Privileged Root Sessions + +`AssumeRoot` returns "short term credentials you can use to perform privileged tasks on a member +account in your organization". The session acts as that member account's root user, which no +identity policy grants or denies, scoped by the `TaskPolicyArn` the request names: the five AWS +managed policies the model names for it, under `arn:aws:iam::aws:policy/root-task/`, each deny +everything they do not name, so the policy is the whole of the session's bound. Whose policy it is +counts as much as where it sits: a customer-managed policy can carry the same path, and installing +one would bound the session by whatever that document allows, so only AWS's own are accepted and +anything else is refused. + +The caller has to be able to manage root access: the management account or a delegated +administrator for IAM, in an organization with All features and trusted access for IAM enabled, and +with `RootSessions` on. The target has to be a member account other than the management account, +privileged tasks being what the management account performs on members. `DurationSeconds` is 0 to +900 and defaults to 900, "the maximum session duration of 900 seconds (15 minutes)". + +Four things are deviations rather than readings, since the operation models only +`RegionDisabledException` and `ExpiredTokenException`: + +- Every caller, target and feature refusal is `AccessDenied` 403, and a task policy outside the + root-task path is a `ValidationError`, which is the shape every other member violation answers. +- "You cannot use root user credentials to call sts:AssumeRoot" is the guide's rule; what is + decided here is which credential that means. Both the one resolving to a root ARN, a privileged + session opening another among them, and the bare 12-digit account-id key are refused, the latter + because the enforcement filter already reads it as "floci's account-root principal, never an IAM + user's key". A privileged session is therefore opened by an IAM user or role of the management + account, as on AWS, rather than by the account itself. +- "The global endpoint is not supported for AssumeRoot" is refused when the request arrives on the + partition's global STS host. A request to a local host carries no such name, and the signing + region cannot tell the two apart, so there is nothing to refuse there. +- `SessionTokenSize` is answered as the length of the token issued, and `MinimumSessionTokenSize` + pads it to at least the size asked for, held to the 0 to 4096 the model declares, "The value must + not exceed 4,096 bytes", since the size asked for is the size materialized. Out of that range is + a `ValidationError` and a value that is no integer an `InvalidParameterValue`, the pair + `DurationSeconds` already answers. `SessionTokenUtilization` is not answered: the model documents + neither member, so only the one with an obvious meaning is filled. + +The audit reads the `IAMAuditRootUserCredentials` task policy allows name the member account's root +user when they are called with no `UserName`, which is what that policy's own `arn:aws:iam::*:root` +asks for. Floci keeps no user record for a root user, so those reads answer `NoSuchEntity` rather +than the credentials report AWS returns. ## Access Key Info diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/CentralRootAccess.java b/src/main/java/io/github/hectorvent/floci/services/iam/CentralRootAccess.java new file mode 100644 index 0000000000..d63ed283fe --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/iam/CentralRootAccess.java @@ -0,0 +1,146 @@ +package io.github.hectorvent.floci.services.iam; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RequestScopes; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.inject.Instance; +import jakarta.inject.Inject; + +import java.util.List; +import java.util.Optional; +import java.util.function.Supplier; + +/** + * Centralized root access: who may turn the two root features on and off, and who may launch a + * privileged session with them. The five IAM operations behind the feature set + * ({@code ListOrganizationsFeatures}, {@code Enable}/{@code DisableOrganizationsRootCredentialsManagement}, + * {@code Enable}/{@code DisableOrganizationsRootSessions}) all answer for one organization, so + * every one of them goes through here and {@link IamService} keeps only the toggles themselves. + * + *

Two things this fixes about those toggles. They took no caller check at all, so any account + * could enable or disable organization-wide root features; the reference models five refusals on + * them and they are all made here. And the record they write is account-scoped like every other + * IAM record, so the management account's toggle was invisible to a delegated administrator: the + * feature set belongs to the organization, so it is read and written in the management account's + * scope whoever asks. A toggle set before this change sat in the calling account's scope and is + * not read any more, so it is set again once. + * + *

The organization itself is answered by {@link RootAccessOrganization}, which Organizations + * implements, so IAM still does not depend on Organizations. + */ +@ApplicationScoped +public class CentralRootAccess { + + /** The wire code is the shape name: botocore gives these five shapes no {@code error.code}. */ + private static final int REFUSED = 400; + + private final IamService iamService; + private final Instance organizations; + + @Inject + public CentralRootAccess(IamService iamService, Instance organizations) { + this.iamService = iamService; + this.organizations = organizations; + } + + /** The organization id and its enabled features, which every one of the five operations answers. */ + public record Features(String organizationId, List enabledFeatures) {} + + public Features list(String callerAccountId) { + RootAccessOrganization.Membership organization = authorize(callerAccountId, false); + return features(organization, iamService::listOrganizationsFeatures); + } + + public Features enableRootCredentialsManagement(String callerAccountId) { + RootAccessOrganization.Membership organization = authorize(callerAccountId, true); + return features(organization, iamService::enableOrganizationsRootCredentialsManagement); + } + + public Features enableRootSessions(String callerAccountId) { + RootAccessOrganization.Membership organization = authorize(callerAccountId, true); + return features(organization, iamService::enableOrganizationsRootSessions); + } + + public Features disableRootCredentialsManagement(String callerAccountId) { + RootAccessOrganization.Membership organization = authorize(callerAccountId, false); + return features(organization, iamService::disableOrganizationsRootCredentialsManagement); + } + + public Features disableRootSessions(String callerAccountId) { + RootAccessOrganization.Membership organization = authorize(callerAccountId, false); + return features(organization, iamService::disableOrganizationsRootSessions); + } + + /** + * The organization a privileged session may be launched in, or a refusal. The caller must be + * able to manage root access and {@code RootSessions} must be enabled, which is what the guide + * means by "You have enabled centralized root access in your organization". + * + *

{@code AssumeRoot} models neither refusal, so both are {@code AccessDenied} 403, the + * answer STS publishes for a caller it will not mint credentials for. + */ + RootAccessOrganization.Membership privilegedSessionOrganization(String callerAccountId) { + Optional found = membershipOf(callerAccountId); + if (found.isEmpty() || !found.get().allFeatures() || !found.get().iamTrustedAccess() + || !found.get().isManagementOrDelegatedAdministrator(callerAccountId)) { + throw new AwsException("AccessDenied", "User: " + callerAccountId + " is not authorized to perform:" + + " sts:AssumeRoot because it is not the management account or a delegated administrator" + + " account for centralized root access.", 403); + } + RootAccessOrganization.Membership organization = found.get(); + if (!features(organization, iamService::listOrganizationsFeatures) + .enabledFeatures().contains(IamService.FEATURE_ROOT_SESSIONS)) { + throw new AwsException("AccessDenied", "User: " + callerAccountId + " is not authorized to perform:" + + " sts:AssumeRoot because centralized root access is not enabled for the organization." + + " Call EnableOrganizationsRootSessions first.", 403); + } + return organization; + } + + /** + * The five refusals the reference models on the feature operations, in the order they are + * asked: whether there is an organization at all, what it has enabled, and who is asking. + * {@code CallerIsNotManagementAccount} is modeled on the two enable operations only, so a + * delegated administrator may list and disable but not enable. + */ + private RootAccessOrganization.Membership authorize(String callerAccountId, boolean managementOnly) { + RootAccessOrganization.Membership organization = membershipOf(callerAccountId) + .orElseThrow(() -> refused("OrganizationNotFoundException", + "The request was rejected because no organization is associated with your account.")); + if (!organization.allFeatures()) { + throw refused("OrganizationNotInAllFeaturesModeException", "The request was rejected because your" + + " organization does not have All features enabled."); + } + if (!organization.iamTrustedAccess()) { + throw refused("ServiceAccessNotEnabledException", "The request was rejected because trusted access" + + " is not enabled for IAM in Organizations."); + } + if (!organization.isManagementOrDelegatedAdministrator(callerAccountId)) { + throw refused("AccountNotManagementOrDelegatedAdministratorException", "The request was rejected" + + " because the account making the request is not the management account or delegated" + + " administrator account for centralized root access."); + } + if (managementOnly && !organization.isManagementAccount(callerAccountId)) { + throw refused("CallerIsNotManagementAccountException", "The request was rejected because the account" + + " making the request is not the management account for the organization."); + } + return organization; + } + + /** The feature set belongs to the organization, so the management account's scope holds it. */ + private Features features(RootAccessOrganization.Membership organization, Supplier> toggle) { + return new Features(organization.organizationId(), + RequestScopes.callAs(organization.managementAccountId(), toggle)); + } + + private Optional membershipOf(String accountId) { + if (!organizations.isResolvable()) { + return Optional.empty(); + } + return organizations.get().membershipOf(accountId); + } + + private static AwsException refused(String code, String message) { + return new AwsException(code, message, REFUSED); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java index 1d53a6a797..ab7348b0eb 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java @@ -85,6 +85,7 @@ public class IamQueryHandler { private final ServiceLastAccessedService serviceLastAccessedService; private final OrganizationsAccessReportService organizationsAccessReportService; private final DelegationRequestService delegationRequestService; + private final CentralRootAccess centralRootAccess; private final RegionResolver regionResolver; private final Instance serverCertificateReferenceProviders; /** Signs each page's Marker, so only a marker this handler issued names an item. */ @@ -96,6 +97,7 @@ public class IamQueryHandler { ServiceLastAccessedService serviceLastAccessedService, OrganizationsAccessReportService organizationsAccessReportService, DelegationRequestService delegationRequestService, + CentralRootAccess centralRootAccess, RegionResolver regionResolver, Instance serverCertificateReferenceProviders) { this.iamService = iamService; @@ -105,6 +107,7 @@ public class IamQueryHandler { this.serviceLastAccessedService = serviceLastAccessedService; this.organizationsAccessReportService = organizationsAccessReportService; this.delegationRequestService = delegationRequestService; + this.centralRootAccess = centralRootAccess; this.regionResolver = regionResolver; this.serverCertificateReferenceProviders = serverCertificateReferenceProviders; } @@ -2024,38 +2027,42 @@ public class IamQueryHandler { // ========================================================================= private Response handleListOrganizationsFeatures(MultivaluedMap params) { - return rootFeaturesResponse("ListOrganizationsFeatures", iamService.listOrganizationsFeatures()); + return rootFeaturesResponse("ListOrganizationsFeatures", + centralRootAccess.list(regionResolver.getAccountId())); } private Response handleEnableOrganizationsRootCredentialsManagement(MultivaluedMap params) { return rootFeaturesResponse("EnableOrganizationsRootCredentialsManagement", - iamService.enableOrganizationsRootCredentialsManagement()); + centralRootAccess.enableRootCredentialsManagement(regionResolver.getAccountId())); } private Response handleEnableOrganizationsRootSessions(MultivaluedMap params) { return rootFeaturesResponse("EnableOrganizationsRootSessions", - iamService.enableOrganizationsRootSessions()); + centralRootAccess.enableRootSessions(regionResolver.getAccountId())); } private Response handleDisableOrganizationsRootCredentialsManagement(MultivaluedMap params) { return rootFeaturesResponse("DisableOrganizationsRootCredentialsManagement", - iamService.disableOrganizationsRootCredentialsManagement()); + centralRootAccess.disableRootCredentialsManagement(regionResolver.getAccountId())); } private Response handleDisableOrganizationsRootSessions(MultivaluedMap params) { return rootFeaturesResponse("DisableOrganizationsRootSessions", - iamService.disableOrganizationsRootSessions()); + centralRootAccess.disableRootSessions(regionResolver.getAccountId())); } /** - * Builds the shared {@code ..} result used by - * both {@code ListOrganizationsFeatures} and the enable/disable ops. The org-scoped - * {@code OrganizationId} is intentionally omitted — LZA's root-user-management module reads only - * the enabled-feature set, and omitting it avoids coupling the IAM endpoint to Organizations. + * The shared {@code OrganizationId} and {@code EnabledFeatures} result all five feature + * operations answer, in the order the model declares them. The organization id used to be + * omitted here to keep IAM off Organizations; the caller checks the reference models on these + * operations need the organization anyway, and {@link CentralRootAccess} asks for it through a + * provider interface, so the member is answered as published. */ - private Response rootFeaturesResponse(String action, List features) { - XmlBuilder xml = new XmlBuilder().start("EnabledFeatures"); - for (String feature : features) { + private Response rootFeaturesResponse(String action, CentralRootAccess.Features features) { + XmlBuilder xml = new XmlBuilder() + .elem("OrganizationId", features.organizationId()) + .start("EnabledFeatures"); + for (String feature : features.enabledFeatures()) { xml.elem("member", feature); } String result = xml.end("EnabledFeatures").build(); 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 92e7ff844f..65877f0e22 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 @@ -2388,6 +2388,10 @@ public class IamService implements SessionAccountLookup, ResourceProvider { // Centralized root access management (org-scoped, IAM Query endpoint) // ========================================================================= + // The toggles themselves. Who may read or move them, and which organization's record they + // belong to, is CentralRootAccess: it is the caller of all five and the only one that should + // be, these having no caller check of their own. + /** Currently-enabled centralized root features, in enablement order. Empty for a fresh org. */ public List listOrganizationsFeatures() { return new ArrayList<>(currentRootFeatures().getEnabledFeatures()); @@ -5252,6 +5256,18 @@ public class IamService implements SessionAccountLookup, ResourceProvider { } return sessionTokenContext(session); } + if (isAccountRootArn(session.getRoleArn())) { + // A privileged session (AssumeRoot) acts as the member account's root user, which + // no identity policy grants and none denies: collecting role policies for a root + // ARN finds none, which would refuse everything. What scopes it is its task + // policy, and the five AWS publishes for the purpose carry Deny statements only, + // so it is read beside the root's own allow-all rather than as a session policy, + // where an intersection with nothing to allow would refuse everything too. + return new CallerContext(session.getSessionPolicyDocument() == null + ? List.of(SCOPED_IDENTITY_SESSION_BASE_POLICY) + : List.of(SCOPED_IDENTITY_SESSION_BASE_POLICY, session.getSessionPolicyDocument()), + null, null); + } List identityPolicies = collectRolePolicies(session.getRoleArn()); String boundaryDoc = resolveRoleBoundaryDocument(session.getRoleArn()); return new CallerContext(identityPolicies, session.getSessionPolicyDocument(), boundaryDoc); @@ -5521,6 +5537,13 @@ public class IamService implements SessionAccountLookup, ResourceProvider { } return issuingUser(session).map(IamService::callerForUser); } + if (isAccountRootArn(roleArn)) { + // A privileged session (AssumeRoot) is the member account's root user, not an + // assumed role: the ARN it reports is the root ARN it was minted for, and its + // aws:userid is the account id, as the account root's always is. + return Optional.of(new CallerArns(roleArn, roleArn, CallerArns.TYPE_ACCOUNT, + AwsArnUtils.accountOrDefault(roleArn, regionResolver.getAccountId()), null)); + } String roleName = roleArn.contains("/") ? roleArn.substring(roleArn.lastIndexOf('/') + 1) : "UnknownRole"; String accountId = AwsArnUtils.accountOrDefault(roleArn, regionResolver.getAccountId()); String sessionName = session.getRoleSessionName(); 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 29483ae6b9..589473dfa0 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 @@ -570,10 +570,21 @@ public class ResourceArnBuilder { if (iamService == null) { return List.of("*"); } - return SigV4CredentialScope.accessKeyId(ctx.getHeaderString("Authorization")) - .flatMap(accessKeyId -> iamService.get().findUserNameByAccessKeyId(accessKeyId)) + Optional accessKeyId = SigV4CredentialScope.accessKeyId(ctx.getHeaderString("Authorization")); + Optional> user = accessKeyId + .flatMap(key -> iamService.get().findUserNameByAccessKeyId(key)) .flatMap(userName -> storedIamEntity("user", userName, accountId)) - .map(stored -> List.of(stored.arn())) + .map(stored -> List.of(stored.arn())); + if (user.isPresent()) { + return user.get(); + } + // A caller that is the account root names the root user, which is what these actions act + // on when they are called with no UserName. AWS's own task policy for auditing root + // credentials is written against arn:aws:iam::*:root, so a privileged session calling + // GetUser or ListAccessKeys has to name that resource rather than the wildcard. + return accessKeyId.flatMap(key -> iamService.get().resolveCallerArn(key)) + .filter(arn -> arn.endsWith(":root")) + .map(List::of) .orElse(List.of("*")); } diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/RootAccessOrganization.java b/src/main/java/io/github/hectorvent/floci/services/iam/RootAccessOrganization.java new file mode 100644 index 0000000000..3b3b195603 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/iam/RootAccessOrganization.java @@ -0,0 +1,50 @@ +package io.github.hectorvent.floci.services.iam; + +import io.github.hectorvent.floci.core.common.ServicePrincipals; + +import java.util.Optional; +import java.util.Set; + +/** + * Supplies what centralized root access needs to know about an account's organization: who runs + * it, whether IAM is trusted in it, and who may act for IAM inside it. + * + *

Implemented by the Organizations service; consumed lazily by {@link CentralRootAccess} via + * {@code Instance} so IAM never depends on Organizations directly, the + * way {@link ScpProvider} already does it (Organizations depends on IAM for role provisioning). + */ +public interface RootAccessOrganization { + + /** The IAM service principal whose trusted access and delegated administrators decide this. */ + String IAM_SERVICE_PRINCIPAL = ServicePrincipals.of("iam"); + + /** + * The organization the account belongs to, or empty when it belongs to none. + * + * @param accountId the account a request arrived for + */ + Optional membershipOf(String accountId); + + /** + * One account's view of its organization. + * + * @param organizationId the organization's own id, which the root-feature operations answer + * @param managementAccountId the account that created the organization + * @param allFeatures whether the organization has the All features set enabled + * @param iamTrustedAccess whether trusted access is enabled for IAM in Organizations + * @param iamDelegatedAdmins the accounts registered as delegated administrators for IAM + * @param memberAccountIds every account in the organization, the management account included + */ + record Membership(String organizationId, String managementAccountId, boolean allFeatures, + boolean iamTrustedAccess, Set iamDelegatedAdmins, + Set memberAccountIds) { + + public boolean isManagementAccount(String accountId) { + return managementAccountId.equals(accountId); + } + + public boolean isManagementOrDelegatedAdministrator(String accountId) { + return isManagementAccount(accountId) || iamDelegatedAdmins.contains(accountId); + } + } +} 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 3d0abf11f6..cce27bc01f 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 @@ -7,6 +7,7 @@ import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.AwsNamespaces; import io.github.hectorvent.floci.core.common.AwsQueryController; import io.github.hectorvent.floci.core.common.AwsQueryResponse; +import io.github.hectorvent.floci.core.common.AwsRegions; import io.github.hectorvent.floci.core.common.IamConditionContextResolver; import io.github.hectorvent.floci.core.common.IamEnforcementFilter; import io.github.hectorvent.floci.core.common.OidcIssuerKeyLookup; @@ -16,6 +17,7 @@ import io.github.hectorvent.floci.core.common.WebIdentityToken; import io.github.hectorvent.floci.core.common.WebIdentityTokenVerifier; import io.github.hectorvent.floci.core.common.XmlBuilder; import io.github.hectorvent.floci.services.iam.model.DelegationRequest; +import io.github.hectorvent.floci.services.iam.model.IamPolicy; import io.github.hectorvent.floci.services.iam.model.IamRole; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; @@ -53,6 +55,11 @@ public class StsQueryHandler { private static final Logger LOG = Logger.getLogger(StsQueryHandler.class); private static final String CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + /** Where the five task policies the guide names for a privileged session live. */ + private static final String ROOT_TASK_POLICY_PATH = "/root-task/"; + /** "the maximum session duration of 900 seconds (15 minutes)", which is also the default here. */ + private static final int MAX_ROOT_SESSION_SECONDS = 900; + private static final int MAX_SESSION_TOKEN_SIZE = 4096; private static final String STS_AUDIENCE = "sts.amazonaws.com"; // partition-literal: web-identity audience; no source outside the commercial partition (P9) private final IamService iamService; @@ -66,6 +73,7 @@ public class StsQueryHandler { private final SAMLProviderService samlProviderService; private final SAMLTrustPolicyEvaluator samlTrustEvaluator; private final DelegationRequestService delegationRequestService; + private final CentralRootAccess centralRootAccess; private final Clock clock; /** CSPRNG for session secret keys and session tokens; ordinary IDs keep using {@link ThreadLocalRandom}. */ @@ -85,10 +93,11 @@ public class StsQueryHandler { OidcIssuerKeyLookup oidcIssuerKeys, SAMLProviderService samlProviderService, SAMLTrustPolicyEvaluator samlTrustEvaluator, - DelegationRequestService delegationRequestService) { + DelegationRequestService delegationRequestService, + CentralRootAccess centralRootAccess) { this(iamService, accountResolver, regionResolver, config, trustPolicyEvaluator, webIdentityTrustEvaluator, tokenVerifier, oidcIssuerKeys, samlProviderService, samlTrustEvaluator, delegationRequestService, - Clock.systemUTC()); + centralRootAccess, Clock.systemUTC()); } StsQueryHandler(IamService iamService, AccountResolver accountResolver, RegionResolver regionResolver, @@ -99,6 +108,7 @@ public class StsQueryHandler { SAMLProviderService samlProviderService, SAMLTrustPolicyEvaluator samlTrustEvaluator, DelegationRequestService delegationRequestService, + CentralRootAccess centralRootAccess, Clock clock) { this.iamService = iamService; this.accountResolver = accountResolver; @@ -111,6 +121,7 @@ public class StsQueryHandler { this.samlProviderService = samlProviderService; this.samlTrustEvaluator = samlTrustEvaluator; this.delegationRequestService = delegationRequestService; + this.centralRootAccess = centralRootAccess; this.clock = clock; } @@ -127,6 +138,7 @@ public class StsQueryHandler { case "GetFederationToken" -> handleGetFederationToken(params); case "DecodeAuthorizationMessage" -> handleDecodeAuthorizationMessage(params); case "GetDelegatedAccessToken" -> handleGetDelegatedAccessToken(params); + case "AssumeRoot" -> handleAssumeRoot(params); default -> AwsQueryResponse.error("UnsupportedOperation", "Operation " + action + " is not supported by STS.", AwsNamespaces.STS, 400); }; @@ -710,6 +722,187 @@ public class StsQueryHandler { AwsNamespaces.STS, result)).build(); } + /** + * A privileged session on a member account: "Returns a set of short term credentials you can + * use to perform privileged tasks on a member account in your organization." The session acts + * as that account's root user, scoped by the task policy the request names, which is what the + * guide means by "you must define TaskPolicyArn to scope the session to the privileged action + * to be performed during the session". + * + *

Four refusals, each from a published sentence and each {@code AccessDenied} 403 because + * the operation models only {@code RegionDisabled} and {@code ExpiredToken}: the caller must + * be the management account or a delegated administrator for IAM, must not be root ("You + * cannot use root user credentials to call sts:AssumeRoot"), must have {@code RootSessions} + * enabled for the organization, and the target must be a member account other than the + * management account, privileged tasks being what the management account does to members. Both + * credentials this emulator reads as the account root are refused, so the caller is an IAM + * user or role of that account. The + * task policy is held to the five AWS publishes for it, by the {@code /root-task/} path of an + * AWS managed policy rather than by a list of names, and anything else is a + * {@code ValidationError}: no source gives a code for that one, so it is the shape every other + * member violation answers here. + * + *

The global endpoint is refused when the request arrives on it, "The global endpoint is + * not supported for AssumeRoot. You must send this request to a Regional AWS STS endpoint." A + * request to a local host carries no such name, so there is nothing to refuse there. + */ + private Response handleAssumeRoot(MultivaluedMap params) { + if (arrivedOnTheGlobalEndpoint()) { + return AwsQueryResponse.error("ValidationError", "The global endpoint is not supported for" + + " AssumeRoot. You must send this request to a Regional AWS STS endpoint.", + AwsNamespaces.STS, 400); + } + Response validation = validateRequired(params, "TargetPrincipal", "TaskPolicyArn.arn"); + if (validation != null) { + return validation; + } + String targetPrincipal = getParam(params, "TargetPrincipal"); + if (targetPrincipal.length() < 12 || targetPrincipal.length() > 2048) { + String constraint = targetPrincipal.length() < 12 + ? "Member must have length greater than or equal to 12" + : "Member must have length less than or equal to 2048"; + return AwsQueryResponse.error("ValidationError", + SmithyValidationErrors.message(List.of("Value '" + targetPrincipal + + "' at 'targetPrincipal' failed to satisfy constraint: " + constraint)), + AwsNamespaces.STS, 400); + } + Response durationValidation = validateDurationSeconds(params, 0, 900); + if (durationValidation != null) { + return durationValidation; + } + Response tokenSizeValidation = validateMinimumSessionTokenSize(params); + if (tokenSizeValidation != null) { + return tokenSizeValidation; + } + String callerAccountId = regionResolver.getAccountId(); + Response rootCaller = refuseRootCredentials(callerAccountId); + if (rootCaller != null) { + return rootCaller; + } + RootAccessOrganization.Membership organization = + centralRootAccess.privilegedSessionOrganization(callerAccountId); + String targetAccountId = accountOf(targetPrincipal); + if (targetAccountId == null || !organization.memberAccountIds().contains(targetAccountId) + || organization.isManagementAccount(targetAccountId)) { + return AwsQueryResponse.error("AccessDenied", "User: " + callerAccountId + " is not authorized to" + + " perform: sts:AssumeRoot on " + targetPrincipal + " because it is not a member account" + + " of the organization.", AwsNamespaces.STS, 403); + } + String taskPolicyArn = getParam(params, "TaskPolicyArn.arn"); + if (!namesARootTaskPolicy(taskPolicyArn)) { + return AwsQueryResponse.error("ValidationError", "The task policy " + + taskPolicyArn + " cannot scope a privileged session. Use one of the AWS managed" + + " policies under " + ROOT_TASK_POLICY_PATH + ".", AwsNamespaces.STS, 400); + } + IamPolicy taskPolicy = iamService.getPolicy(taskPolicyArn); + + int durationSeconds = getIntParam(params, "DurationSeconds", MAX_ROOT_SESSION_SECONDS); + Instant expiration = clock.instant().plusSeconds(durationSeconds); + String accessKeyId = "ASIA" + randomId(16); + String secretKey = randomSecret(40); + String sessionToken = randomSecret(Math.max(200, + getIntParam(params, "MinimumSessionTokenSize", 0))); + // The session is the member account's root user, bounded by the task policy. The origin is + // the member account too: the privileged task is performed there, not where it was asked for. + iamService.registerSession(accessKeyId, secretKey, sessionToken, + regionResolver.buildGlobalArn("iam", targetAccountId, "root"), expiration, + taskPolicy.getVersions().get(taskPolicy.getDefaultVersionId()).getDocument(), + targetAccountId); + LOG.debugv("Privileged session for {0} opened by {1} under {2}", targetAccountId, callerAccountId, + taskPolicy.getArn()); + + String result = new XmlBuilder() + .raw(credentialsXml(accessKeyId, secretKey, sessionToken, expiration)) + .elem("SessionTokenSize", String.valueOf(sessionToken.length())) + .build(); + return Response.ok(AwsQueryResponse.envelope("AssumeRoot", AwsNamespaces.STS, result)).build(); + } + + /** + * True when the ARN names one of the AWS managed policies a privileged session may be scoped + * by. The member's own documentation is the list: "You must use one of following Amazon Web + * Services managed policies to scope root session actions", naming the five that sit under + * {@code /root-task/}. Whose policy it is counts as much as the path: a customer-managed + * policy at the same path is the caller's own document, and installing one would leave the + * session bounded by whatever that document says rather than by a privileged task. + */ + private static boolean namesARootTaskPolicy(String arn) { + if (!AwsManagedPolicies.isManagedPolicyArn(arn) || !AwsArnUtils.isArn(arn)) { + return false; + } + return AwsArnUtils.parse(arn).resource().startsWith("policy" + ROOT_TASK_POLICY_PATH); + } + + /** + * {@code MinimumSessionTokenSize} is 0 to 4096 in the model, "The value must not exceed 4,096 + * bytes", and the size it asks for is materialized, so the bound is enforced rather than + * clamped: a value outside it is the same {@code ValidationError} every other member violation + * answers, and one that is no integer at all the same {@code InvalidParameterValue} + * {@code DurationSeconds} gives. + */ + private Response validateMinimumSessionTokenSize(MultivaluedMap params) { + String value = params.getFirst("MinimumSessionTokenSize"); + if (value == null) { + return null; + } + int size; + try { + size = Integer.parseInt(value); + } catch (NumberFormatException e) { + return AwsQueryResponse.error("InvalidParameterValue", "Value " + value + " for parameter" + + " MinimumSessionTokenSize is invalid. Reason: Must be an integer.", + AwsNamespaces.STS, 400); + } + if (size < 0 || size > MAX_SESSION_TOKEN_SIZE) { + String constraint = size < 0 + ? "Member must have value greater than or equal to 0" + : "Member must have value less than or equal to " + MAX_SESSION_TOKEN_SIZE; + return AwsQueryResponse.error("ValidationError", + SmithyValidationErrors.message(List.of("Value '" + size + + "' at 'minimumSessionTokenSize' failed to satisfy constraint: " + constraint)), + AwsNamespaces.STS, 400); + } + return null; + } + + /** The account a {@code TargetPrincipal} names, whether it is an account id or a principal ARN. */ + private static String accountOf(String targetPrincipal) { + if (targetPrincipal.matches("\\d{12}")) { + return targetPrincipal; + } + return AwsArnUtils.isArn(targetPrincipal) ? AwsArnUtils.parse(targetPrincipal).accountId() : null; + } + + /** + * "You cannot use root user credentials to call sts:AssumeRoot." Two credentials are the + * account root here and neither may open a session. One resolves to a root ARN, which is how a + * privileged session opening another is caught. The other is the bare 12-digit account-id key, + * which {@code IamEnforcementFilter} reads as "floci's account-root principal, never an IAM + * user's key": it resolves to no ARN at all, so the first test cannot see it, and refusing it + * is what leaves the operation to an IAM user or role of the management account, which is the + * caller AWS asks for. + */ + private Response refuseRootCredentials(String callerAccountId) { + String accessKeyId = callerAccessKeyId(); + boolean accountRootKey = accessKeyId != null && accessKeyId.equals(callerAccountId); + String callerArn = accountRootKey ? null : iamService.resolveCallerArn(accessKeyId).orElse(null); + if (!accountRootKey && (callerArn == null || !callerArn.endsWith(":root"))) { + return null; + } + return AwsQueryResponse.error("AccessDenied", "Root user credentials cannot call sts:AssumeRoot." + + " Call it as an IAM user or role with the sts:AssumeRoot permission.", AwsNamespaces.STS, 403); + } + + /** True when the request arrived on the partition's global STS host rather than a Regional one. */ + private boolean arrivedOnTheGlobalEndpoint() { + String host = headers == null ? null : headers.getHeaderString(HttpHeaders.HOST); + if (host == null || host.isBlank()) { + return false; + } + String name = host.split(":", 2)[0]; + return name.equalsIgnoreCase("sts." + AwsRegions.dnsSuffixFor(regionResolver.getRegion())); + } + private Response handleDecodeAuthorizationMessage(MultivaluedMap params) { Response validation = validateRequired(params, "EncodedMessage"); if (validation != null) { diff --git a/src/main/java/io/github/hectorvent/floci/services/organizations/OrganizationsService.java b/src/main/java/io/github/hectorvent/floci/services/organizations/OrganizationsService.java index d6619faeb4..f2593a8850 100644 --- a/src/main/java/io/github/hectorvent/floci/services/organizations/OrganizationsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/organizations/OrganizationsService.java @@ -7,8 +7,10 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.common.ServicePrincipals; import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.iam.RootAccessOrganization; import io.github.hectorvent.floci.services.iam.ScpProvider; import io.github.hectorvent.floci.services.organizations.model.CreateAccountStatus; import io.github.hectorvent.floci.services.organizations.model.Handshake; @@ -30,6 +32,7 @@ import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Comparator; import java.util.LinkedHashMap; +import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Optional; @@ -53,7 +56,7 @@ import java.util.regex.Pattern; * @see AWS Organizations API Reference */ @ApplicationScoped -public class OrganizationsService implements ScpProvider { +public class OrganizationsService implements ScpProvider, RootAccessOrganization { private static final Logger LOG = Logger.getLogger(OrganizationsService.class); @@ -1405,6 +1408,31 @@ public class OrganizationsService implements ScpProvider { // ──────────────────────────── Collection helpers ──────────────────────────── + @Override + public Optional membershipOf(String accountId) { + return findOrganizationForAccount(accountId).map(organization -> { + Set delegatedAdmins = new LinkedHashSet<>(); + Set members = new LinkedHashSet<>(); + members.add(organization.getMasterAccountId()); + for (OrganizationAccount account : accountsIn(organization)) { + members.add(account.getId()); + if (namesIam(account.getDelegatedServices().keySet())) { + delegatedAdmins.add(account.getId()); + } + } + return new Membership(organization.getId(), organization.getMasterAccountId(), + FEATURE_SET_ALL.equals(organization.getFeatureSet()), + namesIam(organization.getEnabledServicePrincipals().keySet()), + delegatedAdmins, members); + }); + } + + /** Whether IAM is among these principals, legacy per-partition spellings folded in. */ + private static boolean namesIam(Set principals) { + return principals.stream() + .anyMatch(principal -> IAM_SERVICE_PRINCIPAL.equals(ServicePrincipals.canonical(principal))); + } + private List accountsIn(Organization organization) { return accounts.scanAllAccounts().stream() .filter(account -> organization.getId().equals(account.getOrganizationId())) diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/CentralRootAccessTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/CentralRootAccessTest.java new file mode 100644 index 0000000000..59ccbdfc7b --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/iam/CentralRootAccessTest.java @@ -0,0 +1,160 @@ +package io.github.hectorvent.floci.services.iam; + +import io.github.hectorvent.floci.core.common.AwsException; +import jakarta.enterprise.inject.Instance; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; + +import java.util.List; +import java.util.Optional; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * The caller checks the reference models on the five centralized root features. Each refusal is a + * shape botocore declares on those operations and no other, and the order they are asked in is + * the order below: whether there is an organization, what it has enabled, then who is asking. + */ +class CentralRootAccessTest { + + private static final String ORGANIZATION = "o-rootaccess1"; + private static final String MANAGEMENT = "100000000001"; + private static final String DELEGATED_ADMIN = "100000000002"; + private static final String MEMBER = "100000000003"; + + private IamService iamService; + private RootAccessOrganization organizations; + private CentralRootAccess rootAccess; + + @SuppressWarnings("unchecked") + @BeforeEach + void setUp() { + iamService = mock(IamService.class); + organizations = mock(RootAccessOrganization.class); + Instance instance = mock(Instance.class); + when(instance.isResolvable()).thenReturn(true); + when(instance.get()).thenReturn(organizations); + rootAccess = new CentralRootAccess(iamService, instance); + } + + private void organizationOf(String caller, boolean allFeatures, boolean trustedAccess) { + when(organizations.membershipOf(caller)).thenReturn(Optional.of( + new RootAccessOrganization.Membership(ORGANIZATION, MANAGEMENT, allFeatures, trustedAccess, + Set.of(DELEGATED_ADMIN), Set.of(MANAGEMENT, DELEGATED_ADMIN, MEMBER)))); + } + + private static String codeOf(Executable call) { + return assertThrows(AwsException.class, call).getErrorCode(); + } + + @Test + void anAccountInNoOrganizationIsRefused() { + when(organizations.membershipOf(MANAGEMENT)).thenReturn(Optional.empty()); + + assertEquals("OrganizationNotFoundException", codeOf(() -> rootAccess.list(MANAGEMENT))); + verify(iamService, never()).listOrganizationsFeatures(); + } + + @Test + void anOrganizationWithoutAllFeaturesIsRefused() { + organizationOf(MANAGEMENT, false, true); + + assertEquals("OrganizationNotInAllFeaturesModeException", codeOf(() -> rootAccess.list(MANAGEMENT))); + } + + @Test + void iamNeedsTrustedAccessInOrganizations() { + organizationOf(MANAGEMENT, true, false); + + assertEquals("ServiceAccessNotEnabledException", codeOf(() -> rootAccess.list(MANAGEMENT))); + } + + @Test + void anOrdinaryMemberAccountCannotSeeOrMoveTheFeatures() { + organizationOf(MEMBER, true, true); + + assertEquals("AccountNotManagementOrDelegatedAdministratorException", + codeOf(() -> rootAccess.list(MEMBER))); + assertEquals("AccountNotManagementOrDelegatedAdministratorException", + codeOf(() -> rootAccess.enableRootSessions(MEMBER))); + verify(iamService, never()).enableOrganizationsRootSessions(); + } + + /** + * {@code CallerIsNotManagementAccount} is modeled on the two enable operations and on neither + * disable one, so a delegated administrator may read the features and turn them off but not on. + */ + @Test + void aDelegatedAdministratorMayListAndDisableButNotEnable() { + organizationOf(DELEGATED_ADMIN, true, true); + when(iamService.listOrganizationsFeatures()).thenReturn(List.of(IamService.FEATURE_ROOT_SESSIONS)); + when(iamService.disableOrganizationsRootSessions()).thenReturn(List.of()); + + assertEquals(List.of(IamService.FEATURE_ROOT_SESSIONS), rootAccess.list(DELEGATED_ADMIN).enabledFeatures()); + assertEquals(List.of(), rootAccess.disableRootSessions(DELEGATED_ADMIN).enabledFeatures()); + assertEquals("CallerIsNotManagementAccountException", + codeOf(() -> rootAccess.enableRootSessions(DELEGATED_ADMIN))); + assertEquals("CallerIsNotManagementAccountException", + codeOf(() -> rootAccess.enableRootCredentialsManagement(DELEGATED_ADMIN))); + verify(iamService, never()).enableOrganizationsRootSessions(); + } + + @Test + void theFeatureSetIsAnsweredWithTheOrganizationItBelongsTo() { + organizationOf(MANAGEMENT, true, true); + when(iamService.enableOrganizationsRootSessions()) + .thenReturn(List.of(IamService.FEATURE_ROOT_SESSIONS)); + + CentralRootAccess.Features features = rootAccess.enableRootSessions(MANAGEMENT); + + assertEquals(ORGANIZATION, features.organizationId()); + assertEquals(List.of(IamService.FEATURE_ROOT_SESSIONS), features.enabledFeatures()); + } + + /** + * A privileged session needs the feature the guide asks for: "You have enabled centralized + * root access in your organization", which is {@code EnableOrganizationsRootSessions}. + */ + @Test + void aPrivilegedSessionNeedsRootSessionsEnabled() { + organizationOf(MANAGEMENT, true, true); + when(iamService.listOrganizationsFeatures()) + .thenReturn(List.of(IamService.FEATURE_ROOT_CREDENTIALS)); + + AwsException refused = assertThrows(AwsException.class, + () -> rootAccess.privilegedSessionOrganization(MANAGEMENT)); + + assertEquals("AccessDenied", refused.getErrorCode()); + assertEquals(403, refused.getHttpStatus()); + } + + @Test + void aPrivilegedSessionAnswersTheOrganizationOnceItIsEnabled() { + organizationOf(DELEGATED_ADMIN, true, true); + when(iamService.listOrganizationsFeatures()).thenReturn(List.of(IamService.FEATURE_ROOT_SESSIONS)); + + RootAccessOrganization.Membership organization = + rootAccess.privilegedSessionOrganization(DELEGATED_ADMIN); + + assertEquals(ORGANIZATION, organization.organizationId()); + assertEquals(MANAGEMENT, organization.managementAccountId()); + } + + @Test + void anAccountOutsideTheOrganizationCannotOpenAPrivilegedSession() { + when(organizations.membershipOf(MEMBER)).thenReturn(Optional.empty()); + + AwsException refused = assertThrows(AwsException.class, + () -> rootAccess.privilegedSessionOrganization(MEMBER)); + + assertEquals("AccessDenied", refused.getErrorCode()); + assertEquals(403, refused.getHttpStatus()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamQueryHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamQueryHandlerTest.java index fad7003311..f13d33db18 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/IamQueryHandlerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamQueryHandlerTest.java @@ -61,7 +61,7 @@ class IamQueryHandlerTest { "fabricated-key", null, Map.of())).thenReturn(certificate); when(service.getServerCertificate(CERTIFICATE_NAME)).thenReturn(certificate); when(service.listServerCertificates(null)).thenReturn(List.of(certificate)); - IamQueryHandler handler = new IamQueryHandler(service, null, null, null, null, null, null, null, null); + IamQueryHandler handler = new IamQueryHandler(service, null, null, null, null, null, null, null, null, null); MultivaluedMap params = new MultivaluedHashMap<>(); params.putSingle("ServerCertificateName", CERTIFICATE_NAME); @@ -90,7 +90,7 @@ class IamQueryHandlerTest { IamService service = mock(IamService.class); when(service.createRole(ROLE_NAME, "/", "{}", null, 3600, Map.of(), null)).thenReturn(role); when(service.getValidatedRole(ROLE_NAME)).thenReturn(role); - IamQueryHandler handler = new IamQueryHandler(service, null, null, null, null, null, null, null, null); + IamQueryHandler handler = new IamQueryHandler(service, null, null, null, null, null, null, null, null, null); MultivaluedMap params = new MultivaluedHashMap<>(); params.putSingle("RoleName", ROLE_NAME); diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/StsAssumeRootEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/StsAssumeRootEnforcementIntegrationTest.java new file mode 100644 index 0000000000..f96d9c094a --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/iam/StsAssumeRootEnforcementIntegrationTest.java @@ -0,0 +1,132 @@ +package io.github.hectorvent.floci.services.iam; + +import io.github.hectorvent.floci.testing.EnforcementFixtures; +import io.github.hectorvent.floci.testing.OrganizationsRequests; +import io.github.hectorvent.floci.testing.PartitionCleanup; +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.github.hectorvent.floci.testing.S3IamEnforcementProfile; +import io.quarkus.test.common.http.TestHTTPResource; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.restassured.response.ExtractableResponse; +import io.restassured.response.Response; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import java.net.URI; +import java.util.UUID; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; + +/** + * What a privileged session may do, under IAM enforcement. The session is the member account's + * root user, which no identity policy grants or denies, so the whole of the bound is the task + * policy the request named: "you must define TaskPolicyArn to scope the session to the privileged + * action to be performed during the session". + * + *

{@code IAMAuditRootUserCredentials} is the one used here. It denies every action it does not + * name and then denies the ones it does on any resource but {@code arn:aws:iam::*:root}, so one + * policy shows both halves of the scope: the audit reads it allows on the root user, and + * everything else refused. + */ +@QuarkusTest +@TestProfile(S3IamEnforcementProfile.class) +class StsAssumeRootEnforcementIntegrationTest { + + private static final String MANAGEMENT = "777777777771"; + private static final String TASK_POLICY = "arn:aws:iam::aws:policy/root-task/IAMAuditRootUserCredentials"; + + @TestHTTPResource("/") + static URI baseUri; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void aPrivilegedSessionMayAuditTheRootUserAndNothingElse() { + String member = memberAccountWithRootSessions(); + ExtractableResponse session = privilegedSession(member, callerWithAssumeRoot()); + String accessKeyId = session.path("AssumeRootResponse.AssumeRootResult.Credentials.AccessKeyId"); + String sessionToken = session.path("AssumeRootResponse.AssumeRootResult.Credentials.SessionToken"); + + // Allowed: the policy's first statement denies every action it does not name, and the + // account summary is one it names, on no particular resource. + privileged(accessKeyId, sessionToken, "GetAccountSummary") + .when().post("/").then().statusCode(200); + + // Denied on any resource but the root user, which is the policy's second statement. The + // audit reads it allows with no UserName name that root user here, since a root caller's + // self-resource is its root ARN, but Floci keeps no user record for the root user, so + // those calls answer NoSuchEntity rather than the credentials report AWS gives. + privileged(accessKeyId, sessionToken, "GetUser") + .formParam("UserName", "someone-else") + .when().post("/").then().statusCode(403) + .body("ErrorResponse.Error.Code", equalTo("AccessDenied")); + // And denied outright for an action the policy does not name, which is its first. + privileged(accessKeyId, sessionToken, "CreateUser") + .formParam("UserName", "made-by-a-privileged-session") + .when().post("/").then().statusCode(403) + .body("ErrorResponse.Error.Code", equalTo("AccessDenied")); + } + + /** An organization with one member account and {@code RootSessions} enabled. */ + private String memberAccountWithRootSessions() { + OrganizationsRequests.request(MANAGEMENT, "CreateOrganization", "{\"FeatureSet\":\"ALL\"}") + .when().post("/").then().statusCode(200); + String member = OrganizationsRequests.request(MANAGEMENT, "CreateAccount", + "{\"Email\":\"audit@example.com\",\"AccountName\":\"Audit\"}") + .when().post("/").then().statusCode(200) + .extract().jsonPath().getString("CreateAccountStatus.AccountId"); + OrganizationsRequests.request(MANAGEMENT, "EnableAWSServiceAccess", + "{\"ServicePrincipal\":\"iam.amazonaws.com\"}") + .when().post("/").then().statusCode(200); + given().header("Authorization", EnforcementFixtures.auth(MANAGEMENT, "iam")) + .formParam("Action", "EnableOrganizationsRootSessions") + .formParam("Version", "2010-05-08") + .when().post("/").then().statusCode(200); + return member; + } + + /** + * An IAM user of the management account allowed {@code sts:AssumeRoot}, which is the caller the + * guide's prerequisites ask for. The account root cannot be it, AssumeRoot refusing root + * credentials, so under enforcement the permission is granted to somebody rather than + * inherited from the account's own allow-all. + */ + private String callerWithAssumeRoot() { + String userName = "root-session-caller-" + UUID.randomUUID(); + String authorization = EnforcementFixtures.auth(MANAGEMENT, "iam"); + String accessKeyId = EnforcementFixtures + .createUser(cleanup, baseUri.getPort(), authorization, userName).accessKeyId(); + EnforcementFixtures.putUserPolicy(baseUri.getPort(), authorization, userName, "assume-root", + "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"," + + "\"Action\":\"sts:AssumeRoot\",\"Resource\":\"*\"}]}"); + return accessKeyId; + } + + private ExtractableResponse privilegedSession(String member, String callerKey) { + return given() + .header("Authorization", EnforcementFixtures.auth(callerKey, "sts")) + .formParam("Action", "AssumeRoot") + .formParam("Version", "2011-06-15") + .formParam("TargetPrincipal", member) + .formParam("TaskPolicyArn.arn", TASK_POLICY) + .when().post("/").then().statusCode(200).extract(); + } + + private static RequestSpecification privileged(String accessKeyId, String sessionToken, String action) { + return given() + .header("Authorization", EnforcementFixtures.auth(accessKeyId, "iam")) + .header("X-Amz-Security-Token", sessionToken) + .formParam("Action", action) + .formParam("Version", "2010-05-08"); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/StsAssumeRootIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/StsAssumeRootIntegrationTest.java new file mode 100644 index 0000000000..8777fb3a74 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/iam/StsAssumeRootIntegrationTest.java @@ -0,0 +1,308 @@ +package io.github.hectorvent.floci.services.iam; + +import io.github.hectorvent.floci.testing.EnforcementFixtures; +import io.github.hectorvent.floci.testing.OrganizationsRequests; +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.api.TestMethodOrder; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.startsWith; + +/** + * Centralized root access end to end: the management account turns the feature on, a delegated + * administrator sees the same organization-wide answer, and a privileged session acts as a member + * account's root user scoped to the task policy it names. + * + *

Floci resolves a 12-digit access key id straight to an account id, so each request carries a + * SigV4-shaped {@code Authorization} header naming the calling account. The accounts here are + * their own, so this class never contends with another over one organization. + */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class StsAssumeRootIntegrationTest { + + private static final String MANAGEMENT = "666666666661"; + private static final String OUTSIDER = "666666666669"; + private static final String UNRELATED_ACCOUNT = "666666666668"; + private static final String TASK_POLICY = "arn:aws:iam::aws:policy/root-task/S3UnlockBucketPolicy"; + + private String organizationId; + private String memberAccount; + private String delegatedAdmin; + private String managementKey; + private String adminKey; + private String outsiderKey; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + /** + * An IAM user of {@code accountId} holding one access key. AssumeRoot refuses the account root, + * both the key that resolves to its ARN and the bare account-id key floci reads as that + * principal, so every caller here is a user of the account rather than the account itself. + */ + private static String accessKeyFor(String accountId, String userName) { + iam(accountId, "CreateUser").formParam("UserName", userName) + .when().post("/").then().statusCode(200); + return iam(accountId, "CreateAccessKey").formParam("UserName", userName) + .when().post("/").then().statusCode(200) + .extract().path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.AccessKeyId"); + } + + private static RequestSpecification iam(String accountId, String action) { + return given() + .header("Authorization", EnforcementFixtures.auth(accountId, "iam")) + .formParam("Action", action) + .formParam("Version", "2010-05-08"); + } + + private static RequestSpecification assumeRoot(String accessKeyId, String targetPrincipal, + String taskPolicyArn) { + return given() + .header("Authorization", EnforcementFixtures.auth(accessKeyId, "sts")) + .formParam("Action", "AssumeRoot") + .formParam("Version", "2011-06-15") + .formParam("TargetPrincipal", targetPrincipal) + .formParam("TaskPolicyArn.arn", taskPolicyArn); + } + + @Test + @Order(1) + void anOrganizationWithAMemberAndADelegatedAdministrator() { + organizationId = OrganizationsRequests.request(MANAGEMENT, "CreateOrganization", "{\"FeatureSet\":\"ALL\"}") + .when().post("/").then().statusCode(200) + .extract().jsonPath().getString("Organization.Id"); + + memberAccount = OrganizationsRequests.request(MANAGEMENT, "CreateAccount", + "{\"Email\":\"member@example.com\",\"AccountName\":\"Member\"}") + .when().post("/").then().statusCode(200) + .extract().jsonPath().getString("CreateAccountStatus.AccountId"); + delegatedAdmin = OrganizationsRequests.request(MANAGEMENT, "CreateAccount", + "{\"Email\":\"iam-admin@example.com\",\"AccountName\":\"IamAdmin\"}") + .when().post("/").then().statusCode(200) + .extract().jsonPath().getString("CreateAccountStatus.AccountId"); + + OrganizationsRequests.request(MANAGEMENT, "EnableAWSServiceAccess", + "{\"ServicePrincipal\":\"iam.amazonaws.com\"}") + .when().post("/").then().statusCode(200); + OrganizationsRequests.request(MANAGEMENT, "RegisterDelegatedAdministrator", + "{\"AccountId\":\"" + delegatedAdmin + "\",\"ServicePrincipal\":\"iam.amazonaws.com\"}") + .when().post("/").then().statusCode(200); + + managementKey = accessKeyFor(MANAGEMENT, "root-session-caller"); + adminKey = accessKeyFor(delegatedAdmin, "delegated-session-caller"); + outsiderKey = accessKeyFor(OUTSIDER, "outsider-session-caller"); + } + + /** "You have enabled centralized root access in your organization" is a prerequisite, not a default. */ + @Test + @Order(2) + void aPrivilegedSessionIsRefusedBeforeRootSessionsIsEnabled() { + assumeRoot(managementKey, memberAccount, TASK_POLICY) + .when().post("/").then().statusCode(403) + .body("ErrorResponse.Error.Code", equalTo("AccessDenied")); + } + + @Test + @Order(3) + void theManagementAccountEnablesRootSessions() { + iam(MANAGEMENT, "EnableOrganizationsRootSessions") + .when().post("/").then().statusCode(200) + .body("EnableOrganizationsRootSessionsResponse.EnableOrganizationsRootSessionsResult" + + ".OrganizationId", equalTo(organizationId)) + .body("EnableOrganizationsRootSessionsResponse.EnableOrganizationsRootSessionsResult" + + ".EnabledFeatures.member", equalTo("RootSessions")); + } + + /** The feature set is the organization's, so the delegated administrator reads what was enabled. */ + @Test + @Order(4) + void aDelegatedAdministratorSeesTheOrganizationsOwnFeatureSet() { + iam(delegatedAdmin, "ListOrganizationsFeatures") + .when().post("/").then().statusCode(200) + .body("ListOrganizationsFeaturesResponse.ListOrganizationsFeaturesResult.OrganizationId", + equalTo(organizationId)) + .body("ListOrganizationsFeaturesResponse.ListOrganizationsFeaturesResult" + + ".EnabledFeatures.member", equalTo("RootSessions")); + } + + @Test + @Order(5) + void onlyTheRightCallerMayMoveTheFeatures() { + iam(delegatedAdmin, "EnableOrganizationsRootCredentialsManagement") + .when().post("/").then().statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("CallerIsNotManagementAccountException")); + iam(memberAccount, "ListOrganizationsFeatures") + .when().post("/").then().statusCode(400) + .body("ErrorResponse.Error.Code", + equalTo("AccountNotManagementOrDelegatedAdministratorException")); + iam(OUTSIDER, "ListOrganizationsFeatures") + .when().post("/").then().statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("OrganizationNotFoundException")); + } + + @Test + @Order(6) + void aPrivilegedSessionActsAsTheMemberAccountRoot() { + String accessKeyId = assumeRoot(managementKey, memberAccount, TASK_POLICY) + .formParam("DurationSeconds", "900") + .when().post("/").then().statusCode(200) + .body("AssumeRootResponse.AssumeRootResult.Credentials.AccessKeyId", startsWith("ASIA")) + .body("AssumeRootResponse.AssumeRootResult.Credentials.Expiration", notNullValue()) + .body("AssumeRootResponse.AssumeRootResult.SessionTokenSize", notNullValue()) + .extract().path("AssumeRootResponse.AssumeRootResult.Credentials.AccessKeyId"); + String sessionToken = assumeRoot(managementKey, memberAccount, TASK_POLICY) + .when().post("/").then().statusCode(200) + .extract().path("AssumeRootResponse.AssumeRootResult.Credentials.SessionToken"); + + given() + .header("Authorization", EnforcementFixtures.auth(accessKeyId, "sts")) + .header("X-Amz-Security-Token", sessionToken) + .formParam("Action", "GetCallerIdentity") + .formParam("Version", "2011-06-15") + .when().post("/").then().statusCode(200) + .body("GetCallerIdentityResponse.GetCallerIdentityResult.Account", equalTo(memberAccount)) + .body("GetCallerIdentityResponse.GetCallerIdentityResult.Arn", + equalTo("arn:aws:iam::" + memberAccount + ":root")); + } + + @Test + @Order(7) + void aDelegatedAdministratorMayOpenOneToo() { + assumeRoot(adminKey, memberAccount, TASK_POLICY) + .when().post("/").then().statusCode(200) + .body("AssumeRootResponse.AssumeRootResult.Credentials.AccessKeyId", startsWith("ASIA")); + } + + @Test + @Order(8) + void theCallerTheTargetAndTheTaskPolicyAreAllChecked() { + assumeRoot(outsiderKey, memberAccount, TASK_POLICY) + .when().post("/").then().statusCode(403) + .body("ErrorResponse.Error.Code", equalTo("AccessDenied")); + assumeRoot(managementKey, UNRELATED_ACCOUNT, TASK_POLICY) + .when().post("/").then().statusCode(403) + .body("ErrorResponse.Error.Code", equalTo("AccessDenied")); + // Privileged tasks are what the management account performs on members, not on itself. + assumeRoot(managementKey, MANAGEMENT, TASK_POLICY) + .when().post("/").then().statusCode(403) + .body("ErrorResponse.Error.Code", equalTo("AccessDenied")); + assumeRoot(managementKey, memberAccount, "arn:aws:iam::aws:policy/AdministratorAccess") + .when().post("/").then().statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("ValidationError")); + assumeRoot(managementKey, memberAccount, TASK_POLICY) + .formParam("DurationSeconds", "901") + .when().post("/").then().statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("ValidationError")); + given() + .header("Authorization", EnforcementFixtures.auth(managementKey, "sts")) + .formParam("Action", "AssumeRoot") + .formParam("Version", "2011-06-15") + .formParam("TaskPolicyArn.arn", TASK_POLICY) + .when().post("/").then().statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("ValidationError")); + } + + /** + * "The global endpoint is not supported for AssumeRoot. You must send this request to a + * Regional AWS STS endpoint." Floci can only see that when the request names the global host, + * which is why the refusal is on the host rather than on the signing region. + */ + @Test + @Order(9) + void theGlobalEndpointIsRefusedWhenTheRequestArrivesOnIt() { + assumeRoot(managementKey, memberAccount, TASK_POLICY) + .header("Host", "sts.amazonaws.com") + .when().post("/").then().statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("ValidationError")); + } + + /** The five task policies the guide names all live under the one path the check reads. */ + @Test + @Order(10) + void everyTaskPolicyTheGuideNamesIsUsable() { + for (String policy : new String[] {"IAMAuditRootUserCredentials", "IAMCreateRootUserPassword", + "IAMDeleteRootUserCredentials", "S3UnlockBucketPolicy", "SQSUnlockQueuePolicy"}) { + assumeRoot(managementKey, memberAccount, "arn:aws:iam::aws:policy/root-task/" + policy) + .when().post("/").then().statusCode(200) + .body("AssumeRootResponse.AssumeRootResult.Credentials.SessionToken", notNullValue()); + } + iam(MANAGEMENT, "ListOrganizationsFeatures") + .when().post("/").then().statusCode(200) + .body("ListOrganizationsFeaturesResponse.ListOrganizationsFeaturesResult" + + ".EnabledFeatures.member", equalTo("RootSessions")); + } + + /** + * A customer-managed policy can carry the {@code /root-task/} path as easily as AWS's own, so + * whose policy it is decides and not only where it sits: the model names five AWS managed + * policies, and a document of the caller's own would scope the session to whatever it allows. + */ + @Test + @Order(11) + void onlyAwsOwnRootTaskPoliciesCanScopeASession() { + String ownPolicy = iam(MANAGEMENT, "CreatePolicy") + .formParam("PolicyName", "LooksLikeATaskPolicy") + .formParam("Path", "/root-task/") + .formParam("PolicyDocument", "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\"" + + ":\"Allow\",\"Action\":\"*\",\"Resource\":\"*\"}]}") + .when().post("/").then().statusCode(200) + .extract().path("CreatePolicyResponse.CreatePolicyResult.Policy.Arn"); + + assumeRoot(managementKey, memberAccount, ownPolicy) + .when().post("/").then().statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("ValidationError")); + } + + /** + * {@code MinimumSessionTokenSize} is 0 to 4096 in the model, "The value must not exceed 4,096 + * bytes", and the size it asks for is the size issued, so it is held to that bound rather than + * clamped to it. + */ + @Test + @Order(12) + void theMinimumSessionTokenSizeIsHeldToTheBoundTheModelDeclares() { + assumeRoot(managementKey, memberAccount, TASK_POLICY) + .formParam("MinimumSessionTokenSize", "4097") + .when().post("/").then().statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("ValidationError")); + assumeRoot(managementKey, memberAccount, TASK_POLICY) + .formParam("MinimumSessionTokenSize", "-1") + .when().post("/").then().statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("ValidationError")); + assumeRoot(managementKey, memberAccount, TASK_POLICY) + .formParam("MinimumSessionTokenSize", "two thousand") + .when().post("/").then().statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("InvalidParameterValue")); + assumeRoot(managementKey, memberAccount, TASK_POLICY) + .formParam("MinimumSessionTokenSize", "1024") + .when().post("/").then().statusCode(200) + .body("AssumeRootResponse.AssumeRootResult.SessionTokenSize", equalTo("1024")); + } + + /** + * "You cannot use root user credentials to call sts:AssumeRoot." The bare account-id key is + * floci's own account-root principal, which {@code IamEnforcementFilter} says in as many words, so it + * is refused here as the credential it stands for even though it resolves to no ARN. + */ + @Test + @Order(13) + void theAccountRootCannotOpenAPrivilegedSession() { + assumeRoot(MANAGEMENT, memberAccount, TASK_POLICY) + .when().post("/").then().statusCode(403) + .body("ErrorResponse.Error.Code", equalTo("AccessDenied")) + .body("ErrorResponse.Error.Message", startsWith("Root user credentials cannot call")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/StsQueryHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/StsQueryHandlerTest.java index a6f51f17a3..5113348e95 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/StsQueryHandlerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/StsQueryHandlerTest.java @@ -107,6 +107,7 @@ class StsQueryHandlerTest { mock(SAMLProviderService.class), mock(SAMLTrustPolicyEvaluator.class), delegation, + mock(CentralRootAccess.class), clock); } @@ -661,7 +662,7 @@ class StsQueryHandlerTest { StsQueryHandler handler = new StsQueryHandler(iamService, mock(AccountResolver.class), new RegionResolver(REGION, "000000000000"), config, mock(AssumeRolePolicyEvaluator.class), trust, verifier, keys, mock(SAMLProviderService.class), mock(SAMLTrustPolicyEvaluator.class), - mock(DelegationRequestService.class)); + mock(DelegationRequestService.class), mock(CentralRootAccess.class)); MultivaluedMap params = new MultivaluedHashMap<>(); params.putSingle("RoleArn", requestedRoleArn); params.putSingle("RoleSessionName", "app"); diff --git a/src/test/java/io/github/hectorvent/floci/testing/OrganizationsRequests.java b/src/test/java/io/github/hectorvent/floci/testing/OrganizationsRequests.java new file mode 100644 index 0000000000..71826f21c5 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/testing/OrganizationsRequests.java @@ -0,0 +1,27 @@ +package io.github.hectorvent.floci.testing; + +import io.restassured.specification.RequestSpecification; + +import static io.restassured.RestAssured.given; + +/** + * Organizations calls over its JSON 1.1 wire, signed as the calling account the way + * {@link EnforcementFixtures#auth} signs every other fixture here. + */ +public final class OrganizationsRequests { + + private static final String CONTENT_TYPE = "application/x-amz-json-1.1"; + private static final String TARGET_PREFIX = "AWSOrganizationsV20161128."; + + private OrganizationsRequests() { + } + + /** One call, named by its action, carrying {@code body} as its payload. */ + public static RequestSpecification request(String accountId, String action, String body) { + return given() + .header("Authorization", EnforcementFixtures.auth(accountId, "organizations")) + .header("X-Amz-Target", TARGET_PREFIX + action) + .contentType(CONTENT_TYPE) + .body(body); + } +}