Search in sources :

Example 71 with Request

use of org.opensaml.saml.saml2.ecp.Request in project cas by apereo.

the class SamlObjectEncrypter method encode.

/**
 * Encode a given saml object by invoking a number of outbound security handlers on the context.
 *
 * @param samlObject the saml object
 * @param service    the service
 * @param adaptor    the adaptor
 * @param response   the response
 * @param request    the request
 * @return the t
 * @throws SamlException the saml exception
 */
@SneakyThrows
public EncryptedAssertion encode(final Assertion samlObject, final SamlRegisteredService service, final SamlRegisteredServiceServiceProviderMetadataFacade adaptor, final HttpServletResponse response, final HttpServletRequest request) throws SamlException {
    final String className = samlObject.getClass().getName();
    final String entityId = adaptor.getEntityId();
    LOGGER.debug("Attempting to encrypt [{}] for [{}]", className, entityId);
    final Credential credential = getKeyEncryptionCredential(entityId, adaptor, service);
    LOGGER.info("Found encryption public key: [{}]", EncodingUtils.encodeBase64(credential.getPublicKey().getEncoded()));
    final KeyEncryptionParameters keyEncParams = getKeyEncryptionParameters(samlObject, service, adaptor, credential);
    LOGGER.debug("Key encryption algorithm for [{}] is [{}]", keyEncParams.getRecipient(), keyEncParams.getAlgorithm());
    final DataEncryptionParameters dataEncParams = getDataEncryptionParameters(samlObject, service, adaptor);
    LOGGER.debug("Data encryption algorithm for [{}] is [{}]", entityId, dataEncParams.getAlgorithm());
    final Encrypter encrypter = getEncrypter(samlObject, service, adaptor, keyEncParams, dataEncParams);
    LOGGER.debug("Attempting to encrypt [{}] for [{}] with key placement of [{}]", className, entityId, encrypter.getKeyPlacement());
    return encrypter.encrypt(samlObject);
}
Also used : Encrypter(org.opensaml.saml.saml2.encryption.Encrypter) KeyEncryptionParameters(org.opensaml.xmlsec.encryption.support.KeyEncryptionParameters) Credential(org.opensaml.security.credential.Credential) DataEncryptionParameters(org.opensaml.xmlsec.encryption.support.DataEncryptionParameters) SneakyThrows(lombok.SneakyThrows)

Example 72 with Request

use of org.opensaml.saml.saml2.ecp.Request 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 73 with Request

use of org.opensaml.saml.saml2.ecp.Request in project cas by apereo.

the class SamlProfileSamlNameIdBuilder method encodeNameIdBasedOnNameFormat.

/**
 * Encode name id based on name format name id.
 *
 * @param authnRequest the authn request
 * @param assertion    the assertion
 * @param nameFormat   the name format
 * @param service      the service
 * @param adaptor      the adaptor
 * @return the name id
 */
protected NameID encodeNameIdBasedOnNameFormat(final RequestAbstractType authnRequest, final Object assertion, final String nameFormat, final SamlRegisteredService service, final SamlRegisteredServiceServiceProviderMetadataFacade adaptor) {
    try {
        if (authnRequest instanceof AttributeQuery) {
            final AttributeQuery query = AttributeQuery.class.cast(authnRequest);
            final NameID nameID = query.getSubject().getNameID();
            nameID.detach();
            return nameID;
        }
        final IdPAttribute attribute = prepareNameIdAttribute(assertion, nameFormat, adaptor);
        final SAML2StringNameIDEncoder encoder = prepareNameIdEncoder(authnRequest, nameFormat, attribute, service, adaptor);
        LOGGER.debug("Encoding NameID based on [{}]", nameFormat);
        final NameID nameid = encoder.encode(attribute);
        LOGGER.debug("Final NameID encoded with format [{}] has value [{}]", nameid.getFormat(), nameid.getValue());
        return nameid;
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
    return null;
}
Also used : AttributeQuery(org.opensaml.saml.saml2.core.AttributeQuery) NameID(org.opensaml.saml.saml2.core.NameID) IdPAttribute(net.shibboleth.idp.attribute.IdPAttribute) SAML2StringNameIDEncoder(net.shibboleth.idp.saml.attribute.encoding.impl.SAML2StringNameIDEncoder) SamlException(org.apereo.cas.support.saml.SamlException)

Example 74 with Request

use of org.opensaml.saml.saml2.ecp.Request in project cas by apereo.

the class SamlProfileSamlNameIdBuilder method buildNameId.

/**
 * Build name id.
 * If there are no explicitly defined NameIDFormats, include the default format.
 * see: http://saml2int.org/profile/current/#section92
 *
 * @param authnRequest the authn request
 * @param assertion    the assertion
 * @param service      the service
 * @param adaptor      the adaptor
 * @return the name id
 * @throws SamlException the saml exception
 */
private NameID buildNameId(final RequestAbstractType authnRequest, final Object assertion, final SamlRegisteredService service, final SamlRegisteredServiceServiceProviderMetadataFacade adaptor) throws SamlException {
    final List<String> supportedNameFormats = getSupportedNameIdFormats(service, adaptor);
    final String requiredNameFormat = getRequiredNameIdFormatIfAny(authnRequest);
    validateRequiredNameIdFormatIfAny(authnRequest, adaptor, supportedNameFormats, requiredNameFormat);
    final NameID nameid = determineNameId(authnRequest, assertion, supportedNameFormats, service, adaptor);
    return finalizeNameId(nameid, authnRequest, assertion, supportedNameFormats, service, adaptor);
}
Also used : NameID(org.opensaml.saml.saml2.core.NameID)

Example 75 with Request

use of org.opensaml.saml.saml2.ecp.Request in project cas by apereo.

the class SamlProfileSamlNameIdBuilder method determineNameId.

/**
 * Determine name id name id.
 *
 * @param authnRequest         the authn request
 * @param assertion            the assertion
 * @param supportedNameFormats the supported name formats
 * @param service              the service
 * @param adaptor              the adaptor
 * @return the name id
 */
protected NameID determineNameId(final RequestAbstractType authnRequest, final Object assertion, final List<String> supportedNameFormats, final SamlRegisteredService service, final SamlRegisteredServiceServiceProviderMetadataFacade adaptor) {
    for (final String nameFormat : supportedNameFormats) {
        LOGGER.debug("Evaluating NameID format [{}]", nameFormat);
        final NameID nameid = encodeNameIdBasedOnNameFormat(authnRequest, assertion, nameFormat, service, adaptor);
        if (nameid != null) {
            return nameid;
        }
    }
    return null;
}
Also used : NameID(org.opensaml.saml.saml2.core.NameID)

Aggregations

AuthnRequest (org.opensaml.saml.saml2.core.AuthnRequest)24 IOException (java.io.IOException)13 LogoutResponse (org.opensaml.saml.saml2.core.LogoutResponse)13 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)12 SamlRegisteredServiceServiceProviderMetadataFacade (org.apereo.cas.support.saml.services.idp.metadata.SamlRegisteredServiceServiceProviderMetadataFacade)11 Test (org.junit.Test)10 ValidationException (ddf.security.samlp.ValidationException)9 Response (javax.ws.rs.core.Response)9 SamlRegisteredService (org.apereo.cas.support.saml.services.SamlRegisteredService)9 Assertion (org.jasig.cas.client.validation.Assertion)9 MessageContext (org.opensaml.messaging.context.MessageContext)9 Assertion (org.opensaml.saml.saml2.core.Assertion)9 Document (org.w3c.dom.Document)9 XMLStreamException (javax.xml.stream.XMLStreamException)8 LogoutRequest (org.opensaml.saml.saml2.core.LogoutRequest)8 NameID (org.opensaml.saml.saml2.core.NameID)7 ByteArrayInputStream (java.io.ByteArrayInputStream)6 SimpleSign (ddf.security.samlp.SimpleSign)5 ZonedDateTime (java.time.ZonedDateTime)5 Path (javax.ws.rs.Path)5