mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(sts): give web identity and SAML trust policies the sts:RoleSessionName key (#8920)
This commit is contained in:
1 parent
91ed539910
commit
7b88a31956
12 files changed
+448
-41
No files matched your search
@@ -25,6 +25,7 @@ import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/** Verifies the specific SAML assertion contract consumed by STS. */
|
||||
final class SAMLAssertionVerifier {
|
||||
@@ -33,14 +34,19 @@ final class SAMLAssertionVerifier {
|
||||
private static final String AUDIENCE = "urn:amazon:webservices";
|
||||
static final String ASSERTION_INVALID = "The SAML assertion is invalid.";
|
||||
static final String SIGNATURE_INVALID = "Response signature invalid";
|
||||
private static final String ROLE_SESSION_NAME = "https://aws.amazon.com/SAML/Attributes/RoleSessionName";
|
||||
// The pattern AWS names in its error for a RoleSessionName attribute outside it.
|
||||
static final String ROLE_SESSION_NAME_INVALID = "RoleSessionName in AuthnResponse must match [a-zA-Z_0-9+=,.@-]{2,64}";
|
||||
private static final Pattern ROLE_SESSION_NAME_PATTERN = Pattern.compile("[a-zA-Z_0-9+=,.@-]{2,64}");
|
||||
// SAML 2.0 core 5.4.4. AWS rejects any other reference transform as an invalid signature.
|
||||
private static final Set<String> ALLOWED_TRANSFORMS = Set.of(
|
||||
Transform.ENVELOPED, CanonicalizationMethod.EXCLUSIVE, CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS);
|
||||
|
||||
private SAMLAssertionVerifier() {}
|
||||
|
||||
/** {@code roleSessionName} is null when the assertion carries no RoleSessionName attribute. */
|
||||
record Verified(String issuer, String subject, String subjectType, String nameQualifier,
|
||||
Instant expiration, List<RolePair> roles) {}
|
||||
Instant expiration, List<RolePair> roles, String roleSessionName) {}
|
||||
record RolePair(String roleArn, String principalArn) {}
|
||||
|
||||
static Verified verify(String encoded, SAMLProvider provider, Instant now) throws InvalidAssertionException {
|
||||
@@ -169,9 +175,10 @@ final class SAMLAssertionVerifier {
|
||||
if (roles.isEmpty()) {
|
||||
throw invalid("role pair missing");
|
||||
}
|
||||
String roleSessionName = roleSessionName(attributes);
|
||||
String nameQualifier = Base64.getEncoder().encodeToString(
|
||||
Digests.sha1((issuer + provider.getArn()).getBytes(StandardCharsets.UTF_8)));
|
||||
return new Verified(issuer, name, subjectType, nameQualifier, notOnOrAfter, roles);
|
||||
return new Verified(issuer, name, subjectType, nameQualifier, notOnOrAfter, roles, roleSessionName);
|
||||
} catch (InvalidAssertionException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
@@ -179,6 +186,26 @@ final class SAMLAssertionVerifier {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The value of the RoleSessionName attribute, whose name is case-sensitive and which "contains
|
||||
* one AttributeValue element", or null when the assertion has no such attribute.
|
||||
*/
|
||||
private static String roleSessionName(NodeList attributes) throws InvalidAssertionException {
|
||||
for (int i = 0; i < attributes.getLength(); i++) {
|
||||
Element attribute = (Element) attributes.item(i);
|
||||
if (!ROLE_SESSION_NAME.equals(attribute.getAttribute("Name"))) {
|
||||
continue;
|
||||
}
|
||||
Element value = first(attribute, SAML, "AttributeValue");
|
||||
String sessionName = value == null ? "" : value.getTextContent();
|
||||
if (!ROLE_SESSION_NAME_PATTERN.matcher(sessionName).matches()) {
|
||||
throw new InvalidAssertionException("role session name", ROLE_SESSION_NAME_INVALID);
|
||||
}
|
||||
return sessionName;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static X509Certificate certificate(String encoded) throws Exception {
|
||||
byte[] der = Base64.getDecoder().decode(encoded.replaceAll("\\s+", ""));
|
||||
return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(new ByteArrayInputStream(der));
|
||||
|
||||
@@ -13,13 +13,19 @@ import java.util.stream.StreamSupport;
|
||||
/** Evaluates the federated principal and SAML action in a role trust policy. */
|
||||
@ApplicationScoped
|
||||
public class SAMLTrustPolicyEvaluator {
|
||||
private static final String ROLE_SESSION_NAME_KEY = "sts:RoleSessionName";
|
||||
private final ObjectMapper mapper;
|
||||
@Inject
|
||||
public SAMLTrustPolicyEvaluator(ObjectMapper mapper) {
|
||||
this.mapper = mapper;
|
||||
}
|
||||
|
||||
public boolean allows(String document, String providerArn, Map<String, List<String>> claims) {
|
||||
/**
|
||||
* {@code roleSessionName} is the assertion's {@code RoleSessionName} attribute, which a policy
|
||||
* reads as {@code sts:RoleSessionName}, or null when the assertion carries none.
|
||||
*/
|
||||
public boolean allows(String document, String providerArn, Map<String, List<String>> claims,
|
||||
String roleSessionName) {
|
||||
try {
|
||||
JsonNode statements = mapper.readTree(document).path("Statement");
|
||||
if (!TrustPolicyStatements.wellFormed(statements)) {
|
||||
@@ -28,7 +34,7 @@ public class SAMLTrustPolicyEvaluator {
|
||||
if (statements.isArray()) {
|
||||
boolean allowed = false;
|
||||
for (JsonNode statement : statements) {
|
||||
int result = evaluate(statement, providerArn, claims);
|
||||
int result = evaluate(statement, providerArn, claims, roleSessionName);
|
||||
if (result < 0) {
|
||||
return false;
|
||||
}
|
||||
@@ -38,21 +44,23 @@ public class SAMLTrustPolicyEvaluator {
|
||||
}
|
||||
return allowed;
|
||||
}
|
||||
return statements.isObject() && evaluate(statements, providerArn, claims) > 0;
|
||||
return statements.isObject() && evaluate(statements, providerArn, claims, roleSessionName) > 0;
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private int evaluate(JsonNode statement, String providerArn, Map<String, List<String>> claims) {
|
||||
private int evaluate(JsonNode statement, String providerArn, Map<String, List<String>> claims,
|
||||
String roleSessionName) {
|
||||
if (!actionApplies(statement) || !principal(statement.path("Principal"), providerArn)
|
||||
|| !conditionsSatisfied(statement.get("Condition"), claims)) {
|
||||
|| !conditionsSatisfied(statement.get("Condition"), claims, roleSessionName)) {
|
||||
return 0;
|
||||
}
|
||||
return TrustPolicyStatements.denies(statement) ? -1 : 1;
|
||||
}
|
||||
|
||||
private boolean conditionsSatisfied(JsonNode condition, Map<String, List<String>> claims) {
|
||||
private boolean conditionsSatisfied(JsonNode condition, Map<String, List<String>> claims,
|
||||
String roleSessionName) {
|
||||
if (condition == null || condition.isNull()) {
|
||||
return true;
|
||||
}
|
||||
@@ -68,10 +76,7 @@ public class SAMLTrustPolicyEvaluator {
|
||||
Iterator<Map.Entry<String, JsonNode>> entries = operator.getValue().fields();
|
||||
while (entries.hasNext()) {
|
||||
Map.Entry<String, JsonNode> entry = entries.next();
|
||||
String key = entry.getKey();
|
||||
int colon = key.indexOf(':');
|
||||
String claimName = colon < 0 ? key : key.substring(colon + 1);
|
||||
List<String> actual = claims.getOrDefault(claimName, List.of());
|
||||
List<String> actual = conditionValues(entry.getKey(), claims, roleSessionName);
|
||||
List<String> expected = entry.getValue().isArray()
|
||||
? StreamSupport.stream(entry.getValue().spliterator(), false)
|
||||
.filter(JsonNode::isTextual).map(JsonNode::asText).toList()
|
||||
@@ -87,6 +92,16 @@ public class SAMLTrustPolicyEvaluator {
|
||||
return true;
|
||||
}
|
||||
|
||||
private static List<String> conditionValues(String key, Map<String, List<String>> claims,
|
||||
String roleSessionName) {
|
||||
if (ROLE_SESSION_NAME_KEY.equalsIgnoreCase(key)) {
|
||||
return roleSessionName == null ? List.of() : List.of(roleSessionName);
|
||||
}
|
||||
int colon = key.indexOf(':');
|
||||
String claimName = colon < 0 ? key : key.substring(colon + 1);
|
||||
return claims.getOrDefault(claimName, List.of());
|
||||
}
|
||||
|
||||
private boolean operatorMatches(String operator, List<String> actual, List<String> expected) {
|
||||
if ("StringEquals".equals(operator)) {
|
||||
return actual.stream().anyMatch(value -> expected.contains(value));
|
||||
|
||||
@@ -579,7 +579,8 @@ public class StsQueryHandler {
|
||||
String callerAccountId = regionResolver.getAccountId();
|
||||
String accountId = AwsArnUtils.accountOrDefault(roleArn, callerAccountId);
|
||||
|
||||
WebIdentityOutcome outcome = verifyWebIdentityToken(webIdentityToken, roleName, accountId, roleArn);
|
||||
WebIdentityOutcome outcome = verifyWebIdentityToken(webIdentityToken, roleName, accountId, roleArn,
|
||||
sessionName);
|
||||
if (outcome.denial() != null) {
|
||||
return outcome.denial();
|
||||
}
|
||||
@@ -666,9 +667,12 @@ public class StsQueryHandler {
|
||||
}
|
||||
}
|
||||
|
||||
/** Inspects {@code token} and decides whether it may assume {@code roleArn}. */
|
||||
/**
|
||||
* Inspects {@code token} and decides whether it may assume {@code roleArn} as the session
|
||||
* {@code sessionName}, which the trust policy reads as {@code sts:RoleSessionName}.
|
||||
*/
|
||||
private WebIdentityOutcome verifyWebIdentityToken(String token, String roleName, String roleAccountId,
|
||||
String roleArn) {
|
||||
String roleArn, String sessionName) {
|
||||
Optional<String> issuer = tokenVerifier.peekIssuer(token);
|
||||
if (issuer.isEmpty()) {
|
||||
return config.services().iam().enforcementEnabled()
|
||||
@@ -714,7 +718,7 @@ public class StsQueryHandler {
|
||||
"aud", claims.audiences());
|
||||
|
||||
if (!webIdentityTrustEvaluator.allows(role.get().getAssumeRolePolicyDocument(),
|
||||
oidcProviderArn, issuerKeyPrefix, conditionClaims)) {
|
||||
oidcProviderArn, issuerKeyPrefix, conditionClaims, sessionName)) {
|
||||
LOG.debugv("Trust policy on role {0} denies web identity subject {1}",
|
||||
roleArn, claims.subject());
|
||||
return WebIdentityOutcome.deny(accessDenied(roleArn));
|
||||
@@ -793,7 +797,7 @@ public class StsQueryHandler {
|
||||
"aud", List.of(STS_AUDIENCE),
|
||||
"iss", List.of(verified.issuer()),
|
||||
"sub", List.of(verified.subject()),
|
||||
"namequalifier", List.of(verified.nameQualifier())))) {
|
||||
"namequalifier", List.of(verified.nameQualifier())), verified.roleSessionName())) {
|
||||
throw new AwsException("AccessDenied", "Not authorized to perform sts:AssumeRoleWithSAML on resource: " + roleArn, 403);
|
||||
}
|
||||
|
||||
@@ -802,9 +806,14 @@ public class StsQueryHandler {
|
||||
return roleDurationError;
|
||||
}
|
||||
|
||||
String sessionName = verified.subject().replaceAll("[^A-Za-z0-9+=,.@_-]", "_");
|
||||
if (sessionName.length() > 64) {
|
||||
sessionName = sessionName.substring(0, 64);
|
||||
String sessionName = verified.roleSessionName();
|
||||
// AWS refuses an assertion without the attribute; Floci has always accepted one, naming the
|
||||
// session after its subject, and keeps doing so.
|
||||
if (sessionName == null) {
|
||||
sessionName = verified.subject().replaceAll("[^A-Za-z0-9+=,.@_-]", "_");
|
||||
if (sessionName.length() > 64) {
|
||||
sessionName = sessionName.substring(0, 64);
|
||||
}
|
||||
}
|
||||
Instant requestedExpiration = clock.instant().plusSeconds(durationSeconds);
|
||||
Instant expiration = verified.expiration().isBefore(requestedExpiration) ? verified.expiration() : requestedExpiration;
|
||||
|
||||
@@ -15,7 +15,7 @@ import java.util.stream.StreamSupport;
|
||||
/**
|
||||
* Evaluates a role's trust policy for {@code sts:AssumeRoleWithWebIdentity}, matching the
|
||||
* {@code Federated} principal and the {@code Condition} block that pins an OIDC subject and
|
||||
* audience.
|
||||
* audience, and the session name the request passes.
|
||||
*
|
||||
* <p>Separate from {@link AssumeRolePolicyEvaluator} on purpose. That evaluator serves the
|
||||
* {@code sts:AssumeRole} path, hardcodes that action, reads only {@code Principal.AWS}, and ignores
|
||||
@@ -32,6 +32,7 @@ public class WebIdentityTrustPolicyEvaluator {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(WebIdentityTrustPolicyEvaluator.class);
|
||||
private static final String WEB_IDENTITY_ACTION = "sts:assumerolewithwebidentity";
|
||||
private static final String ROLE_SESSION_NAME_KEY = "sts:RoleSessionName";
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@@ -46,11 +47,12 @@ public class WebIdentityTrustPolicyEvaluator {
|
||||
*
|
||||
* <p>{@code claims} holds the OIDC condition context keyed <em>without</em> the provider
|
||||
* prefix — {@code sub}, {@code aud} — which this evaluator resolves against policy keys of the
|
||||
* form {@code <provider-host-and-path>:sub}. An explicit {@code Deny} wins over any
|
||||
* {@code Allow}, per AWS precedence.
|
||||
* form {@code <provider-host-and-path>:sub}. {@code roleSessionName} is the request's
|
||||
* {@code RoleSessionName}, which a policy reads as {@code sts:RoleSessionName}. An explicit
|
||||
* {@code Deny} wins over any {@code Allow}, per AWS precedence.
|
||||
*/
|
||||
public boolean allows(String trustPolicyDocument, String oidcProviderArn, String issuerKeyPrefix,
|
||||
Map<String, List<String>> claims) {
|
||||
Map<String, List<String>> claims, String roleSessionName) {
|
||||
if (trustPolicyDocument == null || trustPolicyDocument.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
@@ -68,7 +70,7 @@ public class WebIdentityTrustPolicyEvaluator {
|
||||
boolean allow = false;
|
||||
if (statements.isArray()) {
|
||||
for (JsonNode stmt : statements) {
|
||||
switch (evaluate(stmt, oidcProviderArn, issuerKeyPrefix, claims)) {
|
||||
switch (evaluate(stmt, oidcProviderArn, issuerKeyPrefix, claims, roleSessionName)) {
|
||||
case DENY -> { return false; }
|
||||
case ALLOW -> allow = true;
|
||||
case NO_MATCH -> { }
|
||||
@@ -77,7 +79,7 @@ public class WebIdentityTrustPolicyEvaluator {
|
||||
return allow;
|
||||
}
|
||||
if (statements.isObject()) {
|
||||
return evaluate(statements, oidcProviderArn, issuerKeyPrefix, claims) == Match.ALLOW;
|
||||
return evaluate(statements, oidcProviderArn, issuerKeyPrefix, claims, roleSessionName) == Match.ALLOW;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -85,14 +87,14 @@ public class WebIdentityTrustPolicyEvaluator {
|
||||
private enum Match { ALLOW, DENY, NO_MATCH }
|
||||
|
||||
private Match evaluate(JsonNode stmt, String oidcProviderArn, String issuerKeyPrefix,
|
||||
Map<String, List<String>> claims) {
|
||||
Map<String, List<String>> claims, String roleSessionName) {
|
||||
if (!actionApplies(stmt)) {
|
||||
return Match.NO_MATCH;
|
||||
}
|
||||
if (!matchesFederatedPrincipal(stmt.get("Principal"), oidcProviderArn)) {
|
||||
return Match.NO_MATCH;
|
||||
}
|
||||
if (!conditionsSatisfied(stmt.get("Condition"), issuerKeyPrefix, claims)) {
|
||||
if (!conditionsSatisfied(stmt.get("Condition"), issuerKeyPrefix, claims, roleSessionName)) {
|
||||
return Match.NO_MATCH;
|
||||
}
|
||||
return TrustPolicyStatements.denies(stmt) ? Match.DENY : Match.ALLOW;
|
||||
@@ -170,7 +172,7 @@ public class WebIdentityTrustPolicyEvaluator {
|
||||
* using anything else does not match, which fails closed.
|
||||
*/
|
||||
private boolean conditionsSatisfied(JsonNode conditionNode, String issuerKeyPrefix,
|
||||
Map<String, List<String>> claims) {
|
||||
Map<String, List<String>> claims, String roleSessionName) {
|
||||
if (conditionNode == null || conditionNode.isNull()) {
|
||||
// No condition constraints — the federated principal alone is enough.
|
||||
return true;
|
||||
@@ -191,7 +193,7 @@ public class WebIdentityTrustPolicyEvaluator {
|
||||
while (keyIterator.hasNext()) {
|
||||
Map.Entry<String, JsonNode> keyEntry = keyIterator.next();
|
||||
if (!keySatisfied(operator, keyEntry.getKey(), keyEntry.getValue(),
|
||||
issuerKeyPrefix, claims)) {
|
||||
issuerKeyPrefix, claims, roleSessionName)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -200,8 +202,11 @@ public class WebIdentityTrustPolicyEvaluator {
|
||||
}
|
||||
|
||||
private boolean keySatisfied(String operator, String conditionKey, JsonNode expected,
|
||||
String issuerKeyPrefix, Map<String, List<String>> claims) {
|
||||
List<String> actual = resolveClaim(conditionKey, issuerKeyPrefix, claims);
|
||||
String issuerKeyPrefix, Map<String, List<String>> claims,
|
||||
String roleSessionName) {
|
||||
List<String> actual = ROLE_SESSION_NAME_KEY.equalsIgnoreCase(conditionKey)
|
||||
? (roleSessionName == null ? List.of() : List.of(roleSessionName))
|
||||
: resolveClaim(conditionKey, issuerKeyPrefix, claims);
|
||||
List<String> expectedValues = textValues(expected);
|
||||
if (expectedValues.isEmpty()) {
|
||||
return false;
|
||||
|
||||
Reference in new issue
Block a user