mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
fix(auth): verify query signatures and retain STS caller identity (#5584)
* fix(sts): retain caller identity for query credentials * fix(sts): retain form token precedence for caller identity * docs(sts): clarify credential header precedence * fix(sts): verify presigned caller identity requests * test(sts): respect the configured signature-checking mode * fix(auth): verify query signatures across services
This commit is contained in:
1 parent
1acedaf068
commit
a017c94ecc
13 files changed
+765
-29
No files matched your search
+98
-11
@@ -10,6 +10,7 @@ import io.github.hectorvent.floci.services.apigateway.ApiGatewayExecuteControlle
|
||||
import io.github.hectorvent.floci.services.apigateway.ApiGatewayUserRequestController;
|
||||
import io.github.hectorvent.floci.services.appsync.graphql.AppSyncExecutionController;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.iam.RequestBodyReader;
|
||||
import io.github.hectorvent.floci.services.s3.S3ControlController;
|
||||
import io.github.hectorvent.floci.services.s3.S3Controller;
|
||||
import io.quarkus.vertx.http.runtime.CurrentVertxRequest;
|
||||
@@ -24,6 +25,7 @@ import jakarta.ws.rs.container.ContainerRequestFilter;
|
||||
import jakarta.ws.rs.container.ResourceInfo;
|
||||
import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
import jakarta.ws.rs.ext.Provider;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
@@ -45,7 +47,7 @@ import java.util.Set;
|
||||
import java.util.function.UnaryOperator;
|
||||
|
||||
/**
|
||||
* Verifies the SigV4 signature in the {@code Authorization} header of every request outside S3
|
||||
* Verifies header and query SigV4 signatures on every request outside S3
|
||||
* when {@code floci.auth.validate-signatures} is enabled, so a request signed with the wrong
|
||||
* secret is refused by SQS, KMS, IAM, Scheduler and the rest as it already is by S3.
|
||||
*
|
||||
@@ -75,8 +77,10 @@ import java.util.function.UnaryOperator;
|
||||
* Everything else is verified here, S3 Control included, whatever service its scope names.
|
||||
*
|
||||
* <p>As with S3, signature verification is authentication only, and an unsigned request is let
|
||||
* through: whether a caller may act is IAM enforcement's decision. Presigned query-string
|
||||
* signatures and SigV4a ({@code AWS4-ECDSA-P256-SHA256}) are not verified here.
|
||||
* through: whether a caller may act is IAM enforcement's decision. A nonblank Authorization
|
||||
* header takes precedence over query credentials. Query signatures expire at X-Amz-Expires;
|
||||
* both placements share credential lookup, canonicalization and protocol error mapping.
|
||||
* SigV4a ({@code AWS4-ECDSA-P256-SHA256}) is not verified here.
|
||||
*
|
||||
* <p>Errors follow the protocol the request used: a Query or REST-XML request (Route 53,
|
||||
* CloudFront, S3 Control) receives an {@code <ErrorResponse>}, a CBOR request a CBOR body, and
|
||||
@@ -96,6 +100,7 @@ public class SigV4HeaderSignatureFilter implements ContainerRequestFilter {
|
||||
private static final Logger LOG = Logger.getLogger(SigV4HeaderSignatureFilter.class);
|
||||
|
||||
private static final Duration MAX_CLOCK_SKEW = Duration.ofMinutes(15);
|
||||
private static final long MAX_EXPIRY_SECONDS = 604800;
|
||||
private static final DateTimeFormatter AMZ_DATE =
|
||||
DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC);
|
||||
|
||||
@@ -145,9 +150,22 @@ public class SigV4HeaderSignatureFilter implements ContainerRequestFilter {
|
||||
if (resource != null && VERIFIED_ELSEWHERE.contains(resource)) {
|
||||
return;
|
||||
}
|
||||
SigV4AuthorizationHeader signed = SigV4AuthorizationHeader.parse(ctx.getHeaderString("Authorization"));
|
||||
if (signed == null) {
|
||||
return;
|
||||
String authorization = ctx.getHeaderString("Authorization");
|
||||
MultivaluedMap<String, String> query = ctx.getUriInfo().getQueryParameters();
|
||||
boolean presigned = isBlank(authorization) && query.containsKey("X-Amz-Credential");
|
||||
SigV4AuthorizationHeader signed;
|
||||
if (presigned) {
|
||||
if (!"AWS4-HMAC-SHA256".equals(query.getFirst("X-Amz-Algorithm"))) {
|
||||
incompleteSignature(ctx, resource, "Presigned request requires X-Amz-Algorithm=AWS4-HMAC-SHA256.");
|
||||
return;
|
||||
}
|
||||
signed = new SigV4AuthorizationHeader(query.getFirst("X-Amz-Credential"),
|
||||
query.getFirst("X-Amz-SignedHeaders"), query.getFirst("X-Amz-Signature"));
|
||||
} else {
|
||||
signed = SigV4AuthorizationHeader.parse(authorization);
|
||||
if (signed == null) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
CredentialScope scope = CredentialScope.parse(signed.credential());
|
||||
@@ -162,14 +180,42 @@ public class SigV4HeaderSignatureFilter implements ContainerRequestFilter {
|
||||
"'Host' or ':authority' must be a 'SignedHeader' in the AWS Authorization.");
|
||||
return;
|
||||
}
|
||||
Instant requestTime = requestTime(ctx);
|
||||
Instant requestTime = presigned ? parseAmzDate(query.getFirst("X-Amz-Date")) : requestTime(ctx);
|
||||
if (requestTime == null) {
|
||||
incompleteSignature(ctx, resource, "Authorization header requires existence of either a "
|
||||
+ "'X-Amz-Date' or a 'Date' header.");
|
||||
return;
|
||||
}
|
||||
|
||||
Optional<String> secretKey = resolveSecretKey(scope.accessKeyId(), ctx.getHeaderString("X-Amz-Security-Token"));
|
||||
long expires = 0;
|
||||
if (presigned) {
|
||||
try {
|
||||
expires = Long.parseLong(query.getFirst("X-Amz-Expires"));
|
||||
if (expires < 1 || expires > MAX_EXPIRY_SECONDS) {
|
||||
throw new IllegalArgumentException("Invalid expiry");
|
||||
}
|
||||
} catch (RuntimeException error) {
|
||||
incompleteSignature(ctx, resource, "Presigned request requires X-Amz-Expires between 1 and 604800.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
String token = ctx.getHeaderString("X-Amz-Security-Token");
|
||||
boolean scopeMatches = true;
|
||||
if (presigned) {
|
||||
try {
|
||||
if (token == null) {
|
||||
token = RequestBodyReader.formField(ctx, "X-Amz-Security-Token");
|
||||
if (token == null) {
|
||||
token = query.getFirst("X-Amz-Security-Token");
|
||||
}
|
||||
}
|
||||
scopeMatches = queryScopeMatchesResource(ctx, resource, scope.service());
|
||||
} catch (IllegalArgumentException error) {
|
||||
incompleteSignature(ctx, resource, "Cannot read presigned request form parameters.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
Optional<String> secretKey = resolveSecretKey(scope.accessKeyId(), token);
|
||||
if (secretKey.isEmpty()) {
|
||||
LOG.debugv("Refusing {0} request signed with unknown access key {1}",
|
||||
scope.service(), SigV4RequestValidator.sanitizeForLog(scope.accessKeyId()));
|
||||
@@ -179,7 +225,9 @@ public class SigV4HeaderSignatureFilter implements ContainerRequestFilter {
|
||||
|
||||
String amzDate = AMZ_DATE.format(requestTime);
|
||||
Instant now = Instant.now();
|
||||
if (Duration.between(requestTime, now).abs().compareTo(MAX_CLOCK_SKEW) > 0) {
|
||||
if (presigned ? requestTime.isAfter(now.plus(MAX_CLOCK_SKEW))
|
||||
|| !now.isBefore(requestTime.plusSeconds(expires))
|
||||
: Duration.between(requestTime, now).abs().compareTo(MAX_CLOCK_SKEW) > 0) {
|
||||
signatureDoesNotMatch(ctx, resource, "Signature expired: " + amzDate + " is outside the "
|
||||
+ MAX_CLOCK_SKEW.toMinutes() + " minute window around the server time "
|
||||
+ AMZ_DATE.format(now) + ".");
|
||||
@@ -192,6 +240,11 @@ public class SigV4HeaderSignatureFilter implements ContainerRequestFilter {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!scopeMatches) {
|
||||
signatureDoesNotMatch(ctx, resource, "Credential should be scoped to the service receiving the request.");
|
||||
return;
|
||||
}
|
||||
|
||||
byte[] body = signedBody(ctx);
|
||||
UnaryOperator<String> headers = name -> "content-length".equals(name)
|
||||
&& ctx.getProperty(SqsQueueUrlRouterFilter.APPENDED_BODY_BYTES_PROPERTY) != null
|
||||
@@ -200,7 +253,7 @@ public class SigV4HeaderSignatureFilter implements ContainerRequestFilter {
|
||||
boolean matches;
|
||||
try {
|
||||
matches = signatureMatches(ctx.getMethod(), rawPath(ctx), rawQuery(ctx), signed.signedHeaders(),
|
||||
headers, body, secretKey.get(), amzDate, scope, signed.signature());
|
||||
headers, body, secretKey.get(), amzDate, scope, signed.signature(), presigned);
|
||||
} catch (Exception e) {
|
||||
LOG.debugv(e, "SigV4 verification failed to complete for accessKey={0}",
|
||||
SigV4RequestValidator.sanitizeForLog(scope.accessKeyId()));
|
||||
@@ -217,14 +270,48 @@ public class SigV4HeaderSignatureFilter implements ContainerRequestFilter {
|
||||
static boolean signatureMatches(String method, String rawPath, String rawQuery, String signedHeaders,
|
||||
UnaryOperator<String> headers, byte[] body, String secretKey,
|
||||
String amzDate, CredentialScope scope, String signature) throws Exception {
|
||||
return signatureMatches(method, rawPath, rawQuery, signedHeaders, headers, body,
|
||||
secretKey, amzDate, scope, signature, false);
|
||||
}
|
||||
|
||||
// Non-S3 body-bearing SDK presigners hash the body; only a signed payload marker opts out.
|
||||
private static boolean signatureMatches(String method, String rawPath, String rawQuery, String signedHeaders,
|
||||
UnaryOperator<String> headers, byte[] body, String secretKey,
|
||||
String amzDate, CredentialScope scope, String signature,
|
||||
boolean presigned) throws Exception {
|
||||
return SigV4Canonicalization.signatureMatches(method, rawPath,
|
||||
SigV4Canonicalization.canonicalQueryString(rawQuery, false),
|
||||
SigV4Canonicalization.canonicalQueryString(rawQuery, presigned),
|
||||
SigV4Canonicalization.canonicalHeaders(signedHeaders, headers),
|
||||
signedHeaders,
|
||||
SigV4Canonicalization.payloadHash(headers.apply("x-amz-content-sha256"), signedHeaders, body, false),
|
||||
amzDate, scope, secretKey, signature);
|
||||
}
|
||||
|
||||
private boolean queryScopeMatchesResource(ContainerRequestContext ctx, Class<?> resource, String service) {
|
||||
ServiceDescriptor descriptor;
|
||||
if (resource == AwsQueryController.class) {
|
||||
String action = AwsQueryServiceResolver.action(RequestBodyReader.formField(ctx, "Action"),
|
||||
RequestBodyReader.formField(ctx, "Operation"));
|
||||
String target = action == null ? null
|
||||
: AwsQueryController.inferServiceFromAction(action, RequestBodyReader.formField(ctx, "Version"));
|
||||
descriptor = target == null ? null : catalog.byExternalKey(target).orElse(null);
|
||||
} else if (ctx.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY) instanceof ProtocolClaim claim
|
||||
&& claim.service() != null) {
|
||||
descriptor = claim.service();
|
||||
} else {
|
||||
descriptor = resource == null ? null : catalog.byResourceClass(resource).orElse(null);
|
||||
}
|
||||
return descriptor == null || descriptor.credentialScopes().contains(service);
|
||||
}
|
||||
|
||||
private static Instant parseAmzDate(String value) {
|
||||
try {
|
||||
return value == null ? null : Instant.from(AMZ_DATE.parse(value));
|
||||
} catch (DateTimeParseException error) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The path as the client sent it, before any filter rewrote it or JAX-RS normalized it. Falls
|
||||
* back to the request URI when no Vert.x request is current.
|
||||
|
||||
+3
-2
@@ -136,8 +136,9 @@ public final class SigV4Canonicalization {
|
||||
*
|
||||
* <p>The sentinels ({@code UNSIGNED-PAYLOAD}, the {@code STREAMING-*} forms) mean the caller
|
||||
* chose not to sign the body, and are honoured only when {@code x-amz-content-sha256} is itself
|
||||
* in {@code SignedHeaders}: that is, when the choice is covered by the signature. A presigned
|
||||
* request is unsigned-payload by convention; every AWS presigner emits it that way.
|
||||
* in {@code SignedHeaders}: that is, when the choice is covered by the signature. Callers whose
|
||||
* presigning protocol uses an unsigned payload select it explicitly; body-bearing STS
|
||||
* requests from the Java SDK instead carry the actual body hash.
|
||||
*/
|
||||
public static String payloadHash(String declaredContentSha256, String signedHeaders, byte[] body,
|
||||
boolean presigned) throws Exception {
|
||||
|
||||
@@ -13,7 +13,7 @@ import java.net.URLDecoder;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
final class RequestBodyReader {
|
||||
public final class RequestBodyReader {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(RequestBodyReader.class);
|
||||
private static final String BUFFERED_BODY_PROPERTY =
|
||||
@@ -44,7 +44,7 @@ final class RequestBodyReader {
|
||||
return body;
|
||||
}
|
||||
|
||||
static String formField(ContainerRequestContext ctx, String key) {
|
||||
public static String formField(ContainerRequestContext ctx, String key) {
|
||||
MediaType mt = ctx.getMediaType();
|
||||
if (mt == null
|
||||
|| !"application".equalsIgnoreCase(mt.getType())
|
||||
|
||||
@@ -228,12 +228,14 @@ public class StsQueryHandler {
|
||||
|
||||
private Response handleGetCallerIdentity(MultivaluedMap<String, String> params) {
|
||||
String accountId = regionResolver.getAccountId();
|
||||
String authorization = headers == null ? null : headers.getHeaderString("Authorization");
|
||||
String accessKeyId = authorization == null ? null : accountResolver.extractAccessKeyId(authorization);
|
||||
String accessKeyId = callerAccessKeyId();
|
||||
String sessionToken = headers == null ? null : headers.getHeaderString("X-Amz-Security-Token");
|
||||
if (sessionToken == null && params != null) {
|
||||
sessionToken = getParam(params, "X-Amz-Security-Token");
|
||||
}
|
||||
if (sessionToken == null && uriInfo != null) {
|
||||
sessionToken = uriInfo.getQueryParameters().getFirst("X-Amz-Security-Token");
|
||||
}
|
||||
String arn = iamService.resolveCallerArn(accessKeyId)
|
||||
.orElse(regionResolver.buildGlobalArn("iam", accountId, "root"));
|
||||
String userId = iamService.resolveCallerUserId(accessKeyId, sessionToken).orElse(accountId);
|
||||
|
||||
Reference in new issue
Block a user