Search in sources :

Example 1 with EvaluableEntityRoleEntityDescriptorCriterion

use of org.opensaml.saml.metadata.criteria.entity.impl.EvaluableEntityRoleEntityDescriptorCriterion in project cas by apereo.

the class SamlProfileSaml2ResponseBuilder method buildResponse.

@Override
public Response buildResponse(final Assertion assertion, final SamlProfileBuilderContext context) throws Exception {
    val id = '_' + String.valueOf(RandomUtils.nextLong());
    val samlResponse = newResponse(id, ZonedDateTime.now(ZoneOffset.UTC), context.getSamlRequest().getID(), null);
    samlResponse.setVersion(SAMLVersion.VERSION_20);
    val issuerId = FunctionUtils.doIf(StringUtils.isNotBlank(context.getRegisteredService().getIssuerEntityId()), context.getRegisteredService()::getIssuerEntityId, Unchecked.supplier(() -> {
        val criteriaSet = new CriteriaSet(new EvaluableEntityRoleEntityDescriptorCriterion(IDPSSODescriptor.DEFAULT_ELEMENT_NAME), new SamlIdPSamlRegisteredServiceCriterion(context.getRegisteredService()));
        LOGGER.trace("Resolving entity id from SAML2 IdP metadata to determine issuer for [{}]", context.getRegisteredService().getName());
        val entityDescriptor = Objects.requireNonNull(getConfigurationContext().getSamlIdPMetadataResolver().resolveSingle(criteriaSet));
        return entityDescriptor.getEntityID();
    })).get();
    samlResponse.setIssuer(buildSamlResponseIssuer(issuerId));
    val acs = SamlIdPUtils.determineEndpointForRequest(Pair.of(context.getSamlRequest(), context.getMessageContext()), context.getAdaptor(), context.getBinding());
    val location = StringUtils.isBlank(acs.getResponseLocation()) ? acs.getLocation() : acs.getResponseLocation();
    samlResponse.setDestination(location);
    if (getConfigurationContext().getCasProperties().getAuthn().getSamlIdp().getCore().isAttributeQueryProfileEnabled()) {
        storeAttributeQueryTicketInRegistry(assertion, context);
    }
    val finalAssertion = encryptAssertion(assertion, context);
    if (finalAssertion instanceof EncryptedAssertion) {
        LOGGER.trace("Built assertion is encrypted, so the response will add it to the encrypted assertions collection");
        samlResponse.getEncryptedAssertions().add(EncryptedAssertion.class.cast(finalAssertion));
    } else {
        LOGGER.trace("Built assertion is not encrypted, so the response will add it to the assertions collection");
        samlResponse.getAssertions().add(Assertion.class.cast(finalAssertion));
    }
    val status = newStatus(StatusCode.SUCCESS, null);
    samlResponse.setStatus(status);
    SamlUtils.logSamlObject(this.openSamlConfigBean, samlResponse);
    if (context.getRegisteredService().isSignResponses()) {
        LOGGER.debug("SAML entity id [{}] indicates that SAML responses should be signed", context.getAdaptor().getEntityId());
        val samlResponseSigned = getConfigurationContext().getSamlObjectSigner().encode(samlResponse, context.getRegisteredService(), context.getAdaptor(), context.getHttpResponse(), context.getHttpRequest(), context.getBinding(), context.getSamlRequest(), context.getMessageContext());
        SamlUtils.logSamlObject(openSamlConfigBean, samlResponseSigned);
        return samlResponseSigned;
    }
    return samlResponse;
}
Also used : lombok.val(lombok.val) EvaluableEntityRoleEntityDescriptorCriterion(org.opensaml.saml.metadata.criteria.entity.impl.EvaluableEntityRoleEntityDescriptorCriterion) SamlIdPSamlRegisteredServiceCriterion(org.apereo.cas.support.saml.idp.metadata.locator.SamlIdPSamlRegisteredServiceCriterion) EncryptedAssertion(org.opensaml.saml.saml2.core.EncryptedAssertion) CriteriaSet(net.shibboleth.utilities.java.support.resolver.CriteriaSet) EncryptedAssertion(org.opensaml.saml.saml2.core.EncryptedAssertion) Assertion(org.opensaml.saml.saml2.core.Assertion)

Example 2 with EvaluableEntityRoleEntityDescriptorCriterion

use of org.opensaml.saml.metadata.criteria.entity.impl.EvaluableEntityRoleEntityDescriptorCriterion in project cas by apereo.

the class DefaultSamlIdPObjectSigner method getSignatureSigningConfiguration.

/**
 * Gets signature signing configuration.
 * The resolved used is {@link SamlIdPMetadataCredentialResolver} that
 * allows the entire criteria set to be passed to the role descriptor resolver.
 * This behavior allows the passing of {@link SamlIdPSamlRegisteredServiceCriterion}
 * so signing configuration, etc can be fetched for a specific service as an override,
 * if on is in fact defined for the service.
 *
 * @param service the service
 * @return the signature signing configuration
 * @throws Exception the exception
 */
protected SignatureSigningConfiguration getSignatureSigningConfiguration(final SamlRegisteredService service) throws Exception {
    val config = configureSignatureSigningSecurityConfiguration(service);
    val samlIdp = casProperties.getAuthn().getSamlIdp();
    val privateKey = getSigningPrivateKey(service);
    val mdCredentialResolver = new SamlIdPMetadataCredentialResolver();
    val roleDescriptorResolver = SamlIdPUtils.getRoleDescriptorResolver(samlIdPMetadataResolver, samlIdp.getMetadata().getCore().isRequireValidMetadata());
    mdCredentialResolver.setRoleDescriptorResolver(roleDescriptorResolver);
    mdCredentialResolver.setKeyInfoCredentialResolver(DefaultSecurityConfigurationBootstrap.buildBasicInlineKeyInfoCredentialResolver());
    mdCredentialResolver.initialize();
    val criteriaSet = new CriteriaSet();
    criteriaSet.add(new SignatureSigningConfigurationCriterion(config));
    criteriaSet.add(new UsageCriterion(UsageType.SIGNING));
    val entityIdCriteriaSet = new CriteriaSet(new EvaluableEntityRoleEntityDescriptorCriterion(IDPSSODescriptor.DEFAULT_ELEMENT_NAME), new SamlIdPSamlRegisteredServiceCriterion(service));
    LOGGER.trace("Resolving entity id from SAML2 IdP metadata for signature signing configuration is [{}]", service.getName());
    val entityId = Objects.requireNonNull(samlIdPMetadataResolver.resolveSingle(entityIdCriteriaSet)).getEntityID();
    LOGGER.trace("Resolved entity id from SAML2 IdP metadata is [{}]", entityId);
    criteriaSet.add(new EntityIdCriterion(entityId));
    criteriaSet.add(new EntityRoleCriterion(IDPSSODescriptor.DEFAULT_ELEMENT_NAME));
    criteriaSet.add(new SamlIdPSamlRegisteredServiceCriterion(service));
    LOGGER.trace("Resolved signing credentials based on criteria [{}]", criteriaSet);
    val credentials = Sets.newLinkedHashSet(mdCredentialResolver.resolve(criteriaSet));
    LOGGER.trace("Resolved [{}] signing credentials", credentials.size());
    val finalCredentials = new ArrayList<Credential>();
    credentials.stream().map(c -> getResolvedSigningCredential(c, privateKey, service)).filter(Objects::nonNull).filter(c -> doesCredentialFingerprintMatch(c, service)).forEach(finalCredentials::add);
    if (finalCredentials.isEmpty()) {
        LOGGER.error("Unable to locate any signing credentials for service [{}]", service.getName());
        throw new IllegalArgumentException("Unable to locate signing credentials");
    }
    config.setSigningCredentials(finalCredentials);
    LOGGER.trace("Signature signing credentials configured with [{}] credentials", finalCredentials.size());
    return config;
}
Also used : lombok.val(lombok.val) CasConfigurationProperties(org.apereo.cas.configuration.CasConfigurationProperties) MessageContext(org.opensaml.messaging.context.MessageContext) SneakyThrows(lombok.SneakyThrows) RequiredArgsConstructor(lombok.RequiredArgsConstructor) SignatureSigningConfiguration(org.opensaml.xmlsec.SignatureSigningConfiguration) StringUtils(org.apache.commons.lang3.StringUtils) PrivateKeyFactoryBean(org.apereo.cas.util.crypto.PrivateKeyFactoryBean) SamlUtils(org.apereo.cas.support.saml.SamlUtils) SignatureSigningParameters(org.opensaml.xmlsec.SignatureSigningParameters) LoggingUtils(org.apereo.cas.util.LoggingUtils) Pair(org.apache.commons.lang3.tuple.Pair) SamlException(org.apereo.cas.support.saml.SamlException) BasicCredential(org.opensaml.security.credential.BasicCredential) SAMLMetadataSignatureSigningParametersResolver(org.opensaml.saml.security.impl.SAMLMetadataSignatureSigningParametersResolver) UsageType(org.opensaml.security.credential.UsageType) SAMLOutboundDestinationHandler(org.opensaml.saml.common.binding.impl.SAMLOutboundDestinationHandler) MetadataResolver(org.opensaml.saml.metadata.resolver.MetadataResolver) RequestAbstractType(org.opensaml.saml.saml2.core.RequestAbstractType) BasicX509Credential(org.opensaml.security.x509.BasicX509Credential) SamlIdPUtils(org.apereo.cas.support.saml.SamlIdPUtils) Sets(com.google.common.collect.Sets) AbstractCredential(org.opensaml.security.credential.AbstractCredential) Objects(java.util.Objects) Slf4j(lombok.extern.slf4j.Slf4j) SAMLObject(org.opensaml.saml.common.SAMLObject) PrivateKey(java.security.PrivateKey) EntityRoleCriterion(org.opensaml.saml.criterion.EntityRoleCriterion) SignatureSigningConfigurationCriterion(org.opensaml.xmlsec.criterion.SignatureSigningConfigurationCriterion) EndpointURLSchemeSecurityHandler(org.opensaml.saml.common.binding.security.impl.EndpointURLSchemeSecurityHandler) SamlRegisteredServiceServiceProviderMetadataFacade(org.apereo.cas.support.saml.services.idp.metadata.SamlRegisteredServiceServiceProviderMetadataFacade) CriteriaSet(net.shibboleth.utilities.java.support.resolver.CriteriaSet) Optional(java.util.Optional) Pattern(java.util.regex.Pattern) MutableCredential(org.opensaml.security.credential.MutableCredential) SAMLOutboundProtocolMessageSigningHandler(org.opensaml.saml.common.binding.security.impl.SAMLOutboundProtocolMessageSigningHandler) UsageCriterion(org.opensaml.security.criteria.UsageCriterion) Getter(lombok.Getter) DigestUtils(org.apereo.cas.util.DigestUtils) SamlIdPMetadataCredentialResolver(org.apereo.cas.support.saml.idp.metadata.locator.SamlIdPMetadataCredentialResolver) ArrayList(java.util.ArrayList) HttpServletRequest(javax.servlet.http.HttpServletRequest) SamlRegisteredService(org.apereo.cas.support.saml.services.SamlRegisteredService) SecurityParametersContext(org.opensaml.xmlsec.context.SecurityParametersContext) SamlIdPSamlRegisteredServiceCriterion(org.apereo.cas.support.saml.idp.metadata.locator.SamlIdPSamlRegisteredServiceCriterion) SamlIdPResponseProperties(org.apereo.cas.configuration.model.support.saml.idp.SamlIdPResponseProperties) IDPSSODescriptor(org.opensaml.saml.saml2.metadata.IDPSSODescriptor) BasicAlgorithmPolicyConfiguration(org.opensaml.xmlsec.impl.BasicAlgorithmPolicyConfiguration) RoleDescriptorCriterion(org.opensaml.saml.criterion.RoleDescriptorCriterion) DefaultSecurityConfigurationBootstrap(org.opensaml.xmlsec.config.impl.DefaultSecurityConfigurationBootstrap) Credential(org.opensaml.security.credential.Credential) lombok.val(lombok.val) HttpServletResponse(javax.servlet.http.HttpServletResponse) RoleDescriptor(org.opensaml.saml.saml2.metadata.RoleDescriptor) RegexUtils(org.apereo.cas.util.RegexUtils) CertUtils(org.apereo.cas.util.crypto.CertUtils) SamlIdPMetadataLocator(org.apereo.cas.support.saml.idp.metadata.locator.SamlIdPMetadataLocator) EvaluableEntityRoleEntityDescriptorCriterion(org.opensaml.saml.metadata.criteria.entity.impl.EvaluableEntityRoleEntityDescriptorCriterion) EntityIdCriterion(org.opensaml.core.criterion.EntityIdCriterion) BasicSignatureSigningConfiguration(org.opensaml.xmlsec.impl.BasicSignatureSigningConfiguration) UsageCriterion(org.opensaml.security.criteria.UsageCriterion) EvaluableEntityRoleEntityDescriptorCriterion(org.opensaml.saml.metadata.criteria.entity.impl.EvaluableEntityRoleEntityDescriptorCriterion) SamlIdPSamlRegisteredServiceCriterion(org.apereo.cas.support.saml.idp.metadata.locator.SamlIdPSamlRegisteredServiceCriterion) EntityIdCriterion(org.opensaml.core.criterion.EntityIdCriterion) ArrayList(java.util.ArrayList) SamlIdPMetadataCredentialResolver(org.apereo.cas.support.saml.idp.metadata.locator.SamlIdPMetadataCredentialResolver) CriteriaSet(net.shibboleth.utilities.java.support.resolver.CriteriaSet) EntityRoleCriterion(org.opensaml.saml.criterion.EntityRoleCriterion) Objects(java.util.Objects) SignatureSigningConfigurationCriterion(org.opensaml.xmlsec.criterion.SignatureSigningConfigurationCriterion)

Example 3 with EvaluableEntityRoleEntityDescriptorCriterion

use of org.opensaml.saml.metadata.criteria.entity.impl.EvaluableEntityRoleEntityDescriptorCriterion in project cas by apereo.

the class SamlProfileSamlAssertionBuilder method build.

@Override
public Assertion build(final SamlProfileBuilderContext context) throws Exception {
    val statements = new ArrayList<Statement>();
    val authnStatement = this.samlProfileSamlAuthNStatementBuilder.build(context);
    statements.add(authnStatement);
    val attrStatement = this.samlProfileSamlAttributeStatementBuilder.build(context);
    if (!attrStatement.getAttributes().isEmpty() || !attrStatement.getEncryptedAttributes().isEmpty()) {
        statements.add(attrStatement);
    }
    val issuerId = FunctionUtils.doIf(StringUtils.isNotBlank(context.getRegisteredService().getIssuerEntityId()), context.getRegisteredService()::getIssuerEntityId, Unchecked.supplier(() -> {
        val criteriaSet = new CriteriaSet(new EvaluableEntityRoleEntityDescriptorCriterion(IDPSSODescriptor.DEFAULT_ELEMENT_NAME), new SamlIdPSamlRegisteredServiceCriterion(context.getRegisteredService()));
        LOGGER.trace("Resolving entity id from SAML2 IdP metadata to determine issuer for [{}]", context.getRegisteredService().getName());
        val entityDescriptor = Objects.requireNonNull(samlIdPMetadataResolver.resolveSingle(criteriaSet));
        return entityDescriptor.getEntityID();
    })).get();
    val id = '_' + String.valueOf(RandomUtils.nextLong());
    val assertion = newAssertion(statements, issuerId, ZonedDateTime.now(ZoneOffset.UTC), id);
    assertion.setSubject(this.samlProfileSamlSubjectBuilder.build(context));
    assertion.setConditions(this.samlProfileSamlConditionsBuilder.build(context));
    signAssertion(assertion, context);
    return assertion;
}
Also used : lombok.val(lombok.val) EvaluableEntityRoleEntityDescriptorCriterion(org.opensaml.saml.metadata.criteria.entity.impl.EvaluableEntityRoleEntityDescriptorCriterion) SamlIdPSamlRegisteredServiceCriterion(org.apereo.cas.support.saml.idp.metadata.locator.SamlIdPSamlRegisteredServiceCriterion) ArrayList(java.util.ArrayList) CriteriaSet(net.shibboleth.utilities.java.support.resolver.CriteriaSet)

Example 4 with EvaluableEntityRoleEntityDescriptorCriterion

use of org.opensaml.saml.metadata.criteria.entity.impl.EvaluableEntityRoleEntityDescriptorCriterion in project cas by apereo.

the class SamlIdPMetadataResolverTests method verifyOperationWithoutEntityId.

@RepeatedTest(2)
public void verifyOperationWithoutEntityId() throws Exception {
    val criteria = new CriteriaSet(new EvaluableEntityRoleEntityDescriptorCriterion(IDPSSODescriptor.DEFAULT_ELEMENT_NAME));
    val result1 = casSamlIdPMetadataResolver.resolve(criteria);
    assertFalse(Iterables.isEmpty(result1));
    assertEquals(casProperties.getAuthn().getSamlIdp().getCore().getEntityId(), Iterables.getFirst(result1, null).getEntityID());
}
Also used : lombok.val(lombok.val) EvaluableEntityRoleEntityDescriptorCriterion(org.opensaml.saml.metadata.criteria.entity.impl.EvaluableEntityRoleEntityDescriptorCriterion) CriteriaSet(net.shibboleth.utilities.java.support.resolver.CriteriaSet) RepeatedTest(org.junit.jupiter.api.RepeatedTest)

Example 5 with EvaluableEntityRoleEntityDescriptorCriterion

use of org.opensaml.saml.metadata.criteria.entity.impl.EvaluableEntityRoleEntityDescriptorCriterion 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)

Aggregations

lombok.val (lombok.val)6 CriteriaSet (net.shibboleth.utilities.java.support.resolver.CriteriaSet)6 EvaluableEntityRoleEntityDescriptorCriterion (org.opensaml.saml.metadata.criteria.entity.impl.EvaluableEntityRoleEntityDescriptorCriterion)6 SamlIdPSamlRegisteredServiceCriterion (org.apereo.cas.support.saml.idp.metadata.locator.SamlIdPSamlRegisteredServiceCriterion)4 ArrayList (java.util.ArrayList)2 EntityIdCriterion (org.opensaml.core.criterion.EntityIdCriterion)2 Sets (com.google.common.collect.Sets)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 PrivateKey (java.security.PrivateKey)1 List (java.util.List)1 Objects (java.util.Objects)1 Optional (java.util.Optional)1 Pattern (java.util.regex.Pattern)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 HttpServletResponse (javax.servlet.http.HttpServletResponse)1 Getter (lombok.Getter)1 RequiredArgsConstructor (lombok.RequiredArgsConstructor)1 SneakyThrows (lombok.SneakyThrows)1 Slf4j (lombok.extern.slf4j.Slf4j)1 StringUtils (org.apache.commons.lang3.StringUtils)1