diff --git a/docs/services/iam.md b/docs/services/iam.md index 76d2c5ac78..d070f7735c 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -1210,26 +1210,32 @@ hold reports that user instead. Hardware TOTP tokens and FIDO security keys are not modeled, so `ListMFADevices` returns only virtual devices where AWS would return every type. -#### What a device does not yet affect +#### What a device affects -Enabling a device records state and nothing more. It does not change what a request is allowed to -do: +An enabled device is a device a session can be minted behind, and that session is what a statement +conditioned on MFA reads: -- **Policy evaluation ignores MFA.** `aws:MultiFactorAuthPresent` and `aws:MultiFactorAuthAge` are - never placed in the request context, so under [enforcement](#iam-enforcement-mode) a statement - conditioned on either key does not behave as it would on AWS. Both directions fail closed rather - than open: an `Allow` gated on `Bool: {"aws:MultiFactorAuthPresent": "true"}` never grants, - because a missing key fails the condition block; and the common - `Deny` + `BoolIfExists: {"aws:MultiFactorAuthPresent": "false"}` lockout idiom always denies, - because `IfExists` passes on a missing key. So an MFA-gated policy is stricter than AWS here, not - laxer, but a device being enabled will not unlock it. -- **No MFA-authenticated credentials.** `GetSessionToken` and `AssumeRole` accept `SerialNumber` - and `TokenCode` on AWS and return credentials that carry the MFA context keys. Floci's - [STS](sts.md) implementations ignore both parameters, so there is no way to obtain a session that - would satisfy an MFA condition even once the keys are populated. +- **Policy evaluation sees MFA.** `aws:MultiFactorAuthPresent` and `aws:MultiFactorAuthAge` are + placed in the request context from the credentials the request was signed with, as + [Condition keys floci populates](#condition-keys-floci-populates) describes: neither for a + long-term access key, the first alone and `false` for a session minted without a device, and both + for a session minted behind one. So under [enforcement](#iam-enforcement-mode) an `Allow` gated + on `Bool: {"aws:MultiFactorAuthPresent": "true"}` grants the MFA-authenticated requests and no + others, and the `Deny` + `BoolIfExists: {"aws:MultiFactorAuthPresent": "false"}` lockout idiom + denies everything else, long-term keys included, which is the behaviour the guide describes for + each shape. +- **MFA-authenticated credentials.** `GetSessionToken` and `AssumeRole` read `SerialNumber` and + `TokenCode`, hold the code to the seed of the device that serial names, spend that code so it + mints nothing further, and refuse a claim that does not hold with `AccessDenied`; see + [STS MFA](sts.md#mfa). A trust policy that tests for `aws:MultiFactorAuthPresent`, and the + caller's own permission to make the call, are both satisfied by the device the call presents. What + the session then carries differs by operation, as it does on AWS: a `GetSessionToken` session is + MFA-authenticated on its own requests, while an assumed-role session is not, "once the user has + assumed the role, no further MFA checks are made". -Both are out of scope here: this covers the device lifecycle only, and wiring MFA into -authorization means touching the request context and STS session shape, which is separate work. +What a device still does not reach is the console sign-in AWS also gates on one, there being no +sign-in here, and the hardware and FIDO device types above, so the device behind a session is +always a virtual one. ### Account @@ -3241,6 +3247,29 @@ floci populates: session, a federated user or the account root it is absent, and a statement that matches on it cannot match: an absent key has no equal or like value. That absence is the enforcement rather than a gap in it. +- `aws:MultiFactorAuthPresent` and `aws:MultiFactorAuthAge`: what the credentials the request was + signed with say about MFA. Both are "included in the request context only when the principal uses + temporary credentials to make the request", so a long-term access key carries **neither**, and a + statement matching on one cannot match such a request: that is why the guide recommends + `BoolIfExists` for a deny and warns that plain `Bool` on `false` "is not a reliable way to check + whether a request is authenticated using MFA". A session carries the first one either way, `true` + when it was minted behind an MFA device and `false` when it was not, the guide being explicit that + for temporary credentials without MFA "the `aws:MultiFactorAuthPresent` key is present in the + request and set to a value of `false`". The age is published only where there is an authentication + to measure, the key counting "the number of seconds since the requesting principal was authorized + using MFA", so a session that used no device carries no age rather than a zero one. Which sessions + can carry `true` is AWS's own line: "because temporary credentials returned by `GetSessionToken` + include MFA information, you can check for MFA in individual API operations made by the + credentials", while "the temporary credentials returned by `AssumeRole` do not include MFA + information in the context, so you cannot check individual API operations for MFA". So a role + session publishes `false` whatever device got it issued, since "once the user has assumed the role, + no further MFA checks are made", and a `GetFederationToken` session carries neither key, the guide + putting federated identities with the long-term keys: "This condition key is not present for + federated identities or requests made using access keys to sign AWS CLI, AWS API, or AWS SDK + requests." The device reaches a session through `SerialNumber` and `TokenCode` on + `GetSessionToken`, and decides an `AssumeRole` without outliving it; a call that presents one also + publishes the keys for that call itself, so the permission to make it can be conditioned on MFA. + See [STS MFA](sts.md#mfa). - `aws:TagKeys`: the case-sensitive requested tag keys for all 16 IAM tagging actions in the generated table (tag structures or a list of keys), EC2 `RunInstances` and `CreateTags`, S3 `PutBucketTagging`, S3 Control `TagResource` (its `Tags` body) and diff --git a/docs/services/sts.md b/docs/services/sts.md index cdcba80711..1317a5a4d4 100644 --- a/docs/services/sts.md +++ b/docs/services/sts.md @@ -304,6 +304,59 @@ key or one that belongs to another account, or by an IAM user since deleted and a valid credential: it is refused like an unknown access key. A key IAM does not know anywhere mints sessions that act as the account root, as the key itself does. +## MFA + +`GetSessionToken` and `AssumeRole` read `SerialNumber` and `TokenCode`. AWS describes the pair on +both: `SerialNumber` is "the identification number of the MFA device that is associated with the IAM +user who is making the GetSessionToken call", and `TokenCode` is "the value provided by the MFA +device", six digits. Floci holds the code to the seed of the virtual MFA device that serial names, +with the one step of drift `EnableMFADevice` allows, and the device has to be enabled for the +identity that signed the call: a serial naming a device enabled for somebody else authenticates +nobody. The window is the wall clock's, as it is on the IAM actions that take codes, since the code +comes from a device keeping time of its own rather than from the emulator's clock. + +A call that names neither parameter claims nothing and keeps whatever its own credentials carry, so +a session minted behind a device assumes a role as an MFA-authenticated caller without naming the +device again: "because temporary credentials returned by `GetSessionToken` include MFA information, +you can check for MFA in individual API operations made by the credentials". A call that names +either one is a claim of MFA and has to make it good, a code naming no device and a device with no +code both proving nothing, and the code is spent once it authenticates: RFC 6238 has a verifier +"MUST NOT accept the second attempt of the OTP generated for the same time step", so one code mints +one session rather than every session its window allows. A key IAM holds nowhere is the one caller +whose claim is taken as made, there being no identity behind it whose devices could be checked, +which is the reading Floci already takes of such a key everywhere else. A claim that fails is +refused with `AccessDenied` (403), +which is the outcome AWS documents ("an incorrect MFA code causes the API to return an access denied +error", and for `AssumeRole` "if the role being assumed requires MFA and if the TokenCode value is +missing or expired, the AssumeRole call returns an access denied error"). The sentence Floci writes +with it is its own, the one the IAM actions already write for a code that does not match, since AWS +publishes no message for this refusal. + +What the authentication then buys differs by operation, and AWS draws the line itself. A +`GetSessionToken` session carries it onward: a request signed with it has +`aws:MultiFactorAuthPresent` as `true` and `aws:MultiFactorAuthAge` as the seconds since the device +was used, which [IAM](iam.md#condition-keys-floci-populates) populates, "because temporary +credentials returned by `GetSessionToken` include MFA information, you can check for MFA in +individual API operations made by the credentials". An `AssumeRole` session does not: "the temporary +credentials returned by `AssumeRole` do not include MFA information in the context, so you cannot +check individual API operations for MFA", and "once the user has assumed the role, no further MFA +checks are made". So a role session publishes the key as `false` whatever device got it issued, and +Floci records none on it. + +The device a call presents is part of that request's own context, which is how a long-term key +reaches an MFA-protected role at all. A trust policy may require it, AWS's own example being +`"Condition": {"Bool": {"aws:MultiFactorAuthPresent": true}}`, and then "if the caller does not +include valid MFA information, the request to assume the role is denied". The caller's own +permission to make the call is read against that same context, since AWS denies such a request when +"users have not been MFA authenticated, or if they provide an invalid MFA device identifier or +invalid TOTP", so an identity policy conditioned on MFA for `sts:AssumeRole` is satisfied by the +device the call carries. + +One difference from AWS is known and open: AWS says temporary credentials from a `GetSessionToken` +request "can access IAM and AWS STS API operations *only* if you include MFA information in the +request for credentials". Floci does not hold a session to that: one minted without a device reaches +IAM and STS with whatever its user's policies allow. + ## Trust Policy Enforcement `AssumeRole` and `AssumeRoleWithWebIdentity` require the target role to exist in IAM, returning `AccessDenied` (403) diff --git a/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java b/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java index 451d79389d..98e004a3bf 100644 --- a/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java +++ b/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java @@ -45,6 +45,7 @@ import org.jboss.logging.Logger; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.time.Clock; +import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.HashMap; @@ -570,6 +571,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter { Optional callerArns = accountRootPrincipal ? Optional.of(accountRootArns(accountId)) : iamService.resolveCallerArns(akid); + callerArns = callerArns.map(arns -> withPresentedDevice(arns, action, ctx, akid)); if (callerArns.isPresent()) { caller = caller.withPrincipalArn(callerArns.get().callerArn()); conditionContext = conditionContext == null ? new HashMap<>() : new HashMap<>(conditionContext); @@ -1041,6 +1043,35 @@ public class IamEnforcementFilter implements ContainerRequestFilter { } /** Floci's account-root principal, which is both the caller and the request's aws:PrincipalArn. */ + /** + * The caller as this request authenticated it, which for the two operations that take a device + * includes the device the request itself presents. AWS "provides two API operations that let + * users pass MFA information: GetSessionToken and AssumeRole", and a policy on such a call is + * evaluated against the request carrying the device rather than against the credentials that + * signed it: "if a policy includes an MFA condition, a request is denied if users have not been + * MFA authenticated, or if they provide an invalid MFA device identifier or invalid TOTP". The + * refusal of a claim that fails belongs to the operation, which answers in its own namespace + * and reads the same claim this leaves on the request. + */ + private CallerArns withPresentedDevice(CallerArns caller, String action, + ContainerRequestContext ctx, String akid) { + if (!"sts:AssumeRole".equals(action) && !"sts:GetSessionToken".equals(action)) { + return caller; + } + Map form = IamConditionContextResolver.formParameters(ctx); + String serialNumber = form.get("SerialNumber"); + String tokenCode = form.get("TokenCode"); + if (serialNumber == null && tokenCode == null) { + return caller; + } + RequestMfaClaim claim = iamService.requestMfaClaim(requestContext, akid, serialNumber, tokenCode); + if (claim.authenticatedAt() == null) { + return caller; + } + return caller.withSessionMfa(new CallerArns.SessionMfa(true, + Math.max(0, Duration.between(claim.authenticatedAt(), clock.instant()).toSeconds()))); + } + private CallerArns accountRootArns(String accountId) { String rootArn = AwsArnUtils.Arn.global(requestPartition(), "iam", accountId, "root").toString(); return CallerArns.accountRoot(rootArn, accountId); diff --git a/src/main/java/io/floci/aws/core/common/RequestContext.java b/src/main/java/io/floci/aws/core/common/RequestContext.java index f7cb58fe93..bb7170993c 100644 --- a/src/main/java/io/floci/aws/core/common/RequestContext.java +++ b/src/main/java/io/floci/aws/core/common/RequestContext.java @@ -16,6 +16,12 @@ public class RequestContext { private String accessKeyId; private String sessionToken; private Boolean iamGovernanceBypass; + /** + * What this request's MFA members amounted to, or null until something asks. Held here because + * the enforcement filter and the STS operation both read it and a code is spent when it + * authenticates, so the two have to read one answer rather than each take their own. + */ + private RequestMfaClaim mfaClaim; public String getAccountId() { return accountId; @@ -68,6 +74,14 @@ public class RequestContext { * may bypass it, false when it overrides none, so no bypass permission was checked, and null when * IAM did not decide. S3Controller lets the operation bypass a lock only as far as this allows. */ + public RequestMfaClaim getMfaClaim() { + return mfaClaim; + } + + public void setMfaClaim(RequestMfaClaim mfaClaim) { + this.mfaClaim = mfaClaim; + } + public Boolean getIamGovernanceBypass() { return iamGovernanceBypass; } diff --git a/src/main/java/io/floci/aws/core/common/RequestMfaClaim.java b/src/main/java/io/floci/aws/core/common/RequestMfaClaim.java new file mode 100644 index 0000000000..4edd41a216 --- /dev/null +++ b/src/main/java/io/floci/aws/core/common/RequestMfaClaim.java @@ -0,0 +1,30 @@ +package io.floci.aws.core.common; + +import java.time.Instant; + +/** + * What one request's MFA members amount to: nothing claimed, a device presented and authenticated + * at an instant, or a claim that failed. + * + *

AWS "provides two API operations that let users pass MFA information: GetSessionToken and + * AssumeRole", and a claim either holds or is refused: "if a policy includes an MFA condition, a + * request is denied if users have not been MFA authenticated, or if they provide an invalid MFA + * device identifier or invalid TOTP". + * + *

It is read twice in one request and computed once, which is why it is held on the request + * rather than recomputed where it is needed. The enforcement filter needs it because the policy for + * the call is evaluated there, against the request that carries the device; the STS operation needs + * it because it answers the refusal and mints the session, and because it runs whether or not + * enforcement is on. Computing it twice would not do: a code is spent when it authenticates, so the + * second reading would find the step taken and refuse what the first allowed. + */ +public record RequestMfaClaim(boolean claimed, Instant authenticatedAt) { + + /** A request that named neither member, which claims nothing and refuses nothing. */ + public static final RequestMfaClaim NONE = new RequestMfaClaim(false, null); + + /** A claim this emulator could not make good, which is the operation's to answer. */ + public boolean failed() { + return claimed && authenticatedAt == null; + } +} diff --git a/src/main/java/io/floci/aws/services/iam/IamService.java b/src/main/java/io/floci/aws/services/iam/IamService.java index 5b256fdfc2..d5c8a0b82a 100644 --- a/src/main/java/io/floci/aws/services/iam/IamService.java +++ b/src/main/java/io/floci/aws/services/iam/IamService.java @@ -15,6 +15,8 @@ import io.floci.aws.core.common.AwsRegions; import io.floci.aws.core.common.CertificateMaterialException; import io.floci.aws.core.common.Pem; import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.common.RequestContext; +import io.floci.aws.core.common.RequestMfaClaim; import io.floci.aws.core.common.RequestScopes; import io.floci.aws.core.common.ServicePrincipals; import io.floci.aws.core.common.SessionAccountLookup; @@ -81,6 +83,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.OptionalLong; import java.util.Set; import java.util.UUID; import java.util.WeakHashMap; @@ -4585,6 +4588,121 @@ public class IamService implements SessionAccountLookup, ResourceProvider { } } + /** + * The MFA claim of the request in flight, computed on the first ask and remembered on the + * request for every later one, since a code is spent when it authenticates and the filter and + * the operation both have to read one answer. + */ + public RequestMfaClaim requestMfaClaim(RequestContext requestContext, String accessKeyId, + String serialNumber, String tokenCode) { + RequestMfaClaim remembered = requestContext == null ? null : requestContext.getMfaClaim(); + if (remembered != null) { + return remembered; + } + RequestMfaClaim claim = claimMfa(accessKeyId, serialNumber, tokenCode); + if (requestContext != null) { + requestContext.setMfaClaim(claim); + } + return claim; + } + + /** + * What the MFA members of one request amount to. A request naming neither claims nothing. One + * naming either is a claim and has to make it good, since a code naming no device and a device + * with no code both prove nothing, and the device has to be one the caller can present: AWS + * takes the device "that is associated with the IAM user who is making the GetSessionToken + * call", so a serial naming a device enabled for somebody else authenticates nobody. + * + *

A key IAM does not hold is the one caller whose claim is taken as made. There is no + * identity behind such a key and so no device of its own to check, and this emulator already + * reads those keys as the account root acting as itself rather than as nobody: refusing the + * claim instead would leave a client configured with an MFA profile unable to mint a session + * against the default credentials at all. + * + *

The code is held to the device's own seed, as {@code EnableMFADevice} and + * {@code ResyncMFADevice} hold theirs, with the same one step of drift the enable path allows, + * and the step it matched is then spent: RFC 6238 says a verifier "MUST NOT accept the second + * attempt of the OTP generated for the same time step", so the same code cannot mint a second + * session inside its window. The check and the spending are one step under the device lock, so + * two racing calls cannot both take the same step. + * + *

The window is the wall clock's rather than this service's, which is the reading the two + * IAM actions take as well: the code was produced by a device keeping time of its own, so the + * step it was generated for is a fact about the world and not about the emulator. What the + * service clock does measure is the age of the authentication afterwards, which is its own to + * tell and moves with it. + */ + RequestMfaClaim claimMfa(String accessKeyId, String serialNumber, String tokenCode) { + if (serialNumber == null && tokenCode == null) { + return RequestMfaClaim.NONE; + } + if (serialNumber == null || tokenCode == null) { + return new RequestMfaClaim(true, null); + } + Optional userName = mfaUserName(accessKeyId); + if (userName.isEmpty()) { + return new RequestMfaClaim(true, holdsKey(accessKeyId) ? null : clock.instant()); + } + synchronized (mfaDeviceLock) { + Optional device = virtualMfaDevices.get(serialNumber) + .filter(candidate -> userName.get().equals(candidate.getUserName())); + if (device.isEmpty()) { + return new RequestMfaClaim(true, null); + } + OptionalLong step = Totp.matchingStep(device.get().getBase32Seed(), tokenCode, + ENABLE_DRIFT_STEPS, Instant.now()); + Long spent = device.get().getLastUsedTotpStep(); + if (step.isEmpty() || (spent != null && step.getAsLong() <= spent)) { + return new RequestMfaClaim(true, null); + } + device.get().setLastUsedTotpStep(step.getAsLong()); + virtualMfaDevices.put(serialNumber, device.get()); + return new RequestMfaClaim(true, clock.instant()); + } + } + + /** + * The user whose devices a credential may present, which is the user an access key belongs to + * and, for a session that acts as the identity that minted it, that identity. A role session + * reaches no device: a device is enabled for a user, and the role is not one. + */ + private Optional mfaUserName(String accessKeyId) { + Optional accessKey = accessKeys.get(accessKeyId); + if (accessKey.isPresent()) { + return users.get(accessKey.get().getUserName()).map(IamUser::getUserName); + } + return findSessionForCallerContext(accessKeyId) + .filter(session -> session.getRoleArn() == null) + .flatMap(this::issuingUser) + .map(IamUser::getUserName); + } + + /** + * Records that the session {@code sessionAccessKeyId} names was minted behind an MFA device + * used at {@code authenticatedAt}, which is what its requests then publish as + * {@code aws:MultiFactorAuthPresent} and count {@code aws:MultiFactorAuthAge} from. + */ + public void recordSessionMfa(String sessionAccessKeyId, Instant authenticatedAt) { + if (sessionAccessKeyId == null || authenticatedAt == null) { + return; + } + sessions.get(sessionAccessKeyId).ifPresent(session -> { + session.setMfaAuthenticatedAt(authenticatedAt); + sessions.put(sessionAccessKeyId, session); + }); + } + + /** + * When the credentials {@code accessKeyId} names last authenticated with an MFA device, empty + * for a session minted without one and for every long-term key. A session assumed from such a + * session inherits the instant rather than taking the instant of the assume, so the age the + * new session publishes keeps counting from the authentication itself. + */ + public Optional callerMfaAuthenticatedAt(String accessKeyId) { + return findSessionForCallerContext(accessKeyId) + .flatMap(session -> Optional.ofNullable(session.getMfaAuthenticatedAt())); + } + // OIDC Identity Providers // ========================================================================= @@ -5813,12 +5931,38 @@ public class IamService implements SessionAccountLookup, ResourceProvider { */ public record CallerArns(String callerArn, String principalArn, String principalType, String userId, String userName, boolean permissionsBoundary, - Map principalTags) { + Map principalTags, SessionMfa sessionMfa) { public CallerArns { principalTags = Map.copyOf(principalTags); } + /** + * What the credentials a request was signed with say about multi-factor authentication. + * {@code present} is the value of {@code aws:MultiFactorAuthPresent}, and + * {@code authAgeSeconds} is {@code aws:MultiFactorAuthAge}, meaningful only when the + * device was used. A null {@code SessionMfa} says the credentials publish neither key, + * which the guide gives long-term keys: "The aws:MultiFactorAuthPresent key is not present + * when an API or CLI command is called with long-term credentials, such as user access key + * pairs." + */ + public record SessionMfa(boolean present, long authAgeSeconds) { + } + + /** A caller whose credentials say nothing about MFA, which is every long-term key. */ + public CallerArns(String callerArn, String principalArn, String principalType, + String userId, String userName, boolean permissionsBoundary, + Map principalTags) { + this(callerArn, principalArn, principalType, userId, userName, permissionsBoundary, + principalTags, null); + } + + /** Copy of this caller with what the session it signed with says about MFA. */ + public CallerArns withSessionMfa(SessionMfa mfa) { + return new CallerArns(callerArn, principalArn, principalType, userId, userName, + permissionsBoundary, principalTags, mfa); + } + /** A caller without stored principal tags, including account-root and federated identities. */ public CallerArns(String callerArn, String principalArn, String principalType, String userId, String userName, boolean permissionsBoundary) { @@ -5875,6 +6019,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { */ public void putPrincipalKeys(Map> context) { context.put("aws:PrincipalArn", List.of(principalArn)); + putMfaKeys(context); if (principalType != null) { context.put("aws:PrincipalType", List.of(principalType)); } @@ -5886,6 +6031,31 @@ public class IamService implements SessionAccountLookup, ResourceProvider { } principalTags.forEach((key, value) -> context.put("aws:PrincipalTag/" + key, List.of(value))); } + + /** + * The two MFA keys, which say something only about temporary credentials. The guide gives + * {@code aws:MultiFactorAuthPresent} and {@code aws:MultiFactorAuthAge} the same + * availability, "included in the request context only when the principal uses temporary + * credentials to make the request", and is explicit that a session minted without a device + * still carries the first one: "In these cases, the aws:MultiFactorAuthPresent key is + * present in the request and set to a value of false." A long-term key carries neither, so + * a statement matching on one cannot match such a request at all, which is why the guide + * recommends {@code BoolIfExists} for a deny and warns that plain {@code Bool} on false + * "is not a reliable way to check whether a request is authenticated using MFA". + * + *

The age is published only where there is an authentication to measure: the key counts + * "the number of seconds since the requesting principal was authorized using MFA", so a + * session that used no device publishes no age rather than a zero one. + */ + private void putMfaKeys(Map> context) { + if (sessionMfa == null) { + return; + } + context.put("aws:MultiFactorAuthPresent", List.of(Boolean.toString(sessionMfa.present()))); + if (sessionMfa.present()) { + context.put("aws:MultiFactorAuthAge", List.of(Long.toString(sessionMfa.authAgeSeconds()))); + } + } } /** @@ -5954,48 +6124,76 @@ public class IamService implements SessionAccountLookup, ResourceProvider { deleteSession(accessKeyId, session); return Optional.empty(); } - if (session.getDelegatedApproverArn() != null) { - return delegatedApproverArns(session); - } - if (isFederatedUserSession(session)) { - // A federated user has no aws:username at all, only the account:name userid. - String federatedArn = session.getRoleArn(); - return Optional.of(new CallerArns(federatedArn, federatedArn, - CallerArns.TYPE_FEDERATED_USER, - sessionUserId(session).orElse(null), null)); - } - String roleArn = session.getRoleArn(); - if (roleArn == null) { - // GetSessionToken credentials act as the identity that minted them. - if (issuedByRoot(session)) { - // The account root's aws:userid is the account id, and it has no - // aws:username: the guide lists it as not present for this principal. - String issuerArn = session.getIssuerArn(); - return Optional.of(new CallerArns(issuerArn, issuerArn, - CallerArns.TYPE_ACCOUNT, - AwsArnUtils.accountOrDefault(issuerArn, regionResolver.getAccountId()), - null)); - } - 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 sessionArn = assumedRoleSessionArn(session, roleArn); - Optional role = roleFromArnOrName(roleArn); - return Optional.of(new CallerArns(sessionArn, roleArn, CallerArns.TYPE_ASSUMED_ROLE, - sessionUserId(session).orElse(null), null, - role.map(IamRole::getPermissionsBoundaryArn).isPresent(), - role.map(IamRole::getTags).orElse(Map.of()))); + // Whatever identity the session resolves to, the MFA state belongs to the credentials + // rather than to the identity, so it is attached once here instead of at each of the + // identities below. + CallerArns.SessionMfa mfa = sessionMfa(session); + return callerForSession(session).map(caller -> caller.withSessionMfa(mfa)); } return Optional.empty(); } + /** + * What the identity behind a session's credentials says about MFA, or null when the session + * publishes neither key. A federated user is one such session: the guide's note that the keys + * are "not present for federated identities or requests made using access keys to sign AWS + * CLI, AWS API, or AWS SDK requests" puts GetFederationToken credentials with the long-term + * keys rather than with the sessions that can carry a device. + */ + private CallerArns.SessionMfa sessionMfa(SessionCredential session) { + if (isFederatedUserSession(session)) { + return null; + } + Instant authenticatedAt = session.getMfaAuthenticatedAt(); + if (authenticatedAt == null) { + return new CallerArns.SessionMfa(false, 0); + } + long age = Duration.between(authenticatedAt, clock.instant()).toSeconds(); + return new CallerArns.SessionMfa(true, Math.max(0, age)); + } + + /** The identity a session's credentials act as, which is what its own fields record. */ + private Optional callerForSession(SessionCredential session) { + if (session.getDelegatedApproverArn() != null) { + return delegatedApproverArns(session); + } + if (isFederatedUserSession(session)) { + // A federated user has no aws:username at all, only the account:name userid. + String federatedArn = session.getRoleArn(); + return Optional.of(new CallerArns(federatedArn, federatedArn, + CallerArns.TYPE_FEDERATED_USER, + sessionUserId(session).orElse(null), null)); + } + String roleArn = session.getRoleArn(); + if (roleArn == null) { + // GetSessionToken credentials act as the identity that minted them. + if (issuedByRoot(session)) { + // The account root's aws:userid is the account id, and it has no + // aws:username: the guide lists it as not present for this principal. + String issuerArn = session.getIssuerArn(); + return Optional.of(new CallerArns(issuerArn, issuerArn, + CallerArns.TYPE_ACCOUNT, + AwsArnUtils.accountOrDefault(issuerArn, regionResolver.getAccountId()), + null)); + } + 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 sessionArn = assumedRoleSessionArn(session, roleArn); + Optional role = roleFromArnOrName(roleArn); + return Optional.of(new CallerArns(sessionArn, roleArn, CallerArns.TYPE_ASSUMED_ROLE, + sessionUserId(session).orElse(null), null, + role.map(IamRole::getPermissionsBoundaryArn).isPresent(), + role.map(IamRole::getTags).orElse(Map.of()))); + } + /** * The caller's {@code aws:PrincipalArn}. For an IAM user it is the user's ARN, as * {@link #resolveCallerArn} returns. For a role session AWS reports the ARN of the role that diff --git a/src/main/java/io/floci/aws/services/iam/StsQueryHandler.java b/src/main/java/io/floci/aws/services/iam/StsQueryHandler.java index 1c10103c52..c54fe1cd3b 100644 --- a/src/main/java/io/floci/aws/services/iam/StsQueryHandler.java +++ b/src/main/java/io/floci/aws/services/iam/StsQueryHandler.java @@ -14,6 +14,8 @@ import io.floci.aws.core.common.IamEnforcementFilter; import io.floci.aws.core.common.OidcIssuerKeyLookup; import io.floci.aws.core.common.QueryConstraintCheck; import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.common.RequestContext; +import io.floci.aws.core.common.RequestMfaClaim; import io.floci.aws.core.common.ResteasyRequests; import io.floci.aws.core.common.SmithyValidationErrors; import io.floci.aws.core.common.WebIdentityToken; @@ -35,6 +37,7 @@ import org.jboss.logging.Logger; import java.security.SecureRandom; import java.security.interfaces.RSAPublicKey; import java.time.Clock; +import java.time.Duration; import java.time.Instant; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; @@ -78,6 +81,7 @@ public class StsQueryHandler { private final DelegationRequestService delegationRequestService; private final CentralRootAccess centralRootAccess; private final WebIdentityTokenIssuer tokenIssuer; + private final RequestContext requestContext; private final Clock clock; /** CSPRNG for session secret keys and session tokens; ordinary IDs keep using {@link ThreadLocalRandom}. */ @@ -99,10 +103,11 @@ public class StsQueryHandler { SAMLTrustPolicyEvaluator samlTrustEvaluator, DelegationRequestService delegationRequestService, CentralRootAccess centralRootAccess, - WebIdentityTokenIssuer tokenIssuer) { + WebIdentityTokenIssuer tokenIssuer, + RequestContext requestContext) { this(iamService, accountResolver, regionResolver, config, trustPolicyEvaluator, webIdentityTrustEvaluator, tokenVerifier, oidcIssuerKeys, samlProviderService, samlTrustEvaluator, delegationRequestService, - centralRootAccess, tokenIssuer, Clock.systemUTC()); + centralRootAccess, tokenIssuer, requestContext, Clock.systemUTC()); } StsQueryHandler(IamService iamService, AccountResolver accountResolver, RegionResolver regionResolver, @@ -115,6 +120,7 @@ public class StsQueryHandler { DelegationRequestService delegationRequestService, CentralRootAccess centralRootAccess, WebIdentityTokenIssuer tokenIssuer, + RequestContext requestContext, Clock clock) { this.iamService = iamService; this.accountResolver = accountResolver; @@ -129,6 +135,7 @@ public class StsQueryHandler { this.delegationRequestService = delegationRequestService; this.centralRootAccess = centralRootAccess; this.tokenIssuer = tokenIssuer; + this.requestContext = requestContext; this.clock = clock; } @@ -161,6 +168,10 @@ public class StsQueryHandler { if (validation != null) { return validation; } + MfaOutcome mfa = authenticateMfa(params); + if (mfa.denial() != null) { + return mfa.denial(); + } String roleArn = getParam(params, "RoleArn"); String sessionName = getParam(params, "RoleSessionName"); int durationSeconds = getIntParam(params, "DurationSeconds", 3600); @@ -177,7 +188,7 @@ public class StsQueryHandler { String accountId = AwsArnUtils.accountOrDefault(roleArn, callerAccountId); IamRole role = iamService.findRole(accountId, roleName).orElse(null); - Response trustDenied = enforceTrustPolicy(roleArn, role, accountId, params); + Response trustDenied = enforceTrustPolicy(roleArn, role, accountId, params, mfa); if (trustDenied != null) { return trustDenied; } @@ -218,6 +229,62 @@ public class StsQueryHandler { return Response.ok(AwsQueryResponse.envelope("AssumeRole", AwsNamespaces.STS, result)).build(); } + /** + * What a call's MFA parameters authenticated: the instant the device was used, or the denial + * that answers a device the caller cannot present. Both {@code GetSessionToken} and + * {@code AssumeRole} take the same pair, {@code SerialNumber} naming "the identification + * number of the MFA device that is associated with the IAM user who is making the + * GetSessionToken call" and {@code TokenCode} carrying "the value provided by the MFA device". + * + *

A call that names neither claims nothing, and takes whatever its own credentials already + * carry, which is how a session minted behind a device assumes a role that tests for MFA + * without presenting the device again: "because temporary credentials returned by + * GetSessionToken include MFA information, you can check for MFA in individual API operations + * made by the credentials". A call that names either member is a claim of MFA and has to make + * it good; what answers a claim that fails is the access denied AWS documents for the case, + * "an incorrect MFA code causes the API to return an access denied error", carrying the + * sentence the IAM actions already write for a code that does not match. + * + *

The claim is read through the request's own holder rather than taken here, because the + * policy for this call was evaluated before the operation ran and had to see the same device, + * and because a code is spent when it authenticates: one request is one claim. + */ + private MfaOutcome authenticateMfa(MultivaluedMap params) { + String serialNumber = getParam(params, "SerialNumber"); + String tokenCode = getParam(params, "TokenCode"); + if (serialNumber == null && tokenCode == null) { + return new MfaOutcome(iamService.callerMfaAuthenticatedAt(callerAccessKeyId()).orElse(null), null); + } + RequestMfaClaim claim = + iamService.requestMfaClaim(requestContext, callerAccessKeyId(), serialNumber, tokenCode); + if (claim.failed()) { + return new MfaOutcome(null, AwsQueryResponse.error("AccessDenied", + "Invalid MFA one time pass code.", AwsNamespaces.STS, 403)); + } + return new MfaOutcome(claim.authenticatedAt(), null); + } + + /** The MFA a call authenticated, or the refusal it earned. */ + private record MfaOutcome(Instant authenticatedAt, Response denial) { + } + + /** + * Hands a {@code GetSessionToken} session the device behind it, so its own requests publish the + * two keys: "because temporary credentials returned by GetSessionToken include MFA + * information, you can check for MFA in individual API operations made by the credentials". + * + *

An assumed-role session is not given one, and this is not called there. AWS draws the line + * itself: "the temporary credentials returned by AssumeRole do not include MFA information in + * the context, so you cannot check individual API operations for MFA", and "once the user has + * assumed the role, no further MFA checks are made". The device decides the assume and stops + * there. + */ + private void recordIssuedSessionMfa(String sessionAccessKeyId, MfaOutcome mfa) { + if (mfa.authenticatedAt() != null) { + iamService.recordSessionMfa(sessionAccessKeyId, mfa.authenticatedAt()); + } + } + /** * When IAM enforcement is enabled, denies AssumeRole if the target role's trust policy does not * permit the caller. Returns {@code null} to allow when enforcement is disabled or the caller is @@ -235,11 +302,21 @@ public class StsQueryHandler { * principal does wherever else Floci builds it. */ private Response enforceTrustPolicy(String roleArn, IamRole role, String roleAccountId, - MultivaluedMap params) { + MultivaluedMap params, MfaOutcome mfa) { String callerAccount = regionResolver.getAccountId(); IamService.CallerArns caller = iamService.resolveCallerArns(callerAccessKeyId()) .orElseGet(() -> IamService.CallerArns.accountRoot( regionResolver.buildGlobalArn("iam", callerAccount, "root"), callerAccount)); + if (mfa.authenticatedAt() != null) { + // A device this call presented is this request's own authentication, which is how a + // long-term key reaches a role whose trust policy "includes a condition that tests for + // MFA authentication". It rides on the caller rather than onto the context, because the + // caller is what writes those keys wherever a policy is evaluated: written onto the + // context, a session that presented a fresh device would still be described by what it + // was minted with. + caller = caller.withSessionMfa(new IamService.CallerArns.SessionMfa(true, + Math.max(0, Duration.between(mfa.authenticatedAt(), clock.instant()).toSeconds()))); + } String callerArn = caller.callerArn(); if (role == null || !IamService.roleArnMatches(roleArn, role)) { @@ -251,15 +328,15 @@ public class StsQueryHandler { return null; } - Map> requestContext = IamConditionContextResolver.withGlobalContext( + Map> trustContext = IamConditionContextResolver.withGlobalContext( null, roleArn, regionResolver.getRegion(), callerAccount, roleAccountId); - requestContext.put("sts:RoleSessionName", List.of(getParam(params, "RoleSessionName"))); + trustContext.put("sts:RoleSessionName", List.of(getParam(params, "RoleSessionName"))); String externalId = getParam(params, "ExternalId"); if (externalId != null) { - requestContext.put("sts:ExternalId", List.of(externalId)); + trustContext.put("sts:ExternalId", List.of(externalId)); } if (trustPolicyEvaluator.allows(role.getAssumeRolePolicyDocument(), caller, callerAccount, - requestContext)) { + trustContext)) { return null; } return AwsQueryResponse.error("AccessDenied", @@ -347,6 +424,10 @@ public class StsQueryHandler { if (validation != null) { return validation; } + MfaOutcome mfa = authenticateMfa(params); + if (mfa.denial() != null) { + return mfa.denial(); + } int durationSeconds = longTermTokenDuration(params); String accessKeyId = "ASIA" + randomId(16); String secretKey = randomSecret(40); @@ -357,6 +438,7 @@ public class StsQueryHandler { // No role ARN: the credentials route back to the caller's account and act as the caller. iamService.registerIssuedSession(accessKeyId, secretKey, sessionToken, null, expiration, null, regionResolver.getAccountId(), callerAccessKeyId()); + recordIssuedSessionMfa(accessKeyId, mfa); return Response.ok(AwsQueryResponse.envelope("GetSessionToken", AwsNamespaces.STS, result)).build(); } diff --git a/src/main/java/io/floci/aws/services/iam/StsRequestShapes.java b/src/main/java/io/floci/aws/services/iam/StsRequestShapes.java index c90f887216..0c369d7746 100644 --- a/src/main/java/io/floci/aws/services/iam/StsRequestShapes.java +++ b/src/main/java/io/floci/aws/services/iam/StsRequestShapes.java @@ -25,7 +25,8 @@ import java.util.Map; * each one chosen where no operation answers a declared constraint in a wording of its own. * {@code GetAccessKeyInfo} is the parity case, its own check having answered {@code accessKeyId} * from the same bounds and the same pattern; {@code GetSessionToken} brings {@code SerialNumber}, - * {@code TokenCode} and {@code MinimumSessionTokenSize}, which nothing read at all; and + * {@code TokenCode} and {@code MinimumSessionTokenSize}, the first two of which the operation + * reads now, as a device and its code, while nothing reads the third; and * {@code GetWebIdentityToken} is where the audience and tag checks come off hand-written code. */ final class StsRequestShapes { diff --git a/src/main/java/io/floci/aws/services/iam/model/SessionCredential.java b/src/main/java/io/floci/aws/services/iam/model/SessionCredential.java index fceb390d2d..bdf098dcec 100644 --- a/src/main/java/io/floci/aws/services/iam/model/SessionCredential.java +++ b/src/main/java/io/floci/aws/services/iam/model/SessionCredential.java @@ -59,6 +59,16 @@ public class SessionCredential { * long-term half of temporary delegation: a role created with this session carries one. */ private List delegatedRoleBoundaryArns = new ArrayList<>(); + /** + * When the identity behind these credentials last authenticated with an MFA device, which is + * what {@code aws:MultiFactorAuthAge} counts from and what makes + * {@code aws:MultiFactorAuthPresent} true. Null for a session minted without MFA, which is a + * different thing from a long-term key: that session publishes the key as false, where a + * long-term key publishes no key at all. A session assumed from an MFA session keeps the + * instant the device was used rather than the instant of the assume, so the age keeps + * counting from the authentication itself. + */ + private Instant mfaAuthenticatedAt; public SessionCredential() {} @@ -171,4 +181,12 @@ public class SessionCredential { ? new ArrayList<>() : new ArrayList<>(delegatedRoleBoundaryArns); } public void setDelegatedApproverArn(String arn) { this.delegatedApproverArn = arn; } + + public Instant getMfaAuthenticatedAt() { + return mfaAuthenticatedAt; + } + + public void setMfaAuthenticatedAt(Instant mfaAuthenticatedAt) { + this.mfaAuthenticatedAt = mfaAuthenticatedAt; + } } diff --git a/src/main/java/io/floci/aws/services/iam/model/VirtualMfaDevice.java b/src/main/java/io/floci/aws/services/iam/model/VirtualMfaDevice.java index 9a8f7cd545..8781307b0f 100644 --- a/src/main/java/io/floci/aws/services/iam/model/VirtualMfaDevice.java +++ b/src/main/java/io/floci/aws/services/iam/model/VirtualMfaDevice.java @@ -30,9 +30,18 @@ public class VirtualMfaDevice { private Instant enableDate; private Instant createDate = Instant.now(); private Map tags = new ConcurrentHashMap<>(); + /** + * The last TOTP step this device authenticated an STS call with, or null while it has + * authenticated none. RFC 6238 says a verifier "MUST NOT accept the second attempt of the OTP + * generated for the same time step", so a step at or before this one is refused and one code + * cannot mint a second session inside its window. + */ + private Long lastUsedTotpStep; public VirtualMfaDevice() {} + public Long getLastUsedTotpStep() { return lastUsedTotpStep; } + public void setLastUsedTotpStep(Long lastUsedTotpStep) { this.lastUsedTotpStep = lastUsedTotpStep; } public String getSerialNumber() { return serialNumber; } public void setSerialNumber(String serialNumber) { this.serialNumber = serialNumber; } public String getDeviceName() { return deviceName; } diff --git a/src/test/java/io/floci/aws/services/iam/IamServiceTest.java b/src/test/java/io/floci/aws/services/iam/IamServiceTest.java index 8d2241e834..b3b93e8f99 100644 --- a/src/test/java/io/floci/aws/services/iam/IamServiceTest.java +++ b/src/test/java/io/floci/aws/services/iam/IamServiceTest.java @@ -499,9 +499,12 @@ class IamServiceTest { // The principal keys ride along from the same lookup: a role session is typed as an // assumed role, its aws:userid is the stored role-id:session-name, and it has no // aws:username, which the guide lists as not present for a role. + // It carries what its credentials say about MFA as well, which for a session minted + // without a device is the key present and false. assertEquals(new IamService.CallerArns("arn:aws:sts::123456789012:assumed-role/TestRole/s", "arn:aws:iam::123456789012:role/team/TestRole", - IamService.CallerArns.TYPE_ASSUMED_ROLE, "AROATESTROLEID:s", null), + IamService.CallerArns.TYPE_ASSUMED_ROLE, "AROATESTROLEID:s", null) + .withSessionMfa(new IamService.CallerArns.SessionMfa(false, 0)), service.resolveCallerArns("ASIALIVESESSION").orElseThrow()); // An expired session answers for neither, never for one and not the other. assertTrue(service.resolveCallerArns("ASIAEXPIREDSESSION").isEmpty()); @@ -743,7 +746,8 @@ class IamServiceTest { // Acting as the user means carrying the user's principal keys, aws:username included: // the guide gives one to an IAM user and to no other principal. assertEquals(new IamService.CallerArns(alice.getArn(), alice.getArn(), - IamService.CallerArns.TYPE_USER, alice.getUserId(), "alice"), + IamService.CallerArns.TYPE_USER, alice.getUserId(), "alice") + .withSessionMfa(new IamService.CallerArns.SessionMfa(false, 0)), service.resolveCallerArns("ASIASESSIONTOKEN").orElseThrow()); assertEquals(alice.getUserId(), service.resolveCallerUserId("ASIASESSIONTOKEN", "token").orElseThrow()); } @@ -762,7 +766,8 @@ class IamServiceTest { // present for the account root. assertEquals(new IamService.CallerArns("arn:aws:iam::000000000000:root", "arn:aws:iam::000000000000:root", IamService.CallerArns.TYPE_ACCOUNT, - "000000000000", null), + "000000000000", null) + .withSessionMfa(new IamService.CallerArns.SessionMfa(false, 0)), service.resolveCallerArns("ASIAROOTSESSION").orElseThrow()); } @@ -870,7 +875,9 @@ class IamServiceTest { assertFederatedUserLimits(withPolicy.identityPolicies().getLast()); assertEquals(ALL_S3, withPolicy.sessionPolicyDocument()); // The same aws:userid both ways, since one derivation now serves both readers, and no - // aws:username: the guide lists it as not present for a federated user. + // aws:username: the guide lists it as not present for a federated user. No MFA state + // either, the same guide putting federated identities with the long-term keys, so this + // session publishes neither MFA key where every other session publishes the first. assertEquals(new IamService.CallerArns(federatedArn, federatedArn, IamService.CallerArns.TYPE_FEDERATED_USER, "000000000000:Bob", null), service.resolveCallerArns("ASIAWITHPOLICY").orElseThrow()); diff --git a/src/test/java/io/floci/aws/services/iam/StsMfaEnforcementIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/StsMfaEnforcementIntegrationTest.java new file mode 100644 index 0000000000..2272eb7d22 --- /dev/null +++ b/src/test/java/io/floci/aws/services/iam/StsMfaEnforcementIntegrationTest.java @@ -0,0 +1,345 @@ +package io.floci.aws.services.iam; + +import io.floci.aws.core.common.Totp; +import io.floci.aws.testing.S3IamEnforcementProfile; +import io.floci.aws.testutil.S3RequestSigner; +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.response.ValidatableResponse; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.Base64; +import java.util.UUID; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; + +/** + * The two MFA condition keys, and the device a session is minted behind. + * + *

{@code aws:MultiFactorAuthPresent} says "whether multi-factor authentication (MFA) was used to + * validate the temporary security credentials that made the request", and both it and + * {@code aws:MultiFactorAuthAge} are "included in the request context only when the principal uses + * temporary credentials to make the request". A session minted without a device still carries the + * first one: "In these cases, the aws:MultiFactorAuthPresent key is present in the request and set + * to a value of false." A long-term key carries neither, which is why the guide recommends + * {@code BoolIfExists} for a deny and warns that plain {@code Bool} on false "is not a reliable way + * to check whether a request is authenticated using MFA". + * + *

The device reaches a session through {@code SerialNumber} and {@code TokenCode} on + * {@code GetSessionToken} and {@code AssumeRole}. A trust policy may require it, AWS's own example + * being {@code "Bool": {"aws:MultiFactorAuthPresent": true}}, and then "if the caller does not + * include valid MFA information, the request to assume the role is denied". + * + *

The two operations do not carry the authentication equally far, and AWS draws the line + * itself. "Because temporary credentials returned by GetSessionToken include MFA information, you + * can check for MFA in individual API operations made by the credentials", while "the temporary + * credentials returned by AssumeRole do not include MFA information in the context, so you cannot + * check individual API operations for MFA": the device decides the assume and stops there, since + * "once the user has assumed the role, no further MFA checks are made". + */ +@QuarkusTest +@TestProfile(S3IamEnforcementProfile.class) +class StsMfaEnforcementIntegrationTest { + + private static final String ACCOUNT = "000000000000"; + + private static final String CODE = "ErrorResponse.Error.Code"; + + /** Allows the listing only where the request was authenticated with a device. */ + private static final String LIST_WITH_MFA = """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":["iam:ListUsers","sts:GetSessionToken","sts:AssumeRole"], + "Resource":"*","Condition":{"Bool":{"aws:MultiFactorAuthPresent":"true"}}}, + {"Effect":"Allow","Action":["sts:GetSessionToken","sts:AssumeRole"],"Resource":"*"}]}"""; + + /** The guide's recommended shape: an allow, and a deny for anything not MFA-authenticated. */ + private static final String LIST_DENIED_WITHOUT_MFA = """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":["iam:ListUsers","sts:GetSessionToken"],"Resource":"*"}, + {"Effect":"Deny","Action":"iam:ListUsers","Resource":"*", + "Condition":{"BoolIfExists":{"aws:MultiFactorAuthPresent":"false"}}}]}"""; + + /** Allows the assume only where the request that makes it was authenticated with a device. */ + private static final String ASSUME_WITH_MFA = """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":"sts:AssumeRole","Resource":"*", + "Condition":{"Bool":{"aws:MultiFactorAuthPresent":"true"}}}]}"""; + + /** Allows the listing only while the authentication is recent. */ + private static final String LIST_WHILE_FRESH = """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":["iam:ListUsers","sts:GetSessionToken"],"Resource":"*", + "Condition":{"NumericLessThan":{"aws:MultiFactorAuthAge":"3600"}}}, + {"Effect":"Allow","Action":"sts:GetSessionToken","Resource":"*"}]}"""; + + @Test + void aSessionMintedBehindADeviceIsTheOneThatCarriesThePresentKeyAsTrue() { + String userName = unique("mfa-present"); + S3RequestSigner user = userWithPolicy(userName, LIST_WITH_MFA); + Device device = enabledDeviceFor(userName); + + // The same user, the same policy, two sessions: the key is the only difference between them. + listUsers(sessionWith(user, device), 200); + listUsers(sessionWith(user, null), 403); + // And the long-term key itself, which publishes no key at all, so a plain Bool cannot match. + listUsers(user, 403); + } + + @Test + void theDenyTheGuideRecommendsRefusesALongTermKeyAndAnMfaLessSession() { + String userName = unique("mfa-ifexists"); + S3RequestSigner user = userWithPolicy(userName, LIST_DENIED_WITHOUT_MFA); + Device device = enabledDeviceFor(userName); + + // "This combination of Deny, BoolIfExists, and false denies requests that are not + // authenticated using MFA... It also denies requests that are made using long-term + // credentials, such as AWS CLI or AWS API operations made using access keys." + listUsers(user, 403); + listUsers(sessionWith(user, null), 403); + listUsers(sessionWith(user, device), 200); + } + + @Test + void theAgeIsPublishedOnlyWhereThereIsAnAuthenticationToMeasure() { + String userName = unique("mfa-age"); + S3RequestSigner user = userWithPolicy(userName, LIST_WHILE_FRESH); + Device device = enabledDeviceFor(userName); + + // The device was just used, so the age is inside the hour the policy allows. + listUsers(sessionWith(user, device), 200); + // A session that used no device publishes no age, and a Numeric comparison on an absent + // key does not match, so the same statement cannot allow it. + listUsers(sessionWith(user, null), 403); + } + + @Test + void aCodeTheDeviceDidNotProduceAuthenticatesNothing() { + String userName = unique("mfa-code"); + S3RequestSigner user = userWithPolicy(userName, LIST_WITH_MFA); + Device device = enabledDeviceFor(userName); + + // "An incorrect MFA code causes the API to return an access denied error." + getSessionToken(user, device.serialNumber(), "000000").statusCode(403) + .body(CODE, equalTo("AccessDenied")); + // A device with no code proves nothing, and a code naming no device names nothing. + getSessionToken(user, device.serialNumber(), null).statusCode(403); + getSessionToken(user, null, device.codeNow()).statusCode(403); + // A device enabled for somebody else is not this caller's to present. + Device other = enabledDeviceFor(unique("mfa-other")); + getSessionToken(user, other.serialNumber(), other.codeNow()).statusCode(403); + } + + @Test + void aTrustPolicyThatTestsForMfaTakesTheDeviceTheAssumePresents() { + String userName = unique("mfa-trust"); + S3RequestSigner user = userWithPolicy(userName, LIST_WITH_MFA); + Device device = enabledDeviceFor(userName); + String roleName = unique("mfa-role"); + createRoleRequiringMfa(roleName, userName); + + // "If the caller does not include valid MFA information, the request to assume the role is + // denied", and a long-term key on its own carries none. + assumeRole(user, roleName, null, null).statusCode(403); + assumeRole(user, roleName, device.serialNumber(), device.codeNow()).statusCode(200); + } + + @Test + void aRoleSessionAssumedWithADeviceStillCarriesNoAuthenticationOfItsOwn() { + String userName = unique("mfa-chain-user"); + S3RequestSigner user = userWithPolicy(userName, LIST_WITH_MFA); + Device device = enabledDeviceFor(userName); + String roleName = unique("mfa-chain-role"); + createRoleRequiringMfa(roleName, userName); + + // The device got the caller through the trust policy, and that is as far as it goes: "the + // temporary credentials returned by AssumeRole do not include MFA information in the + // context, so you cannot check individual API operations for MFA". The role's own policy is + // the same MFA condition, and the session it minted cannot satisfy it. + S3RequestSigner roleSession = assumedSession(user, roleName, device); + listUsers(roleSession, 403); + } + + @Test + void aCodeThatMintedASessionMintsNoSecondOne() { + String userName = unique("mfa-replay"); + S3RequestSigner user = userWithPolicy(userName, LIST_WITH_MFA); + Device device = enabledDeviceFor(userName); + String code = device.codeNow(); + + getSessionToken(user, device.serialNumber(), code).statusCode(200); + // The code is still inside the window it was generated for, and spent: RFC 6238 has a + // verifier "MUST NOT accept the second attempt of the OTP generated for the same time + // step", so one code is one authentication. + getSessionToken(user, device.serialNumber(), code).statusCode(403) + .body(CODE, equalTo("AccessDenied")); + } + + @Test + void thePolicyForTheAssumeItselfSeesTheDeviceTheCallPresents() { + String userName = unique("mfa-identity"); + S3RequestSigner user = userWithPolicy(userName, ASSUME_WITH_MFA); + Device device = enabledDeviceFor(userName); + String roleName = unique("mfa-identity-role"); + createRoleTrustingUser(roleName, userName); + + // Nothing in the trust policy asks for MFA here: what does is the caller's own permission + // to call the operation, which is evaluated before the operation runs. AWS denies such a + // request when "users have not been MFA authenticated", and allows it on the device the + // call carries. + assumeRole(user, roleName, device.serialNumber(), device.codeNow()).statusCode(200); + assumeRole(user, roleName, null, null).statusCode(403); + } + + @Test + void aSessionMintedBehindADeviceAssumesARoleThatRequiresOneWithoutPresentingItAgain() { + String userName = unique("mfa-carry"); + S3RequestSigner user = userWithPolicy(userName, LIST_WITH_MFA); + Device device = enabledDeviceFor(userName); + String roleName = unique("mfa-carry-role"); + createRoleRequiringMfa(roleName, userName); + + // The session already authenticated with the device, so the assume it makes is an + // MFA-authenticated request though it names no device of its own. + assumeRole(sessionWith(user, device), roleName, null, null).statusCode(200); + // The session minted without one is refused by the same trust policy. + assumeRole(sessionWith(user, null), roleName, null, null).statusCode(403); + } + + /** A virtual device and its seed, which is what produces the codes a client sends. */ + private record Device(String serialNumber, String seed) { + + String codeNow() { + return Totp.codeAt(seed, Totp.stepAt(Instant.now())); + } + } + + private static void listUsers(S3RequestSigner caller, int status) { + given().filter(caller).formParam("Action", "ListUsers").formParam("Version", "2010-05-08") + .when().post("/").then().statusCode(status); + } + + private static ValidatableResponse getSessionToken(S3RequestSigner caller, String serialNumber, + String tokenCode) { + RequestSpecification request = given().filter(caller).formParam("Action", "GetSessionToken"); + if (serialNumber != null) { + request = request.formParam("SerialNumber", serialNumber); + } + if (tokenCode != null) { + request = request.formParam("TokenCode", tokenCode); + } + return request.when().post("/").then(); + } + + /** The caller's own session, minted behind {@code device} when one is given. */ + private static S3RequestSigner sessionWith(S3RequestSigner caller, Device device) { + ExtractableResponse issued = (device == null + ? getSessionToken(caller, null, null) + : getSessionToken(caller, device.serialNumber(), device.codeNow())) + .statusCode(200).extract(); + String base = "GetSessionTokenResponse.GetSessionTokenResult.Credentials."; + return S3RequestSigner.signedAs(issued.path(base + "AccessKeyId"), + issued.path(base + "SecretAccessKey"), issued.path(base + "SessionToken")); + } + + private static ValidatableResponse assumeRole(S3RequestSigner caller, String roleName, + String serialNumber, String tokenCode) { + RequestSpecification request = given().filter(caller).formParam("Action", "AssumeRole") + .formParam("RoleArn", "arn:aws:iam::" + ACCOUNT + ":role/" + roleName) + .formParam("RoleSessionName", "mfa-session"); + if (serialNumber != null) { + request = request.formParam("SerialNumber", serialNumber); + } + if (tokenCode != null) { + request = request.formParam("TokenCode", tokenCode); + } + return request.when().post("/").then(); + } + + private static S3RequestSigner assumedSession(S3RequestSigner caller, String roleName, Device device) { + ExtractableResponse issued = + assumeRole(caller, roleName, device.serialNumber(), device.codeNow()) + .statusCode(200).extract(); + String base = "AssumeRoleResponse.AssumeRoleResult.Credentials."; + return S3RequestSigner.signedAs(issued.path(base + "AccessKeyId"), + issued.path(base + "SecretAccessKey"), issued.path(base + "SessionToken")); + } + + /** A role only an MFA-authenticated {@code userName} may assume, holding the same condition. */ + private static void createRoleRequiringMfa(String roleName, String userName) { + iam("CreateRole", "RoleName", roleName, "AssumeRolePolicyDocument", """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow", + "Principal":{"AWS":"arn:aws:iam::%s:user/%s"},"Action":"sts:AssumeRole", + "Condition":{"Bool":{"aws:MultiFactorAuthPresent":"true"}}}]}""" + .formatted(ACCOUNT, userName)); + iam("PutRolePolicy", "RoleName", roleName, "PolicyName", "inline", + "PolicyDocument", LIST_WITH_MFA); + } + + /** A role {@code userName} may assume, with nothing in the trust policy about MFA. */ + private static void createRoleTrustingUser(String roleName, String userName) { + iam("CreateRole", "RoleName", roleName, "AssumeRolePolicyDocument", """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow", + "Principal":{"AWS":"arn:aws:iam::%s:user/%s"},"Action":"sts:AssumeRole"}]}""" + .formatted(ACCOUNT, userName)); + } + + /** A virtual device created and enabled for a fresh user, the way a client sets one up. */ + private static Device enabledDeviceFor(String userName) { + if (!userExists(userName)) { + iam("CreateUser", "UserName", userName); + } + String base = "CreateVirtualMFADeviceResponse.CreateVirtualMFADeviceResult.VirtualMFADevice."; + ExtractableResponse created = given().header("Authorization", auth(ACCOUNT, "iam")) + .formParam("Action", "CreateVirtualMFADevice") + .formParam("VirtualMFADeviceName", userName + "-device") + .when().post("/").then().statusCode(200).extract(); + String seed = new String(Base64.getDecoder().decode( + created.path(base + "Base32StringSeed").toString().trim()), StandardCharsets.UTF_8); + String serialNumber = created.path(base + "SerialNumber"); + long step = Totp.stepAt(Instant.now()); + iam("EnableMFADevice", "UserName", userName, "SerialNumber", serialNumber, + "AuthenticationCode1", Totp.codeAt(seed, step - 1), + "AuthenticationCode2", Totp.codeAt(seed, step)); + return new Device(serialNumber, seed); + } + + private static boolean userExists(String userName) { + return given().header("Authorization", auth(ACCOUNT, "iam")) + .formParam("Action", "GetUser").formParam("UserName", userName) + .when().post("/").then().extract().statusCode() == 200; + } + + private static S3RequestSigner userWithPolicy(String userName, String policy) { + iam("CreateUser", "UserName", userName); + iam("PutUserPolicy", "UserName", userName, "PolicyName", "inline", "PolicyDocument", policy); + ExtractableResponse key = given().header("Authorization", auth(ACCOUNT, "iam")) + .formParam("Action", "CreateAccessKey").formParam("UserName", userName) + .when().post("/").then().statusCode(200).extract(); + String base = "CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey."; + return S3RequestSigner.signedAs(key.path(base + "AccessKeyId"), key.path(base + "SecretAccessKey")); + } + + private static void iam(String action, String... params) { + RequestSpecification request = given().header("Authorization", auth(ACCOUNT, "iam")) + .formParam("Action", action); + for (int i = 0; i < params.length; i += 2) { + request = request.formParam(params[i], params[i + 1]); + } + request.when().post("/").then().statusCode(200); + } + + private static String unique(String prefix) { + return prefix + "-" + UUID.randomUUID().toString().substring(0, 8); + } + + private static String auth(String accessKeyId, String service) { + return "AWS4-HMAC-SHA256 Credential=" + accessKeyId + "/20261116/us-east-1/" + service + + "/aws4_request, SignedHeaders=host, Signature=abc"; + } +} diff --git a/src/test/java/io/floci/aws/services/iam/StsQueryHandlerTest.java b/src/test/java/io/floci/aws/services/iam/StsQueryHandlerTest.java index 0ea62bab2d..62d33ef47d 100644 --- a/src/test/java/io/floci/aws/services/iam/StsQueryHandlerTest.java +++ b/src/test/java/io/floci/aws/services/iam/StsQueryHandlerTest.java @@ -4,6 +4,7 @@ import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.AccountResolver; import io.floci.aws.core.common.OidcIssuerKeyLookup; import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.common.RequestContext; import io.floci.aws.core.common.WebIdentityToken; import io.floci.aws.core.common.WebIdentityTokenVerifier; import io.floci.aws.services.iam.model.DelegationRequest; @@ -119,6 +120,7 @@ class StsQueryHandlerTest { delegation, mock(CentralRootAccess.class), tokenIssuer, + new RequestContext(), clock); } @@ -969,7 +971,7 @@ class StsQueryHandlerTest { new RegionResolver(REGION, "000000000000"), config, mock(AssumeRolePolicyEvaluator.class), trust, verifier, keys, mock(SAMLProviderService.class), mock(SAMLTrustPolicyEvaluator.class), mock(DelegationRequestService.class), mock(CentralRootAccess.class), - mock(WebIdentityTokenIssuer.class)); + mock(WebIdentityTokenIssuer.class), new RequestContext()); MultivaluedMap params = new MultivaluedHashMap<>(); params.putSingle("RoleArn", requestedRoleArn); params.putSingle("RoleSessionName", "app"); diff --git a/src/test/java/io/floci/aws/services/iam/StsRequestConstraintsIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/StsRequestConstraintsIntegrationTest.java index 879e63b896..6761840924 100644 --- a/src/test/java/io/floci/aws/services/iam/StsRequestConstraintsIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/iam/StsRequestConstraintsIntegrationTest.java @@ -49,10 +49,10 @@ class StsRequestConstraintsIntegrationTest { } /** - * {@code serialNumberType} and {@code tokenCodeType} are declared and were read by nothing, so - * a request naming either is now held to it. Both are reported together, in the order the model - * lists them, and a well-formed pair is still accepted and still unused: the MFA check itself - * is not built. + * {@code serialNumberType} and {@code tokenCodeType} are declared, so a request naming either + * is held to it. Both are reported together, in the order the model lists them, and the shapes + * are answered before any device is resolved: a pair that breaks them is a + * {@code ValidationError} rather than the refusal of a device that could not have existed. */ @Test void theMfaMembersAreReadWhereNothingReadThemBefore() { @@ -81,6 +81,11 @@ class StsRequestConstraintsIntegrationTest { .body(MESSAGE, containsString("Value 'abcdef' at 'tokenCode' failed to satisfy" + " constraint: Member must satisfy regular expression pattern: [\\d]*")); + // A well-formed pair clears the declared shapes and reaches the device. This key is one + // IAM holds nowhere, so there is no identity behind it whose devices could be checked, and + // the claim is taken as made rather than refused: the same reading this emulator takes of + // such a key everywhere else. A key that does name an identity is held to its own devices, + // which is what StsMfaEnforcementIntegrationTest walks. sts("GetSessionToken") .formParam("SerialNumber", "arn:aws:iam::000000000000:mfa/user") .formParam("TokenCode", "123456")