diff --git a/docs/modules/ROOT/pages/servlet/saml2/metadata.adoc b/docs/modules/ROOT/pages/servlet/saml2/metadata.adoc index ac9b697013..e4f96a783c 100644 --- a/docs/modules/ROOT/pages/servlet/saml2/metadata.adoc +++ b/docs/modules/ROOT/pages/servlet/saml2/metadata.adoc @@ -42,7 +42,7 @@ This allows three valuable features: * Implementations of `RelyingPartyRegistrationRepository` can more easily articulate a relationship between a relying party and its one or many corresponding asserting parties * Implementations can verify metadata signatures -For example, `OpenSamlAssertingPartyMetadataRepository` uses OpenSAML's `MetadataResolver`, and API whose implementations regularly refresh the underlying metadata in an expiry-aware fashion. +For example, `OpenSaml4AssertingPartyMetadataRepository` uses OpenSAML's `MetadataResolver`, and API whose implementations regularly refresh the underlying metadata in an expiry-aware fashion. This means that you can now create a refreshable `RelyingPartyRegistrationRepository` in just a few lines of code: @@ -119,11 +119,11 @@ class RefreshableRelyingPartyRegistrationRepository : IterableRelyingPartyRegist ====== [TIP] -`OpenSamlAssertingPartyMetadataRepository` also ships with a constructor so you can provide a custom `MetadataResolver`. Since the underlying `MetadataResolver` is doing the expirying and refreshing, if you use the constructor directly, you will only get these features by providing an implementation that does so. +`OpenSaml4AssertingPartyMetadataRepository` also ships with a constructor so you can provide a custom `MetadataResolver`. Since the underlying `MetadataResolver` is doing the expirying and refreshing, if you use the constructor directly, you will only get these features by providing an implementation that does so. === Verifying Metadata Signatures -You can also verify metadata signatures using `OpenSamlAssertingPartyMetadataRepository` by providing the appropriate set of ``Saml2X509Credential``s as follows: +You can also verify metadata signatures using `OpenSaml4AssertingPartyMetadataRepository` by providing the appropriate set of ``Saml2X509Credential``s as follows: [tabs] ====== diff --git a/saml2/saml2-service-provider/spring-security-saml2-service-provider.gradle b/saml2/saml2-service-provider/spring-security-saml2-service-provider.gradle index c4309e23b4..253a9fc113 100644 --- a/saml2/saml2-service-provider/spring-security-saml2-service-provider.gradle +++ b/saml2/saml2-service-provider/spring-security-saml2-service-provider.gradle @@ -43,6 +43,12 @@ sourceSets.configureEach { set -> filter { line -> line.replaceAll(".saml2.internal", ".saml2.provider.service.web") } with from } + + copy { + into "$projectDir/src/$set.name/java/org/springframework/security/saml2/provider/service/registration" + filter { line -> line.replaceAll(".saml2.internal", ".saml2.provider.service.registration") } + with from + } } dependencies { diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/registration/AssertingPartyMetadataRepository.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/registration/AssertingPartyMetadataRepository.java index d03cea8c8c..b9ef8a5254 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/registration/AssertingPartyMetadataRepository.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/registration/AssertingPartyMetadataRepository.java @@ -23,7 +23,7 @@ import org.springframework.lang.Nullable; * * @author Josh Cummings * @since 6.4 - * @see OpenSamlAssertingPartyMetadataRepository + * @see BaseOpenSamlAssertingPartyMetadataRepository * @see org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrations */ public interface AssertingPartyMetadataRepository extends Iterable { diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/registration/OpenSamlAssertingPartyMetadataRepository.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/registration/BaseOpenSamlAssertingPartyMetadataRepository.java similarity index 58% rename from saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/registration/OpenSamlAssertingPartyMetadataRepository.java rename to saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/registration/BaseOpenSamlAssertingPartyMetadataRepository.java index 847883dc0f..8de0b9b13a 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/registration/OpenSamlAssertingPartyMetadataRepository.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/registration/BaseOpenSamlAssertingPartyMetadataRepository.java @@ -30,9 +30,6 @@ import java.util.function.Supplier; import javax.annotation.Nonnull; -import net.shibboleth.utilities.java.support.component.ComponentInitializationException; -import net.shibboleth.utilities.java.support.resolver.CriteriaSet; -import net.shibboleth.utilities.java.support.resolver.ResolverException; import org.opensaml.core.criterion.EntityIdCriterion; import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; import org.opensaml.saml.criterion.EntityRoleCriterion; @@ -58,35 +55,21 @@ import org.springframework.lang.NonNull; import org.springframework.lang.Nullable; import org.springframework.security.saml2.Saml2Exception; import org.springframework.security.saml2.core.OpenSamlInitializationService; -import org.springframework.security.saml2.core.Saml2X509Credential; import org.springframework.util.Assert; -/** - * An implementation of {@link AssertingPartyMetadataRepository} that uses a - * {@link MetadataResolver} to retrieve {@link AssertingPartyMetadata} instances. - * - *

- * The {@link MetadataResolver} constructed in {@link #withTrustedMetadataLocation} - * provides expiry-aware refreshing. - * - * @author Josh Cummings - * @since 6.4 - * @see AssertingPartyMetadataRepository - * @see RelyingPartyRegistrations - */ -public final class OpenSamlAssertingPartyMetadataRepository implements AssertingPartyMetadataRepository { +class BaseOpenSamlAssertingPartyMetadataRepository implements AssertingPartyMetadataRepository { static { OpenSamlInitializationService.initialize(); } - private final MetadataResolver metadataResolver; + private final MetadataResolverAdapter metadataResolver; private final Supplier> descriptors; /** - * Construct an {@link OpenSamlAssertingPartyMetadataRepository} using the provided - * {@link MetadataResolver}. + * Construct an {@link BaseOpenSamlAssertingPartyMetadataRepository} using the + * provided {@link MetadataResolver}. * *

* The {@link MetadataResolver} should either be of type @@ -94,12 +77,12 @@ public final class OpenSamlAssertingPartyMetadataRepository implements Asserting * configured. * @param metadataResolver the {@link MetadataResolver} to use */ - public OpenSamlAssertingPartyMetadataRepository(MetadataResolver metadataResolver) { + BaseOpenSamlAssertingPartyMetadataRepository(MetadataResolverAdapter metadataResolver) { Assert.notNull(metadataResolver, "metadataResolver cannot be null"); - if (isRoleIndexed(metadataResolver)) { + if (isRoleIndexed(metadataResolver.metadataResolver)) { this.descriptors = this::allIndexedEntities; } - else if (metadataResolver instanceof IterableMetadataSource source) { + else if (metadataResolver.metadataResolver instanceof IterableMetadataSource source) { this.descriptors = source::iterator; } else { @@ -122,11 +105,11 @@ public final class OpenSamlAssertingPartyMetadataRepository implements Asserting } private Iterator allIndexedEntities() { - CriteriaSet all = new CriteriaSet(new EntityRoleCriterion(IDPSSODescriptor.DEFAULT_ELEMENT_NAME)); + EntityRoleCriterion idps = new EntityRoleCriterion(IDPSSODescriptor.DEFAULT_ELEMENT_NAME); try { - return this.metadataResolver.resolve(all).iterator(); + return this.metadataResolver.resolve(idps).iterator(); } - catch (ResolverException ex) { + catch (Exception ex) { throw new Saml2Exception(ex); } } @@ -151,80 +134,30 @@ public final class OpenSamlAssertingPartyMetadataRepository implements Asserting @Nullable @Override public AssertingPartyMetadata findByEntityId(String entityId) { - CriteriaSet byEntityId = new CriteriaSet(new EntityIdCriterion(entityId)); - EntityDescriptor descriptor = resolveSingle(byEntityId); + EntityDescriptor descriptor = resolveSingle(new EntityIdCriterion(entityId)); if (descriptor == null) { return null; } return OpenSamlAssertingPartyDetails.withEntityDescriptor(descriptor).build(); } - private EntityDescriptor resolveSingle(CriteriaSet criteria) { + private EntityDescriptor resolveSingle(EntityIdCriterion criterion) { try { - return this.metadataResolver.resolveSingle(criteria); + return this.metadataResolver.resolveSingle(criterion); } - catch (ResolverException ex) { + catch (Exception ex) { throw new Saml2Exception(ex); } } /** - * Use this trusted {@code metadataLocation} to retrieve refreshable, expiry-aware - * SAML 2.0 Asserting Party (IDP) metadata. - * - *

- * Valid locations can be classpath- or file-based or they can be HTTPS endpoints. - * Some valid endpoints might include: - * - *

-	 *   metadataLocation = "classpath:asserting-party-metadata.xml";
-	 *   metadataLocation = "file:asserting-party-metadata.xml";
-	 *   metadataLocation = "https://ap.example.org/metadata";
-	 * 
- * - *

- * Resolution of location is attempted immediately. To defer, wrap in - * {@link CachingRelyingPartyRegistrationRepository}. - * @param metadataLocation the classpath- or file-based locations or HTTPS endpoints - * of the asserting party metadata file - * @return the {@link MetadataLocationRepositoryBuilder} for further configuration - */ - public static MetadataLocationRepositoryBuilder withTrustedMetadataLocation(String metadataLocation) { - return new MetadataLocationRepositoryBuilder(metadataLocation, true); - } - - /** - * Use this {@code metadataLocation} to retrieve refreshable, expiry-aware SAML 2.0 - * Asserting Party (IDP) metadata. Verification credentials are required. - * - *

- * Valid locations can be classpath- or file-based or they can be remote endpoints. - * Some valid endpoints might include: - * - *

-	 *   metadataLocation = "classpath:asserting-party-metadata.xml";
-	 *   metadataLocation = "file:asserting-party-metadata.xml";
-	 *   metadataLocation = "https://ap.example.org/metadata";
-	 * 
- * - *

- * Resolution of location is attempted immediately. To defer, wrap in - * {@link CachingRelyingPartyRegistrationRepository}. - * @param metadataLocation the classpath- or file-based locations or remote endpoints - * of the asserting party metadata file - * @return the {@link MetadataLocationRepositoryBuilder} for further configuration - */ - public static MetadataLocationRepositoryBuilder withMetadataLocation(String metadataLocation) { - return new MetadataLocationRepositoryBuilder(metadataLocation, false); - } - - /** - * A builder class for configuring {@link OpenSamlAssertingPartyMetadataRepository} - * for a specific metadata location. + * A builder class for configuring + * {@link BaseOpenSamlAssertingPartyMetadataRepository} for a specific metadata + * location. * * @author Josh Cummings */ - public static final class MetadataLocationRepositoryBuilder { + static final class MetadataLocationRepositoryBuilder { private final String metadataLocation; @@ -234,42 +167,23 @@ public final class OpenSamlAssertingPartyMetadataRepository implements Asserting private ResourceLoader resourceLoader = new DefaultResourceLoader(); - private MetadataLocationRepositoryBuilder(String metadataLocation, boolean trusted) { + MetadataLocationRepositoryBuilder(String metadataLocation, boolean trusted) { this.metadataLocation = metadataLocation; this.requireVerificationCredentials = !trusted; } - /** - * Apply this {@link Consumer} to the list of {@link Saml2X509Credential}s to use - * for verifying metadata signatures. - * - *

- * If no credentials are supplied, no signature verification is performed. - * @param credentials a {@link Consumer} of the {@link Collection} of - * {@link Saml2X509Credential}s - * @return the {@link MetadataLocationRepositoryBuilder} for further configuration - */ - public MetadataLocationRepositoryBuilder verificationCredentials(Consumer> credentials) { + MetadataLocationRepositoryBuilder verificationCredentials(Consumer> credentials) { credentials.accept(this.verificationCredentials); return this; } - /** - * Use this {@link ResourceLoader} for resolving the {@code metadataLocation} - * @param resourceLoader the {@link ResourceLoader} to use - * @return the {@link MetadataLocationRepositoryBuilder} for further configuration - */ - public MetadataLocationRepositoryBuilder resourceLoader(ResourceLoader resourceLoader) { + MetadataLocationRepositoryBuilder resourceLoader(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; return this; } - /** - * Build the {@link OpenSamlAssertingPartyMetadataRepository} - * @return the {@link OpenSamlAssertingPartyMetadataRepository} - */ - public OpenSamlAssertingPartyMetadataRepository build() { - ResourceBackedMetadataResolver metadataResolver = metadataResolver(); + MetadataResolver metadataResolver() { + ResourceBackedMetadataResolver metadataResolver = resourceBackedMetadataResolver(); if (!this.verificationCredentials.isEmpty()) { SignatureTrustEngine engine = new ExplicitKeySignatureTrustEngine( new CollectionCredentialResolver(this.verificationCredentials), @@ -277,13 +191,13 @@ public final class OpenSamlAssertingPartyMetadataRepository implements Asserting SignatureValidationFilter filter = new SignatureValidationFilter(engine); filter.setRequireSignedRoot(true); metadataResolver.setMetadataFilter(filter); - return new OpenSamlAssertingPartyMetadataRepository(initialize(metadataResolver)); + return initialize(metadataResolver); } Assert.isTrue(!this.requireVerificationCredentials, "Verification credentials are required"); - return new OpenSamlAssertingPartyMetadataRepository(initialize(metadataResolver)); + return initialize(metadataResolver); } - private ResourceBackedMetadataResolver metadataResolver() { + private ResourceBackedMetadataResolver resourceBackedMetadataResolver() { Resource resource = this.resourceLoader.getResource(this.metadataLocation); try { return new ResourceBackedMetadataResolver(new SpringResource(resource)); @@ -301,7 +215,7 @@ public final class OpenSamlAssertingPartyMetadataRepository implements Asserting metadataResolver.initialize(); return metadataResolver; } - catch (ComponentInitializationException ex) { + catch (Exception ex) { throw new Saml2Exception(ex); } } @@ -380,4 +294,18 @@ public final class OpenSamlAssertingPartyMetadataRepository implements Asserting } + abstract static class MetadataResolverAdapter { + + final MetadataResolver metadataResolver; + + MetadataResolverAdapter(MetadataResolver metadataResolver) { + this.metadataResolver = metadataResolver; + } + + abstract EntityDescriptor resolveSingle(EntityIdCriterion entityId) throws Exception; + + abstract Iterable resolve(EntityRoleCriterion role) throws Exception; + + } + } diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/registration/OpenSaml4AssertingPartyMetadataRepository.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/registration/OpenSaml4AssertingPartyMetadataRepository.java new file mode 100644 index 0000000000..4d85a683b1 --- /dev/null +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/registration/OpenSaml4AssertingPartyMetadataRepository.java @@ -0,0 +1,212 @@ +/* + * Copyright 2002-2024 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.security.saml2.provider.service.registration; + +import java.util.Collection; +import java.util.Iterator; +import java.util.function.Consumer; + +import net.shibboleth.utilities.java.support.resolver.CriteriaSet; +import org.opensaml.core.criterion.EntityIdCriterion; +import org.opensaml.saml.criterion.EntityRoleCriterion; +import org.opensaml.saml.metadata.IterableMetadataSource; +import org.opensaml.saml.metadata.resolver.MetadataResolver; +import org.opensaml.saml.metadata.resolver.index.impl.RoleMetadataIndex; +import org.opensaml.saml.saml2.metadata.EntityDescriptor; +import org.opensaml.security.credential.Credential; + +import org.springframework.core.io.ResourceLoader; +import org.springframework.lang.NonNull; +import org.springframework.lang.Nullable; +import org.springframework.security.saml2.core.Saml2X509Credential; +import org.springframework.security.saml2.provider.service.registration.BaseOpenSamlAssertingPartyMetadataRepository.MetadataResolverAdapter; +import org.springframework.util.Assert; + +/** + * An implementation of {@link AssertingPartyMetadataRepository} that uses a + * {@link MetadataResolver} to retrieve {@link AssertingPartyMetadata} instances. + * + *

+ * The {@link MetadataResolver} constructed in {@link #withTrustedMetadataLocation} + * provides expiry-aware refreshing. + * + * @author Josh Cummings + * @since 6.4 + * @see AssertingPartyMetadataRepository + * @see RelyingPartyRegistrations + */ +public final class OpenSaml4AssertingPartyMetadataRepository implements AssertingPartyMetadataRepository { + + private final BaseOpenSamlAssertingPartyMetadataRepository delegate; + + /** + * Construct an {@link OpenSaml4AssertingPartyMetadataRepository} using the provided + * {@link MetadataResolver}. + * + *

+ * The {@link MetadataResolver} should either be of type + * {@link IterableMetadataSource} or it should have a {@link RoleMetadataIndex} + * configured. + * @param metadataResolver the {@link MetadataResolver} to use + */ + public OpenSaml4AssertingPartyMetadataRepository(MetadataResolver metadataResolver) { + Assert.notNull(metadataResolver, "metadataResolver cannot be null"); + this.delegate = new BaseOpenSamlAssertingPartyMetadataRepository( + new CriteriaSetResolverWrapper(metadataResolver)); + } + + /** + * {@inheritDoc} + */ + @Override + @NonNull + public Iterator iterator() { + return this.delegate.iterator(); + } + + /** + * {@inheritDoc} + */ + @Nullable + @Override + public AssertingPartyMetadata findByEntityId(String entityId) { + return this.delegate.findByEntityId(entityId); + } + + /** + * Use this trusted {@code metadataLocation} to retrieve refreshable, expiry-aware + * SAML 2.0 Asserting Party (IDP) metadata. + * + *

+ * Valid locations can be classpath- or file-based or they can be HTTPS endpoints. + * Some valid endpoints might include: + * + *

+	 *   metadataLocation = "classpath:asserting-party-metadata.xml";
+	 *   metadataLocation = "file:asserting-party-metadata.xml";
+	 *   metadataLocation = "https://ap.example.org/metadata";
+	 * 
+ * + *

+ * Resolution of location is attempted immediately. To defer, wrap in + * {@link CachingRelyingPartyRegistrationRepository}. + * @param metadataLocation the classpath- or file-based locations or HTTPS endpoints + * of the asserting party metadata file + * @return the {@link MetadataLocationRepositoryBuilder} for further configuration + */ + public static MetadataLocationRepositoryBuilder withTrustedMetadataLocation(String metadataLocation) { + return new MetadataLocationRepositoryBuilder(metadataLocation, true); + } + + /** + * Use this {@code metadataLocation} to retrieve refreshable, expiry-aware SAML 2.0 + * Asserting Party (IDP) metadata. Verification credentials are required. + * + *

+ * Valid locations can be classpath- or file-based or they can be remote endpoints. + * Some valid endpoints might include: + * + *

+	 *   metadataLocation = "classpath:asserting-party-metadata.xml";
+	 *   metadataLocation = "file:asserting-party-metadata.xml";
+	 *   metadataLocation = "https://ap.example.org/metadata";
+	 * 
+ * + *

+ * Resolution of location is attempted immediately. To defer, wrap in + * {@link CachingRelyingPartyRegistrationRepository}. + * @param metadataLocation the classpath- or file-based locations or remote endpoints + * of the asserting party metadata file + * @return the {@link MetadataLocationRepositoryBuilder} for further configuration + */ + public static MetadataLocationRepositoryBuilder withMetadataLocation(String metadataLocation) { + return new MetadataLocationRepositoryBuilder(metadataLocation, false); + } + + /** + * A builder class for configuring {@link OpenSaml4AssertingPartyMetadataRepository} + * for a specific metadata location. + * + * @author Josh Cummings + */ + public static final class MetadataLocationRepositoryBuilder { + + private final BaseOpenSamlAssertingPartyMetadataRepository.MetadataLocationRepositoryBuilder builder; + + MetadataLocationRepositoryBuilder(String metadataLocation, boolean trusted) { + this.builder = new BaseOpenSamlAssertingPartyMetadataRepository.MetadataLocationRepositoryBuilder( + metadataLocation, trusted); + } + + /** + * Apply this {@link Consumer} to the list of {@link Saml2X509Credential}s to use + * for verifying metadata signatures. + * + *

+ * If no credentials are supplied, no signature verification is performed. + * @param credentials a {@link Consumer} of the {@link Collection} of + * {@link Saml2X509Credential}s + * @return the + * {@link BaseOpenSamlAssertingPartyMetadataRepository.MetadataLocationRepositoryBuilder} + * for further configuration + */ + public MetadataLocationRepositoryBuilder verificationCredentials(Consumer> credentials) { + this.builder.verificationCredentials(credentials); + return this; + } + + /** + * Use this {@link ResourceLoader} for resolving the {@code metadataLocation} + * @param resourceLoader the {@link ResourceLoader} to use + * @return the + * {@link BaseOpenSamlAssertingPartyMetadataRepository.MetadataLocationRepositoryBuilder} + * for further configuration + */ + public MetadataLocationRepositoryBuilder resourceLoader(ResourceLoader resourceLoader) { + this.builder.resourceLoader(resourceLoader); + return this; + } + + /** + * Build the {@link OpenSaml4AssertingPartyMetadataRepository} + * @return the {@link OpenSaml4AssertingPartyMetadataRepository} + */ + public OpenSaml4AssertingPartyMetadataRepository build() { + return new OpenSaml4AssertingPartyMetadataRepository(this.builder.metadataResolver()); + } + + } + + private static final class CriteriaSetResolverWrapper extends MetadataResolverAdapter { + + CriteriaSetResolverWrapper(MetadataResolver metadataResolver) { + super(metadataResolver); + } + + @Override + EntityDescriptor resolveSingle(EntityIdCriterion entityId) throws Exception { + return super.metadataResolver.resolveSingle(new CriteriaSet(entityId)); + } + + @Override + Iterable resolve(EntityRoleCriterion role) throws Exception { + return super.metadataResolver.resolve(new CriteriaSet(role)); + } + + } + +} diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/registration/OpenSaml4Template.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/registration/OpenSaml4Template.java new file mode 100644 index 0000000000..a56bcf8100 --- /dev/null +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/registration/OpenSaml4Template.java @@ -0,0 +1,617 @@ +/* + * Copyright 2002-2024 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.security.saml2.provider.service.registration; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.security.PrivateKey; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.xml.namespace.QName; + +import net.shibboleth.utilities.java.support.resolver.CriteriaSet; +import net.shibboleth.utilities.java.support.xml.SerializeSupport; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.opensaml.core.criterion.EntityIdCriterion; +import org.opensaml.core.xml.XMLObject; +import org.opensaml.core.xml.XMLObjectBuilder; +import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; +import org.opensaml.core.xml.io.Marshaller; +import org.opensaml.core.xml.io.MarshallingException; +import org.opensaml.core.xml.io.Unmarshaller; +import org.opensaml.core.xml.io.UnmarshallerFactory; +import org.opensaml.core.xml.util.XMLObjectSupport; +import org.opensaml.saml.common.xml.SAMLConstants; +import org.opensaml.saml.criterion.ProtocolCriterion; +import org.opensaml.saml.ext.saml2delrestrict.Delegate; +import org.opensaml.saml.ext.saml2delrestrict.DelegationRestrictionType; +import org.opensaml.saml.metadata.criteria.role.impl.EvaluableProtocolRoleDescriptorCriterion; +import org.opensaml.saml.saml2.core.Assertion; +import org.opensaml.saml.saml2.core.Attribute; +import org.opensaml.saml.saml2.core.AttributeStatement; +import org.opensaml.saml.saml2.core.Condition; +import org.opensaml.saml.saml2.core.EncryptedAssertion; +import org.opensaml.saml.saml2.core.EncryptedAttribute; +import org.opensaml.saml.saml2.core.Issuer; +import org.opensaml.saml.saml2.core.LogoutRequest; +import org.opensaml.saml.saml2.core.NameID; +import org.opensaml.saml.saml2.core.RequestAbstractType; +import org.opensaml.saml.saml2.core.Response; +import org.opensaml.saml.saml2.core.StatusResponseType; +import org.opensaml.saml.saml2.core.Subject; +import org.opensaml.saml.saml2.core.SubjectConfirmation; +import org.opensaml.saml.saml2.encryption.Decrypter; +import org.opensaml.saml.saml2.encryption.EncryptedElementTypeEncryptedKeyResolver; +import org.opensaml.saml.security.impl.SAMLMetadataSignatureSigningParametersResolver; +import org.opensaml.saml.security.impl.SAMLSignatureProfileValidator; +import org.opensaml.security.SecurityException; +import org.opensaml.security.credential.BasicCredential; +import org.opensaml.security.credential.Credential; +import org.opensaml.security.credential.CredentialResolver; +import org.opensaml.security.credential.CredentialSupport; +import org.opensaml.security.credential.UsageType; +import org.opensaml.security.credential.criteria.impl.EvaluableEntityIDCredentialCriterion; +import org.opensaml.security.credential.criteria.impl.EvaluableUsageCredentialCriterion; +import org.opensaml.security.credential.impl.CollectionCredentialResolver; +import org.opensaml.security.criteria.UsageCriterion; +import org.opensaml.security.x509.BasicX509Credential; +import org.opensaml.xmlsec.SignatureSigningParameters; +import org.opensaml.xmlsec.SignatureSigningParametersResolver; +import org.opensaml.xmlsec.config.impl.DefaultSecurityConfigurationBootstrap; +import org.opensaml.xmlsec.criterion.SignatureSigningConfigurationCriterion; +import org.opensaml.xmlsec.crypto.XMLSigningUtil; +import org.opensaml.xmlsec.encryption.support.ChainingEncryptedKeyResolver; +import org.opensaml.xmlsec.encryption.support.DecryptionException; +import org.opensaml.xmlsec.encryption.support.EncryptedKeyResolver; +import org.opensaml.xmlsec.encryption.support.InlineEncryptedKeyResolver; +import org.opensaml.xmlsec.encryption.support.SimpleRetrievalMethodEncryptedKeyResolver; +import org.opensaml.xmlsec.impl.BasicSignatureSigningConfiguration; +import org.opensaml.xmlsec.keyinfo.KeyInfoCredentialResolver; +import org.opensaml.xmlsec.keyinfo.KeyInfoGeneratorManager; +import org.opensaml.xmlsec.keyinfo.NamedKeyInfoGeneratorManager; +import org.opensaml.xmlsec.keyinfo.impl.CollectionKeyInfoCredentialResolver; +import org.opensaml.xmlsec.keyinfo.impl.X509KeyInfoGeneratorFactory; +import org.opensaml.xmlsec.signature.SignableXMLObject; +import org.opensaml.xmlsec.signature.Signature; +import org.opensaml.xmlsec.signature.support.SignatureConstants; +import org.opensaml.xmlsec.signature.support.SignatureSupport; +import org.opensaml.xmlsec.signature.support.SignatureTrustEngine; +import org.opensaml.xmlsec.signature.support.impl.ExplicitKeySignatureTrustEngine; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +import org.springframework.security.saml2.Saml2Exception; +import org.springframework.security.saml2.core.Saml2Error; +import org.springframework.security.saml2.core.Saml2ErrorCodes; +import org.springframework.security.saml2.core.Saml2ParameterNames; +import org.springframework.security.saml2.core.Saml2X509Credential; +import org.springframework.util.Assert; +import org.springframework.web.util.UriComponentsBuilder; +import org.springframework.web.util.UriUtils; + +/** + * For internal use only. Subject to breaking changes at any time. + */ +final class OpenSaml4Template implements OpenSamlOperations { + + private static final Log logger = LogFactory.getLog(OpenSaml4Template.class); + + @Override + public T build(QName elementName) { + XMLObjectBuilder builder = XMLObjectProviderRegistrySupport.getBuilderFactory().getBuilder(elementName); + if (builder == null) { + throw new Saml2Exception("Unable to resolve Builder for " + elementName); + } + return (T) builder.buildObject(elementName); + } + + @Override + public T deserialize(String serialized) { + return deserialize(new ByteArrayInputStream(serialized.getBytes(StandardCharsets.UTF_8))); + } + + @Override + public T deserialize(InputStream serialized) { + try { + Document document = XMLObjectProviderRegistrySupport.getParserPool().parse(serialized); + Element element = document.getDocumentElement(); + UnmarshallerFactory factory = XMLObjectProviderRegistrySupport.getUnmarshallerFactory(); + Unmarshaller unmarshaller = factory.getUnmarshaller(element); + if (unmarshaller == null) { + throw new Saml2Exception("Unsupported element of type " + element.getTagName()); + } + return (T) unmarshaller.unmarshall(element); + } + catch (Saml2Exception ex) { + throw ex; + } + catch (Exception ex) { + throw new Saml2Exception("Failed to deserialize payload", ex); + } + } + + @Override + public OpenSaml4SerializationConfigurer serialize(XMLObject object) { + Marshaller marshaller = XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(object); + try { + return serialize(marshaller.marshall(object)); + } + catch (MarshallingException ex) { + throw new Saml2Exception(ex); + } + } + + @Override + public OpenSaml4SerializationConfigurer serialize(Element element) { + return new OpenSaml4SerializationConfigurer(element); + } + + @Override + public OpenSaml4SignatureConfigurer withSigningKeys(Collection credentials) { + return new OpenSaml4SignatureConfigurer(credentials); + } + + @Override + public OpenSaml4VerificationConfigurer withVerificationKeys(Collection credentials) { + return new OpenSaml4VerificationConfigurer(credentials); + } + + @Override + public OpenSaml4DecryptionConfigurer withDecryptionKeys(Collection credentials) { + return new OpenSaml4DecryptionConfigurer(credentials); + } + + OpenSaml4Template() { + + } + + static final class OpenSaml4SerializationConfigurer + implements SerializationConfigurer { + + private final Element element; + + boolean pretty; + + OpenSaml4SerializationConfigurer(Element element) { + this.element = element; + } + + @Override + public OpenSaml4SerializationConfigurer prettyPrint(boolean pretty) { + this.pretty = pretty; + return this; + } + + @Override + public String serialize() { + if (this.pretty) { + return SerializeSupport.prettyPrintXML(this.element); + } + return SerializeSupport.nodeToString(this.element); + } + + } + + static final class OpenSaml4SignatureConfigurer implements SignatureConfigurer { + + private final Collection credentials; + + private final Map components = new LinkedHashMap<>(); + + private List algs = List.of(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256); + + OpenSaml4SignatureConfigurer(Collection credentials) { + this.credentials = credentials; + } + + @Override + public OpenSaml4SignatureConfigurer algorithms(List algs) { + this.algs = algs; + return this; + } + + @Override + public O sign(O object) { + SignatureSigningParameters parameters = resolveSigningParameters(); + try { + SignatureSupport.signObject(object, parameters); + } + catch (Exception ex) { + throw new Saml2Exception(ex); + } + return object; + } + + @Override + public Map sign(Map params) { + SignatureSigningParameters parameters = resolveSigningParameters(); + this.components.putAll(params); + Credential credential = parameters.getSigningCredential(); + String algorithmUri = parameters.getSignatureAlgorithm(); + this.components.put(Saml2ParameterNames.SIG_ALG, algorithmUri); + UriComponentsBuilder builder = UriComponentsBuilder.newInstance(); + for (Map.Entry component : this.components.entrySet()) { + builder.queryParam(component.getKey(), + UriUtils.encode(component.getValue(), StandardCharsets.ISO_8859_1)); + } + String queryString = builder.build(true).toString().substring(1); + try { + byte[] rawSignature = XMLSigningUtil.signWithURI(credential, algorithmUri, + queryString.getBytes(StandardCharsets.UTF_8)); + String b64Signature = Saml2Utils.samlEncode(rawSignature); + this.components.put(Saml2ParameterNames.SIGNATURE, b64Signature); + } + catch (SecurityException ex) { + throw new Saml2Exception(ex); + } + return this.components; + } + + private SignatureSigningParameters resolveSigningParameters() { + List credentials = resolveSigningCredentials(); + List digests = Collections.singletonList(SignatureConstants.ALGO_ID_DIGEST_SHA256); + String canonicalization = SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS; + SignatureSigningParametersResolver resolver = new SAMLMetadataSignatureSigningParametersResolver(); + BasicSignatureSigningConfiguration signingConfiguration = new BasicSignatureSigningConfiguration(); + signingConfiguration.setSigningCredentials(credentials); + signingConfiguration.setSignatureAlgorithms(this.algs); + signingConfiguration.setSignatureReferenceDigestMethods(digests); + signingConfiguration.setSignatureCanonicalizationAlgorithm(canonicalization); + signingConfiguration.setKeyInfoGeneratorManager(buildSignatureKeyInfoGeneratorManager()); + CriteriaSet criteria = new CriteriaSet(new SignatureSigningConfigurationCriterion(signingConfiguration)); + try { + SignatureSigningParameters parameters = resolver.resolveSingle(criteria); + Assert.notNull(parameters, "Failed to resolve any signing credential"); + return parameters; + } + catch (Exception ex) { + throw new Saml2Exception(ex); + } + } + + private NamedKeyInfoGeneratorManager buildSignatureKeyInfoGeneratorManager() { + final NamedKeyInfoGeneratorManager namedManager = new NamedKeyInfoGeneratorManager(); + + namedManager.setUseDefaultManager(true); + final KeyInfoGeneratorManager defaultManager = namedManager.getDefaultManager(); + + // Generator for X509Credentials + final X509KeyInfoGeneratorFactory x509Factory = new X509KeyInfoGeneratorFactory(); + x509Factory.setEmitEntityCertificate(true); + x509Factory.setEmitEntityCertificateChain(true); + + defaultManager.registerFactory(x509Factory); + + return namedManager; + } + + private List resolveSigningCredentials() { + List credentials = new ArrayList<>(); + for (Saml2X509Credential x509Credential : this.credentials) { + X509Certificate certificate = x509Credential.getCertificate(); + PrivateKey privateKey = x509Credential.getPrivateKey(); + BasicCredential credential = CredentialSupport.getSimpleCredential(certificate, privateKey); + credential.setUsageType(UsageType.SIGNING); + credentials.add(credential); + } + return credentials; + } + + } + + static final class OpenSaml4VerificationConfigurer implements VerificationConfigurer { + + private final Collection credentials; + + private String entityId; + + OpenSaml4VerificationConfigurer(Collection credentials) { + this.credentials = credentials; + } + + @Override + public VerificationConfigurer entityId(String entityId) { + this.entityId = entityId; + return this; + } + + private SignatureTrustEngine trustEngine(Collection keys) { + Set credentials = new HashSet<>(); + for (Saml2X509Credential key : keys) { + BasicX509Credential cred = new BasicX509Credential(key.getCertificate()); + cred.setUsageType(UsageType.SIGNING); + cred.setEntityId(this.entityId); + credentials.add(cred); + } + CredentialResolver credentialsResolver = new CollectionCredentialResolver(credentials); + return new ExplicitKeySignatureTrustEngine(credentialsResolver, + DefaultSecurityConfigurationBootstrap.buildBasicInlineKeyInfoCredentialResolver()); + } + + private CriteriaSet verificationCriteria(Issuer issuer) { + return new CriteriaSet(new EvaluableEntityIDCredentialCriterion(new EntityIdCriterion(issuer.getValue())), + new EvaluableProtocolRoleDescriptorCriterion(new ProtocolCriterion(SAMLConstants.SAML20P_NS)), + new EvaluableUsageCredentialCriterion(new UsageCriterion(UsageType.SIGNING))); + } + + @Override + public Collection verify(SignableXMLObject signable) { + if (signable instanceof StatusResponseType response) { + return verifySignature(response.getID(), response.getIssuer(), response.getSignature()); + } + if (signable instanceof RequestAbstractType request) { + return verifySignature(request.getID(), request.getIssuer(), request.getSignature()); + } + if (signable instanceof Assertion assertion) { + return verifySignature(assertion.getID(), assertion.getIssuer(), assertion.getSignature()); + } + throw new Saml2Exception("Unsupported object of type: " + signable.getClass().getName()); + } + + private Collection verifySignature(String id, Issuer issuer, Signature signature) { + SignatureTrustEngine trustEngine = trustEngine(this.credentials); + CriteriaSet criteria = verificationCriteria(issuer); + Collection errors = new ArrayList<>(); + SAMLSignatureProfileValidator profileValidator = new SAMLSignatureProfileValidator(); + try { + profileValidator.validate(signature); + } + catch (Exception ex) { + errors.add(new Saml2Error(Saml2ErrorCodes.INVALID_SIGNATURE, + "Invalid signature for object [" + id + "]: ")); + } + + try { + if (!trustEngine.validate(signature, criteria)) { + errors.add(new Saml2Error(Saml2ErrorCodes.INVALID_SIGNATURE, + "Invalid signature for object [" + id + "]")); + } + } + catch (Exception ex) { + errors.add(new Saml2Error(Saml2ErrorCodes.INVALID_SIGNATURE, + "Invalid signature for object [" + id + "]: ")); + } + + return errors; + } + + @Override + public Collection verify(RedirectParameters parameters) { + SignatureTrustEngine trustEngine = trustEngine(this.credentials); + CriteriaSet criteria = verificationCriteria(parameters.getIssuer()); + if (parameters.getAlgorithm() == null) { + return Collections.singletonList(new Saml2Error(Saml2ErrorCodes.INVALID_SIGNATURE, + "Missing signature algorithm for object [" + parameters.getId() + "]")); + } + if (!parameters.hasSignature()) { + return Collections.singletonList(new Saml2Error(Saml2ErrorCodes.INVALID_SIGNATURE, + "Missing signature for object [" + parameters.getId() + "]")); + } + Collection errors = new ArrayList<>(); + String algorithmUri = parameters.getAlgorithm(); + try { + if (!trustEngine.validate(parameters.getSignature(), parameters.getContent(), algorithmUri, criteria, + null)) { + errors.add(new Saml2Error(Saml2ErrorCodes.INVALID_SIGNATURE, + "Invalid signature for object [" + parameters.getId() + "]")); + } + } + catch (Exception ex) { + errors.add(new Saml2Error(Saml2ErrorCodes.INVALID_SIGNATURE, + "Invalid signature for object [" + parameters.getId() + "]: ")); + } + return errors; + } + + } + + static final class OpenSaml4DecryptionConfigurer implements DecryptionConfigurer { + + private static final EncryptedKeyResolver encryptedKeyResolver = new ChainingEncryptedKeyResolver( + Arrays.asList(new InlineEncryptedKeyResolver(), new EncryptedElementTypeEncryptedKeyResolver(), + new SimpleRetrievalMethodEncryptedKeyResolver())); + + private final Decrypter decrypter; + + OpenSaml4DecryptionConfigurer(Collection decryptionCredentials) { + this.decrypter = decrypter(decryptionCredentials); + } + + private static Decrypter decrypter(Collection decryptionCredentials) { + Collection credentials = new ArrayList<>(); + for (Saml2X509Credential key : decryptionCredentials) { + Credential cred = CredentialSupport.getSimpleCredential(key.getCertificate(), key.getPrivateKey()); + credentials.add(cred); + } + KeyInfoCredentialResolver resolver = new CollectionKeyInfoCredentialResolver(credentials); + Decrypter decrypter = new Decrypter(null, resolver, encryptedKeyResolver); + decrypter.setRootInNewDocument(true); + return decrypter; + } + + @Override + public void decrypt(XMLObject object) { + if (object instanceof Response response) { + decryptResponse(response); + return; + } + if (object instanceof Assertion assertion) { + decryptAssertion(assertion); + } + if (object instanceof LogoutRequest request) { + decryptLogoutRequest(request); + } + } + + /* + * The methods that follow are adapted from OpenSAML's {@link DecryptAssertions}, + * {@link DecryptNameIDs}, and {@link DecryptAttributes}. + * + *

The reason that these OpenSAML classes are not used directly is because they + * reference {@link javax.servlet.http.HttpServletRequest} which is a lower + * Servlet API version than what Spring Security SAML uses. + * + * If OpenSAML 5 updates to {@link jakarta.servlet.http.HttpServletRequest}, then + * this arrangement can be revisited. + */ + + private void decryptResponse(Response response) { + Collection decrypteds = new ArrayList<>(); + Collection encrypteds = new ArrayList<>(); + + int count = 0; + int size = response.getEncryptedAssertions().size(); + for (EncryptedAssertion encrypted : response.getEncryptedAssertions()) { + logger.trace(String.format("Decrypting EncryptedAssertion (%d/%d) in Response [%s]", count, size, + response.getID())); + try { + Assertion decrypted = this.decrypter.decrypt(encrypted); + if (decrypted != null) { + encrypteds.add(encrypted); + decrypteds.add(decrypted); + } + count++; + } + catch (DecryptionException ex) { + throw new Saml2Exception(ex); + } + } + + response.getEncryptedAssertions().removeAll(encrypteds); + response.getAssertions().addAll(decrypteds); + + // Re-marshall the response so that any ID attributes within the decrypted + // Assertions + // will have their ID-ness re-established at the DOM level. + if (!decrypteds.isEmpty()) { + try { + XMLObjectSupport.marshall(response); + } + catch (final MarshallingException ex) { + throw new Saml2Exception(ex); + } + } + } + + private void decryptAssertion(Assertion assertion) { + for (AttributeStatement statement : assertion.getAttributeStatements()) { + decryptAttributes(statement); + } + decryptSubject(assertion.getSubject()); + if (assertion.getConditions() != null) { + for (Condition c : assertion.getConditions().getConditions()) { + if (!(c instanceof DelegationRestrictionType delegation)) { + continue; + } + for (Delegate d : delegation.getDelegates()) { + if (d.getEncryptedID() != null) { + try { + NameID decrypted = (NameID) this.decrypter.decrypt(d.getEncryptedID()); + if (decrypted != null) { + d.setNameID(decrypted); + d.setEncryptedID(null); + } + } + catch (DecryptionException ex) { + throw new Saml2Exception(ex); + } + } + } + } + } + } + + private void decryptAttributes(AttributeStatement statement) { + Collection decrypteds = new ArrayList<>(); + Collection encrypteds = new ArrayList<>(); + for (EncryptedAttribute encrypted : statement.getEncryptedAttributes()) { + try { + Attribute decrypted = this.decrypter.decrypt(encrypted); + if (decrypted != null) { + encrypteds.add(encrypted); + decrypteds.add(decrypted); + } + } + catch (Exception ex) { + throw new Saml2Exception(ex); + } + } + statement.getEncryptedAttributes().removeAll(encrypteds); + statement.getAttributes().addAll(decrypteds); + } + + private void decryptSubject(Subject subject) { + if (subject != null) { + if (subject.getEncryptedID() != null) { + try { + NameID decrypted = (NameID) this.decrypter.decrypt(subject.getEncryptedID()); + if (decrypted != null) { + subject.setNameID(decrypted); + subject.setEncryptedID(null); + } + } + catch (final DecryptionException ex) { + throw new Saml2Exception(ex); + } + } + + for (final SubjectConfirmation sc : subject.getSubjectConfirmations()) { + if (sc.getEncryptedID() != null) { + try { + NameID decrypted = (NameID) this.decrypter.decrypt(sc.getEncryptedID()); + if (decrypted != null) { + sc.setNameID(decrypted); + sc.setEncryptedID(null); + } + } + catch (final DecryptionException ex) { + throw new Saml2Exception(ex); + } + } + } + } + } + + private void decryptLogoutRequest(LogoutRequest request) { + if (request.getEncryptedID() != null) { + try { + NameID decrypted = (NameID) this.decrypter.decrypt(request.getEncryptedID()); + if (decrypted != null) { + request.setNameID(decrypted); + request.setEncryptedID(null); + } + } + catch (DecryptionException ex) { + throw new Saml2Exception(ex); + } + } + } + + } + +} diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/registration/OpenSamlOperations.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/registration/OpenSamlOperations.java new file mode 100644 index 0000000000..994030e683 --- /dev/null +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/registration/OpenSamlOperations.java @@ -0,0 +1,184 @@ +/* + * Copyright 2002-2024 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.security.saml2.provider.service.registration; + +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import javax.xml.namespace.QName; + +import org.opensaml.core.xml.XMLObject; +import org.opensaml.saml.saml2.core.Issuer; +import org.opensaml.saml.saml2.core.RequestAbstractType; +import org.opensaml.saml.saml2.core.StatusResponseType; +import org.opensaml.xmlsec.signature.SignableXMLObject; +import org.w3c.dom.Element; + +import org.springframework.security.saml2.core.Saml2Error; +import org.springframework.security.saml2.core.Saml2ParameterNames; +import org.springframework.security.saml2.core.Saml2X509Credential; +import org.springframework.web.util.UriComponentsBuilder; + +interface OpenSamlOperations { + + T build(QName elementName); + + T deserialize(String serialized); + + T deserialize(InputStream serialized); + + SerializationConfigurer serialize(XMLObject object); + + SerializationConfigurer serialize(Element element); + + SignatureConfigurer withSigningKeys(Collection credentials); + + VerificationConfigurer withVerificationKeys(Collection credentials); + + DecryptionConfigurer withDecryptionKeys(Collection credentials); + + interface SerializationConfigurer> { + + B prettyPrint(boolean pretty); + + String serialize(); + + } + + interface SignatureConfigurer> { + + B algorithms(List algs); + + O sign(O object); + + Map sign(Map params); + + } + + interface VerificationConfigurer { + + VerificationConfigurer entityId(String entityId); + + Collection verify(SignableXMLObject signable); + + Collection verify(VerificationConfigurer.RedirectParameters parameters); + + final class RedirectParameters { + + private final String id; + + private final Issuer issuer; + + private final String algorithm; + + private final byte[] signature; + + private final byte[] content; + + RedirectParameters(Map parameters, String parametersQuery, RequestAbstractType request) { + this.id = request.getID(); + this.issuer = request.getIssuer(); + this.algorithm = parameters.get(Saml2ParameterNames.SIG_ALG); + if (parameters.get(Saml2ParameterNames.SIGNATURE) != null) { + this.signature = Saml2Utils.samlDecode(parameters.get(Saml2ParameterNames.SIGNATURE)); + } + else { + this.signature = null; + } + Map queryParams = UriComponentsBuilder.newInstance() + .query(parametersQuery) + .build(true) + .getQueryParams() + .toSingleValueMap(); + String relayState = parameters.get(Saml2ParameterNames.RELAY_STATE); + this.content = getContent(Saml2ParameterNames.SAML_REQUEST, relayState, queryParams); + } + + RedirectParameters(Map parameters, String parametersQuery, StatusResponseType response) { + this.id = response.getID(); + this.issuer = response.getIssuer(); + this.algorithm = parameters.get(Saml2ParameterNames.SIG_ALG); + if (parameters.get(Saml2ParameterNames.SIGNATURE) != null) { + this.signature = Saml2Utils.samlDecode(parameters.get(Saml2ParameterNames.SIGNATURE)); + } + else { + this.signature = null; + } + Map queryParams = UriComponentsBuilder.newInstance() + .query(parametersQuery) + .build(true) + .getQueryParams() + .toSingleValueMap(); + String relayState = parameters.get(Saml2ParameterNames.RELAY_STATE); + this.content = getContent(Saml2ParameterNames.SAML_RESPONSE, relayState, queryParams); + } + + static byte[] getContent(String samlObject, String relayState, final Map queryParams) { + if (Objects.nonNull(relayState)) { + return String + .format("%s=%s&%s=%s&%s=%s", samlObject, queryParams.get(samlObject), + Saml2ParameterNames.RELAY_STATE, queryParams.get(Saml2ParameterNames.RELAY_STATE), + Saml2ParameterNames.SIG_ALG, queryParams.get(Saml2ParameterNames.SIG_ALG)) + .getBytes(StandardCharsets.UTF_8); + } + else { + return String + .format("%s=%s&%s=%s", samlObject, queryParams.get(samlObject), Saml2ParameterNames.SIG_ALG, + queryParams.get(Saml2ParameterNames.SIG_ALG)) + .getBytes(StandardCharsets.UTF_8); + } + } + + String getId() { + return this.id; + } + + Issuer getIssuer() { + return this.issuer; + } + + byte[] getContent() { + return this.content; + } + + String getAlgorithm() { + return this.algorithm; + } + + byte[] getSignature() { + return this.signature; + } + + boolean hasSignature() { + return this.signature != null; + } + + } + + } + + interface DecryptionConfigurer { + + void decrypt(XMLObject object); + + } + +} diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/registration/Saml2Utils.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/registration/Saml2Utils.java new file mode 100644 index 0000000000..2923e4ef4f --- /dev/null +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/registration/Saml2Utils.java @@ -0,0 +1,196 @@ +/* + * Copyright 2002-2024 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.security.saml2.provider.service.registration; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Base64; +import java.util.zip.Deflater; +import java.util.zip.DeflaterOutputStream; +import java.util.zip.Inflater; +import java.util.zip.InflaterOutputStream; + +import org.springframework.security.saml2.Saml2Exception; + +/** + * Utility methods for working with serialized SAML messages. + * + * For internal use only. + * + * @author Josh Cummings + */ +final class Saml2Utils { + + private Saml2Utils() { + } + + static String samlEncode(byte[] b) { + return Base64.getEncoder().encodeToString(b); + } + + static byte[] samlDecode(String s) { + return Base64.getMimeDecoder().decode(s); + } + + static byte[] samlDeflate(String s) { + try { + ByteArrayOutputStream b = new ByteArrayOutputStream(); + DeflaterOutputStream deflater = new DeflaterOutputStream(b, new Deflater(Deflater.DEFLATED, true)); + deflater.write(s.getBytes(StandardCharsets.UTF_8)); + deflater.finish(); + return b.toByteArray(); + } + catch (IOException ex) { + throw new Saml2Exception("Unable to deflate string", ex); + } + } + + static String samlInflate(byte[] b) { + try { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + InflaterOutputStream iout = new InflaterOutputStream(out, new Inflater(true)); + iout.write(b); + iout.finish(); + return new String(out.toByteArray(), StandardCharsets.UTF_8); + } + catch (IOException ex) { + throw new Saml2Exception("Unable to inflate string", ex); + } + } + + static EncodingConfigurer withDecoded(String decoded) { + return new EncodingConfigurer(decoded); + } + + static DecodingConfigurer withEncoded(String encoded) { + return new DecodingConfigurer(encoded); + } + + static final class EncodingConfigurer { + + private final String decoded; + + private boolean deflate; + + private EncodingConfigurer(String decoded) { + this.decoded = decoded; + } + + EncodingConfigurer deflate(boolean deflate) { + this.deflate = deflate; + return this; + } + + String encode() { + byte[] bytes = (this.deflate) ? Saml2Utils.samlDeflate(this.decoded) + : this.decoded.getBytes(StandardCharsets.UTF_8); + return Saml2Utils.samlEncode(bytes); + } + + } + + static final class DecodingConfigurer { + + private static final Base64Checker BASE_64_CHECKER = new Base64Checker(); + + private final String encoded; + + private boolean inflate; + + private boolean requireBase64; + + private DecodingConfigurer(String encoded) { + this.encoded = encoded; + } + + DecodingConfigurer inflate(boolean inflate) { + this.inflate = inflate; + return this; + } + + DecodingConfigurer requireBase64(boolean requireBase64) { + this.requireBase64 = requireBase64; + return this; + } + + String decode() { + if (this.requireBase64) { + BASE_64_CHECKER.checkAcceptable(this.encoded); + } + byte[] bytes = Saml2Utils.samlDecode(this.encoded); + return (this.inflate) ? Saml2Utils.samlInflate(bytes) : new String(bytes, StandardCharsets.UTF_8); + } + + static class Base64Checker { + + private static final int[] values = genValueMapping(); + + Base64Checker() { + + } + + private static int[] genValueMapping() { + byte[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" + .getBytes(StandardCharsets.ISO_8859_1); + + int[] values = new int[256]; + Arrays.fill(values, -1); + for (int i = 0; i < alphabet.length; i++) { + values[alphabet[i] & 0xff] = i; + } + return values; + } + + boolean isAcceptable(String s) { + int goodChars = 0; + int lastGoodCharVal = -1; + + // count number of characters from Base64 alphabet + for (int i = 0; i < s.length(); i++) { + int val = values[0xff & s.charAt(i)]; + if (val != -1) { + lastGoodCharVal = val; + goodChars++; + } + } + + // in cases of an incomplete final chunk, ensure the unused bits are zero + switch (goodChars % 4) { + case 0: + return true; + case 2: + return (lastGoodCharVal & 0b1111) == 0; + case 3: + return (lastGoodCharVal & 0b11) == 0; + default: + return false; + } + } + + void checkAcceptable(String ins) { + if (!isAcceptable(ins)) { + throw new IllegalArgumentException("Failed to decode SAMLResponse"); + } + } + + } + + } + +} diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/registration/OpenSamlAssertingPartyMetadataRepositoryTests.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/registration/OpenSaml4AssertingPartyMetadataRepositoryTests.java similarity index 87% rename from saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/registration/OpenSamlAssertingPartyMetadataRepositoryTests.java rename to saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/registration/OpenSaml4AssertingPartyMetadataRepositoryTests.java index 8020a970a1..8609e71645 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/registration/OpenSamlAssertingPartyMetadataRepositoryTests.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/registration/OpenSaml4AssertingPartyMetadataRepositoryTests.java @@ -24,7 +24,6 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Set; -import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import net.shibboleth.utilities.java.support.xml.SerializeSupport; @@ -63,9 +62,9 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.withSettings; /** - * Tests for {@link OpenSamlAssertingPartyMetadataRepository} + * Tests for {@link BaseOpenSamlAssertingPartyMetadataRepository} */ -public class OpenSamlAssertingPartyMetadataRepositoryTests { +public class OpenSaml4AssertingPartyMetadataRepositoryTests { static { OpenSamlInitializationService.initialize(); @@ -90,8 +89,8 @@ public class OpenSamlAssertingPartyMetadataRepositoryTests { @Test public void withMetadataUrlLocationWhenResolvableThenFindByEntityIdReturns() throws Exception { try (MockWebServer server = new MockWebServer()) { - server.setDispatcher(new AlwaysDispatch(this.metadata)); - AssertingPartyMetadataRepository parties = OpenSamlAssertingPartyMetadataRepository + server.setDispatcher(new AlwaysDispatch(new MockResponse().setBody(this.metadata).setResponseCode(200))); + AssertingPartyMetadataRepository parties = OpenSaml4AssertingPartyMetadataRepository .withTrustedMetadataLocation(server.url("/").toString()) .build(); AssertingPartyMetadata party = parties.findByEntityId("https://idp.example.com/idp/shibboleth"); @@ -107,9 +106,10 @@ public class OpenSamlAssertingPartyMetadataRepositoryTests { @Test public void withMetadataUrlLocationnWhenResolvableThenIteratorReturns() throws Exception { try (MockWebServer server = new MockWebServer()) { - server.setDispatcher(new AlwaysDispatch(this.entitiesDescriptor)); + server.setDispatcher( + new AlwaysDispatch(new MockResponse().setBody(this.entitiesDescriptor).setResponseCode(200))); List parties = new ArrayList<>(); - OpenSamlAssertingPartyMetadataRepository.withTrustedMetadataLocation(server.url("/").toString()) + OpenSaml4AssertingPartyMetadataRepository.withTrustedMetadataLocation(server.url("/").toString()) .build() .iterator() .forEachRemaining(parties::add); @@ -126,7 +126,7 @@ public class OpenSamlAssertingPartyMetadataRepositoryTests { String url = server.url("/").toString(); server.shutdown(); assertThatExceptionOfType(Saml2Exception.class) - .isThrownBy(() -> OpenSamlAssertingPartyMetadataRepository.withTrustedMetadataLocation(url).build()); + .isThrownBy(() -> OpenSaml4AssertingPartyMetadataRepository.withTrustedMetadataLocation(url).build()); } } @@ -136,14 +136,14 @@ public class OpenSamlAssertingPartyMetadataRepositoryTests { server.setDispatcher(new AlwaysDispatch("malformed")); String url = server.url("/").toString(); assertThatExceptionOfType(Saml2Exception.class) - .isThrownBy(() -> OpenSamlAssertingPartyMetadataRepository.withTrustedMetadataLocation(url).build()); + .isThrownBy(() -> OpenSaml4AssertingPartyMetadataRepository.withTrustedMetadataLocation(url).build()); } } @Test public void fromMetadataFileLocationWhenResolvableThenFindByEntityIdReturns() { File file = new File("src/test/resources/test-metadata.xml"); - AssertingPartyMetadata party = OpenSamlAssertingPartyMetadataRepository + AssertingPartyMetadata party = OpenSaml4AssertingPartyMetadataRepository .withTrustedMetadataLocation("file:" + file.getAbsolutePath()) .build() .findByEntityId("https://idp.example.com/idp/shibboleth"); @@ -159,7 +159,7 @@ public class OpenSamlAssertingPartyMetadataRepositoryTests { public void fromMetadataFileLocationWhenResolvableThenIteratorReturns() { File file = new File("src/test/resources/test-entitiesdescriptor.xml"); Collection parties = new ArrayList<>(); - OpenSamlAssertingPartyMetadataRepository.withTrustedMetadataLocation("file:" + file.getAbsolutePath()) + OpenSaml4AssertingPartyMetadataRepository.withTrustedMetadataLocation("file:" + file.getAbsolutePath()) .build() .iterator() .forEachRemaining(parties::add); @@ -171,12 +171,12 @@ public class OpenSamlAssertingPartyMetadataRepositoryTests { @Test public void withMetadataFileLocationWhenNotFoundThenSaml2Exception() { assertThatExceptionOfType(Saml2Exception.class).isThrownBy( - () -> OpenSamlAssertingPartyMetadataRepository.withTrustedMetadataLocation("file:path").build()); + () -> OpenSaml4AssertingPartyMetadataRepository.withTrustedMetadataLocation("file:path").build()); } @Test public void fromMetadataClasspathLocationWhenResolvableThenFindByEntityIdReturns() { - AssertingPartyMetadata party = OpenSamlAssertingPartyMetadataRepository + AssertingPartyMetadata party = OpenSaml4AssertingPartyMetadataRepository .withTrustedMetadataLocation("classpath:test-entitiesdescriptor.xml") .build() .findByEntityId("https://ap.example.org/idp/shibboleth"); @@ -191,7 +191,7 @@ public class OpenSamlAssertingPartyMetadataRepositoryTests { @Test public void fromMetadataClasspathLocationWhenResolvableThenIteratorReturns() { Collection parties = new ArrayList<>(); - OpenSamlAssertingPartyMetadataRepository.withTrustedMetadataLocation("classpath:test-entitiesdescriptor.xml") + OpenSaml4AssertingPartyMetadataRepository.withTrustedMetadataLocation("classpath:test-entitiesdescriptor.xml") .build() .iterator() .forEachRemaining(parties::add); @@ -203,7 +203,7 @@ public class OpenSamlAssertingPartyMetadataRepositoryTests { @Test public void withMetadataClasspathLocationWhenNotFoundThenSaml2Exception() { assertThatExceptionOfType(Saml2Exception.class).isThrownBy( - () -> OpenSamlAssertingPartyMetadataRepository.withTrustedMetadataLocation("classpath:path").build()); + () -> OpenSaml4AssertingPartyMetadataRepository.withTrustedMetadataLocation("classpath:path").build()); } @Test @@ -218,7 +218,7 @@ public class OpenSamlAssertingPartyMetadataRepositoryTests { try (MockWebServer server = new MockWebServer()) { server.start(); server.setDispatcher(new AlwaysDispatch(serialized)); - AssertingPartyMetadataRepository parties = OpenSamlAssertingPartyMetadataRepository + AssertingPartyMetadataRepository parties = OpenSaml4AssertingPartyMetadataRepository .withTrustedMetadataLocation(server.url("/").toString()) .verificationCredentials((c) -> c.add(credential)) .build(); @@ -238,7 +238,7 @@ public class OpenSamlAssertingPartyMetadataRepositoryTests { try (MockWebServer server = new MockWebServer()) { server.start(); server.setDispatcher(new AlwaysDispatch(serialized)); - assertThatExceptionOfType(Saml2Exception.class).isThrownBy(() -> OpenSamlAssertingPartyMetadataRepository + assertThatExceptionOfType(Saml2Exception.class).isThrownBy(() -> OpenSaml4AssertingPartyMetadataRepository .withTrustedMetadataLocation(server.url("/").toString()) .verificationCredentials((c) -> c.add(credential)) .build()); @@ -255,7 +255,7 @@ public class OpenSamlAssertingPartyMetadataRepositoryTests { try (MockWebServer server = new MockWebServer()) { server.start(); server.setDispatcher(new AlwaysDispatch(serialized)); - AssertingPartyMetadataRepository parties = OpenSamlAssertingPartyMetadataRepository + AssertingPartyMetadataRepository parties = OpenSaml4AssertingPartyMetadataRepository .withTrustedMetadataLocation(server.url("/").toString()) .build(); assertThat(parties.findByEntityId(registration.getAssertingPartyDetails().getEntityId())).isNotNull(); @@ -266,7 +266,7 @@ public class OpenSamlAssertingPartyMetadataRepositoryTests { public void withTrustedMetadataLocationWhenCustomResourceLoaderThenUses() { ResourceLoader resourceLoader = mock(ResourceLoader.class); given(resourceLoader.getResource(any())).willReturn(new ClassPathResource("test-metadata.xml")); - AssertingPartyMetadata party = OpenSamlAssertingPartyMetadataRepository + AssertingPartyMetadata party = OpenSaml4AssertingPartyMetadataRepository .withTrustedMetadataLocation("classpath:wrong") .resourceLoader(resourceLoader) .build() @@ -285,7 +285,7 @@ public class OpenSamlAssertingPartyMetadataRepositoryTests { public void constructorWhenNoIndexAndNoIteratorThenException() { MetadataResolver resolver = mock(MetadataResolver.class); assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> new OpenSamlAssertingPartyMetadataRepository(resolver)); + .isThrownBy(() -> new OpenSaml4AssertingPartyMetadataRepository(resolver)); } @Test @@ -295,7 +295,7 @@ public class OpenSamlAssertingPartyMetadataRepositoryTests { MetadataResolver resolver = mock(MetadataResolver.class, withSettings().extraInterfaces(IterableMetadataSource.class)); given(((IterableMetadataSource) resolver).iterator()).willReturn(List.of(descriptor).iterator()); - AssertingPartyMetadataRepository parties = new OpenSamlAssertingPartyMetadataRepository(resolver); + AssertingPartyMetadataRepository parties = new OpenSaml4AssertingPartyMetadataRepository(resolver); parties.iterator() .forEachRemaining((p) -> assertThat(p.getEntityId()) .isEqualTo(registration.getAssertingPartyDetails().getEntityId())); @@ -311,7 +311,7 @@ public class OpenSamlAssertingPartyMetadataRepositoryTests { resolver.setParserPool(XMLObjectProviderRegistrySupport.getParserPool()); resolver.initialize(); MetadataResolver spied = spy(resolver); - AssertingPartyMetadataRepository parties = new OpenSamlAssertingPartyMetadataRepository(spied); + AssertingPartyMetadataRepository parties = new OpenSaml4AssertingPartyMetadataRepository(spied); parties.iterator() .forEachRemaining((p) -> assertThat(p.getEntityId()).isEqualTo("https://idp.example.com/idp/shibboleth")); verify(spied).resolve(any()); @@ -320,7 +320,7 @@ public class OpenSamlAssertingPartyMetadataRepositoryTests { @Test public void withMetadataLocationWhenNoCredentialsThenException() { assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy( - () -> OpenSamlAssertingPartyMetadataRepository.withMetadataLocation("classpath:test-metadata.xml") + () -> OpenSaml4AssertingPartyMetadataRepository.withMetadataLocation("classpath:test-metadata.xml") .build()); } @@ -336,7 +336,7 @@ public class OpenSamlAssertingPartyMetadataRepositoryTests { try (MockWebServer server = new MockWebServer()) { server.start(); server.setDispatcher(new AlwaysDispatch(serialized)); - AssertingPartyMetadataRepository parties = OpenSamlAssertingPartyMetadataRepository + AssertingPartyMetadataRepository parties = OpenSaml4AssertingPartyMetadataRepository .withMetadataLocation(server.url("/").toString()) .verificationCredentials((c) -> c.add(credential)) .build(); @@ -360,9 +360,7 @@ public class OpenSamlAssertingPartyMetadataRepositoryTests { private final MockResponse response; private AlwaysDispatch(String body) { - this.response = new MockResponse().setBody(body) - .setResponseCode(200) - .setBodyDelay(1, TimeUnit.MILLISECONDS); + this.response = new MockResponse().setBody(body).setResponseCode(200); } private AlwaysDispatch(MockResponse response) {