Search in sources :

Example 31 with EntityIdCriterion

use of org.opensaml.core.criterion.EntityIdCriterion in project cas by apereo.

the class SamlRegisteredServiceCachedMetadataEndpoint method getCachedMetadataObject.

/**
 * Gets cached metadata object.
 *
 * @param serviceId the service id
 * @param entityId  the entity id
 * @return the cached metadata object
 */
@ReadOperation
@Operation(summary = "Get SAML2 cached metadata", parameters = { @Parameter(name = "serviceId", required = true), @Parameter(name = "entityId") })
public Map<String, Object> getCachedMetadataObject(final String serviceId, @Nullable final String entityId) {
    try {
        val registeredService = findRegisteredService(serviceId);
        val issuer = StringUtils.defaultIfBlank(entityId, registeredService.getServiceId());
        val criteriaSet = new CriteriaSet();
        criteriaSet.add(new EntityIdCriterion(issuer));
        criteriaSet.add(new EntityRoleCriterion(SPSSODescriptor.DEFAULT_ELEMENT_NAME));
        val metadataResolver = cachingMetadataResolver.resolve(registeredService, criteriaSet);
        val iteration = metadataResolver.resolve(criteriaSet).spliterator();
        return StreamSupport.stream(iteration, false).map(entity -> Pair.of(entity.getEntityID(), SamlUtils.transformSamlObject(openSamlConfigBean, entity).toString())).collect(Collectors.toMap(Pair::getLeft, Pair::getRight));
    } catch (final Exception e) {
        LoggingUtils.error(LOGGER, e);
        return CollectionUtils.wrap("error", e.getMessage());
    }
}
Also used : lombok.val(lombok.val) CasConfigurationProperties(org.apereo.cas.configuration.CasConfigurationProperties) ReadOperation(org.springframework.boot.actuate.endpoint.annotation.ReadOperation) SamlRegisteredServiceCachingMetadataResolver(org.apereo.cas.support.saml.services.idp.metadata.cache.SamlRegisteredServiceCachingMetadataResolver) StringUtils(org.apache.commons.lang3.StringUtils) DeleteOperation(org.springframework.boot.actuate.endpoint.annotation.DeleteOperation) SamlUtils(org.apereo.cas.support.saml.SamlUtils) LoggingUtils(org.apereo.cas.util.LoggingUtils) Operation(io.swagger.v3.oas.annotations.Operation) SamlRegisteredService(org.apereo.cas.support.saml.services.SamlRegisteredService) Pair(org.apache.commons.lang3.tuple.Pair) Map(java.util.Map) CollectionUtils(org.apereo.cas.util.CollectionUtils) Nullable(org.springframework.lang.Nullable) StreamSupport(java.util.stream.StreamSupport) ServicesManager(org.apereo.cas.services.ServicesManager) AuditableContext(org.apereo.cas.audit.AuditableContext) Endpoint(org.springframework.boot.actuate.endpoint.annotation.Endpoint) Collection(java.util.Collection) lombok.val(lombok.val) Collectors(java.util.stream.Collectors) RegisteredService(org.apereo.cas.services.RegisteredService) BaseCasActuatorEndpoint(org.apereo.cas.web.BaseCasActuatorEndpoint) SPSSODescriptor(org.opensaml.saml.saml2.metadata.SPSSODescriptor) OpenSamlConfigBean(org.apereo.cas.support.saml.OpenSamlConfigBean) Parameter(io.swagger.v3.oas.annotations.Parameter) Slf4j(lombok.extern.slf4j.Slf4j) AuditableExecution(org.apereo.cas.audit.AuditableExecution) EntityRoleCriterion(org.opensaml.saml.criterion.EntityRoleCriterion) NumberUtils(org.apache.commons.lang3.math.NumberUtils) EntityIdCriterion(org.opensaml.core.criterion.EntityIdCriterion) CriteriaSet(net.shibboleth.utilities.java.support.resolver.CriteriaSet) CriteriaSet(net.shibboleth.utilities.java.support.resolver.CriteriaSet) EntityIdCriterion(org.opensaml.core.criterion.EntityIdCriterion) EntityRoleCriterion(org.opensaml.saml.criterion.EntityRoleCriterion) ReadOperation(org.springframework.boot.actuate.endpoint.annotation.ReadOperation) ReadOperation(org.springframework.boot.actuate.endpoint.annotation.ReadOperation) DeleteOperation(org.springframework.boot.actuate.endpoint.annotation.DeleteOperation) Operation(io.swagger.v3.oas.annotations.Operation)

Example 32 with EntityIdCriterion

use of org.opensaml.core.criterion.EntityIdCriterion in project cas by apereo.

the class SamlRegisteredServiceCachedMetadataEndpoint method invalidate.

/**
 * Invalidate.
 *
 * @param serviceId the service id
 */
@DeleteOperation
@Operation(summary = "Invalidate SAML2 metadata cache using an entity id.", parameters = { @Parameter(name = "serviceId") })
public void invalidate(@Nullable final String serviceId) {
    if (StringUtils.isBlank(serviceId)) {
        cachingMetadataResolver.invalidate();
    } else {
        val registeredService = findRegisteredService(serviceId);
        val criteriaSet = new CriteriaSet();
        criteriaSet.add(new EntityIdCriterion(serviceId));
        criteriaSet.add(new EntityRoleCriterion(SPSSODescriptor.DEFAULT_ELEMENT_NAME));
        cachingMetadataResolver.invalidate(registeredService, criteriaSet);
    }
}
Also used : lombok.val(lombok.val) CriteriaSet(net.shibboleth.utilities.java.support.resolver.CriteriaSet) EntityIdCriterion(org.opensaml.core.criterion.EntityIdCriterion) EntityRoleCriterion(org.opensaml.saml.criterion.EntityRoleCriterion) DeleteOperation(org.springframework.boot.actuate.endpoint.annotation.DeleteOperation) ReadOperation(org.springframework.boot.actuate.endpoint.annotation.ReadOperation) DeleteOperation(org.springframework.boot.actuate.endpoint.annotation.DeleteOperation) Operation(io.swagger.v3.oas.annotations.Operation)

Example 33 with EntityIdCriterion

use of org.opensaml.core.criterion.EntityIdCriterion in project cas by apereo.

the class SamlRegisteredServiceServiceProviderMetadataFacade method get.

@SneakyThrows
private static Optional<SamlRegisteredServiceServiceProviderMetadataFacade> get(final SamlRegisteredServiceCachingMetadataResolver resolver, final SamlRegisteredService registeredService, final String entityID, final CriteriaSet criterions) {
    try {
        LOGGER.trace("Adapting SAML metadata for CAS service [{}] issued by [{}]", registeredService.getName(), entityID);
        criterions.add(new EntityIdCriterion(entityID), true);
        LOGGER.debug("Locating metadata for entityID [{}] by attempting to run through the metadata chain...", entityID);
        val chainingMetadataResolver = resolver.resolve(registeredService, criterions);
        LOGGER.debug("Resolved metadata chain from [{}] using [{}]. Filtering the chain by entity ID [{}]", registeredService.getMetadataLocation(), chainingMetadataResolver.getId(), entityID);
        val entityDescriptor = chainingMetadataResolver.resolveSingle(criterions);
        if (entityDescriptor == null) {
            LOGGER.warn("Cannot find entity [{}] in metadata provider for criteria [{}]", entityID, criterions);
            return Optional.empty();
        }
        LOGGER.trace("Located entity descriptor in metadata for [{}]", entityID);
        if (entityDescriptor.getValidUntil() != null) {
            val expired = entityDescriptor.getValidUntil().isBefore(ZonedDateTime.now(ZoneOffset.UTC).toInstant());
            if (expired) {
                LOGGER.warn("Entity descriptor in the metadata has expired at [{}]", entityDescriptor.getValidUntil());
                return Optional.empty();
            }
        }
        return getServiceProviderSsoDescriptor(entityID, chainingMetadataResolver, entityDescriptor);
    } catch (final Exception e) {
        LoggingUtils.error(LOGGER, e);
    }
    return Optional.empty();
}
Also used : lombok.val(lombok.val) EntityIdCriterion(org.opensaml.core.criterion.EntityIdCriterion) SneakyThrows(lombok.SneakyThrows)

Example 34 with EntityIdCriterion

use of org.opensaml.core.criterion.EntityIdCriterion in project cas by apereo.

the class WsFederationMetadataCertificateProvider method getSigningCredentials.

@Override
public List<Credential> getSigningCredentials() throws Exception {
    try (val is = metadataResource.getInputStream()) {
        val resolver = new InMemoryResourceMetadataResolver(is, openSamlConfigBean);
        resolver.setId(UUID.randomUUID().toString());
        resolver.initialize();
        val criteria = new CriteriaSet(new EntityIdCriterion(configuration.getIdentityProviderIdentifier()), new EvaluableEntityRoleEntityDescriptorCriterion(IDPSSODescriptor.DEFAULT_ELEMENT_NAME));
        LOGGER.debug("Locating entity descriptor in the metadata for [{}]", configuration.getIdentityProviderIdentifier());
        val entityDescriptor = resolver.resolveSingle(criteria);
        val roleDescriptors = entityDescriptor.getRoleDescriptors(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
        val keyDescriptors = roleDescriptors.get(0).getKeyDescriptors();
        val keyDescriptor = keyDescriptors.stream().filter(key -> key.getUse() == UsageType.SIGNING).findFirst().orElseThrow(() -> new RuntimeException("Unable to find key descriptor marked for signing usage"));
        return keyDescriptor.getKeyInfo().getX509Datas().stream().map(X509Data::getX509Certificates).flatMap(List::stream).map(Unchecked.function(cert -> {
            LOGGER.debug("Parsing signing certificate [{}]", cert.getValue());
            val decode = EncodingUtils.decodeBase64(cert.getValue());
            try (val value = new ByteArrayInputStream(decode)) {
                return WsFederationCertificateProvider.readCredential(value);
            }
        })).collect(Collectors.toList());
    }
}
Also used : lombok.val(lombok.val) EvaluableEntityRoleEntityDescriptorCriterion(org.opensaml.saml.metadata.criteria.entity.impl.EvaluableEntityRoleEntityDescriptorCriterion) ByteArrayInputStream(java.io.ByteArrayInputStream) CriteriaSet(net.shibboleth.utilities.java.support.resolver.CriteriaSet) EntityIdCriterion(org.opensaml.core.criterion.EntityIdCriterion) List(java.util.List) InMemoryResourceMetadataResolver(org.apereo.cas.support.saml.InMemoryResourceMetadataResolver)

Example 35 with EntityIdCriterion

use of org.opensaml.core.criterion.EntityIdCriterion in project cas by apereo.

the class WsFederationHelper method validateSignature.

/**
 * validateSignature checks to see if the signature on an assertion is valid.
 *
 * @param resultPair a provided assertion
 * @return true if the assertion's signature is valid, otherwise false
 */
public boolean validateSignature(final Pair<Assertion, WsFederationConfiguration> resultPair) {
    if (resultPair == null) {
        LOGGER.warn("No assertion or its configuration was provided to validate signatures");
        return false;
    }
    val configuration = resultPair.getValue();
    val assertion = resultPair.getKey();
    if (assertion == null || configuration == null) {
        LOGGER.warn("No signature or configuration was provided to validate signatures");
        return false;
    }
    val signature = assertion.getSignature();
    if (signature == null) {
        LOGGER.warn("No signature is attached to the assertion to validate");
        return false;
    }
    try {
        LOGGER.debug("Validating the signature...");
        val validator = new SAMLSignatureProfileValidator();
        validator.validate(signature);
        val 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(configuration.getIdentityProviderIdentifier()));
        val engine = buildSignatureTrustEngine(configuration);
        LOGGER.debug("Validating signature via trust engine for [{}]", configuration.getIdentityProviderIdentifier());
        return engine.validate(signature, criteriaSet);
    } catch (final Exception e) {
        LoggingUtils.error(LOGGER, "Failed to validate assertion signature", e);
    }
    SamlUtils.logSamlObject(this.openSamlConfigBean, assertion);
    LOGGER.error("Signature doesn't match any signing credential and cannot be validated.");
    return false;
}
Also used : lombok.val(lombok.val) UsageCriterion(org.opensaml.security.criteria.UsageCriterion) ProtocolCriterion(org.opensaml.saml.criterion.ProtocolCriterion) 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)

Aggregations

EntityIdCriterion (org.opensaml.core.criterion.EntityIdCriterion)44 CriteriaSet (net.shibboleth.utilities.java.support.resolver.CriteriaSet)39 EntityRoleCriterion (org.opensaml.saml.criterion.EntityRoleCriterion)30 lombok.val (lombok.val)25 Test (org.junit.jupiter.api.Test)9 UsageCriterion (org.opensaml.security.criteria.UsageCriterion)9 SamlRegisteredService (org.apereo.cas.support.saml.services.SamlRegisteredService)7 EntityDescriptor (org.opensaml.saml.saml2.metadata.EntityDescriptor)7 ArrayList (java.util.ArrayList)5 File (java.io.File)4 SamlException (org.apereo.cas.support.saml.SamlException)4 ProtocolCriterion (org.opensaml.saml.criterion.ProtocolCriterion)4 IDPSSODescriptor (org.opensaml.saml.saml2.metadata.IDPSSODescriptor)4 SAMLSignatureProfileValidator (org.opensaml.saml.security.impl.SAMLSignatureProfileValidator)4 ResolverException (net.shibboleth.utilities.java.support.resolver.ResolverException)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