mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
fix(iam): refuse inactive keys and unreadable credentials in enforcement (#5346)
With enforcement on, three kinds of request got past the filter's
credential checks, and an expired session was answered as a key that
exists nowhere.
A deactivated access key could still be used. Account routing skips an
inactive key, so its requests landed in the default account. A key of a
user there kept that user's permissions, since resolveCallerContext
reads the user's policies whatever the key's status. A key of another
account matched no user in the default account, and isKnownAccessKey,
which counts every key in every account, let the request through as a
credential the filter could not map, with no policy check at all.
Deactivating a key of a user allowed nothing let it create IAM users
and mint session tokens. The IAM User Guide ("Manage access keys for
IAM users") says that once deactivated a key "can no longer be used by
API calls" until it is activated again.
An Authorization header the filter could not read a credential from made
it return before any check. That covered a header naming no access key
at all (a Bearer token, SigV2, a Credential without the SigV4 scheme or
with the key left out) and a SigV4 scope missing a part, such as its
aws4_request terminator. Any caller could make any call that way,
including the management calls an unsigned request is refused. Such a
request is now refused as AWS refuses a header it cannot read:
IncompleteSignature for Query services and IncompleteSignatureException
for JSON and CBOR ones (the common errors, and the IAM User Guide's
SigV4 troubleshooting section), and S3's AuthorizationHeaderMalformed
with the wording S3HeaderSignatureFilter already uses, all 400. A
presigned S3 URL sends no header, and S3 answers a mal-formed
X-Amz-Credential with AuthorizationQueryParametersError, so that is
what it gets. Otherwise the request is treated as an unsigned one is: an
operation AWS serves without credentials is left alone, and a REST
request is refused only when the header claims SigV4 and its route maps
to an action, since AppSync, CodeArtifact's package endpoints, Identity
Store's SCIM endpoint and API Gateway's authorizers take Bearer and
Basic tokens of their own. An empty header with nothing else to read is
refused the same way, not as a missing one; next to a presigned URL's
X-Amz-Credential it still defers to that credential. Where the guide
gives the message, the refusal uses it: "Authorization header cannot be
empty." and, for a SigV4 header with no Credential, "Authorization
header requires 'Credential' parameter.". The other shapes get the
common errors' "The request signature does not conform to AWS
standards.".
sts:GetCallerIdentity answered a key that exists nowhere, as the
default account's root, because its exemption ran before the
unknown-key check. The exemption is about permissions only, so the key
checks now run first.
An expired session was refused with InvalidClientTokenId or
UnrecognizedClientException, because resolveCallerContext deletes it and
the known-key check then finds nothing. The common errors of the IAM,
STS, EC2, SNS, CloudFormation, Lambda and Step Functions API references
give ExpiredTokenException, 403, "The security token included in the
request has expired", and S3's error list gives ExpiredToken, 400. The
filter now asks isExpiredSession before resolving the caller, so it no
longer deletes the session, and later uses get the same answer. Both
lookups are asked about one moment: read apart, a session expiring
between them would be deleted and answered as unknown, or on the
presigned POST path below allowed with no policy check. Once Floci's own
sweep has removed the session (the first presigned URL it generates in a
process runs one), the key reads as unknown again, as
docs/services/iam.md says.
The inactive-key, expired-session and unknown-key checks run before the
action is used, on every Query, JSON and CBOR call and on every REST
request whose route maps to an action. A REST request no rule maps is
left alone, as an unsigned one already is: the filter cannot tell it
from the API Gateway execute path, Lambda function URLs and the other
paths it sees that are unsigned by design, and the execute path answers
a bad AWS_IAM signature in its own shape. Every refusal to a CBOR call,
AccessDenied included, now arrives CBOR-encoded, where only the
unsigned-call refusal did before; the others were JSON bodies the client
could not read. AccessDenied keeps its 403, the status the Kinesis and
CloudWatch common errors give it. The filter's JSON errors are now
written from AwsErrorResponse, as AwsExceptionMapper writes every other
JSON error, rather than built as strings. That gives a REST JSON
refusal, such as Lambda's, the X-Amzn-Errortype header the rest of
Floci's REST JSON errors carry.
A presigned POST carries its credential in the form body, which the
filter never sees, so authorizeAdditionalResource is the only IAM check
it gets. That evaluated an inactive key with its user's policies, and
resolved an expired session, which deleted it. Both are now refused
there as the filter refuses them, before the caller is resolved:
InvalidAccessKeyId, 403, and ExpiredToken, 400. A key that exists
nowhere, or a credential that cannot be read, is still left to S3's own
presigned-POST check, and uploads as an unsigned request would when that
check is off. docs/services/iam.md now says so.
isKnownAccessKey keeps counting inactive keys: GetSessionToken relies
on it, so a session minted with an inactive key has no issuer rather
than acting as the account root. resolveCallerContext keeps returning
an inactive key's user policies rather than null, which AppSync and RDS
read as allowed; both verify the signature first, which an inactive key
fails. isInactiveAccessKey looks in the request's account before
scanning the others, since routing sends an active key to its own
account.
Integration tests cover a same-account and another account's inactive
key (including GetCallerIdentity, GetSessionToken, S3, a JSON service,
a presigned POST, and reactivation); an expired session on Query (asked
twice), JSON (with its X-Amzn-Errortype header), S3 and presigned POST
calls; an unreadable credential on Query (eight header shapes, none of
which creates the user), JSON, CBOR and S3 calls, on a presigned S3 URL,
and with the guide's two messages; the cases left alone (a Cognito flow
AWS serves without credentials, a Bearer token on S3, a REST route no
rule maps); an unknown key on GetCallerIdentity and on a CBOR call; and
AccessDenied on a CBOR call. Every refusal fails without this change.
IamServiceTest and IamEnforcementFilterTest check that the expiry check
and the caller lookup are asked about one moment. The SDK compatibility
suite's IamEnforcementTest adds a deactivated key, refused by STS and S3
with the codes the SDK reads and accepted again once activated.
docs/services/iam.md lists the cases in both enforcement tables and
under unsigned requests.
This commit is contained in:
1 parent
4793f1aa77
commit
46f9c23c8b
11 files changed
+1482
-122
No files matched your search
@@ -33,6 +33,7 @@ import org.jboss.logging.Logger;
|
||||
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
@@ -53,9 +54,12 @@ import java.util.regex.Pattern;
|
||||
* <li>Enforcement is disabled (default)</li>
|
||||
* <li>Access key is {@code "test"} (root/admin stand-in)</li>
|
||||
* <li>Access key is a real credential this filter cannot map to policies, such as a session
|
||||
* carrying no role ARN. An access key that exists nowhere is rejected, not bypassed.</li>
|
||||
* carrying no role ARN. An access key that exists nowhere or is inactive, an expired
|
||||
* session, and an {@code Authorization} header with no readable credential are rejected,
|
||||
* not bypassed.</li>
|
||||
* <li>The action cannot be resolved (unknown mapping → permissive)</li>
|
||||
* <li>The action is {@code sts:GetCallerIdentity}, which AWS allows without permissions</li>
|
||||
* <li>The action is {@code sts:GetCallerIdentity}, which AWS allows without permissions. The
|
||||
* key itself is still checked.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>Evaluates the caller's identity policies, optional session policy, and optional
|
||||
@@ -80,6 +84,25 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
/** AWS's wording for a credential it does not recognise. */
|
||||
private static final String INVALID_SECURITY_TOKEN = "The security token included in the request is invalid.";
|
||||
|
||||
/** S3's wording for an access key it does not recognise. */
|
||||
private static final String S3_INVALID_ACCESS_KEY_ID =
|
||||
"The AWS Access Key Id you provided does not exist in our records.";
|
||||
|
||||
/** AWS's wording for temporary credentials past their expiration. */
|
||||
private static final String EXPIRED_TOKEN = "The security token included in the request has expired.";
|
||||
|
||||
/** S3's wording for the same. */
|
||||
private static final String S3_EXPIRED_TOKEN = "The provided token has expired.";
|
||||
|
||||
/** AWS's wording for a signature that does not follow its format. */
|
||||
private static final String INCOMPLETE_SIGNATURE = "The request signature does not conform to AWS standards.";
|
||||
|
||||
/** The IAM User Guide's "Troubleshoot SigV4" wording for an empty header. */
|
||||
private static final String EMPTY_AUTHORIZATION = "Authorization header cannot be empty.";
|
||||
|
||||
/** The same guide's wording for a SigV4 header without its credential. */
|
||||
private static final String MISSING_CREDENTIAL = "Authorization header requires 'Credential' parameter.";
|
||||
|
||||
/** AWS's wording for a request that carries no credentials at all. */
|
||||
private static final String MISSING_AUTHENTICATION_TOKEN =
|
||||
"The request must contain a valid AWS access key ID or X.509 certificate.";
|
||||
@@ -257,21 +280,29 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
}
|
||||
|
||||
String auth = ctx.getHeaderString("Authorization");
|
||||
if (auth == null || auth.isBlank()) {
|
||||
boolean emptyHeader = auth != null && auth.isBlank();
|
||||
if (auth == null || emptyHeader) {
|
||||
auth = requestAuthorization(null, ctx.getUriInfo().getQueryParameters());
|
||||
}
|
||||
if (auth == null) {
|
||||
refuseUnsignedManagementCall(ctx);
|
||||
if (emptyHeader) {
|
||||
// An empty header is not a missing one: "Authorization header cannot be empty" is
|
||||
// among the failures the IAM User Guide's "Troubleshoot SigV4" lists.
|
||||
refuseUnreadableCredential(ctx, "");
|
||||
} else {
|
||||
refuseUnsignedManagementCall(ctx);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
String akid = accountResolver.extractAccessKeyId(auth);
|
||||
if (akid == null || "test".equals(akid)) {
|
||||
if ("test".equals(akid)) {
|
||||
return; // root bypass
|
||||
}
|
||||
|
||||
String rawScope = extractCredentialScope(auth);
|
||||
String rawScope = akid == null ? null : extractCredentialScope(auth);
|
||||
if (rawScope == null) {
|
||||
refuseUnreadableCredential(ctx, auth);
|
||||
return;
|
||||
}
|
||||
// Normalise signing aliases (s3express → s3) before anything keyed by scope runs:
|
||||
@@ -285,11 +316,11 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
if (!"OPTIONS".equalsIgnoreCase(ctx.getMethod())
|
||||
&& iamService.presignedScope(akid).isPresent()) {
|
||||
ctx.abortWith(accessDeniedForRequest("Unknown", credentialScope, ctx));
|
||||
return;
|
||||
}
|
||||
if (!isRpcCall(ctx)) {
|
||||
return; // REST route no rule maps → ALLOW, as an unsigned REST request is
|
||||
}
|
||||
return; // unknown action → ALLOW for ordinary credentials (permissive)
|
||||
}
|
||||
if ("sts:GetCallerIdentity".equals(action)) {
|
||||
return; // AWS returns caller identity even when an identity policy explicitly denies it
|
||||
}
|
||||
|
||||
String region = requestContext.getRegion() == null ? config.defaultRegion() : requestContext.getRegion();
|
||||
@@ -297,42 +328,66 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
? accountResolver.resolve(auth)
|
||||
: requestContext.getAccountId();
|
||||
|
||||
// The key is checked before the action is used: an API call needs a usable key whatever it
|
||||
// asks for, even one that needs no permission, such as GetCallerIdentity. A bare 12-digit
|
||||
// account-id key is floci's account-root principal, never an IAM user's key.
|
||||
boolean accountRootKey = akid.equals(accountId);
|
||||
if (!accountRootKey && iamService.isInactiveAccessKey(akid)) {
|
||||
LOG.debugv("Rejecting request signed with an inactive access key id {0}", akid);
|
||||
ctx.abortWith(unrecognizedClientResponse(credentialScope, ctx));
|
||||
return;
|
||||
}
|
||||
// Both lookups are asked about one moment, so a session that expires between them is not
|
||||
// deleted and then answered as a key that exists nowhere.
|
||||
Instant now = Instant.now();
|
||||
if (iamService.isExpiredSession(akid, now)) {
|
||||
LOG.debugv("Rejecting request signed with an expired session {0}", akid);
|
||||
ctx.abortWith(expiredTokenResponse(credentialScope, ctx));
|
||||
return;
|
||||
}
|
||||
CallerContext caller = iamService.resolveCallerContext(akid, now);
|
||||
if (caller == null && !accountRootKey && !iamService.isKnownAccessKey(akid)) {
|
||||
// No such credential anywhere. Enforcement is on and the caller is unauthenticated,
|
||||
// so allowing it would hand an arbitrary access key id every permission there is.
|
||||
LOG.debugv("Rejecting request signed with an unknown access key id {0}", akid);
|
||||
ctx.abortWith(unrecognizedClientResponse(credentialScope, ctx));
|
||||
return;
|
||||
}
|
||||
if (action == null) {
|
||||
return; // unknown action → ALLOW for ordinary credentials (permissive)
|
||||
}
|
||||
if ("sts:GetCallerIdentity".equals(action)) {
|
||||
return; // AWS returns caller identity even when an identity policy explicitly denies it
|
||||
}
|
||||
|
||||
// Service control policies from the caller's organization, when the Organizations
|
||||
// service is present and SCP enforcement is enabled. Resolved lazily via Instance
|
||||
// to avoid a hard IAM → Organizations dependency.
|
||||
//
|
||||
// Resolved before resolveCallerContext because the account-root branch below needs to
|
||||
// know whether a ceiling exists in order to decide between enforcing and bypassing. That
|
||||
// costs an organization lookup on requests that then bypass; both flags are opt-in, and
|
||||
// effectiveScpLevels returns null immediately when SCP enforcement is off.
|
||||
// Resolved before the account-root branch below, which needs to know whether a ceiling
|
||||
// exists in order to decide between enforcing and bypassing. That costs an organization
|
||||
// lookup on requests that then bypass; both flags are opt-in, and effectiveScpLevels
|
||||
// returns null immediately when SCP enforcement is off.
|
||||
List<List<String>> scpLevels = scpProvider.isResolvable()
|
||||
? scpProvider.get().effectiveScpLevels(accountId)
|
||||
: null;
|
||||
|
||||
boolean accountRootPrincipal = false;
|
||||
CallerContext caller = iamService.resolveCallerContext(akid);
|
||||
if (caller == null) {
|
||||
// A bare 12-digit account-id key is floci's account-root principal: not a registered
|
||||
// IAM identity (resolveCallerContext → null), but in AWS the account root is still
|
||||
// bounded by SCPs. Enforce them when the account actually has an SCP ceiling.
|
||||
if (akid.equals(accountId)) {
|
||||
if (scpLevels == null) {
|
||||
return; // account root with no ceiling → nothing to enforce
|
||||
}
|
||||
caller = CallerContext.of(List.of(ROOT_ALLOW_ALL));
|
||||
accountRootPrincipal = true;
|
||||
} else if (iamService.isKnownAccessKey(akid)) {
|
||||
if (!accountRootKey) {
|
||||
// A real credential this filter cannot map to policies, such as a session Floci mints
|
||||
// for its own presigned URLs with no policy to scope it. Denying it would reject an
|
||||
// authenticated caller.
|
||||
return;
|
||||
} else {
|
||||
// No such credential anywhere. Enforcement is on and the caller is unauthenticated,
|
||||
// so allowing it would hand an arbitrary access key id every permission there is.
|
||||
LOG.debugv("Rejecting request signed with an unknown access key id {0}", akid);
|
||||
ctx.abortWith(unrecognizedClientResponse(credentialScope, ctx.getMediaType()));
|
||||
return;
|
||||
}
|
||||
// A bare 12-digit account-id key is floci's account-root principal: not a registered
|
||||
// IAM identity (resolveCallerContext → null), but in AWS the account root is still
|
||||
// bounded by SCPs. Enforce them when the account actually has an SCP ceiling.
|
||||
if (scpLevels == null) {
|
||||
return; // account root with no ceiling → nothing to enforce
|
||||
}
|
||||
caller = CallerContext.of(List.of(ROOT_ALLOW_ALL));
|
||||
accountRootPrincipal = true;
|
||||
}
|
||||
if (scpLevels != null) {
|
||||
caller = caller.withScpLevels(scpLevels);
|
||||
@@ -480,24 +535,104 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
return new ResolvedAuthorization(servingScope, servingScope + ":" + queryAction);
|
||||
}
|
||||
|
||||
boolean rest = claimValue instanceof ProtocolClaim claim && claim.protocol() == WireProtocol.REST;
|
||||
if (rest && resourceInfo != null && resourceInfo.getResourceClass() != null) {
|
||||
ServiceDescriptor descriptor = catalog.byResourceClass(resourceInfo.getResourceClass()).orElse(null);
|
||||
if (descriptor != null) {
|
||||
ResolvedAuthorization routeAuthorization = resolveRestAuthorization(descriptor, ctx);
|
||||
if (routeAuthorization != null) {
|
||||
return routeAuthorization;
|
||||
}
|
||||
}
|
||||
ResolvedAuthorization routeAuthorization = restRouteAuthorization(ctx);
|
||||
if (routeAuthorization != null) {
|
||||
return routeAuthorization;
|
||||
}
|
||||
|
||||
// A REST request is authorized by its route alone, never by an X-Amz-Target it carries.
|
||||
boolean rest = claimValue instanceof ProtocolClaim claim && claim.protocol() == WireProtocol.REST;
|
||||
String servingScope = servingCredentialScope(claimedScope, ctx);
|
||||
return new ResolvedAuthorization(servingScope, rest
|
||||
? actionRegistry.resolveRoute(servingScope, ctx)
|
||||
: actionRegistry.resolve(servingScope, ctx));
|
||||
}
|
||||
|
||||
/**
|
||||
* The action a REST request's matched route maps to, read from the route alone. Null for any
|
||||
* other request, and for a route no rule maps.
|
||||
*/
|
||||
private ResolvedAuthorization restRouteAuthorization(ContainerRequestContext ctx) {
|
||||
if (!(ctx.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY) instanceof ProtocolClaim claim)
|
||||
|| claim.protocol() != WireProtocol.REST
|
||||
|| resourceInfo == null || resourceInfo.getResourceClass() == null) {
|
||||
return null;
|
||||
}
|
||||
return catalog.byResourceClass(resourceInfo.getResourceClass())
|
||||
.map(descriptor -> resolveRestAuthorization(descriptor, ctx))
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuses a request whose {@code Authorization} header this filter cannot read a credential
|
||||
* from: an empty one, one naming no access key (a Bearer token, SigV2, a credential without the
|
||||
* SigV4 scheme or without its key, see {@link AccountResolver#extractAccessKeyId}), or a SigV4
|
||||
* credential scope missing a part, such as its {@code aws4_request} terminator. With no key or
|
||||
* no scope there is nothing to check, so letting it through would skip enforcement, the key
|
||||
* checks included, for any action. The IAM User Guide's "Troubleshoot SigV4" lists these
|
||||
* failures (an empty header, a missing credential, a header that does not start with an
|
||||
* algorithm name) under {@code IncompleteSignatureException}. The other services' common errors
|
||||
* call it {@code IncompleteSignature}, and S3's error list {@code AuthorizationHeaderMalformed},
|
||||
* or {@code AuthorizationQueryParametersError} for a presigned URL, all 400.
|
||||
*
|
||||
* <p>Otherwise it is treated as an unsigned request is. An operation AWS serves without
|
||||
* credentials is left alone. A REST request is refused only when it claims SigV4 and its route
|
||||
* maps to an action: AppSync, CodeArtifact's package endpoints, Identity Store's SCIM endpoint
|
||||
* and API Gateway's authorizers take Bearer and Basic tokens of their own, and this filter
|
||||
* cannot tell the API Gateway execute path, Lambda function URLs and the other paths it sees
|
||||
* that are unsigned by design from the rest. A SigV4a scope, which has no region segment, does
|
||||
* not get here: {@link AccountContextFilter} reads its service name as the region and refuses
|
||||
* it, unless unknown regions are allowed.
|
||||
*/
|
||||
private void refuseUnreadableCredential(ContainerRequestContext ctx, String auth) {
|
||||
if (ctx.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY) instanceof ProtocolClaim claim
|
||||
&& claim.protocol() != WireProtocol.REST
|
||||
&& servesWithoutCredentials(claim, ctx)) {
|
||||
return;
|
||||
}
|
||||
ResolvedAuthorization routeAuthorization = claimsSigV4(auth) ? restRouteAuthorization(ctx) : null;
|
||||
if (routeAuthorization == null && !isRpcCall(ctx)) {
|
||||
return;
|
||||
}
|
||||
LOG.debugv("Rejecting a {0} request whose Authorization header carries no readable credential",
|
||||
ctx.getMethod());
|
||||
ctx.abortWith(incompleteSignatureResponse(
|
||||
routeAuthorization == null ? null : routeAuthorization.credentialScope(), ctx,
|
||||
incompleteSignatureMessage(auth)));
|
||||
}
|
||||
|
||||
/**
|
||||
* The guide's own wording where it gives one: for an empty header, and for a SigV4 header
|
||||
* without its credential. It gives none for the other shapes, which get the common errors' text.
|
||||
*/
|
||||
private static String incompleteSignatureMessage(String auth) {
|
||||
if (auth.isEmpty()) {
|
||||
return EMPTY_AUTHORIZATION;
|
||||
}
|
||||
if (auth.startsWith("AWS4-") && !auth.contains("Credential=")) {
|
||||
return MISSING_CREDENTIAL;
|
||||
}
|
||||
return INCOMPLETE_SIGNATURE;
|
||||
}
|
||||
|
||||
/**
|
||||
* A SigV4 {@code Authorization} header, or the {@code Credential=} string
|
||||
* {@link #requestAuthorization} builds from a presigned URL.
|
||||
*/
|
||||
private static boolean claimsSigV4(String auth) {
|
||||
return auth.startsWith("AWS4-") || auth.contains("Credential=");
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this is a Query, JSON or CBOR call. Only an AWS API client sends one, whereas a REST
|
||||
* request may be one of the unsigned-by-design paths this filter also sees.
|
||||
*/
|
||||
private static boolean isRpcCall(ContainerRequestContext ctx) {
|
||||
return IamActionRegistry.isQueryRequest(ctx)
|
||||
|| ctx.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY) instanceof ProtocolClaim claim
|
||||
&& claim.protocol() != WireProtocol.REST;
|
||||
}
|
||||
|
||||
private ResolvedAuthorization resolveRestAuthorization(ServiceDescriptor descriptor,
|
||||
ContainerRequestContext ctx) {
|
||||
return descriptor.credentialScopes().stream()
|
||||
@@ -636,7 +771,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
* <p>Returns normally when the action is allowed, or when enforcement does not
|
||||
* apply to this request (enforcement disabled, no Authorization header, root or
|
||||
* unknown access key). Throws {@link AwsException} with the same AccessDenied
|
||||
* shape as {@link #filter} when the caller's policies deny the action.
|
||||
* shape as {@link #filter} when the caller's policies deny the action, and with the
|
||||
* codes {@link #filter} answers when the access key is inactive or the session has expired.
|
||||
*
|
||||
* <p>The account used for policy evaluation is always re-resolved from {@code akid} here
|
||||
* (see {@link #resolveCredentialAccountId}) rather than trusted from {@link RequestContext},
|
||||
@@ -713,11 +849,28 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
String previousAccountId = requestContext.getAccountId();
|
||||
requestContext.setAccountId(accountId);
|
||||
try {
|
||||
// A presigned POST carries its credential only in the form body, which filter() never
|
||||
// sees, so a key IAM holds but that can no longer be used is refused here as filter()
|
||||
// refuses it. Otherwise an inactive key would act with its user's policies, and
|
||||
// resolveCallerContext would delete an expired session, which would then read as a key
|
||||
// that exists nowhere. For a second resource of a request filter() has seen, the key
|
||||
// has already passed these checks.
|
||||
boolean accountRootKey = akid.equals(accountId);
|
||||
if (!accountRootKey && iamService.isInactiveAccessKey(akid)) {
|
||||
throw unrecognizedClientException(credentialScope);
|
||||
}
|
||||
// One moment for both lookups, as in filter(): a session expiring between them would
|
||||
// otherwise be deleted and then allowed below as a credential with no context.
|
||||
Instant now = Instant.now();
|
||||
if (iamService.isExpiredSession(akid, now)) {
|
||||
throw expiredTokenException(credentialScope);
|
||||
}
|
||||
|
||||
List<List<String>> scpLevels = scpProvider.isResolvable()
|
||||
? scpProvider.get().effectiveScpLevels(accountId) : null;
|
||||
|
||||
boolean accountRootPrincipal = false;
|
||||
CallerContext caller = iamService.resolveCallerContext(akid);
|
||||
CallerContext caller = iamService.resolveCallerContext(akid, now);
|
||||
if (caller == null) {
|
||||
// No unknown-key rejection here, unlike filter(), and none is needed. For a second
|
||||
// resource of a request filter() has seen (CopyObject's source, RotateSecret's
|
||||
@@ -726,7 +879,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
// presigned POST carries its credential only in the form body, which filter() never
|
||||
// sees: an unknown key there is refused by S3's presigned-POST signature check when
|
||||
// S3 auth enforcement is on, and otherwise uploads as an unsigned request would.
|
||||
if (scpLevels == null || !akid.equals(accountId)) {
|
||||
if (scpLevels == null || !accountRootKey) {
|
||||
return;
|
||||
}
|
||||
caller = CallerContext.of(List.of(ROOT_ALLOW_ALL));
|
||||
@@ -995,6 +1148,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
* <li>{@code application/x-www-form-urlencoded} body → AWS Query
|
||||
* {@code <ErrorResponse>...</ErrorResponse>} (IAM/STS/EC2/SQS/SNS/...)</li>
|
||||
* <li>JSON 1.x: JSON with HTTP 400; REST-JSON: JSON with HTTP 403</li>
|
||||
* <li>CBOR: the request's own encoding with HTTP 403, from {@link #accessDeniedForRequest},
|
||||
* which has the request to read it from</li>
|
||||
* </ul>
|
||||
*/
|
||||
// Package-private for unit testing.
|
||||
@@ -1012,14 +1167,21 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
|
||||
private static Response accessDeniedForRequest(String action, String credentialScope,
|
||||
ContainerRequestContext ctx, String resourceArn) {
|
||||
WireProtocol protocol = ctx.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY) instanceof ProtocolClaim claim
|
||||
? claim.protocol() : WireProtocol.REST;
|
||||
WireProtocol protocol = claimedProtocol(ctx);
|
||||
if (isCbor(protocol)) {
|
||||
// 403, the status the Kinesis and CloudWatch common errors give AccessDeniedException.
|
||||
return cborError(ctx, "AccessDeniedException", accessDeniedMessage(action), 403);
|
||||
}
|
||||
return accessDeniedResponse(action, credentialScope, ctx.getMediaType(), resourceArn, protocol);
|
||||
}
|
||||
|
||||
private static String accessDeniedMessage(String action) {
|
||||
return "User is not authorized to perform: " + action;
|
||||
}
|
||||
|
||||
static Response accessDeniedResponse(String action, String credentialScope, MediaType requestMediaType,
|
||||
String resourceArn, WireProtocol protocol) {
|
||||
String message = "User is not authorized to perform: " + action;
|
||||
String message = accessDeniedMessage(action);
|
||||
if ("s3".equals(credentialScope)) {
|
||||
String resourcePath = formatS3ResourcePath(resourceArn);
|
||||
return s3XmlAccessDenied(message, resourcePath);
|
||||
@@ -1050,6 +1212,10 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
}
|
||||
|
||||
private static Response queryXmlError(String code, String message) {
|
||||
return queryXmlError(code, message, 403);
|
||||
}
|
||||
|
||||
private static Response queryXmlError(String code, String message, int status) {
|
||||
String xml = new XmlBuilder()
|
||||
.start("ErrorResponse")
|
||||
.start("Error")
|
||||
@@ -1060,22 +1226,22 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
.elem("RequestId", UUID.randomUUID().toString())
|
||||
.end("ErrorResponse")
|
||||
.build();
|
||||
return Response.status(403).type(MediaType.APPLICATION_XML).entity(xml).build();
|
||||
return Response.status(status).type(MediaType.APPLICATION_XML).entity(xml).build();
|
||||
}
|
||||
|
||||
private static Response s3XmlAccessDenied(String message) {
|
||||
return s3XmlAccessDenied(message, null);
|
||||
}
|
||||
|
||||
private static Response s3XmlError(String code, String message) {
|
||||
return s3Xml(code, message, null);
|
||||
private static Response s3XmlError(String code, String message, int status) {
|
||||
return s3Xml(code, message, null, status);
|
||||
}
|
||||
|
||||
private static Response s3XmlAccessDenied(String message, String resourcePath) {
|
||||
return s3Xml("AccessDenied", message, resourcePath);
|
||||
return s3Xml("AccessDenied", message, resourcePath, 403);
|
||||
}
|
||||
|
||||
private static Response s3Xml(String code, String message, String resourcePath) {
|
||||
private static Response s3Xml(String code, String message, String resourcePath, int status) {
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.raw("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
|
||||
.start("Error")
|
||||
@@ -1086,7 +1252,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
}
|
||||
xml.elem("RequestId", UUID.randomUUID().toString())
|
||||
.end("Error");
|
||||
return Response.status(403).type(MediaType.APPLICATION_XML).entity(xml.build()).build();
|
||||
return Response.status(status).type(MediaType.APPLICATION_XML).entity(xml.build()).build();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1099,16 +1265,66 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
* {@code UnrecognizedClientException}, the only place botocore models it (CloudWatch Logs)
|
||||
* and what the API Gateway execute path already returns.
|
||||
*/
|
||||
static Response unrecognizedClientResponse(String credentialScope, MediaType requestMediaType) {
|
||||
static Response unrecognizedClientResponse(String credentialScope, ContainerRequestContext ctx) {
|
||||
if ("s3".equals(credentialScope)) {
|
||||
return s3XmlError("InvalidAccessKeyId",
|
||||
"The AWS Access Key Id you provided does not exist in our records.");
|
||||
return s3XmlError("InvalidAccessKeyId", S3_INVALID_ACCESS_KEY_ID, 403);
|
||||
}
|
||||
if (isFormEncoded(requestMediaType)) {
|
||||
return queryXmlError("InvalidClientTokenId", INVALID_SECURITY_TOKEN);
|
||||
return protocolError(claimedProtocol(ctx), ctx, "InvalidClientTokenId", "UnrecognizedClientException",
|
||||
INVALID_SECURITY_TOKEN, 403);
|
||||
}
|
||||
|
||||
/** {@link #unrecognizedClientResponse} for a caller that renders the error itself. */
|
||||
private static AwsException unrecognizedClientException(String credentialScope) {
|
||||
return "s3".equals(credentialScope)
|
||||
? new AwsException("InvalidAccessKeyId", S3_INVALID_ACCESS_KEY_ID, 403)
|
||||
: new AwsException("UnrecognizedClientException", INVALID_SECURITY_TOKEN, 403);
|
||||
}
|
||||
|
||||
/**
|
||||
* The response for a session whose temporary credentials have expired. S3's error list names it
|
||||
* {@code ExpiredToken}, 400. The other services' common errors name it
|
||||
* {@code ExpiredTokenException}, 403, under the same name for Query services as for JSON ones.
|
||||
*/
|
||||
static Response expiredTokenResponse(String credentialScope, ContainerRequestContext ctx) {
|
||||
if ("s3".equals(credentialScope)) {
|
||||
return s3XmlError("ExpiredToken", S3_EXPIRED_TOKEN, 400);
|
||||
}
|
||||
String body = "{\"__type\":\"UnrecognizedClientException\",\"message\":\"" + INVALID_SECURITY_TOKEN + "\"}";
|
||||
return Response.status(403).type(MediaType.APPLICATION_JSON).entity(body).build();
|
||||
return protocolError(claimedProtocol(ctx), ctx, "ExpiredTokenException", "ExpiredTokenException",
|
||||
EXPIRED_TOKEN, 403);
|
||||
}
|
||||
|
||||
/** {@link #expiredTokenResponse} for a caller that renders the error itself. */
|
||||
private static AwsException expiredTokenException(String credentialScope) {
|
||||
return "s3".equals(credentialScope)
|
||||
? new AwsException("ExpiredToken", S3_EXPIRED_TOKEN, 400)
|
||||
: new AwsException("ExpiredTokenException", EXPIRED_TOKEN, 403);
|
||||
}
|
||||
|
||||
/**
|
||||
* The response for a signature that does not follow AWS's format, from
|
||||
* {@link #refuseUnreadableCredential}. S3 answers with {@code AuthorizationHeaderMalformed}
|
||||
* and the wording {@code S3HeaderSignatureFilter} uses for a mal-formed credential, so S3 answers
|
||||
* the same whichever check catches it. A presigned URL sends no header: its credential is the
|
||||
* {@code X-Amz-Credential} parameter, and S3 answers a mal-formed one with
|
||||
* {@code AuthorizationQueryParametersError}. Other services answer with
|
||||
* {@code IncompleteSignature}, spelled with the {@code Exception} suffix outside Query as the
|
||||
* other codes here are, and the {@code message} the caller picked. All 400.
|
||||
*/
|
||||
static Response incompleteSignatureResponse(String credentialScope, ContainerRequestContext ctx,
|
||||
String message) {
|
||||
if ("s3".equals(credentialScope)) {
|
||||
String header = ctx.getHeaderString("Authorization");
|
||||
if (header == null || header.isBlank()) {
|
||||
return s3XmlError("AuthorizationQueryParametersError", "Error parsing the X-Amz-Credential "
|
||||
+ "parameter; the Credential is mal-formed; expecting "
|
||||
+ "\"<YOUR-AKID>/YYYYMMDD/REGION/SERVICE/aws4_request\".", 400);
|
||||
}
|
||||
return s3XmlError("AuthorizationHeaderMalformed", "The authorization header is malformed; "
|
||||
+ "the Credential is mal-formed; expecting "
|
||||
+ "\"<YOUR-AKID>/YYYYMMDD/REGION/SERVICE/aws4_request\".", 400);
|
||||
}
|
||||
return protocolError(claimedProtocol(ctx), ctx, "IncompleteSignature", "IncompleteSignatureException",
|
||||
message, 400);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1166,27 +1382,56 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
* returns for the same failure on its own path.
|
||||
*/
|
||||
static Response missingAuthenticationTokenResponse(WireProtocol protocol, ContainerRequestContext ctx) {
|
||||
if (protocol == WireProtocol.RPCV2_CBOR || protocol == WireProtocol.AWS_CBOR_TARGET) {
|
||||
// A CBOR client cannot read a JSON body, so the rejection has to arrive in the encoding
|
||||
// the request used, the same shape the rpcv2 controller returns for its own errors.
|
||||
String requestContentType = ctx.getHeaderString(AwsCborContentTypeFilter.ORIGINAL_CONTENT_TYPE_HEADER);
|
||||
if (requestContentType == null) {
|
||||
requestContentType = ctx.getHeaderString("Content-Type");
|
||||
}
|
||||
return CborErrorResponses.of(
|
||||
new AwsException("MissingAuthenticationTokenException", MISSING_AUTHENTICATION_TOKEN, 403),
|
||||
CborErrorResponses.mediaTypeFor(requestContentType));
|
||||
return protocolError(protocol, ctx, "MissingAuthenticationToken", "MissingAuthenticationTokenException",
|
||||
MISSING_AUTHENTICATION_TOKEN, 403);
|
||||
}
|
||||
|
||||
private static WireProtocol claimedProtocol(ContainerRequestContext ctx) {
|
||||
return ctx.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY) instanceof ProtocolClaim claim
|
||||
? claim.protocol() : WireProtocol.REST;
|
||||
}
|
||||
|
||||
/**
|
||||
* An authentication failure outside S3, in the shape the caller's protocol reads: a Query
|
||||
* {@code ErrorResponse} for a form-encoded request, the request's own encoding for a CBOR
|
||||
* call, and JSON otherwise. Query names some failures without the {@code Exception} suffix, and
|
||||
* some differently altogether, so it takes its own code.
|
||||
*/
|
||||
private static Response protocolError(WireProtocol protocol, ContainerRequestContext ctx, String queryCode,
|
||||
String code, String message, int status) {
|
||||
if (isCbor(protocol)) {
|
||||
return cborError(ctx, code, message, status);
|
||||
}
|
||||
if (isFormEncoded(ctx.getMediaType())) {
|
||||
return queryXmlError("MissingAuthenticationToken", MISSING_AUTHENTICATION_TOKEN);
|
||||
return queryXmlError(queryCode, message, status);
|
||||
}
|
||||
String body = "{\"__type\":\"MissingAuthenticationTokenException\",\"message\":\""
|
||||
+ MISSING_AUTHENTICATION_TOKEN + "\"}";
|
||||
return Response.status(403).type(MediaType.APPLICATION_JSON).entity(body).build();
|
||||
return jsonError(code, message, status);
|
||||
}
|
||||
|
||||
private static boolean isCbor(WireProtocol protocol) {
|
||||
return protocol == WireProtocol.RPCV2_CBOR || protocol == WireProtocol.AWS_CBOR_TARGET;
|
||||
}
|
||||
|
||||
/**
|
||||
* A CBOR client cannot read a JSON body, so a rejection has to arrive in the encoding the
|
||||
* request used, the same shape the rpcv2 controller returns for its own errors.
|
||||
*/
|
||||
private static Response cborError(ContainerRequestContext ctx, String code, String message, int status) {
|
||||
String requestContentType = ctx.getHeaderString(AwsCborContentTypeFilter.ORIGINAL_CONTENT_TYPE_HEADER);
|
||||
if (requestContentType == null) {
|
||||
requestContentType = ctx.getHeaderString("Content-Type");
|
||||
}
|
||||
return CborErrorResponses.of(new AwsException(code, message, status),
|
||||
CborErrorResponses.mediaTypeFor(requestContentType));
|
||||
}
|
||||
|
||||
private static Response jsonAccessDenied(String message, int status) {
|
||||
String body = "{\"__type\":\"AccessDeniedException\",\"message\":\"" + message + "\"}";
|
||||
return Response.status(status).type(MediaType.APPLICATION_JSON).entity(body).build();
|
||||
return jsonError("AccessDeniedException", message, status);
|
||||
}
|
||||
|
||||
/** A JSON error in the shape {@link AwsExceptionMapper} gives every other JSON failure. */
|
||||
private static Response jsonError(String code, String message, int status) {
|
||||
return Response.status(status).type(MediaType.APPLICATION_JSON)
|
||||
.entity(new AwsErrorResponse(code, message)).build();
|
||||
}
|
||||
}
|
||||
@@ -4416,6 +4416,15 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
* <p>Returns {@code null} if the access key is unknown (bypass — backward-compatible).
|
||||
*/
|
||||
public CallerContext resolveCallerContext(String accessKeyId) {
|
||||
return resolveCallerContext(accessKeyId, Instant.now());
|
||||
}
|
||||
|
||||
/**
|
||||
* {@link #resolveCallerContext(String)} as of {@code now}. Enforcement passes the moment it
|
||||
* asked {@link #isExpiredSession} about, so a session that expires between the two calls is
|
||||
* neither deleted here nor then answered as a key that exists nowhere.
|
||||
*/
|
||||
public CallerContext resolveCallerContext(String accessKeyId, Instant now) {
|
||||
// Check user access keys
|
||||
Optional<AccessKey> akOpt = accessKeys.get(accessKeyId);
|
||||
if (akOpt.isPresent()) {
|
||||
@@ -4430,7 +4439,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
Optional<SessionCredential> sessionOpt = findSessionForCallerContext(accessKeyId);
|
||||
if (sessionOpt.isPresent()) {
|
||||
SessionCredential session = sessionOpt.get();
|
||||
if (session.getExpiration() != null && session.getExpiration().isBefore(Instant.now())) {
|
||||
if (session.getExpiration() != null && session.getExpiration().isBefore(now)) {
|
||||
deleteSession(accessKeyId, session);
|
||||
return null; // expired — unknown key → bypass
|
||||
}
|
||||
@@ -4465,6 +4474,10 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
* an unauthenticated caller, so enforcement needs to tell them apart. The lookup spans every
|
||||
* account deliberately: a key belonging to another account is a real credential, and denying
|
||||
* it here would be a false rejection rather than a closed hole.
|
||||
*
|
||||
* <p>An inactive key counts too. {@link #registerIssuedSession} relies on that, so a session
|
||||
* minted with an inactive key has no issuer rather than acting as the account root, and
|
||||
* enforcement refuses the key itself through {@link #isInactiveAccessKey}.
|
||||
*/
|
||||
public boolean isKnownAccessKey(String accessKeyId) {
|
||||
if (accessKeyId == null || accessKeyId.isBlank()) {
|
||||
@@ -4480,6 +4493,43 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
&& !aware.scanAllAccountEntries(accessKeyId::equals).isEmpty();
|
||||
}
|
||||
|
||||
/**
|
||||
* True when this is an IAM user's long-term access key, in any account, that is not Active. An
|
||||
* inactive key can't be used for API calls (IAM User Guide, "Manage access keys for IAM
|
||||
* users"), so enforcement refuses it as it refuses a key that exists nowhere, rather than
|
||||
* letting {@link #isKnownAccessKey}, which counts it as a credential, wave it through.
|
||||
*/
|
||||
public boolean isInactiveAccessKey(String accessKeyId) {
|
||||
if (accessKeyId == null || accessKeyId.isBlank() || isTemporaryAccessKey(accessKeyId)) {
|
||||
return false;
|
||||
}
|
||||
// Routing sends an active key to its own account, so the usual case is answered here
|
||||
// without scanning the others. An inactive key lands in the default account instead.
|
||||
Optional<AccessKey> routed = accessKeys.get(accessKeyId);
|
||||
if (routed.isPresent()) {
|
||||
return !"Active".equals(routed.get().getStatus());
|
||||
}
|
||||
return accessKeys instanceof AccountAwareStorageBackend<AccessKey> aware
|
||||
&& aware.scanAllAccountEntries(accessKeyId::equals).stream()
|
||||
.anyMatch(entry -> !"Active".equals(entry.value().getStatus()));
|
||||
}
|
||||
|
||||
/**
|
||||
* True when this temporary access key belongs to a session that had expired by {@code now} but
|
||||
* is still stored. AWS answers its use with {@code ExpiredTokenException} rather than as a key
|
||||
* it does not know, so enforcement asks before {@link #resolveCallerContext(String, Instant)},
|
||||
* which deletes such a session and leaves nothing to tell the two apart.
|
||||
*/
|
||||
public boolean isExpiredSession(String accessKeyId, Instant now) {
|
||||
if (!isTemporaryAccessKey(accessKeyId)) {
|
||||
return false;
|
||||
}
|
||||
return findSessionForCallerContext(accessKeyId)
|
||||
.map(SessionCredential::getExpiration)
|
||||
.filter(expiration -> expiration.isBefore(now))
|
||||
.isPresent();
|
||||
}
|
||||
|
||||
private Optional<SessionCredential> findSessionForCallerContext(String accessKeyId) {
|
||||
if (accessKeyId == null || accessKeyId.isBlank()) {
|
||||
return Optional.empty();
|
||||
|
||||
Reference in new issue
Block a user