Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(sts): Reject SAML signature transforms that AWS rejects (bonus: native image shrunk by 7 MB) (#4372)

TATSUNO “Taz” Yasuhiro59fda495a683
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/StsTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/StsTest.java
index 72ca707f27..0e0f0b8447 100644
--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/StsTest.java
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/StsTest.java
@@ -16,6 +16,7 @@ import software.amazon.awssdk.services.sts.model.*;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
+import javax.xml.crypto.dsig.CanonicalizationMethod;
import javax.xml.crypto.dsig.DigestMethod;
import javax.xml.crypto.dsig.Reference;
import javax.xml.crypto.dsig.SignatureMethod;
@@ -23,6 +24,10 @@ import javax.xml.crypto.dsig.SignedInfo;
import javax.xml.crypto.dsig.Transform;
import javax.xml.crypto.dsig.XMLSignatureFactory;
import javax.xml.crypto.dsig.dom.DOMSignContext;
+import javax.xml.crypto.dsig.spec.TransformParameterSpec;
+import javax.xml.crypto.dsig.spec.XPathFilter2ParameterSpec;
+import javax.xml.crypto.dsig.spec.XPathFilterParameterSpec;
+import javax.xml.crypto.dsig.spec.XPathType;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
@@ -40,6 +45,7 @@ import java.util.Base64;
import java.util.Date;
import java.util.List;
import java.util.UUID;
+import java.util.function.Function;
import static org.assertj.core.api.Assertions.*;
@@ -224,6 +230,21 @@ class StsTest {
assertThat(response.assumedRoleUser().arn()).contains("assumed-role/" + allowedRoleName + "/");
}
+ @Test
+ void assumeRoleWithSamlRejectsXPathTransform() {
+ assertSamlSignatureInvalid(factory -> List.of(transform(factory, Transform.ENVELOPED, null),
+ transform(factory, Transform.XPATH, new XPathFilterParameterSpec("true()")),
+ transform(factory, CanonicalizationMethod.EXCLUSIVE, null)));
+ }
+
+ @Test
+ void assumeRoleWithSamlRejectsXPathFilter2Transform() {
+ assertSamlSignatureInvalid(factory -> List.of(transform(factory, Transform.ENVELOPED, null),
+ transform(factory, Transform.XPATH2,
+ new XPathFilter2ParameterSpec(List.of(new XPathType("/", XPathType.Filter.UNION)))),
+ transform(factory, CanonicalizationMethod.EXCLUSIVE, null)));
+ }
+
@Test
void assumeRoleWithWebIdentityMissingTokenThrows400() {
assertThatThrownBy(() -> sts.assumeRoleWithWebIdentity(
@@ -295,6 +316,30 @@ class StsTest {
.build());
}
+ private static void assertSamlSignatureInvalid(Function<XMLSignatureFactory, List<Transform>> transforms) {
+ String issuer = "https://sdk-test.example.test/saml";
+ AssumeRoleWithSamlRequest request = AssumeRoleWithSamlRequest.builder()
+ .roleArn(allowedRoleArn)
+ .principalArn(providerArn)
+ .samlAssertion(signedAssertion(allowedRoleArn, providerArn, issuer, transforms))
+ .build();
+
+ assertThatThrownBy(() -> sts.assumeRoleWithSAML(request))
+ .isInstanceOfSatisfying(StsException.class, e -> {
+ assertThat(e.statusCode()).isEqualTo(400);
+ assertThat(e.awsErrorDetails().errorCode()).isEqualTo("InvalidIdentityToken");
+ assertThat(e.awsErrorDetails().errorMessage()).isEqualTo("Response signature invalid");
+ });
+ }
+
+ private static Transform transform(XMLSignatureFactory factory, String algorithm, TransformParameterSpec spec) {
+ try {
+ return factory.newTransform(algorithm, spec);
+ } catch (Exception e) {
+ throw new IllegalStateException("Could not create transform " + algorithm, e);
+ }
+ }
+
private static KeyPair createSigningKeys() throws Exception {
Security.addProvider(new BouncyCastleProvider());
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
@@ -316,6 +361,12 @@ class StsTest {
private static String signedAssertion(String roleArn, String principalArn, String issuer) {
+ return signedAssertion(roleArn, principalArn, issuer,
+ factory -> List.of(transform(factory, Transform.ENVELOPED, null)));
+ }
+
+ private static String signedAssertion(String roleArn, String principalArn, String issuer,
+ Function<XMLSignatureFactory, List<Transform>> transforms) {
String id = "_" + UUID.randomUUID();
Instant expiry = Instant.now().plusSeconds(300);
String xml = "<saml:Assertion xmlns:saml=\"urn:oasis:names:tc:SAML:2.0:assertion\" ID=\"" + id
@@ -334,8 +385,7 @@ class StsTest {
XMLSignatureFactory factory = XMLSignatureFactory.getInstance("DOM");
Reference reference = factory.newReference("#" + id,
factory.newDigestMethod(DigestMethod.SHA256, null),
- List.of(factory.newTransform(Transform.ENVELOPED,
- (javax.xml.crypto.dsig.spec.TransformParameterSpec) null)), null, null);
+ transforms.apply(factory), null, null);
SignedInfo signedInfo = factory.newSignedInfo(
factory.newCanonicalizationMethod("http://www.w3.org/2001/10/xml-exc-c14n#",
(javax.xml.crypto.dsig.spec.C14NMethodParameterSpec) null),
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/SAMLAssertionVerifier.java b/src/main/java/io/github/hectorvent/floci/services/iam/SAMLAssertionVerifier.java
index cfb2cfe0d5..e788802ee1 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iam/SAMLAssertionVerifier.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/SAMLAssertionVerifier.java
@@ -5,6 +5,8 @@ import io.github.hectorvent.floci.services.iam.model.SAMLProvider;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
+import javax.xml.crypto.dsig.CanonicalizationMethod;
+import javax.xml.crypto.dsig.Transform;
import javax.xml.crypto.dsig.XMLSignature;
import javax.xml.crypto.dsig.XMLSignatureFactory;
import javax.xml.crypto.dsig.dom.DOMValidateContext;
@@ -18,12 +20,18 @@ import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
+import java.util.Set;
/** 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";
+ static final String ASSERTION_INVALID = "The SAML assertion is invalid.";
+ static final String SIGNATURE_INVALID = "Response signature invalid";
+ // 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() {}
@@ -52,6 +60,18 @@ final class SAMLAssertionVerifier {
if (signature == null) {
throw invalid("signature missing");
}
+ Element signedInfo = first(signature, DS, "SignedInfo");
+ if (signedInfo == null) {
+ throw invalid("signed info missing");
+ }
+ // Checked on the DOM because unmarshalling some transform parameters fails in the native image.
+ NodeList transforms = signedInfo.getElementsByTagNameNS(DS, "Transform");
+ for (int i = 0; i < transforms.getLength(); i++) {
+ String algorithm = ((Element) transforms.item(i)).getAttribute("Algorithm");
+ if (!ALLOWED_TRANSFORMS.contains(algorithm)) {
+ throw new InvalidAssertionException("reference transform " + algorithm, SIGNATURE_INVALID);
+ }
+ }
X509Certificate certificate = certificate(provider.getCertificate());
var context = new DOMValidateContext(certificate.getPublicKey(), signature);
context.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.TRUE);
@@ -197,8 +217,25 @@ final class SAMLAssertionVerifier {
}
static final class InvalidAssertionException extends Exception {
- InvalidAssertionException(Throwable cause) { super(cause); }
- InvalidAssertionException(String message) { super(message); }
+ private final String awsMessage;
+
+ InvalidAssertionException(Throwable cause) {
+ super(cause);
+ this.awsMessage = ASSERTION_INVALID;
+ }
+
+ InvalidAssertionException(String message) {
+ this(message, ASSERTION_INVALID);
+ }
+
+ InvalidAssertionException(String reason, String awsMessage) {
+ super(reason);
+ this.awsMessage = awsMessage;
+ }
+
+ String awsMessage() {
+ return awsMessage;
+ }
}
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java
index 596b4a0208..b98f680022 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java
@@ -351,7 +351,7 @@ public class StsQueryHandler {
try {
verified = SAMLAssertionVerifier.verify(getParam(params, "SAMLAssertion"), provider, Instant.now());
} catch (SAMLAssertionVerifier.InvalidAssertionException e) {
- throw new AwsException("InvalidIdentityToken", "The SAML assertion is invalid.", 400);
+ throw new AwsException("InvalidIdentityToken", e.awsMessage(), 400);
}
boolean rolePair = verified.roles().stream().anyMatch(pair ->
roleArn.equals(pair.roleArn()) && principalArn.equals(pair.principalArn()));
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/XmlSignatureTransformSubstitutions.java b/src/main/java/io/github/hectorvent/floci/services/iam/XmlSignatureTransformSubstitutions.java
new file mode 100644
index 0000000000..08f559e2f9
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/XmlSignatureTransformSubstitutions.java
@@ -0,0 +1,59 @@
+package io.github.hectorvent.floci.services.iam;
+
+import com.oracle.svm.core.annotate.Substitute;
+import com.oracle.svm.core.annotate.TargetClass;
+import org.w3c.dom.Element;
+
+import java.io.OutputStream;
+
+/**
+ * Native image substitutions for the XSLT and XPath transforms of the JDK XML signature code.
+ * SAMLAssertionVerifier rejects every transform except enveloped signature and exclusive
+ * canonicalization before it validates, as AWS does, so these never run. Every registered transform
+ * is reachable through one virtual call, so without these the XSLT compiler and the XPath engine
+ * stay in the image.
+ */
+final class XmlSignatureTransformSubstitutions {
+
+ static final String UNAVAILABLE = " transform is not supported";
+
+ private XmlSignatureTransformSubstitutions() {
+ }
+}
+
+@TargetClass(className = "com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput")
+final class Target_XMLSignatureInput {
+}
+
+@TargetClass(className = "com.sun.org.apache.xml.internal.security.transforms.implementations.TransformXSLT")
+final class Target_TransformXSLT {
+
+ @Substitute
+ protected Target_XMLSignatureInput enginePerformTransform(Target_XMLSignatureInput input, OutputStream os,
+ Element transformElement, String baseURI,
+ boolean secureValidation) {
+ throw new UnsupportedOperationException("XSLT" + XmlSignatureTransformSubstitutions.UNAVAILABLE);
+ }
+}
+
+@TargetClass(className = "com.sun.org.apache.xml.internal.security.transforms.implementations.TransformXPath")
+final class Target_TransformXPath {
+
+ @Substitute
+ protected Target_XMLSignatureInput enginePerformTransform(Target_XMLSignatureInput input, OutputStream os,
+ Element transformElement, String baseURI,
+ boolean secureValidation) {
+ throw new UnsupportedOperationException("XPath" + XmlSignatureTransformSubstitutions.UNAVAILABLE);
+ }
+}
+
+@TargetClass(className = "com.sun.org.apache.xml.internal.security.transforms.implementations.TransformXPath2Filter")
+final class Target_TransformXPath2Filter {
+
+ @Substitute
+ protected Target_XMLSignatureInput enginePerformTransform(Target_XMLSignatureInput input, OutputStream os,
+ Element transformElement, String baseURI,
+ boolean secureValidation) {
+ throw new UnsupportedOperationException("XPath Filter 2.0" + XmlSignatureTransformSubstitutions.UNAVAILABLE);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/AssumeRoleWithSamlValidationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/AssumeRoleWithSamlValidationIntegrationTest.java
index 4ee247faa9..0d77f2d8a3 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/AssumeRoleWithSamlValidationIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/AssumeRoleWithSamlValidationIntegrationTest.java
@@ -13,6 +13,7 @@ import org.junit.jupiter.api.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
+import javax.xml.crypto.dsig.CanonicalizationMethod;
import javax.xml.crypto.dsig.DigestMethod;
import javax.xml.crypto.dsig.Reference;
import javax.xml.crypto.dsig.SignatureMethod;
@@ -20,6 +21,10 @@ import javax.xml.crypto.dsig.SignedInfo;
import javax.xml.crypto.dsig.Transform;
import javax.xml.crypto.dsig.XMLSignatureFactory;
import javax.xml.crypto.dsig.dom.DOMSignContext;
+import javax.xml.crypto.dsig.spec.TransformParameterSpec;
+import javax.xml.crypto.dsig.spec.XPathFilter2ParameterSpec;
+import javax.xml.crypto.dsig.spec.XPathFilterParameterSpec;
+import javax.xml.crypto.dsig.spec.XPathType;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.TransformerFactory;
@@ -37,9 +42,11 @@ import java.util.Base64;
import java.util.Date;
import java.util.List;
import java.util.UUID;
+import java.util.function.Function;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.startsWith;
@QuarkusTest
@@ -113,6 +120,48 @@ class AssumeRoleWithSamlValidationIntegrationTest {
assume(role, altered, PROVIDER).statusCode(400).body(containsString("InvalidIdentityToken"));
}
+ @Test
+ void xpathTransformIsRejectedAsInvalidSignature() {
+ assertSignatureInvalid(factory -> List.of(enveloped(factory),
+ transform(factory, Transform.XPATH, new XPathFilterParameterSpec("true()")),
+ transform(factory, CanonicalizationMethod.EXCLUSIVE, null)));
+ }
+
+ @Test
+ void xpathFilter2TransformIsRejectedAsInvalidSignature() {
+ assertSignatureInvalid(factory -> List.of(enveloped(factory),
+ transform(factory, Transform.XPATH2,
+ new XPathFilter2ParameterSpec(List.of(new XPathType("/", XPathType.Filter.UNION)))),
+ transform(factory, CanonicalizationMethod.EXCLUSIVE, null)));
+ }
+
+ @Test
+ void inclusiveCanonicalizationTransformIsRejectedAsInvalidSignature() {
+ assertSignatureInvalid(factory -> List.of(enveloped(factory),
+ transform(factory, CanonicalizationMethod.INCLUSIVE, null)));
+ }
+
+ @Test
+ void envelopedAndExclusiveCanonicalizationTransformsAreAccepted() {
+ String role = createRole(true);
+ assume(role, assertion(role, PROVIDER, Instant.now().plusSeconds(300), AUDIENCE, ISSUER, true, false,
+ factory -> List.of(enveloped(factory), transform(factory, CanonicalizationMethod.EXCLUSIVE, null))),
+ PROVIDER)
+ .statusCode(200)
+ .body("AssumeRoleWithSAMLResponse.AssumeRoleWithSAMLResult.Credentials.AccessKeyId", startsWith("ASIA"));
+ }
+
+ @Test
+ void envelopedAndExclusiveCanonicalizationWithCommentsTransformsAreAccepted() {
+ String role = createRole(true);
+ assume(role, assertion(role, PROVIDER, Instant.now().plusSeconds(300), AUDIENCE, ISSUER, true, false,
+ factory -> List.of(enveloped(factory),
+ transform(factory, CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS, null))),
+ PROVIDER)
+ .statusCode(200)
+ .body("AssumeRoleWithSAMLResponse.AssumeRoleWithSAMLResult.Credentials.AccessKeyId", startsWith("ASIA"));
+ }
+
@Test
void wrongRoleAndPrincipalPairIsRejected() {
String role = createRole(true);
@@ -185,6 +234,27 @@ class AssumeRoleWithSamlValidationIntegrationTest {
.body("AssumeRoleWithSAMLResponse.AssumeRoleWithSAMLResult.Subject", containsString("saml-subject"));
}
+ private static void assertSignatureInvalid(Function<XMLSignatureFactory, List<Transform>> transforms) {
+ String role = createRole(true);
+ assume(role, assertion(role, PROVIDER, Instant.now().plusSeconds(300), AUDIENCE, ISSUER, true, false, transforms),
+ PROVIDER)
+ .statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("InvalidIdentityToken"))
+ .body("ErrorResponse.Error.Message", equalTo("Response signature invalid"));
+ }
+
+ private static Transform enveloped(XMLSignatureFactory factory) {
+ return transform(factory, Transform.ENVELOPED, null);
+ }
+
+ private static Transform transform(XMLSignatureFactory factory, String algorithm, TransformParameterSpec spec) {
+ try {
+ return factory.newTransform(algorithm, spec);
+ } catch (Exception e) {
+ throw new IllegalStateException(e);
+ }
+ }
+
private static io.restassured.response.ValidatableResponse assume(String role, String assertion, String provider) {
return given().contentType("application/x-www-form-urlencoded")
.formParam("Action", "AssumeRoleWithSAML")
@@ -241,6 +311,13 @@ class AssumeRoleWithSamlValidationIntegrationTest {
private static String assertion(String role, String provider, Instant expiry, String audience,
String issuer, boolean sign, boolean unrelatedConfirmation) {
+ return assertion(role, provider, expiry, audience, issuer, sign, unrelatedConfirmation,
+ factory -> List.of(enveloped(factory)));
+ }
+
+ private static String assertion(String role, String provider, Instant expiry, String audience,
+ String issuer, boolean sign, boolean unrelatedConfirmation,
+ Function<XMLSignatureFactory, List<Transform>> transforms) {
String id = "_" + UUID.randomUUID();
String extraConfirmation = unrelatedConfirmation
? "<saml:SubjectConfirmation Method=\"urn:oasis:names:tc:SAML:2.0:cm:sender-vouches\"><saml:SubjectConfirmationData Recipient=\"https://unrelated.example.test\" NotOnOrAfter=\"" + Instant.now().minusSeconds(1) + "\"/></saml:SubjectConfirmation>"
@@ -260,7 +337,7 @@ class AssumeRoleWithSamlValidationIntegrationTest {
XMLSignatureFactory factory = XMLSignatureFactory.getInstance("DOM");
Reference reference = factory.newReference("#" + id,
factory.newDigestMethod(DigestMethod.SHA256, null),
- List.of(factory.newTransform(Transform.ENVELOPED, (javax.xml.crypto.dsig.spec.TransformParameterSpec) null)), null, null);
+ transforms.apply(factory), null, null);
SignedInfo signedInfo = factory.newSignedInfo(
factory.newCanonicalizationMethod("http://www.w3.org/2001/10/xml-exc-c14n#", (javax.xml.crypto.dsig.spec.C14NMethodParameterSpec) null),
factory.newSignatureMethod(SignatureMethod.RSA_SHA256, null), List.of(reference));