Search in sources :

Example 16 with Credential

use of org.opensaml.security.credential.Credential 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 17 with Credential

use of org.opensaml.security.credential.Credential 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 18 with Credential

use of org.opensaml.security.credential.Credential in project cas by apereo.

the class SamlObjectSignatureValidator method validateSignatureOnProfileRequest.

private void validateSignatureOnProfileRequest(final RequestAbstractType profileRequest, final Signature signature, final RoleDescriptorResolver roleDescriptorResolver) throws Exception {
    final SAMLSignatureProfileValidator validator = new SAMLSignatureProfileValidator();
    LOGGER.debug("Validating profile signature for [{}] via [{}]...", profileRequest.getIssuer(), validator.getClass().getSimpleName());
    validator.validate(signature);
    LOGGER.debug("Successfully validated profile signature for [{}].", profileRequest.getIssuer());
    @NonNull final Set<Credential> credentials = getSigningCredential(roleDescriptorResolver, profileRequest);
    if (credentials.isEmpty()) {
        throw new SamlException("Signing credentials for validation could not be resolved based on the provided signature");
    }
    boolean foundValidCredential = false;
    final Iterator<Credential> it = credentials.iterator();
    while (!foundValidCredential && it.hasNext()) {
        try {
            final Credential c = it.next();
            LOGGER.debug("Validating signature using credentials for [{}]", c.getEntityId());
            SignatureValidator.validate(signature, c);
            LOGGER.info("Successfully validated the request signature.");
            foundValidCredential = true;
        } catch (final Exception e) {
            LOGGER.debug(e.getMessage(), e);
        }
    }
    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) SAMLSignatureProfileValidator(org.opensaml.saml.security.impl.SAMLSignatureProfileValidator) NonNull(lombok.NonNull) SamlException(org.apereo.cas.support.saml.SamlException) SamlException(org.apereo.cas.support.saml.SamlException)

Example 19 with Credential

use of org.opensaml.security.credential.Credential in project cas by apereo.

the class WsFederationConfiguration method getSigningCredential.

/**
 * getSigningCredential loads up an X509Credential from a file.
 *
 * @param resource the signing certificate file
 * @return an X509 credential
 */
private static Credential getSigningCredential(final Resource resource) {
    try (InputStream inputStream = resource.getInputStream()) {
        final CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        final X509Certificate certificate = (X509Certificate) certificateFactory.generateCertificate(inputStream);
        final Credential publicCredential = new BasicX509Credential(certificate);
        LOGGER.debug("Signing credential key retrieved from [{}].", resource);
        return publicCredential;
    } catch (final Exception ex) {
        LOGGER.error(ex.getMessage(), ex);
    }
    return null;
}
Also used : Credential(org.opensaml.security.credential.Credential) BasicX509Credential(org.opensaml.security.x509.BasicX509Credential) BasicX509Credential(org.opensaml.security.x509.BasicX509Credential) InputStream(java.io.InputStream) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate)

Example 20 with Credential

use of org.opensaml.security.credential.Credential in project pac4j by pac4j.

the class DefaultSignatureSigningParametersProvider method getSignatureSigningConfiguration.

protected SignatureSigningConfiguration getSignatureSigningConfiguration() {
    final BasicSignatureSigningConfiguration config = DefaultSecurityConfigurationBootstrap.buildDefaultSignatureSigningConfiguration();
    if (this.configuration.getBlackListedSignatureSigningAlgorithms() != null) {
        config.setBlacklistedAlgorithms(this.configuration.getBlackListedSignatureSigningAlgorithms());
    }
    if (this.configuration.getSignatureAlgorithms() != null) {
        config.setSignatureAlgorithms(this.configuration.getSignatureAlgorithms());
    }
    if (this.configuration.getSignatureCanonicalizationAlgorithm() != null) {
        config.setSignatureCanonicalizationAlgorithm(this.configuration.getSignatureCanonicalizationAlgorithm());
    }
    if (this.configuration.getSignatureReferenceDigestMethods() != null) {
        config.setSignatureReferenceDigestMethods(this.configuration.getSignatureReferenceDigestMethods());
    }
    final List<Credential> creds = new ArrayList<>();
    creds.add(this.credentialProvider.getCredential());
    config.setSigningCredentials(creds);
    return config;
}
Also used : Credential(org.opensaml.security.credential.Credential) ArrayList(java.util.ArrayList) BasicSignatureSigningConfiguration(org.opensaml.xmlsec.impl.BasicSignatureSigningConfiguration)

Aggregations

Credential (org.opensaml.security.credential.Credential)35 BasicCredential (org.opensaml.security.credential.BasicCredential)14 Saml2X509Credential (org.springframework.security.saml2.core.Saml2X509Credential)13 ArrayList (java.util.ArrayList)12 CriteriaSet (net.shibboleth.utilities.java.support.resolver.CriteriaSet)8 BasicSignatureSigningConfiguration (org.opensaml.xmlsec.impl.BasicSignatureSigningConfiguration)8 PrivateKey (java.security.PrivateKey)7 X509Certificate (java.security.cert.X509Certificate)6 BasicX509Credential (org.opensaml.security.x509.BasicX509Credential)6 SignatureSigningParameters (org.opensaml.xmlsec.SignatureSigningParameters)6 MarshallingException (org.opensaml.core.xml.io.MarshallingException)5 SignatureSigningConfigurationCriterion (org.opensaml.xmlsec.criterion.SignatureSigningConfigurationCriterion)5 Decrypter (org.opensaml.saml.saml2.encryption.Decrypter)4 SAMLMetadataSignatureSigningParametersResolver (org.opensaml.saml.security.impl.SAMLMetadataSignatureSigningParametersResolver)4 SecurityException (org.opensaml.security.SecurityException)4 SignatureSigningParametersResolver (org.opensaml.xmlsec.SignatureSigningParametersResolver)4 Saml2Exception (org.springframework.security.saml2.Saml2Exception)4 SneakyThrows (lombok.SneakyThrows)3 SamlException (org.apereo.cas.support.saml.SamlException)3 Test (org.junit.jupiter.api.Test)3