fix(sts): validate SAML assertions before assuming roles (#3204)

* fix(sts): validate SAML assertions before assuming roles

* test(sts): use valid SAML fixture in SDK compatibility tests

* fix(sts): address SAML review findings

* fix(sts): align SAML fixtures with verifier

* test(sts): share compatibility XML parser
This commit is contained in:
Niels Kootstra authored and GitHub committed 2026-09-08 07:14:38 -04:00
1 parent cc8b8e9f14
commit 1b1252505b
12 files changed
+1087 -46

No files matched your search

@@ -1,12 +1,17 @@
package io.github.hectorvent.floci.core.common;
import org.jboss.logging.Logger;
import org.w3c.dom.Document;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import java.io.ByteArrayInputStream;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
@@ -37,6 +42,23 @@ public final class XmlParser {
private XmlParser() {}
/**
* Parses XML into a namespace-aware DOM document with external entities and
* DTD processing disabled. DOM is required by the JDK XML-DSig API.
*/
public static Document parseDocument(String xml) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
factory.setXIncludeAware(false);
factory.setExpandEntityReferences(false);
return factory.newDocumentBuilder().parse(
new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)));
}
/**
* Reads the text content of the current element if it is a leaf (contains only text).
* If the element contains nested child elements, the entire subtree is skipped
@@ -9,6 +9,7 @@ import io.github.hectorvent.floci.services.iam.model.IamRole;
import io.github.hectorvent.floci.services.iam.model.IamUser;
import io.github.hectorvent.floci.services.iam.model.InstanceProfile;
import io.github.hectorvent.floci.services.iam.model.OpenIDConnectProvider;
import io.github.hectorvent.floci.services.iam.model.SAMLProvider;
import io.github.hectorvent.floci.services.iam.model.PolicyVersion;
import io.github.hectorvent.floci.services.iam.model.CallerContext;
import jakarta.enterprise.context.ApplicationScoped;
@@ -38,13 +39,15 @@ public class IamQueryHandler {
private final IamService iamService;
private final IamPolicyEvaluator policyEvaluator;
private final AccountResolver accountResolver;
private final SAMLProviderService samlProviderService;
@Inject
public IamQueryHandler(IamService iamService, IamPolicyEvaluator policyEvaluator,
AccountResolver accountResolver) {
AccountResolver accountResolver, SAMLProviderService samlProviderService) {
this.iamService = iamService;
this.policyEvaluator = policyEvaluator;
this.accountResolver = accountResolver;
this.samlProviderService = samlProviderService;
}
public Response handle(String action, MultivaluedMap<String, String> params, String authorization) {
@@ -64,8 +67,10 @@ public class IamQueryHandler {
case "ListMFADevices" -> handleListMFADevices(params);
case "GetLoginProfile" -> handleGetLoginProfile(params);
// Identity providers & server certificates (read-only, not modeled)
case "ListSAMLProviders" -> handleListSAMLProviders(params);
// Identity providers & server certificates
case "ListSAMLProviders" -> handleListSAMLProviders(authorization);
case "CreateSAMLProvider" -> handleCreateSAMLProvider(params, authorization);
case "GetSAMLProvider" -> handleGetSAMLProvider(params, authorization);
case "ListOpenIDConnectProviders" -> handleListOpenIDConnectProviders(params);
case "CreateOpenIDConnectProvider" -> handleCreateOpenIDConnectProvider(params);
case "GetOpenIDConnectProvider" -> handleGetOpenIDConnectProvider(params);
@@ -312,13 +317,31 @@ public class IamQueryHandler {
AwsNamespaces.IAM, 404);
}
private Response handleListSAMLProviders(MultivaluedMap<String, String> params) {
// SAML identity providers are not modeled; return the wire-accurate empty
// list (ListSAMLProviders is not paginated — no Marker/IsTruncated).
String result = new XmlBuilder()
.start("SAMLProviderList").end("SAMLProviderList")
.build();
return Response.ok(AwsQueryResponse.envelope("ListSAMLProviders", AwsNamespaces.IAM, result)).build();
private Response handleListSAMLProviders(String authorization) {
var xml = new XmlBuilder().start("SAMLProviderList");
for (SAMLProvider provider : samlProviderService.list(accountResolver.resolve(authorization))) {
xml.start("member").elem("Arn", provider.getArn()).end("member");
}
xml.end("SAMLProviderList");
return Response.ok(AwsQueryResponse.envelope("ListSAMLProviders", AwsNamespaces.IAM, xml.build())).build();
}
private Response handleCreateSAMLProvider(MultivaluedMap<String, String> params, String authorization) {
SAMLProvider provider = samlProviderService.create(accountResolver.resolve(authorization),
getParam(params, "Name"), getParam(params, "SAMLMetadataDocument"));
return Response.ok(AwsQueryResponse.envelope("CreateSAMLProvider", AwsNamespaces.IAM,
new XmlBuilder().elem("SAMLProviderArn", provider.getArn()).build())).build();
}
private Response handleGetSAMLProvider(MultivaluedMap<String, String> params, String authorization) {
String accountId = accountResolver.resolve(authorization);
SAMLProvider provider = samlProviderService.getForAccount(accountId, getParam(params, "SAMLProviderArn"));
String metadata = "<md:EntityDescriptor xmlns:md=\"urn:oasis:names:tc:SAML:2.0:metadata\" entityID=\""
+ provider.getEntityId() + "\"><md:KeyDescriptor use=\"signing\"><ds:KeyInfo xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\"><ds:X509Data><ds:X509Certificate>"
+ provider.getCertificate() + "</ds:X509Certificate></ds:X509Data></ds:KeyInfo></md:KeyDescriptor></md:EntityDescriptor>";
return Response.ok(AwsQueryResponse.envelope("GetSAMLProvider", AwsNamespaces.IAM,
new XmlBuilder().elem("SAMLProviderArn", provider.getArn()).elem("CreateDate", isoDate(provider.getCreateDate()))
.elem("ValidUntil", isoDate(provider.getCreateDate().plusSeconds(31536000))).elem("SAMLMetadataDocument", metadata).build())).build();
}
// ListOpenIDConnectProviders is not paginated and carries only ARNs — the client fetches
@@ -0,0 +1,203 @@
package io.github.hectorvent.floci.services.iam;
import io.github.hectorvent.floci.services.iam.model.SAMLProvider;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import javax.xml.crypto.dsig.XMLSignature;
import javax.xml.crypto.dsig.XMLSignatureFactory;
import javax.xml.crypto.dsig.dom.DOMValidateContext;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.time.Instant;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
/** Verifies the specific SAML assertion contract consumed by STS. */
final class SAMLAssertionVerifier {
private static final String SAML = "urn:oasis:names:tc:SAML:2.0:assertion";
private static final String DS = "http://www.w3.org/2000/09/xmldsig#";
private static final String AUDIENCE = "urn:amazon:webservices";
private SAMLAssertionVerifier() {}
record Verified(String issuer, String subject, String subjectType, String nameQualifier,
Instant expiration, List<RolePair> roles) {}
record RolePair(String roleArn, String principalArn) {}
static Verified verify(String encoded, SAMLProvider provider, Instant now) throws InvalidAssertionException {
try {
byte[] bytes = Base64.getDecoder().decode(encoded);
var document = SAMLXml.document(new String(bytes, java.nio.charset.StandardCharsets.UTF_8));
Element assertion = document.getDocumentElement();
if ("Response".equals(assertion.getLocalName())) {
assertion = first(assertion, SAML, "Assertion");
}
if (assertion == null || !"Assertion".equals(assertion.getLocalName())
|| !SAML.equals(assertion.getNamespaceURI())) {
throw invalid("assertion root");
}
String assertionId = assertion.getAttribute("ID");
if (assertionId == null || assertionId.isBlank()) {
throw invalid("assertion ID");
}
assertion.setIdAttribute("ID", true);
Element signature = first(assertion, DS, "Signature");
if (signature == null) {
throw invalid("signature missing");
}
X509Certificate certificate = certificate(provider.getCertificate());
var context = new DOMValidateContext(certificate.getPublicKey(), signature);
context.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.TRUE);
XMLSignature xmlSignature = XMLSignatureFactory.getInstance("DOM").unmarshalXMLSignature(context);
if (xmlSignature.getSignedInfo().getReferences().size() != 1
|| !(xmlSignature.getSignedInfo().getReferences().get(0) instanceof javax.xml.crypto.dsig.Reference reference)
|| !("#" + assertionId).equals(reference.getURI())) {
throw invalid("signature reference");
}
if (!xmlSignature.validate(context)) {
throw invalid("signature validation");
}
String issuer = childText(assertion, SAML, "Issuer");
if (!provider.getEntityId().equals(issuer)) {
throw invalid("issuer");
}
Element conditions = first(assertion, SAML, "Conditions");
if (conditions == null) {
throw invalid("conditions missing");
}
Instant notBefore = instant(conditions.getAttribute("NotBefore"));
Instant notOnOrAfter = instant(conditions.getAttribute("NotOnOrAfter"));
if (notBefore != null && now.isBefore(notBefore)) {
throw invalid("not before");
}
if (notOnOrAfter == null || !now.isBefore(notOnOrAfter)) {
throw invalid("assertion expiry");
}
Element restriction = first(conditions, SAML, "AudienceRestriction");
if (restriction == null || !hasText(restriction, SAML, "Audience", AUDIENCE)) {
throw invalid("audience");
}
Element subject = first(assertion, SAML, "Subject");
String name = childText(subject, SAML, "NameID");
if (name == null || name.isBlank()) {
throw invalid("subject");
}
Element nameId = first(subject, SAML, "NameID");
String subjectType = nameId == null ? null : nameId.getAttribute("Format");
NodeList confirmations = subject == null
? null : ((Element) subject).getElementsByTagNameNS(SAML, "SubjectConfirmation");
if (confirmations == null || confirmations.getLength() == 0) {
throw invalid("subject confirmation missing");
}
boolean validBearer = false;
for (int i = 0; i < confirmations.getLength(); i++) {
Element confirmation = (Element) confirmations.item(i);
if (!"urn:oasis:names:tc:SAML:2.0:cm:bearer".equals(confirmation.getAttribute("Method"))) {
continue;
}
Element confirmationData = first(confirmation, SAML, "SubjectConfirmationData");
if (confirmationData == null) {
continue;
}
String recipient = confirmationData.getAttribute("Recipient");
Instant confirmationExpiry = instant(confirmationData.getAttribute("NotOnOrAfter"));
if ("https://signin.aws.amazon.com/saml".equals(recipient)
&& confirmationExpiry != null && now.isBefore(confirmationExpiry)) {
validBearer = true;
break;
}
}
if (!validBearer) {
throw invalid("valid bearer subject confirmation missing");
}
List<RolePair> roles = new ArrayList<>();
NodeList attributes = assertion.getElementsByTagNameNS(SAML, "Attribute");
for (int i = 0; i < attributes.getLength(); i++) {
Element attribute = (Element) attributes.item(i);
if (!"https://aws.amazon.com/SAML/Attributes/Role".equals(attribute.getAttribute("Name"))) {
continue;
}
NodeList values = attribute.getElementsByTagNameNS(SAML, "AttributeValue");
for (int j = 0; j < values.getLength(); j++) {
String[] pair = values.item(j).getTextContent().trim().split(",", -1);
if (pair.length != 2) {
throw invalid("role pair format");
}
if (pair[0].startsWith("arn:aws:iam::") && pair[1].contains(":saml-provider/")) {
roles.add(new RolePair(pair[0], pair[1]));
} else if (pair[1].startsWith("arn:aws:iam::") && pair[0].contains(":saml-provider/")) {
roles.add(new RolePair(pair[1], pair[0]));
} else {
throw invalid("role pair ARN");
}
}
}
if (roles.isEmpty()) {
throw invalid("role pair missing");
}
String nameQualifier = java.util.Base64.getEncoder().encodeToString(MessageDigest.getInstance("SHA-1")
.digest((issuer + provider.getArn()).getBytes(StandardCharsets.UTF_8)));
return new Verified(issuer, name, subjectType, nameQualifier, notOnOrAfter, roles);
} catch (InvalidAssertionException e) {
throw e;
} catch (Exception e) {
throw new InvalidAssertionException(e);
}
}
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));
}
private static Element first(org.w3c.dom.Node parent, String namespace, String local) {
if (parent == null) {
return null;
}
NodeList list = ((Element) parent).getElementsByTagNameNS(namespace, local);
return list.getLength() == 0 ? null : (Element) list.item(0);
}
private static String childText(org.w3c.dom.Node parent, String namespace, String local) {
Element e = first(parent, namespace, local);
return e == null ? null : e.getTextContent().trim();
}
private static boolean hasText(org.w3c.dom.Node parent, String namespace, String local, String expected) {
NodeList list = ((Element) parent).getElementsByTagNameNS(namespace, local);
for (int i = 0; i < list.getLength(); i++) {
if (expected.equals(list.item(i).getTextContent().trim())) {
return true;
}
}
return false;
}
private static Instant instant(String text) {
if (text == null || text.isBlank()) {
return null;
}
try {
return Instant.parse(text);
} catch (DateTimeParseException e) {
throw new IllegalArgumentException(e);
}
}
private static InvalidAssertionException invalid(String reason) {
return new InvalidAssertionException(reason);
}
static final class InvalidAssertionException extends Exception {
InvalidAssertionException(Throwable cause) { super(cause); }
InvalidAssertionException(String message) { super(message); }
}
}
@@ -0,0 +1,113 @@
package io.github.hectorvent.floci.services.iam;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.iam.model.SAMLProvider;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.Base64;
import java.util.List;
import java.util.Optional;
import java.util.regex.Pattern;
/** Minimal IAM SAML provider registry used by STS assertion verification. */
@ApplicationScoped
public class SAMLProviderService {
private static final Pattern ARN = Pattern.compile("^arn:aws:iam::(\\d{12}):saml-provider/[A-Za-z0-9+=,.@_-]{1,128}$");
private final StorageBackend<String, SAMLProvider> providers;
private final Object providerLock = new Object();
@Inject
public SAMLProviderService(StorageFactory storageFactory) {
this(storageFactory.create("iam", "iam-saml-providers.json", new TypeReference<>() {}));
}
SAMLProviderService(StorageBackend<String, SAMLProvider> providers) {
this.providers = providers;
}
public SAMLProvider create(String accountId, String name, String metadata) {
String arn = "arn:aws:iam::" + accountId + ":saml-provider/" + name;
if (!ARN.matcher(arn).matches()) {
throw new AwsException("InvalidInput", "Invalid SAML provider name.", 400);
}
if (metadata == null || metadata.isBlank()) {
throw new AwsException("InvalidInput", "SAML metadata document must not be empty.", 400);
}
SAMLMetadata.Parsed parsed;
try {
parsed = SAMLMetadata.parse(metadata);
} catch (Exception e) {
throw new AwsException("InvalidInput", "The SAML metadata document is invalid.", 400);
}
SAMLProvider provider = new SAMLProvider();
provider.setArn(arn);
provider.setEntityId(parsed.entityId());
provider.setCertificate(parsed.certificateBase64());
synchronized (providerLock) {
if (findForAccount(accountId, arn).isPresent()) {
throw new AwsException("EntityAlreadyExists",
"SAML provider " + arn + " already exists.", 409);
}
if (providers instanceof AccountAwareStorageBackend<SAMLProvider> aware) {
aware.putForAccount(accountId, arn, provider);
} else {
providers.put(arn, provider);
}
}
return provider;
}
public Optional<SAMLProvider> find(String arn) {
var matcher = ARN.matcher(arn == null ? "" : arn);
if (matcher.matches()) {
return findForAccount(matcher.group(1), arn);
}
return providers.get(arn);
}
public Optional<SAMLProvider> findForAccount(String accountId, String arn) {
var matcher = ARN.matcher(arn == null ? "" : arn);
if (!matcher.matches() || !matcher.group(1).equals(accountId)) {
return Optional.empty();
}
if (providers instanceof AccountAwareStorageBackend<SAMLProvider> aware) {
return aware.getForAccount(accountId, arn);
}
return providers.get(arn);
}
public List<SAMLProvider> list(String accountId) {
if (providers instanceof AccountAwareStorageBackend<SAMLProvider> aware) {
return aware.scanForAccount(accountId, k -> true);
}
return providers.scan(k -> true);
}
public SAMLProvider getForAccount(String accountId, String arn) {
return findForAccount(accountId, arn).orElseThrow(() -> new AwsException("NoSuchEntity",
"The SAML provider with ARN " + arn + " cannot be found.", 404));
}
/** Metadata parser shared by provider registration and the assertion verifier. */
static final class SAMLMetadata {
private SAMLMetadata() {
}
record Parsed(String entityId, String certificateBase64) {}
static Parsed parse(String metadata) throws Exception {
var doc = SAMLXml.document(metadata);
var entity = doc.getDocumentElement().getAttribute("entityID");
var cert = SAMLXml.text(doc, "X509Certificate");
if (entity == null || entity.isBlank() || cert == null || cert.isBlank()) {
throw new Exception();
}
Base64.getDecoder().decode(cert.replaceAll("\\s+", ""));
return new Parsed(entity, cert.replaceAll("\\s+", ""));
}
}
}
@@ -0,0 +1,147 @@
package io.github.hectorvent.floci.services.iam;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.List;
import java.util.Map;
/** Evaluates the federated principal and SAML action in a role trust policy. */
@ApplicationScoped
public class SAMLTrustPolicyEvaluator {
private final ObjectMapper mapper;
@Inject
public SAMLTrustPolicyEvaluator(ObjectMapper mapper) {
this.mapper = mapper;
}
public boolean allows(String document, String providerArn, Map<String, List<String>> claims) {
try {
JsonNode statements = mapper.readTree(document).path("Statement");
if (statements.isArray()) {
boolean allowed = false;
for (JsonNode statement : statements) {
int result = evaluate(statement, providerArn, claims);
if (result < 0) {
return false;
}
if (result > 0) {
allowed = true;
}
}
return allowed;
}
return statements.isObject() && evaluate(statements, providerArn, claims) > 0;
} catch (Exception e) {
return false;
}
}
private int evaluate(JsonNode statement, String providerArn, Map<String, List<String>> claims) {
if (!actionApplies(statement) || !principal(statement.path("Principal"), providerArn)
|| !conditionsSatisfied(statement.get("Condition"), claims)) {
return 0;
}
return "Deny".equalsIgnoreCase(statement.path("Effect").asText()) ? -1 : 1;
}
private boolean conditionsSatisfied(JsonNode condition, Map<String, List<String>> claims) {
if (condition == null || condition.isNull()) {
return true;
}
if (!condition.isObject()) {
return false;
}
var operators = condition.fields();
while (operators.hasNext()) {
var operator = operators.next();
if (!operator.getValue().isObject()) {
return false;
}
var entries = operator.getValue().fields();
while (entries.hasNext()) {
var 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> expected = entry.getValue().isArray()
? java.util.stream.StreamSupport.stream(entry.getValue().spliterator(), false)
.filter(JsonNode::isTextual).map(JsonNode::asText).toList()
: entry.getValue().isTextual() ? List.of(entry.getValue().asText()) : List.of();
if (expected.isEmpty() || actual.isEmpty()) {
return false;
}
if (!operatorMatches(operator.getKey(), actual, expected)) {
return false;
}
}
}
return true;
}
private boolean operatorMatches(String operator, List<String> actual, List<String> expected) {
if ("StringEquals".equals(operator)) {
return actual.stream().anyMatch(value -> expected.contains(value));
}
if ("StringLike".equals(operator)) {
return actual.stream().anyMatch(value -> expected.stream().anyMatch(pattern ->
WebIdentityTrustPolicyEvaluator.globMatchesCaseSensitive(pattern, value)));
}
if ("StringNotEquals".equals(operator)) {
return actual.stream().allMatch(value -> expected.stream().noneMatch(value::equals));
}
if ("StringNotLike".equals(operator)) {
return actual.stream().allMatch(value -> expected.stream().noneMatch(pattern ->
WebIdentityTrustPolicyEvaluator.globMatchesCaseSensitive(pattern, value)));
}
return false;
}
private boolean actionApplies(JsonNode statement) {
JsonNode action = statement.get("Action");
if (action != null) {
return action(action);
}
JsonNode notAction = statement.get("NotAction");
return notAction != null && !action(notAction);
}
private boolean action(JsonNode node) {
if (node.isTextual()) {
return matches(node.asText());
}
if (node.isArray()) {
for (JsonNode value : node) {
if (value.isTextual() && matches(value.asText())) {
return true;
}
}
}
return false;
}
private boolean matches(String action) {
String regex = action.replace(".", "\\.").replace("*", ".*").replace("?", ".");
return "sts:AssumeRoleWithSAML".matches("(?i)^" + regex + "$");
}
private boolean principal(JsonNode node, String providerArn) {
JsonNode federated = node.isObject() ? node.get("Federated") : null;
if (federated == null) {
return "*".equals(node.asText());
}
if (federated.isTextual()) {
return "*".equals(federated.asText()) || providerArn.equals(federated.asText());
}
if (federated.isArray()) {
for (JsonNode value : federated) {
if (value.isTextual()
&& ("*".equals(value.asText()) || providerArn.equals(value.asText()))) {
return true;
}
}
}
return false;
}
}
@@ -0,0 +1,28 @@
package io.github.hectorvent.floci.services.iam;
import io.github.hectorvent.floci.core.common.XmlParser;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
final class SAMLXml {
private SAMLXml() {
}
static Document document(String xml) throws Exception {
return XmlParser.parseDocument(xml);
}
static String text(Document document, String localName) {
NodeList nodes = document.getElementsByTagNameNS("*", localName);
if (nodes.getLength() == 0) {
return null;
}
return nodes.item(0).getTextContent().trim();
}
static String text(Node parent, String namespace, String localName) {
NodeList nodes = ((org.w3c.dom.Element) parent).getElementsByTagNameNS(namespace, localName);
return nodes.getLength() == 0 ? null : nodes.item(0).getTextContent().trim();
}
}
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.iam;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsNamespaces;
import io.github.hectorvent.floci.core.common.AwsQueryController;
import io.github.hectorvent.floci.core.common.AwsQueryResponse;
@@ -48,6 +49,8 @@ public class StsQueryHandler {
private final WebIdentityTrustPolicyEvaluator webIdentityTrustEvaluator;
private final WebIdentityTokenVerifier tokenVerifier;
private final OidcIssuerKeyLookup oidcIssuerKeys;
private final SAMLProviderService samlProviderService;
private final SAMLTrustPolicyEvaluator samlTrustEvaluator;
@Context
HttpHeaders headers;
@@ -57,7 +60,9 @@ public class StsQueryHandler {
EmulatorConfig config, AssumeRolePolicyEvaluator trustPolicyEvaluator,
WebIdentityTrustPolicyEvaluator webIdentityTrustEvaluator,
WebIdentityTokenVerifier tokenVerifier,
OidcIssuerKeyLookup oidcIssuerKeys) {
OidcIssuerKeyLookup oidcIssuerKeys,
SAMLProviderService samlProviderService,
SAMLTrustPolicyEvaluator samlTrustEvaluator) {
this.iamService = iamService;
this.accountResolver = accountResolver;
this.regionResolver = regionResolver;
@@ -66,6 +71,8 @@ public class StsQueryHandler {
this.webIdentityTrustEvaluator = webIdentityTrustEvaluator;
this.tokenVerifier = tokenVerifier;
this.oidcIssuerKeys = oidcIssuerKeys;
this.samlProviderService = samlProviderService;
this.samlTrustEvaluator = samlTrustEvaluator;
}
public Response handle(String action, MultivaluedMap<String, String> params) {
@@ -331,35 +338,59 @@ public class StsQueryHandler {
return validation;
}
String roleArn = getParam(params, "RoleArn");
String sessionName = "saml-session";
String principalArn = getParam(params, "PrincipalArn");
int durationSeconds = getIntParam(params, "DurationSeconds", 3600);
var provider = samlProviderService.find(principalArn).orElseThrow(() ->
new AwsException("InvalidIdentityToken", "The SAML provider is not trusted.", 400));
SAMLAssertionVerifier.Verified verified;
try {
verified = SAMLAssertionVerifier.verify(getParam(params, "SAMLAssertion"), provider, Instant.now());
} catch (SAMLAssertionVerifier.InvalidAssertionException e) {
throw new AwsException("InvalidIdentityToken", "The SAML assertion is invalid.", 400);
}
boolean rolePair = verified.roles().stream().anyMatch(pair ->
roleArn.equals(pair.roleArn()) && principalArn.equals(pair.principalArn()));
if (!rolePair) {
throw new AwsException("InvalidIdentityToken",
"The SAML assertion does not contain the requested role and principal.", 400);
}
String callerAccountId = regionResolver.getAccountId();
String accountId = AwsArnUtils.accountOrDefault(roleArn, callerAccountId);
String roleName = roleArn.contains("/") ? roleArn.substring(roleArn.lastIndexOf('/') + 1) : "UnknownRole";
IamRole role = iamService.findRole(accountId, roleName).orElseThrow(() ->
new AwsException("AccessDenied", "Not authorized to perform sts:AssumeRoleWithSAML on resource: " + roleArn, 403));
if (!samlTrustEvaluator.allows(role.getAssumeRolePolicyDocument(), principalArn, Map.of(
"aud", List.of(STS_AUDIENCE),
"iss", List.of(verified.issuer()),
"sub", List.of(verified.subject()),
"namequalifier", List.of(verified.nameQualifier())))) {
throw new AwsException("AccessDenied", "Not authorized to perform sts:AssumeRoleWithSAML on resource: " + roleArn, 403);
}
String sessionName = verified.subject().replaceAll("[^A-Za-z0-9+=,.@_-]", "_");
if (sessionName.length() > 64) {
sessionName = sessionName.substring(0, 64);
}
Instant requestedExpiration = Instant.now().plusSeconds(durationSeconds);
Instant roleExpiration = Instant.now().plusSeconds(role.getMaxSessionDuration());
Instant expiration = verified.expiration().isBefore(requestedExpiration) ? verified.expiration() : requestedExpiration;
if (roleExpiration.isBefore(expiration)) {
expiration = roleExpiration;
}
String accessKeyId = "ASIA" + randomId(16);
String secretKey = randomSecret(40);
String sessionToken = randomSecret(200);
Instant expiration = Instant.now().plusSeconds(durationSeconds);
String roleName = roleArn.contains("/") ? roleArn.substring(roleArn.lastIndexOf('/') + 1) : "UnknownRole";
String callerAccountId = regionResolver.getAccountId();
String accountId = AwsArnUtils.accountOrDefault(roleArn, callerAccountId);
String assumedRoleArn = AwsArnUtils.Arn.of("sts", "", accountId, "assumed-role/" + roleName + "/" + sessionName).toString();
String assumedRoleId = "AROA" + randomId(16) + ":" + sessionName;
iamService.registerSession(accessKeyId, secretKey, sessionToken, roleArn, expiration, null, callerAccountId);
String result = new XmlBuilder()
.raw(credentialsXml(accessKeyId, secretKey, sessionToken, expiration))
.start("AssumedRoleUser")
.elem("Arn", assumedRoleArn)
.elem("AssumedRoleId", assumedRoleId)
.end("AssumedRoleUser")
.elem("PackedPolicySize", "0")
.elem("Issuer", "https://saml.example.com")
.elem("Audience", "urn:amazon:webservices")
.elem("NameQualifier", "saml-qualifier")
.elem("SubjectType", "persistent")
.elem("Subject", "saml-subject")
.build();
.start("AssumedRoleUser").elem("Arn", assumedRoleArn).elem("AssumedRoleId", assumedRoleId).end("AssumedRoleUser")
.elem("PackedPolicySize", "0").elem("Issuer", verified.issuer()).elem("Audience", "urn:amazon:webservices")
.elem("NameQualifier", verified.nameQualifier()).elem("SubjectType", verified.subjectType()).elem("Subject", verified.subject()).build();
return Response.ok(AwsQueryResponse.envelope("AssumeRoleWithSAML", AwsNamespaces.STS, result)).build();
}
@@ -0,0 +1,26 @@
package io.github.hectorvent.floci.services.iam.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class SAMLProvider {
private String arn;
private String entityId;
private String certificate;
private Instant createDate = Instant.now();
public SAMLProvider() {}
public String getArn() { return arn; }
public void setArn(String arn) { this.arn = arn; }
public String getEntityId() { return entityId; }
public void setEntityId(String entityId) { this.entityId = entityId; }
public String getCertificate() { return certificate; }
public void setCertificate(String certificate) { this.certificate = certificate; }
public Instant getCreateDate() { return createDate; }
public void setCreateDate(Instant createDate) { this.createDate = createDate; }
}