Search in sources :

Example 1 with CriteriaSet

use of net.shibboleth.utilities.java.support.resolver.CriteriaSet in project cas by apereo.

the class WsFederationHelper method validateSignature.

/**
     * validateSignature checks to see if the signature on an assertion is valid.
     *
     * @param assertion                 a provided assertion
     * @param wsFederationConfiguration WS-Fed configuration provided.
     * @return true if the assertion's signature is valid, otherwise false
     */
public boolean validateSignature(final Assertion assertion, final WsFederationConfiguration wsFederationConfiguration) {
    if (assertion == null) {
        LOGGER.warn("No assertion was provided to validate signatures");
        return false;
    }
    boolean valid = false;
    if (assertion.getSignature() != null) {
        final SignaturePrevalidator validator = new SAMLSignatureProfileValidator();
        try {
            validator.validate(assertion.getSignature());
            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(wsFederationConfiguration.getIdentityProviderIdentifier()));
            try {
                final SignatureTrustEngine engine = buildSignatureTrustEngine(wsFederationConfiguration);
                valid = engine.validate(assertion.getSignature(), criteriaSet);
            } catch (final SecurityException e) {
                LOGGER.warn(e.getMessage(), e);
            } finally {
                if (!valid) {
                    LOGGER.warn("Signature doesn't match any signing credential.");
                }
            }
        } catch (final SignatureException e) {
            LOGGER.warn("Failed to validate assertion signature", e);
        }
    }
    SamlUtils.logSamlObject(this.configBean, assertion);
    return valid;
}
Also used : SignaturePrevalidator(org.opensaml.xmlsec.signature.support.SignaturePrevalidator) UsageCriterion(org.opensaml.security.criteria.UsageCriterion) ProtocolCriterion(org.opensaml.saml.criterion.ProtocolCriterion) ExplicitKeySignatureTrustEngine(org.opensaml.xmlsec.signature.support.impl.ExplicitKeySignatureTrustEngine) SignatureTrustEngine(org.opensaml.xmlsec.signature.support.SignatureTrustEngine) 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)

Example 2 with CriteriaSet

use of net.shibboleth.utilities.java.support.resolver.CriteriaSet in project verify-hub by alphagov.

the class CountrySingleSignOnServiceHelper method getSingleSignOn.

public URI getSingleSignOn(String entityId) {
    EidasMetadataResolver metadataResolver = new EidasMetadataResolver(new Timer(), client, URI.create(entityId));
    try {
        EntityDescriptor idpEntityDescriptor;
        try {
            CriteriaSet criteria = new CriteriaSet(new EntityIdCriterion(entityId));
            idpEntityDescriptor = metadataResolver.resolveSingle(criteria);
        } catch (ResolverException e) {
            LOG.error(format("Exception when accessing metadata: {0}", e));
            throw propagate(e);
        }
        if (idpEntityDescriptor != null) {
            final IDPSSODescriptor idpssoDescriptor = idpEntityDescriptor.getIDPSSODescriptor(SAMLConstants.SAML20P_NS);
            final List<SingleSignOnService> singleSignOnServices = idpssoDescriptor.getSingleSignOnServices();
            if (singleSignOnServices.isEmpty()) {
                LOG.error(format("No singleSignOnServices present for IDP entityId: {0}", entityId));
            } else {
                if (singleSignOnServices.size() > 1) {
                    LOG.warn(format("More than one singleSignOnService present: {0} for {1}", singleSignOnServices.size(), entityId));
                }
                return URI.create(singleSignOnServices.get(0).getLocation());
            }
        }
        throw ApplicationException.createUnauditedException(ExceptionType.NOT_FOUND, UUID.randomUUID(), new RuntimeException(format("no entity descriptor for IDP: {0}", entityId)));
    } finally {
        if (metadataResolver != null) {
            metadataResolver.destroy();
        }
    }
}
Also used : EidasMetadataResolver(uk.gov.ida.hub.samlengine.EidasMetadataResolver) EntityDescriptor(org.opensaml.saml.saml2.metadata.EntityDescriptor) ResolverException(net.shibboleth.utilities.java.support.resolver.ResolverException) Timer(java.util.Timer) 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)

Example 3 with CriteriaSet

use of net.shibboleth.utilities.java.support.resolver.CriteriaSet in project cas by apereo.

the class SamlObjectEncrypter method getKeyEncryptionCredential.

/**
 * Gets key encryption credential.
 *
 * @param peerEntityId the peer entity id
 * @param adaptor      the adaptor
 * @param service      the service
 * @return the key encryption credential
 * @throws Exception the exception
 */
protected Credential getKeyEncryptionCredential(final String peerEntityId, final SamlRegisteredServiceServiceProviderMetadataFacade adaptor, final SamlRegisteredService service) throws Exception {
    final SamlIdPProperties idp = casProperties.getAuthn().getSamlIdp();
    final BasicEncryptionConfiguration config = DefaultSecurityConfigurationBootstrap.buildDefaultEncryptionConfiguration();
    if (this.overrideBlackListedEncryptionAlgorithms != null && !this.overrideBlackListedEncryptionAlgorithms.isEmpty()) {
        config.setBlacklistedAlgorithms(this.overrideBlackListedEncryptionAlgorithms);
    }
    if (this.overrideWhiteListedAlgorithms != null && !this.overrideWhiteListedAlgorithms.isEmpty()) {
        config.setWhitelistedAlgorithms(this.overrideWhiteListedAlgorithms);
    }
    if (this.overrideDataEncryptionAlgorithms != null && !this.overrideDataEncryptionAlgorithms.isEmpty()) {
        config.setDataEncryptionAlgorithms(this.overrideDataEncryptionAlgorithms);
    }
    if (this.overrideKeyEncryptionAlgorithms != null && !this.overrideKeyEncryptionAlgorithms.isEmpty()) {
        config.setKeyTransportEncryptionAlgorithms(this.overrideKeyEncryptionAlgorithms);
    }
    LOGGER.debug("Encryption blacklisted algorithms: [{}]", config.getBlacklistedAlgorithms());
    LOGGER.debug("Encryption key algorithms: [{}]", config.getKeyTransportEncryptionAlgorithms());
    LOGGER.debug("Signature data algorithms: [{}]", config.getDataEncryptionAlgorithms());
    LOGGER.debug("Encryption whitelisted algorithms: [{}]", config.getWhitelistedAlgorithms());
    final MetadataCredentialResolver kekCredentialResolver = new MetadataCredentialResolver();
    final List<KeyInfoProvider> providers = new ArrayList<>();
    providers.add(new RSAKeyValueProvider());
    providers.add(new DSAKeyValueProvider());
    providers.add(new InlineX509DataProvider());
    providers.add(new DEREncodedKeyValueProvider());
    providers.add(new KeyInfoReferenceProvider());
    final BasicProviderKeyInfoCredentialResolver keyInfoResolver = new BasicProviderKeyInfoCredentialResolver(providers);
    kekCredentialResolver.setKeyInfoCredentialResolver(keyInfoResolver);
    final RoleDescriptorResolver roleDescriptorResolver = SamlIdPUtils.getRoleDescriptorResolver(adaptor, idp.getMetadata().isRequireValidMetadata());
    kekCredentialResolver.setRoleDescriptorResolver(roleDescriptorResolver);
    kekCredentialResolver.initialize();
    final CriteriaSet criteriaSet = new CriteriaSet();
    criteriaSet.add(new EncryptionConfigurationCriterion(config));
    criteriaSet.add(new EntityIdCriterion(peerEntityId));
    criteriaSet.add(new EntityRoleCriterion(SPSSODescriptor.DEFAULT_ELEMENT_NAME));
    criteriaSet.add(new UsageCriterion(UsageType.ENCRYPTION));
    LOGGER.debug("Attempting to resolve the encryption key for entity id [{}]", peerEntityId);
    return kekCredentialResolver.resolveSingle(criteriaSet);
}
Also used : UsageCriterion(org.opensaml.security.criteria.UsageCriterion) RSAKeyValueProvider(org.opensaml.xmlsec.keyinfo.impl.provider.RSAKeyValueProvider) EncryptionConfigurationCriterion(org.opensaml.xmlsec.criterion.EncryptionConfigurationCriterion) ArrayList(java.util.ArrayList) EntityIdCriterion(org.opensaml.core.criterion.EntityIdCriterion) MetadataCredentialResolver(org.opensaml.saml.security.impl.MetadataCredentialResolver) InlineX509DataProvider(org.opensaml.xmlsec.keyinfo.impl.provider.InlineX509DataProvider) KeyInfoReferenceProvider(org.opensaml.xmlsec.keyinfo.impl.provider.KeyInfoReferenceProvider) BasicProviderKeyInfoCredentialResolver(org.opensaml.xmlsec.keyinfo.impl.BasicProviderKeyInfoCredentialResolver) KeyInfoProvider(org.opensaml.xmlsec.keyinfo.impl.KeyInfoProvider) RoleDescriptorResolver(org.opensaml.saml.metadata.resolver.RoleDescriptorResolver) SamlIdPProperties(org.apereo.cas.configuration.model.support.saml.idp.SamlIdPProperties) CriteriaSet(net.shibboleth.utilities.java.support.resolver.CriteriaSet) EntityRoleCriterion(org.opensaml.saml.criterion.EntityRoleCriterion) BasicEncryptionConfiguration(org.opensaml.xmlsec.impl.BasicEncryptionConfiguration) DSAKeyValueProvider(org.opensaml.xmlsec.keyinfo.impl.provider.DSAKeyValueProvider) DEREncodedKeyValueProvider(org.opensaml.xmlsec.keyinfo.impl.provider.DEREncodedKeyValueProvider)

Example 4 with CriteriaSet

use of net.shibboleth.utilities.java.support.resolver.CriteriaSet in project cas by apereo.

the class SamlObjectSignatureValidator method getSigningCredential.

@SneakyThrows
private Set<Credential> getSigningCredential(final RoleDescriptorResolver resolver, final RequestAbstractType profileRequest) {
    final MetadataCredentialResolver kekCredentialResolver = new MetadataCredentialResolver();
    final SignatureValidationConfiguration config = getSignatureValidationConfiguration();
    kekCredentialResolver.setRoleDescriptorResolver(resolver);
    kekCredentialResolver.setKeyInfoCredentialResolver(DefaultSecurityConfigurationBootstrap.buildBasicInlineKeyInfoCredentialResolver());
    kekCredentialResolver.initialize();
    final CriteriaSet criteriaSet = new CriteriaSet();
    criteriaSet.add(new SignatureValidationConfigurationCriterion(config));
    criteriaSet.add(new UsageCriterion(UsageType.SIGNING));
    buildEntityCriteriaForSigningCredential(profileRequest, criteriaSet);
    return Sets.newLinkedHashSet(kekCredentialResolver.resolve(criteriaSet));
}
Also used : UsageCriterion(org.opensaml.security.criteria.UsageCriterion) CriteriaSet(net.shibboleth.utilities.java.support.resolver.CriteriaSet) MetadataCredentialResolver(org.opensaml.saml.security.impl.MetadataCredentialResolver) BasicSignatureValidationConfiguration(org.opensaml.xmlsec.impl.BasicSignatureValidationConfiguration) SignatureValidationConfiguration(org.opensaml.xmlsec.SignatureValidationConfiguration) SignatureValidationConfigurationCriterion(org.opensaml.xmlsec.criterion.SignatureValidationConfigurationCriterion) SneakyThrows(lombok.SneakyThrows)

Example 5 with CriteriaSet

use of net.shibboleth.utilities.java.support.resolver.CriteriaSet in project syncope by apache.

the class SAML2SPLoader method load.

@Override
public void load() {
    EntitlementsHolder.getInstance().init(SAML2SPEntitlement.values());
    Pair<Properties, String> init = PropertyUtils.read(getClass(), SAML2SP_LOGIC_PROPERTIES, "conf.directory");
    Properties props = init.getLeft();
    String confDirectory = init.getRight();
    assertNotNull(confDirectory, "<conf.directory>");
    String name = props.getProperty("keystore.name");
    assertNotNull(name, "<keystore.name>");
    String type = props.getProperty("keystore.type");
    assertNotNull(type, "<keystore.type>");
    String storePass = props.getProperty("keystore.storepass");
    assertNotNull(storePass, "<keystore.storepass>");
    keyPass = props.getProperty("keystore.keypass");
    assertNotNull(keyPass, "<keystore.keypass>");
    String certAlias = props.getProperty("sp.cert.alias");
    assertNotNull(certAlias, "<sp.cert.alias>");
    signatureAlgorithm = props.getProperty("signature.algorithm");
    LOG.debug("Attempting to load the provided keystore...");
    try {
        ResourceWithFallbackLoader loader = new ResourceWithFallbackLoader();
        loader.setResourceLoader(ApplicationContextProvider.getApplicationContext());
        loader.setPrimary(StringUtils.appendIfMissing("file:" + confDirectory, "/") + name);
        loader.setFallback("classpath:" + name);
        keystore = KeyStore.getInstance(type);
        try (InputStream inputStream = loader.getResource().getInputStream()) {
            keystore.load(inputStream, storePass.toCharArray());
            LOG.debug("Keystore loaded");
        }
        Map<String, String> passwordMap = new HashMap<>();
        passwordMap.put(certAlias, keyPass);
        KeyStoreCredentialResolver resolver = new KeyStoreCredentialResolver(keystore, passwordMap);
        this.credential = resolver.resolveSingle(new CriteriaSet(new EntityIdCriterion(certAlias)));
        LOG.debug("SAML 2.0 Service Provider certificate loaded");
        saml2rw.init();
        inited = true;
    } catch (Exception e) {
        LOG.error("Could not initialize the SAML 2.0 Service Provider certificate", e);
        inited = false;
    }
    domainsHolder.getDomains().keySet().forEach(domain -> {
        AuthContextUtils.execWithAuthContext(domain, () -> {
            idpDAO.findAll().forEach(idp -> {
                try {
                    cache.put(idp);
                } catch (Exception e) {
                    LOG.error("Could not cache the SAML 2.0 IdP with key ", idp.getEntityID(), e);
                }
            });
            return null;
        });
    });
}
Also used : HashMap(java.util.HashMap) InputStream(java.io.InputStream) ResourceWithFallbackLoader(org.apache.syncope.core.spring.ResourceWithFallbackLoader) CriteriaSet(net.shibboleth.utilities.java.support.resolver.CriteriaSet) EntityIdCriterion(org.opensaml.core.criterion.EntityIdCriterion) Properties(java.util.Properties) KeyStoreCredentialResolver(org.opensaml.security.credential.impl.KeyStoreCredentialResolver)

Aggregations

CriteriaSet (net.shibboleth.utilities.java.support.resolver.CriteriaSet)68 lombok.val (lombok.val)44 EntityIdCriterion (org.opensaml.core.criterion.EntityIdCriterion)40 EntityRoleCriterion (org.opensaml.saml.criterion.EntityRoleCriterion)28 SamlRegisteredService (org.apereo.cas.support.saml.services.SamlRegisteredService)18 Test (org.junit.jupiter.api.Test)16 UsageCriterion (org.opensaml.security.criteria.UsageCriterion)11 SamlIdPProperties (org.apereo.cas.configuration.model.support.saml.idp.SamlIdPProperties)10 EntityDescriptor (org.opensaml.saml.saml2.metadata.EntityDescriptor)10 ArrayList (java.util.ArrayList)9 SignatureSigningConfigurationCriterion (org.opensaml.xmlsec.criterion.SignatureSigningConfigurationCriterion)9 MetadataResolver (org.opensaml.saml.metadata.resolver.MetadataResolver)8 SAMLMetadataSignatureSigningParametersResolver (org.opensaml.saml.security.impl.SAMLMetadataSignatureSigningParametersResolver)8 SneakyThrows (lombok.SneakyThrows)7 StringUtils (org.apache.commons.lang3.StringUtils)7 SignatureSigningParameters (org.opensaml.xmlsec.SignatureSigningParameters)7 FileSystemResource (org.springframework.core.io.FileSystemResource)7 SamlException (org.apereo.cas.support.saml.SamlException)6 EvaluableEntityRoleEntityDescriptorCriterion (org.opensaml.saml.metadata.criteria.entity.impl.EvaluableEntityRoleEntityDescriptorCriterion)6 Credential (org.opensaml.security.credential.Credential)6