diff --git a/src/main/java/io/github/hectorvent/floci/core/common/auth/CredentialScope.java b/src/main/java/io/github/hectorvent/floci/core/common/auth/CredentialScope.java new file mode 100644 index 0000000000..6eae14fc5a --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/core/common/auth/CredentialScope.java @@ -0,0 +1,39 @@ +package io.github.hectorvent.floci.core.common.auth; + +import java.util.Locale; + +/** + * A SigV4 credential scope, the {@code accessKeyId/date/region/service/aws4_request} value + * carried by a {@code Credential} parameter, whether that parameter arrived in an + * {@code Authorization} header or an {@code X-Amz-Credential} query/token component. Shared by + * every SigV4 verifier in this codebase that checks an Authorization-header-signed request + * against this exact five-part shape: {@code ExecuteApiSigV4Authorizer} (API Gateway) and + * {@code IamAuthValidator} (AppSync) both parsed and rebuilt this independently before this class + * existed. + */ +public record CredentialScope(String accessKeyId, String date, String region, String service) { + + private static final String TERMINATOR = "aws4_request"; + + public String credentialScope() { + return date + "/" + region + "/" + service + "/" + TERMINATOR; + } + + /** + * {@code credential} is expected already percent-decoded: a header credential is never + * encoded, and JAX-RS decodes a presigned {@code X-Amz-Credential} before this sees it. + */ + public static CredentialScope parse(String credential) { + if (credential == null) { + return null; + } + String[] parts = credential.split("/"); + if (parts.length != 5 || !TERMINATOR.equals(parts[4])) { + return null; + } + if (parts[0].isBlank() || parts[1].length() != 8 || parts[2].isBlank() || parts[3].isBlank()) { + return null; + } + return new CredentialScope(parts[0], parts[1], parts[2], parts[3].toLowerCase(Locale.ROOT)); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/core/common/auth/SigV4RequestValidator.java b/src/main/java/io/github/hectorvent/floci/core/common/auth/SigV4RequestValidator.java index 4608551daf..e6b5eaf3b4 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/auth/SigV4RequestValidator.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/auth/SigV4RequestValidator.java @@ -180,10 +180,15 @@ public final class SigV4RequestValidator { * Strips control characters (CR, LF, etc.) from an attacker-controlled value before it is * interpolated into a log line, preventing log injection / forged multi-line log entries. */ - private static String sanitizeForLog(String value) { + public static String sanitizeForLog(String value) { return value == null ? null : value.replaceAll("\\p{Cntrl}", ""); } + /** SigV4 canonical header value normalization: trim, then collapse whitespace runs to one space. */ + public static String normalizeHeaderValue(String value) { + return value == null ? "" : value.trim().replaceAll("\\s+", " "); + } + /** * Public so other SigV4 verifiers with a different canonical-request shape (e.g. S3's real * REST request signing in {@code PreSignedUrlFilter}) can reuse the crypto primitives below @@ -209,6 +214,11 @@ public final class SigV4RequestValidator { return hexEncode(digest.digest(input.getBytes(StandardCharsets.UTF_8))); } + public static String sha256Hex(byte[] input) throws Exception { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + return hexEncode(digest.digest(input)); + } + public static String hexEncode(byte[] bytes) { StringBuilder sb = new StringBuilder(bytes.length * 2); for (byte b : bytes) { diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ExecuteApiSigV4Authorizer.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ExecuteApiSigV4Authorizer.java index dc5f3844e5..23b029bfcd 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ExecuteApiSigV4Authorizer.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ExecuteApiSigV4Authorizer.java @@ -1,6 +1,8 @@ package io.github.hectorvent.floci.services.apigateway; import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.common.auth.CredentialScope; +import io.github.hectorvent.floci.core.common.auth.SigV4RequestValidator; import io.github.hectorvent.floci.services.iam.IamService; import io.github.hectorvent.floci.services.iam.model.AccessKey; import io.github.hectorvent.floci.services.iam.model.IamUser; @@ -11,8 +13,6 @@ import jakarta.ws.rs.core.MultivaluedMap; import jakarta.ws.rs.core.UriInfo; import org.jboss.logging.Logger; -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; import java.net.URI; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; @@ -61,7 +61,6 @@ public class ExecuteApiSigV4Authorizer { private static final String ALGORITHM = "AWS4-HMAC-SHA256"; private static final String SIGNING_SERVICE = "execute-api"; - private static final String TERMINATOR = "aws4_request"; private static final DateTimeFormatter AMZ_DATE = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC); @@ -182,7 +181,7 @@ public class ExecuteApiSigV4Authorizer { String secretKey = resolveSecretKey(scope.accessKeyId()); if (secretKey == null) { LOG.debugv("execute-api request references unregistered access key={0}", - sanitizeForLog(scope.accessKeyId())); + SigV4RequestValidator.sanitizeForLog(scope.accessKeyId())); return Result.rejected(Failure.UNKNOWN_KEY, "access key is not registered"); } @@ -194,7 +193,8 @@ public class ExecuteApiSigV4Authorizer { String payloadHash = payloadHash(headers, body, presigned, signed.signedHeaders()); String canonicalHeaders = canonicalHeaders(signed.signedHeaders(), headers, uriInfo); String canonicalQueryString = canonicalQueryString(uriInfo.getRequestUri().getRawQuery(), presigned); - byte[] signingKey = deriveSigningKey(secretKey, scope.date(), scope.region(), scope.service()); + byte[] signingKey = SigV4RequestValidator.deriveSigningKey( + secretKey, scope.date(), scope.region(), scope.service()); String rawPath = signedRequestPath != null ? signedRequestPath @@ -209,8 +209,9 @@ public class ExecuteApiSigV4Authorizer { String stringToSign = ALGORITHM + "\n" + signed.amzDate() + "\n" + scope.credentialScope() + "\n" - + sha256Hex(canonicalRequest.getBytes(StandardCharsets.UTF_8)); - String expected = hexEncode(hmacSha256(signingKey, stringToSign)); + + SigV4RequestValidator.sha256Hex(canonicalRequest.getBytes(StandardCharsets.UTF_8)); + String expected = SigV4RequestValidator.hexEncode( + SigV4RequestValidator.hmacSha256(signingKey, stringToSign)); if (MessageDigest.isEqual(expected.getBytes(StandardCharsets.UTF_8), signed.signature().getBytes(StandardCharsets.UTF_8))) { return new Result(null, null, resolveIdentity(scope.accessKeyId())); @@ -218,7 +219,7 @@ public class ExecuteApiSigV4Authorizer { } LOG.debugv("execute-api SigV4 signature mismatch for accessKey={0}", - sanitizeForLog(scope.accessKeyId())); + SigV4RequestValidator.sanitizeForLog(scope.accessKeyId())); return Result.rejected(Failure.MISMATCH, "signature does not match"); } @@ -270,7 +271,7 @@ public class ExecuteApiSigV4Authorizer { } if (iamService.resolveAccountId(accessKeyId).isEmpty()) { LOG.debugv("execute-api request uses an expired or inactive credential: accessKey={0}", - sanitizeForLog(accessKeyId)); + SigV4RequestValidator.sanitizeForLog(accessKeyId)); return null; } return secretKey; @@ -307,7 +308,7 @@ public class ExecuteApiSigV4Authorizer { } if (isBlank(presented)) { LOG.debugv("execute-api request uses temporary credential accessKey={0} with no {1}", - sanitizeForLog(accessKeyId), SECURITY_TOKEN); + SigV4RequestValidator.sanitizeForLog(accessKeyId), SECURITY_TOKEN); return Result.rejected(Failure.UNKNOWN_KEY, "temporary credential presents no session token"); } String issued = iamService.findSessionToken(accessKeyId).orElse(null); @@ -317,7 +318,7 @@ public class ExecuteApiSigV4Authorizer { if (!MessageDigest.isEqual(issued.getBytes(StandardCharsets.UTF_8), presented.getBytes(StandardCharsets.UTF_8))) { LOG.debugv("execute-api request presents a session token that does not match the one" - + " issued for accessKey={0}", sanitizeForLog(accessKeyId)); + + " issued for accessKey={0}", SigV4RequestValidator.sanitizeForLog(accessKeyId)); return Result.rejected(Failure.UNKNOWN_KEY, "session token does not match the issued credential"); } return null; @@ -385,36 +386,13 @@ public class ExecuteApiSigV4Authorizer { expiresSeconds = expires == null ? null : Long.valueOf(expires.trim()); } catch (NumberFormatException e) { LOG.debugv("execute-api presigned request carries a non-numeric X-Amz-Expires: {0}", - sanitizeForLog(expires)); + SigV4RequestValidator.sanitizeForLog(expires)); expiresSeconds = null; } return new SignedRequest(credential, signedHeaders.toLowerCase(Locale.ROOT), signature, amzDate, expiresSeconds); } - private record CredentialScope(String accessKeyId, String date, String region, String service) { - - String credentialScope() { - return date + "/" + region + "/" + service + "/" + TERMINATOR; - } - - /** {@code credential} is expected already percent-decoded: a header credential is never - * encoded, and JAX-RS decodes the presigned {@code X-Amz-Credential} before we see it. */ - static CredentialScope parse(String credential) { - if (credential == null) { - return null; - } - String[] parts = credential.split("/"); - if (parts.length != 5 || !TERMINATOR.equals(parts[4])) { - return null; - } - if (parts[0].isBlank() || parts[1].length() != 8 || parts[2].isBlank() || parts[3].isBlank()) { - return null; - } - return new CredentialScope(parts[0], parts[1], parts[2], parts[3].toLowerCase(Locale.ROOT)); - } - } - // ──────────────────────────── Canonical request ──────────────────────────── /** @@ -474,7 +452,7 @@ public class ExecuteApiSigV4Authorizer { StringBuilder canonical = new StringBuilder(); for (String name : signedHeaders.split(";")) { String value = "host".equals(name) ? hostHeader(headers, uriInfo) : headerValue(headers, name); - canonical.append(name).append(':').append(normalizeHeaderValue(value)).append('\n'); + canonical.append(name).append(':').append(SigV4RequestValidator.normalizeHeaderValue(value)).append('\n'); } return canonical.toString(); } @@ -501,10 +479,6 @@ public class ExecuteApiSigV4Authorizer { : String.valueOf(requestUri.getHost()); } - private static String normalizeHeaderValue(String value) { - return value == null ? "" : value.trim().replaceAll("\\s+", " "); - } - /** * The payload hash the canonical request must carry. * @@ -530,7 +504,7 @@ public class ExecuteApiSigV4Authorizer { if (presigned) { return "UNSIGNED-PAYLOAD"; } - return sha256Hex(body == null ? new byte[0] : body); + return SigV4RequestValidator.sha256Hex(body == null ? new byte[0] : body); } private static boolean containsHeader(String signedHeaders, String name) { @@ -556,33 +530,6 @@ public class ExecuteApiSigV4Authorizer { // ──────────────────────────── Crypto and encoding helpers ──────────────────────────── - private static byte[] deriveSigningKey(String secretKey, String date, String region, String service) - throws Exception { - byte[] kSecret = ("AWS4" + secretKey).getBytes(StandardCharsets.UTF_8); - byte[] kDate = hmacSha256(kSecret, date); - byte[] kRegion = hmacSha256(kDate, region); - byte[] kService = hmacSha256(kRegion, service); - return hmacSha256(kService, TERMINATOR); - } - - private static byte[] hmacSha256(byte[] key, String data) throws Exception { - Mac mac = Mac.getInstance("HmacSHA256"); - mac.init(new SecretKeySpec(key, "HmacSHA256")); - return mac.doFinal(data.getBytes(StandardCharsets.UTF_8)); - } - - private static String sha256Hex(byte[] input) throws Exception { - return hexEncode(MessageDigest.getInstance("SHA-256").digest(input)); - } - - private static String hexEncode(byte[] bytes) { - StringBuilder hex = new StringBuilder(bytes.length * 2); - for (byte b : bytes) { - hex.append(Character.forDigit((b >> 4) & 0xF, 16)).append(Character.forDigit(b & 0xF, 16)); - } - return hex.toString(); - } - /** RFC 3986 percent-encoding as SigV4 defines it: {@code /} is escaped, {@code -._~} are not. */ private static String uriEncode(String value) { StringBuilder encoded = new StringBuilder(value.length()); @@ -616,9 +563,4 @@ public class ExecuteApiSigV4Authorizer { private static boolean isBlank(String value) { return value == null || value.isBlank(); } - - /** Strips control characters from attacker-controlled values before they reach a log line. */ - private static String sanitizeForLog(String value) { - return value == null ? null : value.replaceAll("\\p{Cntrl}", ""); - } } diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/IamAuthValidator.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/IamAuthValidator.java index df9dec33d0..462d71dcb4 100644 --- a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/IamAuthValidator.java +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/IamAuthValidator.java @@ -2,6 +2,8 @@ package io.github.hectorvent.floci.services.appsync.graphql.auth; import io.github.hectorvent.floci.core.common.AwsRegions; import io.github.hectorvent.floci.core.common.AccountResolver; +import io.github.hectorvent.floci.core.common.auth.CredentialScope; +import io.github.hectorvent.floci.core.common.auth.SigV4RequestValidator; import io.github.hectorvent.floci.services.appsync.graphql.AppSyncTransportException; import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator; import io.github.hectorvent.floci.services.iam.IamService; @@ -10,8 +12,6 @@ import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.time.Instant; @@ -44,7 +44,6 @@ public class IamAuthValidator { private static final String ALGORITHM = "AWS4-HMAC-SHA256"; private static final String SIGNING_SERVICE = "appsync"; - private static final String TERMINATOR = "aws4_request"; private static final DateTimeFormatter AMZ_DATE = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC); private static final long MAX_CLOCK_SKEW_SECONDS = 300; @@ -120,23 +119,27 @@ public class IamAuthValidator { } String secretKey = resolveSecretKey(accessKeyId); if (secretKey == null) { - LOG.debugv("AppSync SigV4 request references unregistered access key={0}", sanitizeForLog(accessKeyId)); + LOG.debugv("AppSync SigV4 request references unregistered access key={0}", + SigV4RequestValidator.sanitizeForLog(accessKeyId)); throw AppSyncAuth.unauthorized(); } checkSessionToken(accessKeyId, info.requestHeaders()); try { String canonicalUri = "/v1/apis/" + apiId + "/graphql"; - String payloadHash = sha256Hex(info.rawBody().getBytes(StandardCharsets.UTF_8)); + String payloadHash = SigV4RequestValidator.sha256Hex(info.rawBody().getBytes(StandardCharsets.UTF_8)); String canonicalHeaders = canonicalHeaders(signed.signedHeaders(), info.requestHeaders()); String canonicalRequest = "POST\n" + canonicalUri + "\n\n" + canonicalHeaders + "\n" + signed.signedHeaders() + "\n" + payloadHash; String stringToSign = ALGORITHM + "\n" + signed.amzDate() + "\n" + scope.credentialScope() + "\n" - + sha256Hex(canonicalRequest.getBytes(StandardCharsets.UTF_8)); - byte[] signingKey = deriveSigningKey(secretKey, scope.date(), scope.region(), scope.service()); - String expected = hexEncode(hmacSha256(signingKey, stringToSign)); + + SigV4RequestValidator.sha256Hex(canonicalRequest.getBytes(StandardCharsets.UTF_8)); + byte[] signingKey = SigV4RequestValidator.deriveSigningKey( + secretKey, scope.date(), scope.region(), scope.service()); + String expected = SigV4RequestValidator.hexEncode( + SigV4RequestValidator.hmacSha256(signingKey, stringToSign)); if (!MessageDigest.isEqual(expected.getBytes(StandardCharsets.UTF_8), signed.signature().getBytes(StandardCharsets.UTF_8))) { - LOG.debugv("AppSync SigV4 signature mismatch for accessKey={0}", sanitizeForLog(accessKeyId)); + LOG.debugv("AppSync SigV4 signature mismatch for accessKey={0}", + SigV4RequestValidator.sanitizeForLog(accessKeyId)); throw AppSyncAuth.unauthorized(); } } catch (AppSyncTransportException e) { @@ -182,7 +185,7 @@ public class IamAuthValidator { String presented = header(requestHeaders, SECURITY_TOKEN); if (isBlank(presented)) { LOG.debugv("AppSync SigV4 request uses temporary credential accessKey={0} with no {1}", - sanitizeForLog(accessKeyId), SECURITY_TOKEN); + SigV4RequestValidator.sanitizeForLog(accessKeyId), SECURITY_TOKEN); throw AppSyncAuth.unauthorized(); } String issued = iamService.findSessionToken(accessKeyId).orElse(null); @@ -192,7 +195,7 @@ public class IamAuthValidator { if (!MessageDigest.isEqual(issued.getBytes(StandardCharsets.UTF_8), presented.getBytes(StandardCharsets.UTF_8))) { LOG.debugv("AppSync SigV4 request presents a session token that does not match the one" - + " issued for accessKey={0}", sanitizeForLog(accessKeyId)); + + " issued for accessKey={0}", SigV4RequestValidator.sanitizeForLog(accessKeyId)); throw AppSyncAuth.unauthorized(); } } @@ -233,31 +236,11 @@ public class IamAuthValidator { return new SignedRequest(credential, signedHeaders.toLowerCase(Locale.ROOT), signature, amzDate); } - private record CredentialScope(String accessKeyId, String date, String region, String service) { - - String credentialScope() { - return date + "/" + region + "/" + service + "/" + TERMINATOR; - } - - static CredentialScope parse(String credential) { - if (credential == null) { - return null; - } - String[] parts = credential.split("/"); - if (parts.length != 5 || !TERMINATOR.equals(parts[4])) { - return null; - } - if (parts[0].isBlank() || parts[1].length() != 8 || parts[2].isBlank() || parts[3].isBlank()) { - return null; - } - return new CredentialScope(parts[0], parts[1], parts[2], parts[3].toLowerCase(Locale.ROOT)); - } - } - private static String canonicalHeaders(String signedHeaders, Map requestHeaders) { StringBuilder canonical = new StringBuilder(); for (String name : signedHeaders.split(";")) { - canonical.append(name).append(':').append(normalizeHeaderValue(header(requestHeaders, name))).append('\n'); + canonical.append(name).append(':') + .append(SigV4RequestValidator.normalizeHeaderValue(header(requestHeaders, name))).append('\n'); } return canonical.toString(); } @@ -278,46 +261,10 @@ public class IamAuthValidator { return ""; } - private static String normalizeHeaderValue(String value) { - return value == null ? "" : value.trim().replaceAll("\\s+", " "); - } - - private static byte[] deriveSigningKey(String secretKey, String date, String region, String service) - throws Exception { - byte[] kSecret = ("AWS4" + secretKey).getBytes(StandardCharsets.UTF_8); - byte[] kDate = hmacSha256(kSecret, date); - byte[] kRegion = hmacSha256(kDate, region); - byte[] kService = hmacSha256(kRegion, service); - return hmacSha256(kService, TERMINATOR); - } - - private static byte[] hmacSha256(byte[] key, String data) throws Exception { - Mac mac = Mac.getInstance("HmacSHA256"); - mac.init(new SecretKeySpec(key, "HmacSHA256")); - return mac.doFinal(data.getBytes(StandardCharsets.UTF_8)); - } - - private static String sha256Hex(byte[] input) throws Exception { - return hexEncode(MessageDigest.getInstance("SHA-256").digest(input)); - } - - private static String hexEncode(byte[] bytes) { - StringBuilder hex = new StringBuilder(bytes.length * 2); - for (byte b : bytes) { - hex.append(Character.forDigit((b >> 4) & 0xF, 16)).append(Character.forDigit(b & 0xF, 16)); - } - return hex.toString(); - } - private static boolean isBlank(String value) { return value == null || value.isBlank(); } - /** Strips control characters from attacker-controlled values before they reach a log line. */ - private static String sanitizeForLog(String value) { - return value == null ? null : value.replaceAll("\\p{Cntrl}", ""); - } - public boolean isFieldDenied(String accessKeyId, String fieldArn) { if (accessKeyId == null || isEmulatorAllow(accessKeyId)) { return false;