mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
fix(rds,elasticache): decode IAM auth token parameters once (#5039)
* fix(rds,elasticache): decode IAM auth token parameters once SigV4RequestValidator, which verifies the IAM auth tokens the RDS, Redshift, ElastiCache and MemoryDB proxies receive, URL-decoded every query parameter as it looked it up, then decoded X-Amz-Credential and X-Amz-Security-Token a second time. Session tokens are drawn from an alphabet that includes '+', '/' and '='. A presigner writes '+' as %2B; the first decode restored it and the second turned it into a space, so the session no longer matched and the token was refused with "password authentication failed". Every token signed with a Lambda function's execution-role credentials failed this way, from the AWS CLI, botocore and the Go SDK's feature/rds/auth alike, while AssumeRole credentials passed only because their tokens are alphanumeric. The second decode also let a token carrying %252B stand in for a session whose token holds a literal '+'. SigV4 defines the canonical query string as each parameter name and value URI-encoded (only A-Z a-z 0-9 - . _ ~ left as they are, uppercase hex, a space as %20, '/' encoded), sorted by encoded name and then by value. The validator now decodes each parameter exactly once, keeping a literal '+' as a plus as the API Gateway and EKS verifiers already do, looks the session up with that value, and rebuilds the canonical query string from the decoded parameters rather than hashing the bytes on the wire, so the token is checked against the string its signer hashed whichever valid percent-encoding it travelled in. Using the raw pairs as before would have fixed the session lookup alone, but would still reject a token whose credential travels with literal slashes or lowercase hex. The test token helper encoded values with URLEncoder, whose form encoding writes a space as '+' and leaves '*' unescaped, which no SDK presigner does; it now applies SigV4's UriEncode. S3 presigned URLs do not go through this validator and read X-Amz-Security-Token once already: a URL presigned with a Lambda session's credentials is served, and one whose token reads a space for the '+' is refused. * fix(rds): authorize the key the token's signature was verified with The signature check reads a token's parameters with their names percent-decoded, and takes the first X-Amz-Credential it finds. The rds-db:connect check read the credential again from the raw query, matching the name byte for byte. A token that spelled its signer's credential as X-Amz%2DCredential and added a plain X-Amz-Credential of a key IAM does not know was verified with the signer's key and authorized on the unknown one, which IAM enforcement waves through: the connection was allowed whatever the signer's policy said. SigV4RequestValidator.queryParameter reads a parameter exactly as the signature check does, and RdsSigV4Validator takes the credential scope from there, so the key authorized is the key that signed. validateAuthorizesTheKeyTheSignatureWasVerifiedWith signs such a token as SigV4 signs a query and expects it refused; it was accepted before. RdsIamAuthLambdaSessionIntegrationTest now creates its database inside the try whose finally deletes it, so a create that fails an assertion leaves no container behind.
This commit is contained in:
1 parent
38ce99ba54
commit
3041d6bd90
8 files changed
+453
-43
No files matched your search
+90
-28
@@ -11,7 +11,9 @@ import java.security.MessageDigest;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Arrays;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@@ -71,14 +73,14 @@ public final class SigV4RequestValidator {
|
||||
public boolean validate(String rawQuery, String canonicalHostHeaderValue, String identityParamName,
|
||||
boolean identityRequired, String expectedIdentityValue, String logLabel) {
|
||||
try {
|
||||
String[] rawPairs = rawQuery.split("&");
|
||||
String action = findRawParam(rawPairs, "Action");
|
||||
String identity = findRawParam(rawPairs, identityParamName);
|
||||
String dateTime = findRawParam(rawPairs, "X-Amz-Date");
|
||||
String expires = findRawParam(rawPairs, "X-Amz-Expires");
|
||||
String credential = findRawParam(rawPairs, "X-Amz-Credential");
|
||||
String signedHeaders = findRawParam(rawPairs, "X-Amz-SignedHeaders");
|
||||
String signature = findRawParam(rawPairs, "X-Amz-Signature");
|
||||
List<QueryParameter> parameters = decodeQuery(rawQuery);
|
||||
String action = findParam(parameters, "Action");
|
||||
String identity = findParam(parameters, identityParamName);
|
||||
String dateTime = findParam(parameters, "X-Amz-Date");
|
||||
String expires = findParam(parameters, "X-Amz-Expires");
|
||||
String credential = findParam(parameters, "X-Amz-Credential");
|
||||
String signedHeaders = findParam(parameters, "X-Amz-SignedHeaders");
|
||||
String signature = findParam(parameters, "X-Amz-Signature");
|
||||
|
||||
if (!"connect".equals(action) || (identityRequired && identity == null) || dateTime == null
|
||||
|| expires == null || credential == null || signedHeaders == null || signature == null) {
|
||||
@@ -99,8 +101,7 @@ public final class SigV4RequestValidator {
|
||||
return false;
|
||||
}
|
||||
|
||||
String decodedCredential = urlDecode(credential);
|
||||
String[] credParts = decodedCredential.split("/");
|
||||
String[] credParts = credential.split("/");
|
||||
if (credParts.length < 5) {
|
||||
return false;
|
||||
}
|
||||
@@ -114,9 +115,8 @@ public final class SigV4RequestValidator {
|
||||
if (LEGACY_ACCESS_KEY_ID.equals(accessKeyId)) {
|
||||
secretKey = LEGACY_SECRET_KEY;
|
||||
} else {
|
||||
String sessionToken = findRawParam(rawPairs, "X-Amz-Security-Token");
|
||||
Optional<String> registeredSecretKey = iamService.findSecretKey(
|
||||
accessKeyId, sessionToken == null ? null : urlDecode(sessionToken));
|
||||
accessKeyId, findParam(parameters, "X-Amz-Security-Token"));
|
||||
if (registeredSecretKey.isEmpty()) {
|
||||
LOG.debugv("{0} references unregistered access key={1}", logLabel, sanitizeForLog(accessKeyId));
|
||||
return false;
|
||||
@@ -124,13 +124,8 @@ public final class SigV4RequestValidator {
|
||||
secretKey = registeredSecretKey.get();
|
||||
}
|
||||
|
||||
String canonicalQueryString = Arrays.stream(rawPairs)
|
||||
.filter(p -> !rawParamName(p).equals("X-Amz-Signature"))
|
||||
.sorted((a, b) -> rawParamName(a).compareTo(rawParamName(b)))
|
||||
.collect(Collectors.joining("&"));
|
||||
|
||||
String canonicalRequest = "GET\n/\n"
|
||||
+ canonicalQueryString + "\n"
|
||||
+ canonicalQueryString(parameters) + "\n"
|
||||
+ "host:" + canonicalHostHeaderValue + "\n\n"
|
||||
+ "host\n"
|
||||
+ "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
|
||||
@@ -157,23 +152,90 @@ public final class SigV4RequestValidator {
|
||||
}
|
||||
}
|
||||
|
||||
private static String rawParamName(String rawPair) {
|
||||
int eq = rawPair.indexOf('=');
|
||||
return eq >= 0 ? rawPair.substring(0, eq) : rawPair;
|
||||
private record QueryParameter(String name, String value) {}
|
||||
|
||||
/**
|
||||
* The value of {@code name} in a token's query string, read as {@link #validate} reads it: the
|
||||
* first parameter whose percent-decoded name matches, its value decoded once. A caller that acts
|
||||
* on a parameter after validating the token reads it here, so it acts on what was verified: a
|
||||
* name spelled with a percent-encoded character, or a parameter given twice, cannot make it read
|
||||
* a different credential than the one the signature was checked with.
|
||||
*/
|
||||
public static String queryParameter(String rawQuery, String name) {
|
||||
return findParam(decodeQuery(rawQuery), name);
|
||||
}
|
||||
|
||||
private static String findRawParam(String[] rawPairs, String name) {
|
||||
for (String pair : rawPairs) {
|
||||
/**
|
||||
* Every parameter of the token's query string, its name and value percent-decoded exactly once.
|
||||
* A session token is drawn from an alphabet that includes {@code +}, {@code /} and {@code =}, and
|
||||
* the presigner writes it percent-encoded once; decoding it again would turn every {@code +}
|
||||
* into a space, and a literal {@code %2B} into a {@code +}.
|
||||
*/
|
||||
private static List<QueryParameter> decodeQuery(String rawQuery) {
|
||||
List<QueryParameter> parameters = new ArrayList<>();
|
||||
for (String pair : rawQuery.split("&")) {
|
||||
if (pair.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
int eq = pair.indexOf('=');
|
||||
if (eq >= 0 && name.equals(pair.substring(0, eq))) {
|
||||
return urlDecode(pair.substring(eq + 1));
|
||||
parameters.add(new QueryParameter(
|
||||
decodeQueryComponent(eq >= 0 ? pair.substring(0, eq) : pair),
|
||||
decodeQueryComponent(eq >= 0 ? pair.substring(eq + 1) : "")));
|
||||
}
|
||||
return parameters;
|
||||
}
|
||||
|
||||
private static String findParam(List<QueryParameter> parameters, String name) {
|
||||
for (QueryParameter parameter : parameters) {
|
||||
if (parameter.name().equals(name)) {
|
||||
return parameter.value();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static String urlDecode(String value) {
|
||||
return URLDecoder.decode(value, StandardCharsets.UTF_8);
|
||||
/**
|
||||
* SigV4's canonical query string: every parameter but {@code X-Amz-Signature}, its name and
|
||||
* value each URI-encoded, sorted by encoded name and then by encoded value. Built from the
|
||||
* decoded parameters rather than the bytes on the wire, so it is the string the signer hashed
|
||||
* whichever valid percent-encoding the token travelled in.
|
||||
*/
|
||||
private static String canonicalQueryString(List<QueryParameter> parameters) {
|
||||
return parameters.stream()
|
||||
.filter(parameter -> !"X-Amz-Signature".equals(parameter.name()))
|
||||
.map(parameter -> new QueryParameter(uriEncode(parameter.name()), uriEncode(parameter.value())))
|
||||
.sorted(Comparator.comparing(QueryParameter::name).thenComparing(QueryParameter::value))
|
||||
.map(parameter -> parameter.name() + "=" + parameter.value())
|
||||
.collect(Collectors.joining("&"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Percent-decodes a query-string component without {@code URLDecoder}'s form-encoding rule that
|
||||
* a literal {@code +} means a space: SigV4 signers escape a space as {@code %20}, so a raw
|
||||
* {@code +} on the wire is a plus sign.
|
||||
*/
|
||||
private static String decodeQueryComponent(String value) {
|
||||
return URLDecoder.decode(value.replace("+", "%2B"), StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
/**
|
||||
* SigV4's UriEncode: every byte of the UTF-8 form except {@code A-Z a-z 0-9 - . _ ~} becomes
|
||||
* {@code %XY} with uppercase hex, a space included ({@code %20}, never {@code +}) and {@code /}
|
||||
* included.
|
||||
*/
|
||||
private static String uriEncode(String value) {
|
||||
StringBuilder encoded = new StringBuilder(value.length());
|
||||
for (byte raw : value.getBytes(StandardCharsets.UTF_8)) {
|
||||
int unsigned = Byte.toUnsignedInt(raw);
|
||||
if ((unsigned >= 'A' && unsigned <= 'Z') || (unsigned >= 'a' && unsigned <= 'z')
|
||||
|| (unsigned >= '0' && unsigned <= '9') || unsigned == '-' || unsigned == '.'
|
||||
|| unsigned == '_' || unsigned == '~') {
|
||||
encoded.append((char) unsigned);
|
||||
} else {
|
||||
encoded.append('%').append(String.format("%02X", unsigned));
|
||||
}
|
||||
}
|
||||
return encoded.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -12,8 +12,6 @@ import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Map;
|
||||
import java.util.function.BooleanSupplier;
|
||||
|
||||
@@ -137,17 +135,15 @@ public class RdsSigV4Validator {
|
||||
/**
|
||||
* The {@code X-Amz-Credential} scope split into its parts
|
||||
* ({@code accessKeyId/date/region/service/aws4_request}), or {@code null} if absent or malformed.
|
||||
* Read as the signature check reads it, so the key authorized is the key that signed.
|
||||
*/
|
||||
private static String[] credentialScope(String rawQuery) {
|
||||
for (String pair : rawQuery.split("&")) {
|
||||
int eq = pair.indexOf('=');
|
||||
if (eq >= 0 && "X-Amz-Credential".equals(pair.substring(0, eq))) {
|
||||
String[] parts = URLDecoder.decode(pair.substring(eq + 1), StandardCharsets.UTF_8)
|
||||
.split("/");
|
||||
return parts.length >= 5 ? parts : null;
|
||||
}
|
||||
String credential = SigV4RequestValidator.queryParameter(rawQuery, "X-Amz-Credential");
|
||||
if (credential == null) {
|
||||
return null;
|
||||
}
|
||||
return null;
|
||||
String[] parts = credential.split("/");
|
||||
return parts.length >= 5 ? parts : null;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in new issue
Block a user