Search in sources :

Example 21 with EntityIdCriterion

use of org.opensaml.core.criterion.EntityIdCriterion in project cas by apereo.

the class SamlIdPUtils method getAssertionConsumerServiceFor.

/**
 * Gets assertion consumer service for.
 *
 * @param authnRequest    the authn request
 * @param servicesManager the services manager
 * @param resolver        the resolver
 * @return the assertion consumer service for
 */
public static AssertionConsumerService getAssertionConsumerServiceFor(final AuthnRequest authnRequest, final ServicesManager servicesManager, final SamlRegisteredServiceCachingMetadataResolver resolver) {
    try {
        final AssertionConsumerService acs = new AssertionConsumerServiceBuilder().buildObject();
        if (authnRequest.getAssertionConsumerServiceIndex() != null) {
            final String issuer = getIssuerFromSamlRequest(authnRequest);
            final MetadataResolver samlResolver = getMetadataResolverForAllSamlServices(servicesManager, issuer, resolver);
            final CriteriaSet criteriaSet = new CriteriaSet();
            criteriaSet.add(new EntityIdCriterion(issuer));
            criteriaSet.add(new EntityRoleCriterion(SPSSODescriptor.DEFAULT_ELEMENT_NAME));
            criteriaSet.add(new BindingCriterion(CollectionUtils.wrap(SAMLConstants.SAML2_POST_BINDING_URI)));
            final Iterable<EntityDescriptor> it = samlResolver.resolve(criteriaSet);
            it.forEach(entityDescriptor -> {
                final SPSSODescriptor spssoDescriptor = entityDescriptor.getSPSSODescriptor(SAMLConstants.SAML20P_NS);
                final List<AssertionConsumerService> acsEndpoints = spssoDescriptor.getAssertionConsumerServices();
                if (acsEndpoints.isEmpty()) {
                    throw new IllegalArgumentException("Metadata resolved for entity id " + issuer + " has no defined ACS endpoints");
                }
                final int acsIndex = authnRequest.getAssertionConsumerServiceIndex();
                if (acsIndex + 1 > acsEndpoints.size()) {
                    throw new IllegalArgumentException("AssertionConsumerService index specified in the request " + acsIndex + " is invalid " + "since the total endpoints available to " + issuer + " is " + acsEndpoints.size());
                }
                final AssertionConsumerService foundAcs = acsEndpoints.get(acsIndex);
                acs.setBinding(foundAcs.getBinding());
                acs.setLocation(foundAcs.getLocation());
                acs.setResponseLocation(foundAcs.getResponseLocation());
                acs.setIndex(acsIndex);
            });
        } else {
            acs.setBinding(authnRequest.getProtocolBinding());
            acs.setLocation(authnRequest.getAssertionConsumerServiceURL());
            acs.setResponseLocation(authnRequest.getAssertionConsumerServiceURL());
            acs.setIndex(0);
            acs.setIsDefault(Boolean.TRUE);
        }
        LOGGER.debug("Resolved AssertionConsumerService from the request is [{}]", acs);
        if (StringUtils.isBlank(acs.getBinding())) {
            throw new SamlException("AssertionConsumerService has no protocol binding defined");
        }
        if (StringUtils.isBlank(acs.getLocation()) && StringUtils.isBlank(acs.getResponseLocation())) {
            throw new SamlException("AssertionConsumerService has no location or response location defined");
        }
        return acs;
    } catch (final Exception e) {
        throw new IllegalArgumentException(new SamlException(e.getMessage(), e));
    }
}
Also used : AssertionConsumerServiceBuilder(org.opensaml.saml.saml2.metadata.impl.AssertionConsumerServiceBuilder) EntityIdCriterion(org.opensaml.core.criterion.EntityIdCriterion) BindingCriterion(org.opensaml.saml.criterion.BindingCriterion) SamlRegisteredServiceCachingMetadataResolver(org.apereo.cas.support.saml.services.idp.metadata.cache.SamlRegisteredServiceCachingMetadataResolver) MetadataResolver(org.opensaml.saml.metadata.resolver.MetadataResolver) ChainingMetadataResolver(org.opensaml.saml.metadata.resolver.ChainingMetadataResolver) Endpoint(org.opensaml.saml.saml2.metadata.Endpoint) EntityDescriptor(org.opensaml.saml.saml2.metadata.EntityDescriptor) SPSSODescriptor(org.opensaml.saml.saml2.metadata.SPSSODescriptor) CriteriaSet(net.shibboleth.utilities.java.support.resolver.CriteriaSet) EntityRoleCriterion(org.opensaml.saml.criterion.EntityRoleCriterion) AssertionConsumerService(org.opensaml.saml.saml2.metadata.AssertionConsumerService)

Example 22 with EntityIdCriterion

use of org.opensaml.core.criterion.EntityIdCriterion in project cas by apereo.

the class SamlIdPObjectSigner method getSignatureSigningConfiguration.

/**
 * Gets signature signing configuration.
 *
 * @param roleDescriptor the role descriptor
 * @param service        the service
 * @return the signature signing configuration
 * @throws Exception the exception
 */
protected SignatureSigningConfiguration getSignatureSigningConfiguration(final RoleDescriptor roleDescriptor, final SamlRegisteredService service) throws Exception {
    final BasicSignatureSigningConfiguration config = DefaultSecurityConfigurationBootstrap.buildDefaultSignatureSigningConfiguration();
    final SamlIdPProperties samlIdp = casProperties.getAuthn().getSamlIdp();
    if (this.overrideBlackListedSignatureAlgorithms != null && !samlIdp.getAlgs().getOverrideBlackListedSignatureSigningAlgorithms().isEmpty()) {
        config.setBlacklistedAlgorithms(this.overrideBlackListedSignatureAlgorithms);
    }
    if (this.overrideSignatureAlgorithms != null && !this.overrideSignatureAlgorithms.isEmpty()) {
        config.setSignatureAlgorithms(this.overrideSignatureAlgorithms);
    }
    if (this.overrideSignatureReferenceDigestMethods != null && !this.overrideSignatureReferenceDigestMethods.isEmpty()) {
        config.setSignatureReferenceDigestMethods(this.overrideSignatureReferenceDigestMethods);
    }
    if (this.overrideWhiteListedAlgorithms != null && !this.overrideWhiteListedAlgorithms.isEmpty()) {
        config.setWhitelistedAlgorithms(this.overrideWhiteListedAlgorithms);
    }
    if (StringUtils.isNotBlank(samlIdp.getAlgs().getOverrideSignatureCanonicalizationAlgorithm())) {
        config.setSignatureCanonicalizationAlgorithm(samlIdp.getAlgs().getOverrideSignatureCanonicalizationAlgorithm());
    }
    LOGGER.debug("Signature signing blacklisted algorithms: [{}]", config.getBlacklistedAlgorithms());
    LOGGER.debug("Signature signing signature algorithms: [{}]", config.getSignatureAlgorithms());
    LOGGER.debug("Signature signing signature canonicalization algorithm: [{}]", config.getSignatureCanonicalizationAlgorithm());
    LOGGER.debug("Signature signing whitelisted algorithms: [{}]", config.getWhitelistedAlgorithms());
    LOGGER.debug("Signature signing reference digest methods: [{}]", config.getSignatureReferenceDigestMethods());
    final PrivateKey privateKey = getSigningPrivateKey();
    final SamlIdPProperties idp = casProperties.getAuthn().getSamlIdp();
    final MetadataCredentialResolver kekCredentialResolver = new MetadataCredentialResolver();
    kekCredentialResolver.setRoleDescriptorResolver(SamlIdPUtils.getRoleDescriptorResolver(casSamlIdPMetadataResolver, idp.getMetadata().isRequireValidMetadata()));
    kekCredentialResolver.setKeyInfoCredentialResolver(DefaultSecurityConfigurationBootstrap.buildBasicInlineKeyInfoCredentialResolver());
    kekCredentialResolver.initialize();
    final CriteriaSet criteriaSet = new CriteriaSet();
    criteriaSet.add(new SignatureSigningConfigurationCriterion(config));
    criteriaSet.add(new UsageCriterion(UsageType.SIGNING));
    criteriaSet.add(new EntityIdCriterion(casProperties.getAuthn().getSamlIdp().getEntityId()));
    criteriaSet.add(new EntityRoleCriterion(IDPSSODescriptor.DEFAULT_ELEMENT_NAME));
    final Set<Credential> credentials = Sets.newLinkedHashSet(kekCredentialResolver.resolve(criteriaSet));
    final List<Credential> creds = new ArrayList<>();
    credentials.forEach(c -> {
        final AbstractCredential cred = getResolvedSigningCredential(c, privateKey, service);
        if (cred != null) {
            creds.add(cred);
        }
    });
    config.setSigningCredentials(creds);
    LOGGER.debug("Signature signing credentials configured with [{}] credentials", creds.size());
    return config;
}
Also used : UsageCriterion(org.opensaml.security.criteria.UsageCriterion) BasicCredential(org.opensaml.security.credential.BasicCredential) BasicX509Credential(org.opensaml.security.x509.BasicX509Credential) AbstractCredential(org.opensaml.security.credential.AbstractCredential) Credential(org.opensaml.security.credential.Credential) PrivateKey(java.security.PrivateKey) EntityIdCriterion(org.opensaml.core.criterion.EntityIdCriterion) ArrayList(java.util.ArrayList) MetadataCredentialResolver(org.opensaml.saml.security.impl.MetadataCredentialResolver) AbstractCredential(org.opensaml.security.credential.AbstractCredential) SamlIdPProperties(org.apereo.cas.configuration.model.support.saml.idp.SamlIdPProperties) CriteriaSet(net.shibboleth.utilities.java.support.resolver.CriteriaSet) EntityRoleCriterion(org.opensaml.saml.criterion.EntityRoleCriterion) SignatureSigningConfigurationCriterion(org.opensaml.xmlsec.criterion.SignatureSigningConfigurationCriterion) BasicSignatureSigningConfiguration(org.opensaml.xmlsec.impl.BasicSignatureSigningConfiguration)

Example 23 with EntityIdCriterion

use of org.opensaml.core.criterion.EntityIdCriterion in project cas by apereo.

the class SamlObjectSignatureValidator method buildEntityCriteriaForSigningCredential.

/**
 * Build entity criteria for signing credential.
 *
 * @param profileRequest the profile request
 * @param criteriaSet    the criteria set
 */
protected void buildEntityCriteriaForSigningCredential(final RequestAbstractType profileRequest, final CriteriaSet criteriaSet) {
    criteriaSet.add(new EntityIdCriterion(SamlIdPUtils.getIssuerFromSamlRequest(profileRequest)));
    criteriaSet.add(new EntityRoleCriterion(SPSSODescriptor.DEFAULT_ELEMENT_NAME));
}
Also used : EntityIdCriterion(org.opensaml.core.criterion.EntityIdCriterion) EntityRoleCriterion(org.opensaml.saml.criterion.EntityRoleCriterion)

Example 24 with EntityIdCriterion

use of org.opensaml.core.criterion.EntityIdCriterion in project cas by apereo.

the class SamlObjectSignatureValidator method validateSignatureOnAuthenticationRequest.

private void validateSignatureOnAuthenticationRequest(final RequestAbstractType profileRequest, final HttpServletRequest request, final MessageContext context, final RoleDescriptorResolver roleDescriptorResolver) throws Exception {
    final SAML2HTTPRedirectDeflateSignatureSecurityHandler handler = new SAML2HTTPRedirectDeflateSignatureSecurityHandler();
    final SAMLPeerEntityContext peer = context.getSubcontext(SAMLPeerEntityContext.class, true);
    peer.setEntityId(SamlIdPUtils.getIssuerFromSamlRequest(profileRequest));
    LOGGER.debug("Validating request signature for [{}] via [{}]...", peer.getEntityId(), handler.getClass().getSimpleName());
    LOGGER.debug("Resolving role descriptor for [{}]", peer.getEntityId());
    final RoleDescriptor roleDescriptor = roleDescriptorResolver.resolveSingle(new CriteriaSet(new EntityIdCriterion(peer.getEntityId()), new EntityRoleCriterion(SPSSODescriptor.DEFAULT_ELEMENT_NAME)));
    peer.setRole(roleDescriptor.getElementQName());
    final SAMLProtocolContext protocol = context.getSubcontext(SAMLProtocolContext.class, true);
    protocol.setProtocol(SAMLConstants.SAML20P_NS);
    LOGGER.debug("Building security parameters context for signature validation of [{}]", peer.getEntityId());
    final SecurityParametersContext secCtx = context.getSubcontext(SecurityParametersContext.class, true);
    final SignatureValidationParameters validationParams = new SignatureValidationParameters();
    if (overrideBlackListedSignatureAlgorithms != null && !overrideBlackListedSignatureAlgorithms.isEmpty()) {
        validationParams.setBlacklistedAlgorithms(this.overrideBlackListedSignatureAlgorithms);
        LOGGER.debug("Validation override blacklisted algorithms are [{}]", this.overrideWhiteListedAlgorithms);
    }
    if (overrideWhiteListedAlgorithms != null && !overrideWhiteListedAlgorithms.isEmpty()) {
        validationParams.setWhitelistedAlgorithms(this.overrideWhiteListedAlgorithms);
        LOGGER.debug("Validation override whitelisted algorithms are [{}]", this.overrideWhiteListedAlgorithms);
    }
    LOGGER.debug("Resolving signing credentials for [{}]", peer.getEntityId());
    final Set<Credential> credentials = getSigningCredential(roleDescriptorResolver, profileRequest);
    if (credentials == null || credentials.isEmpty()) {
        throw new SamlException("Signing credentials for validation could not be resolved");
    }
    boolean foundValidCredential = false;
    final Iterator<Credential> it = credentials.iterator();
    while (!foundValidCredential && it.hasNext()) {
        try {
            final Credential c = it.next();
            final CredentialResolver resolver = new StaticCredentialResolver(c);
            final KeyInfoCredentialResolver keyResolver = new StaticKeyInfoCredentialResolver(c);
            final SignatureTrustEngine trustEngine = new ExplicitKeySignatureTrustEngine(resolver, keyResolver);
            validationParams.setSignatureTrustEngine(trustEngine);
            secCtx.setSignatureValidationParameters(validationParams);
            handler.setHttpServletRequest(request);
            LOGGER.debug("Initializing [{}] to execute signature validation for [{}]", handler.getClass().getSimpleName(), peer.getEntityId());
            handler.initialize();
            LOGGER.debug("Invoking [{}] to handle signature validation for [{}]", handler.getClass().getSimpleName(), peer.getEntityId());
            handler.invoke(context);
            LOGGER.debug("Successfully validated request signature for [{}].", profileRequest.getIssuer());
            foundValidCredential = true;
        } catch (final Exception e) {
            LOGGER.debug(e.getMessage(), e);
        } finally {
            handler.destroy();
        }
    }
    if (!foundValidCredential) {
        LOGGER.error("No valid credentials could be found to verify the signature for [{}]", profileRequest.getIssuer());
        throw new SamlException("No valid signing credentials for validation could not be resolved");
    }
}
Also used : Credential(org.opensaml.security.credential.Credential) ExplicitKeySignatureTrustEngine(org.opensaml.xmlsec.signature.support.impl.ExplicitKeySignatureTrustEngine) SignatureTrustEngine(org.opensaml.xmlsec.signature.support.SignatureTrustEngine) SAMLPeerEntityContext(org.opensaml.saml.common.messaging.context.SAMLPeerEntityContext) EntityIdCriterion(org.opensaml.core.criterion.EntityIdCriterion) SAML2HTTPRedirectDeflateSignatureSecurityHandler(org.opensaml.saml.saml2.binding.security.impl.SAML2HTTPRedirectDeflateSignatureSecurityHandler) SamlException(org.apereo.cas.support.saml.SamlException) SamlException(org.apereo.cas.support.saml.SamlException) SignatureValidationParameters(org.opensaml.xmlsec.SignatureValidationParameters) StaticKeyInfoCredentialResolver(org.opensaml.xmlsec.keyinfo.impl.StaticKeyInfoCredentialResolver) SAMLProtocolContext(org.opensaml.saml.common.messaging.context.SAMLProtocolContext) StaticCredentialResolver(org.opensaml.security.credential.impl.StaticCredentialResolver) ExplicitKeySignatureTrustEngine(org.opensaml.xmlsec.signature.support.impl.ExplicitKeySignatureTrustEngine) RoleDescriptor(org.opensaml.saml.saml2.metadata.RoleDescriptor) CriteriaSet(net.shibboleth.utilities.java.support.resolver.CriteriaSet) EntityRoleCriterion(org.opensaml.saml.criterion.EntityRoleCriterion) SecurityParametersContext(org.opensaml.xmlsec.context.SecurityParametersContext) StaticKeyInfoCredentialResolver(org.opensaml.xmlsec.keyinfo.impl.StaticKeyInfoCredentialResolver) KeyInfoCredentialResolver(org.opensaml.xmlsec.keyinfo.KeyInfoCredentialResolver) MetadataCredentialResolver(org.opensaml.saml.security.impl.MetadataCredentialResolver) StaticCredentialResolver(org.opensaml.security.credential.impl.StaticCredentialResolver) StaticKeyInfoCredentialResolver(org.opensaml.xmlsec.keyinfo.impl.StaticKeyInfoCredentialResolver) CredentialResolver(org.opensaml.security.credential.CredentialResolver) KeyInfoCredentialResolver(org.opensaml.xmlsec.keyinfo.KeyInfoCredentialResolver)

Example 25 with EntityIdCriterion

use of org.opensaml.core.criterion.EntityIdCriterion in project verify-hub by alphagov.

the class CountrySingleSignOnServiceHelperTest method getSingleSignOn.

@Test
public void getSingleSignOn() throws Exception {
    // Given
    SingleSignOnServiceBuilder singleSignOnServiceBuilder = new SingleSignOnServiceBuilder();
    SingleSignOnService singleSignOnService = singleSignOnServiceBuilder.buildObject();
    singleSignOnService.setLocation("http://the-sso-location");
    IDPSSODescriptorBuilder idpssoDescriptorBuilder = new IDPSSODescriptorBuilder();
    IDPSSODescriptor idpssoDescriptor = idpssoDescriptorBuilder.buildObject();
    idpssoDescriptor.getSingleSignOnServices().add(singleSignOnService);
    idpssoDescriptor.addSupportedProtocol(SAMLConstants.SAML20P_NS);
    EntityDescriptorBuilder entityDescriptorBuilder = new EntityDescriptorBuilder();
    EntityDescriptor entityDescriptor = entityDescriptorBuilder.buildObject();
    entityDescriptor.setEntityID("the-entity-id");
    entityDescriptor.getRoleDescriptors().add(idpssoDescriptor);
    when(metadataResolver.resolveSingle(new CriteriaSet(new EntityIdCriterion(entityDescriptor.getEntityID())))).thenReturn(entityDescriptor);
    // When
    URI singleSignOnUri = service.getSingleSignOn(entityDescriptor.getEntityID());
    // Then
    assertThat(singleSignOnUri.toString(), equalTo(singleSignOnService.getLocation()));
    verify(metadataResolver).resolveSingle(any(CriteriaSet.class));
}
Also used : EntityDescriptor(org.opensaml.saml.saml2.metadata.EntityDescriptor) IDPSSODescriptor(org.opensaml.saml.saml2.metadata.IDPSSODescriptor) CriteriaSet(net.shibboleth.utilities.java.support.resolver.CriteriaSet) EntityIdCriterion(org.opensaml.core.criterion.EntityIdCriterion) SingleSignOnService(org.opensaml.saml.saml2.metadata.SingleSignOnService) SingleSignOnServiceBuilder(org.opensaml.saml.saml2.metadata.impl.SingleSignOnServiceBuilder) URI(java.net.URI) EntityDescriptorBuilder(org.opensaml.saml.saml2.metadata.impl.EntityDescriptorBuilder) IDPSSODescriptorBuilder(org.opensaml.saml.saml2.metadata.impl.IDPSSODescriptorBuilder) Test(org.junit.Test)

Aggregations

EntityIdCriterion (org.opensaml.core.criterion.EntityIdCriterion)44 CriteriaSet (net.shibboleth.utilities.java.support.resolver.CriteriaSet)39 EntityRoleCriterion (org.opensaml.saml.criterion.EntityRoleCriterion)30 lombok.val (lombok.val)25 Test (org.junit.jupiter.api.Test)9 UsageCriterion (org.opensaml.security.criteria.UsageCriterion)9 SamlRegisteredService (org.apereo.cas.support.saml.services.SamlRegisteredService)7 EntityDescriptor (org.opensaml.saml.saml2.metadata.EntityDescriptor)7 ArrayList (java.util.ArrayList)5 File (java.io.File)4 SamlException (org.apereo.cas.support.saml.SamlException)4 ProtocolCriterion (org.opensaml.saml.criterion.ProtocolCriterion)4 IDPSSODescriptor (org.opensaml.saml.saml2.metadata.IDPSSODescriptor)4 SAMLSignatureProfileValidator (org.opensaml.saml.security.impl.SAMLSignatureProfileValidator)4 ResolverException (net.shibboleth.utilities.java.support.resolver.ResolverException)3 SamlIdPMetadataCredentialResolver (org.apereo.cas.support.saml.idp.metadata.locator.SamlIdPMetadataCredentialResolver)3 SamlIdPSamlRegisteredServiceCriterion (org.apereo.cas.support.saml.idp.metadata.locator.SamlIdPSamlRegisteredServiceCriterion)3 BasicProviderKeyInfoCredentialResolver (org.opensaml.xmlsec.keyinfo.impl.BasicProviderKeyInfoCredentialResolver)3 DEREncodedKeyValueProvider (org.opensaml.xmlsec.keyinfo.impl.provider.DEREncodedKeyValueProvider)3 DSAKeyValueProvider (org.opensaml.xmlsec.keyinfo.impl.provider.DSAKeyValueProvider)3