Search in sources :

Example 16 with EntityRoleCriterion

use of org.opensaml.saml.criterion.EntityRoleCriterion 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 17 with EntityRoleCriterion

use of org.opensaml.saml.criterion.EntityRoleCriterion 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 18 with EntityRoleCriterion

use of org.opensaml.saml.criterion.EntityRoleCriterion 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 19 with EntityRoleCriterion

use of org.opensaml.saml.criterion.EntityRoleCriterion 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 20 with EntityRoleCriterion

use of org.opensaml.saml.criterion.EntityRoleCriterion in project pac4j by pac4j.

the class SAML2LogoutResponseValidator method validateSignature.

/**
 * Validate the given digital signature by checking its profile and value.
 *
 * @param signature the signature
 * @param idpEntityId the idp entity id
 * @param trustEngine the trust engine
 */
protected final void validateSignature(final Signature signature, final String idpEntityId, final SignatureTrustEngine trustEngine) {
    final SAMLSignatureProfileValidator validator = new SAMLSignatureProfileValidator();
    try {
        validator.validate(signature);
    } catch (final SignatureException e) {
        throw new SAMLSignatureValidationException("SAMLSignatureProfileValidator failed to validate signature", e);
    }
    final CriteriaSet criteriaSet = new CriteriaSet();
    criteriaSet.add(new UsageCriterion(UsageType.SIGNING));
    criteriaSet.add(new EntityRoleCriterion(IDPSSODescriptor.DEFAULT_ELEMENT_NAME));
    criteriaSet.add(new ProtocolCriterion(SAMLConstants.SAML20P_NS));
    criteriaSet.add(new EntityIdCriterion(idpEntityId));
    final boolean valid;
    try {
        valid = trustEngine.validate(signature, criteriaSet);
    } catch (final SecurityException e) {
        throw new SAMLSignatureValidationException("An error occurred during signature validation", e);
    }
    if (!valid) {
        throw new SAMLSignatureValidationException("Signature is not trusted");
    }
}
Also used : UsageCriterion(org.opensaml.security.criteria.UsageCriterion) ProtocolCriterion(org.opensaml.saml.criterion.ProtocolCriterion) SAMLSignatureValidationException(org.pac4j.saml.exceptions.SAMLSignatureValidationException) SAMLSignatureProfileValidator(org.opensaml.saml.security.impl.SAMLSignatureProfileValidator) CriteriaSet(net.shibboleth.utilities.java.support.resolver.CriteriaSet) EntityRoleCriterion(org.opensaml.saml.criterion.EntityRoleCriterion) EntityIdCriterion(org.opensaml.core.criterion.EntityIdCriterion) SecurityException(org.opensaml.security.SecurityException) SignatureException(org.opensaml.xmlsec.signature.support.SignatureException)

Aggregations

EntityRoleCriterion (org.opensaml.saml.criterion.EntityRoleCriterion)32 EntityIdCriterion (org.opensaml.core.criterion.EntityIdCriterion)30 CriteriaSet (net.shibboleth.utilities.java.support.resolver.CriteriaSet)28 lombok.val (lombok.val)21 UsageCriterion (org.opensaml.security.criteria.UsageCriterion)9 SamlRegisteredService (org.apereo.cas.support.saml.services.SamlRegisteredService)8 Test (org.junit.jupiter.api.Test)8 ArrayList (java.util.ArrayList)6 SamlException (org.apereo.cas.support.saml.SamlException)4 ProtocolCriterion (org.opensaml.saml.criterion.ProtocolCriterion)4 SAMLSignatureProfileValidator (org.opensaml.saml.security.impl.SAMLSignatureProfileValidator)4 File (java.io.File)3 Slf4j (lombok.extern.slf4j.Slf4j)3 StringUtils (org.apache.commons.lang3.StringUtils)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 InlineX509DataProvider (org.opensaml.xmlsec.keyinfo.impl.provider.InlineX509DataProvider)3