Search in sources :

Example 11 with RequestAbstractType

use of org.opensaml.saml.saml2.core.RequestAbstractType in project cas by apereo.

the class AbstractSamlIdPProfileHandlerController method verifySamlAuthenticationRequest.

/**
 * Verify saml authentication request.
 *
 * @param authenticationContext the pair
 * @param request               the request
 * @return the pair
 * @throws Exception the exception
 */
protected Pair<SamlRegisteredService, SamlRegisteredServiceServiceProviderMetadataFacade> verifySamlAuthenticationRequest(final Pair<? extends RequestAbstractType, MessageContext> authenticationContext, final HttpServletRequest request) throws Exception {
    val authnRequest = (AuthnRequest) authenticationContext.getKey();
    val issuer = SamlIdPUtils.getIssuerFromSamlObject(authnRequest);
    LOGGER.debug("Located issuer [{}] from authentication request", issuer);
    val registeredService = verifySamlRegisteredService(issuer);
    LOGGER.debug("Fetching SAML2 metadata adaptor for [{}]", issuer);
    val adaptor = SamlRegisteredServiceServiceProviderMetadataFacade.get(configurationContext.getSamlRegisteredServiceCachingMetadataResolver(), registeredService, authnRequest);
    if (adaptor.isEmpty()) {
        LOGGER.warn("No metadata could be found for [{}]", issuer);
        throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE, "Cannot find metadata linked to " + issuer);
    }
    val facade = adaptor.get();
    verifyAuthenticationContextSignature(authenticationContext, request, authnRequest, facade, registeredService);
    val binding = determineProfileBinding(authenticationContext);
    val acs = SamlIdPUtils.determineEndpointForRequest(Pair.of(authnRequest, authenticationContext.getRight()), facade, binding);
    LOGGER.debug("Determined SAML2 endpoint for authentication request as [{}]", StringUtils.defaultIfBlank(acs.getResponseLocation(), acs.getLocation()));
    SamlUtils.logSamlObject(configurationContext.getOpenSamlConfigBean(), authnRequest);
    return Pair.of(registeredService, facade);
}
Also used : lombok.val(lombok.val) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) UnauthorizedServiceException(org.apereo.cas.services.UnauthorizedServiceException)

Example 12 with RequestAbstractType

use of org.opensaml.saml.saml2.core.RequestAbstractType in project cas by apereo.

the class SamlProfileSamlAssertionBuilder method build.

@Override
public Assertion build(final RequestAbstractType authnRequest, final HttpServletRequest request, final HttpServletResponse response, final Object casAssertion, final SamlRegisteredService service, final SamlRegisteredServiceServiceProviderMetadataFacade adaptor, final String binding) throws SamlException {
    final List<Statement> statements = new ArrayList<>();
    final AuthnStatement authnStatement = this.samlProfileSamlAuthNStatementBuilder.build(authnRequest, request, response, casAssertion, service, adaptor, binding);
    statements.add(authnStatement);
    final AttributeStatement attrStatement = this.samlProfileSamlAttributeStatementBuilder.build(authnRequest, request, response, casAssertion, service, adaptor, binding);
    if (!attrStatement.getAttributes().isEmpty() || !attrStatement.getEncryptedAttributes().isEmpty()) {
        statements.add(attrStatement);
    }
    final String id = '_' + String.valueOf(Math.abs(RandomUtils.getNativeInstance().nextLong()));
    final Assertion assertion = newAssertion(statements, casProperties.getAuthn().getSamlIdp().getEntityId(), ZonedDateTime.now(ZoneOffset.UTC), id);
    assertion.setSubject(this.samlProfileSamlSubjectBuilder.build(authnRequest, request, response, casAssertion, service, adaptor, binding));
    assertion.setConditions(this.samlProfileSamlConditionsBuilder.build(authnRequest, request, response, casAssertion, service, adaptor, binding));
    signAssertion(assertion, request, response, service, adaptor, binding);
    return assertion;
}
Also used : AuthnStatement(org.opensaml.saml.saml2.core.AuthnStatement) AttributeStatement(org.opensaml.saml.saml2.core.AttributeStatement) Statement(org.opensaml.saml.saml2.core.Statement) AttributeStatement(org.opensaml.saml.saml2.core.AttributeStatement) ArrayList(java.util.ArrayList) AuthnStatement(org.opensaml.saml.saml2.core.AuthnStatement) Assertion(org.opensaml.saml.saml2.core.Assertion)

Example 13 with RequestAbstractType

use of org.opensaml.saml.saml2.core.RequestAbstractType in project cas by apereo.

the class DefaultAuthnContextClassRefBuilder method build.

@Override
public String build(final Object assertion, final RequestAbstractType authnRequest, final SamlRegisteredServiceServiceProviderMetadataFacade adaptor, final SamlRegisteredService service) {
    if (StringUtils.isNotBlank(service.getRequiredAuthenticationContextClass())) {
        LOGGER.debug("Using [{}] as indicated by SAML registered service [{}]", service.getRequiredAuthenticationContextClass(), service.getName());
        return service.getRequiredAuthenticationContextClass();
    }
    final String defClass = StringUtils.defaultIfBlank(casProperties.getAuthn().getSamlIdp().getResponse().getDefaultAuthenticationContextClass(), AuthnContext.PPT_AUTHN_CTX);
    final RequestedAuthnContext requestedAuthnContext = (authnRequest instanceof AuthnRequest) ? AuthnRequest.class.cast(authnRequest).getRequestedAuthnContext() : null;
    if (requestedAuthnContext == null) {
        LOGGER.debug("No specific authN context is requested. Returning [{}]", defClass);
        return defClass;
    }
    final List<AuthnContextClassRef> authnContextClassRefs = requestedAuthnContext.getAuthnContextClassRefs();
    if (authnContextClassRefs == null || authnContextClassRefs.isEmpty()) {
        LOGGER.debug("Requested authN context class ref is unspecified. Returning [{}]", defClass);
        return defClass;
    }
    final String finalCtx = StringUtils.defaultIfBlank(getAuthenticationContextByAssertion(assertion, requestedAuthnContext, authnContextClassRefs), defClass);
    LOGGER.debug("Returning authN context [{}]", finalCtx);
    return finalCtx;
}
Also used : RequestedAuthnContext(org.opensaml.saml.saml2.core.RequestedAuthnContext) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) AuthnContextClassRef(org.opensaml.saml.saml2.core.AuthnContextClassRef)

Example 14 with RequestAbstractType

use of org.opensaml.saml.saml2.core.RequestAbstractType in project cas by apereo.

the class SamlProfileSamlAuthNStatementBuilder method buildSubjectLocality.

/**
 * Build subject locality subject locality.
 *
 * @param assertion    the assertion
 * @param authnRequest the authn request
 * @param adaptor      the adaptor
 * @param binding      the binding
 * @return the subject locality
 * @throws SamlException the saml exception
 */
protected SubjectLocality buildSubjectLocality(final Object assertion, final RequestAbstractType authnRequest, final SamlRegisteredServiceServiceProviderMetadataFacade adaptor, final String binding) throws SamlException {
    final SubjectLocality subjectLocality = newSamlObject(SubjectLocality.class);
    final AssertionConsumerService acs = adaptor.getAssertionConsumerService(binding);
    if (acs != null && StringUtils.isNotBlank(acs.getLocation())) {
        final InetAddress ip = InetAddressUtils.getByName(acs.getLocation());
        if (ip != null) {
            subjectLocality.setAddress(ip.getHostName());
        }
    }
    return subjectLocality;
}
Also used : AssertionConsumerService(org.opensaml.saml.saml2.metadata.AssertionConsumerService) InetAddress(java.net.InetAddress) SubjectLocality(org.opensaml.saml.saml2.core.SubjectLocality)

Example 15 with RequestAbstractType

use of org.opensaml.saml.saml2.core.RequestAbstractType 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)

Aggregations

lombok.val (lombok.val)11 AuthnRequest (org.opensaml.saml.saml2.core.AuthnRequest)8 SAMLObject (org.opensaml.saml.common.SAMLObject)5 RequestAbstractType (org.opensaml.saml.saml2.core.RequestAbstractType)5 MessageContext (org.opensaml.messaging.context.MessageContext)4 Assertion (org.opensaml.saml.saml2.core.Assertion)4 NameID (org.opensaml.saml.saml2.core.NameID)4 ZonedDateTime (java.time.ZonedDateTime)3 HttpServletResponse (javax.servlet.http.HttpServletResponse)3 SneakyThrows (lombok.SneakyThrows)3 CriteriaSet (net.shibboleth.utilities.java.support.resolver.CriteriaSet)3 SamlException (org.apereo.cas.support.saml.SamlException)3 LogoutRequest (org.opensaml.saml.saml2.core.LogoutRequest)3 AssertionConsumerService (org.opensaml.saml.saml2.metadata.AssertionConsumerService)3 Body (org.opensaml.soap.soap11.Body)3 Envelope (org.opensaml.soap.soap11.Envelope)3 Header (org.opensaml.soap.soap11.Header)3 ArrayList (java.util.ArrayList)2 Objects (java.util.Objects)2 Optional (java.util.Optional)2