Search in sources :

Example 96 with Assertion

use of org.opensaml.saml.saml2.core.Assertion in project cas by apereo.

the class Saml10SuccessResponseView method prepareResponse.

@Override
protected void prepareResponse(final Response response, final Map<String, Object> model) {
    final ZonedDateTime issuedAt = DateTimeUtils.zonedDateTimeOf(response.getIssueInstant());
    final Service service = getAssertionFrom(model).getService();
    LOGGER.debug("Preparing SAML response for service [{}]", service);
    final Authentication authentication = getPrimaryAuthenticationFrom(model);
    final Collection<Object> authnMethods = CollectionUtils.toCollection(authentication.getAttributes().get(SamlAuthenticationMetaDataPopulator.ATTRIBUTE_AUTHENTICATION_METHOD));
    LOGGER.debug("Authentication methods found are [{}]", authnMethods);
    final Principal principal = getPrincipal(model);
    final AuthenticationStatement authnStatement = this.samlObjectBuilder.newAuthenticationStatement(authentication.getAuthenticationDate(), authnMethods, principal.getId());
    LOGGER.debug("Built authentication statement for [{}] dated at [{}]", principal, authentication.getAuthenticationDate());
    final Assertion assertion = this.samlObjectBuilder.newAssertion(authnStatement, this.issuer, issuedAt, this.samlObjectBuilder.generateSecureRandomId());
    LOGGER.debug("Built assertion for issuer [{}] dated at [{}]", this.issuer, issuedAt);
    final Conditions conditions = this.samlObjectBuilder.newConditions(issuedAt, service.getId(), this.issueLength);
    assertion.setConditions(conditions);
    LOGGER.debug("Built assertion conditions for issuer [{}] and service [{}] ", this.issuer, service.getId());
    final Subject subject = this.samlObjectBuilder.newSubject(principal.getId());
    LOGGER.debug("Built subject for principal [{}]", principal);
    final Map<String, Object> attributesToSend = prepareSamlAttributes(model, service);
    LOGGER.debug("Authentication statement shall include these attributes [{}]", attributesToSend);
    if (!attributesToSend.isEmpty()) {
        assertion.getAttributeStatements().add(this.samlObjectBuilder.newAttributeStatement(subject, attributesToSend, this.defaultAttributeNamespace));
    }
    response.setStatus(this.samlObjectBuilder.newStatus(StatusCode.SUCCESS, null));
    LOGGER.debug("Set response status code to [{}]", response.getStatus());
    response.getAssertions().add(assertion);
}
Also used : ZonedDateTime(java.time.ZonedDateTime) Authentication(org.apereo.cas.authentication.Authentication) Assertion(org.opensaml.saml.saml1.core.Assertion) RegisteredService(org.apereo.cas.services.RegisteredService) Service(org.apereo.cas.authentication.principal.Service) Principal(org.apereo.cas.authentication.principal.Principal) AuthenticationStatement(org.opensaml.saml.saml1.core.AuthenticationStatement) Conditions(org.opensaml.saml.saml1.core.Conditions) Subject(org.opensaml.saml.saml1.core.Subject)

Example 97 with Assertion

use of org.opensaml.saml.saml2.core.Assertion in project cas by apereo.

the class WsFederationHelper method createCredentialFromToken.

/**
 * createCredentialFromToken converts a SAML 1.1 assertion to a WSFederationCredential.
 *
 * @param assertion the provided assertion
 * @return an equivalent credential.
 */
public WsFederationCredential createCredentialFromToken(final Assertion assertion) {
    final ZonedDateTime retrievedOn = ZonedDateTime.now();
    LOGGER.debug("Retrieved on [{}]", retrievedOn);
    final WsFederationCredential credential = new WsFederationCredential();
    credential.setRetrievedOn(retrievedOn);
    credential.setId(assertion.getID());
    credential.setIssuer(assertion.getIssuer());
    credential.setIssuedOn(ZonedDateTime.parse(assertion.getIssueInstant().toDateTimeISO().toString()));
    final Conditions conditions = assertion.getConditions();
    if (conditions != null) {
        credential.setNotBefore(ZonedDateTime.parse(conditions.getNotBefore().toDateTimeISO().toString()));
        credential.setNotOnOrAfter(ZonedDateTime.parse(conditions.getNotOnOrAfter().toDateTimeISO().toString()));
        if (!conditions.getAudienceRestrictionConditions().isEmpty()) {
            credential.setAudience(conditions.getAudienceRestrictionConditions().get(0).getAudiences().get(0).getUri());
        }
    }
    if (!assertion.getAuthenticationStatements().isEmpty()) {
        credential.setAuthenticationMethod(assertion.getAuthenticationStatements().get(0).getAuthenticationMethod());
    }
    // retrieve an attributes from the assertion
    final HashMap<String, List<Object>> attributes = new HashMap<>();
    assertion.getAttributeStatements().stream().flatMap(attributeStatement -> attributeStatement.getAttributes().stream()).forEach(item -> {
        LOGGER.debug("Processed attribute: [{}]", item.getAttributeName());
        final List<Object> itemList = IntStream.range(0, item.getAttributeValues().size()).mapToObj(i -> ((XSAny) item.getAttributeValues().get(i)).getTextContent()).collect(Collectors.toList());
        if (!itemList.isEmpty()) {
            attributes.put(item.getAttributeName(), itemList);
        }
    });
    credential.setAttributes(attributes);
    LOGGER.debug("Credential: [{}]", credential);
    return credential;
}
Also used : XSAny(org.opensaml.core.xml.schema.XSAny) ChainingEncryptedKeyResolver(org.opensaml.xmlsec.encryption.support.ChainingEncryptedKeyResolver) KeyPair(java.security.KeyPair) ExplicitKeySignatureTrustEngine(org.opensaml.xmlsec.signature.support.impl.ExplicitKeySignatureTrustEngine) SneakyThrows(lombok.SneakyThrows) Assertion(org.opensaml.saml.saml1.core.Assertion) ZonedDateTime(java.time.ZonedDateTime) RequiredArgsConstructor(lombok.RequiredArgsConstructor) StaticCredentialResolver(org.opensaml.security.credential.impl.StaticCredentialResolver) Security(java.security.Security) Signature(org.opensaml.xmlsec.signature.Signature) SamlUtils(org.apereo.cas.support.saml.SamlUtils) Conditions(org.opensaml.saml.saml1.core.Conditions) Pair(org.apache.commons.lang3.tuple.Pair) StaticKeyInfoCredentialResolver(org.opensaml.xmlsec.keyinfo.impl.StaticKeyInfoCredentialResolver) ByteArrayInputStream(java.io.ByteArrayInputStream) SignatureException(org.opensaml.xmlsec.signature.support.SignatureException) Document(org.w3c.dom.Document) PEMEncryptedKeyPair(org.bouncycastle.openssl.PEMEncryptedKeyPair) WsFederationCredential(org.apereo.cas.support.wsfederation.authentication.principal.WsFederationCredential) UsageType(org.opensaml.security.credential.UsageType) SecurityException(org.opensaml.security.SecurityException) PEMParser(org.bouncycastle.openssl.PEMParser) Collection(java.util.Collection) PEMDecryptorProvider(org.bouncycastle.openssl.PEMDecryptorProvider) ProtocolCriterion(org.opensaml.saml.criterion.ProtocolCriterion) BasicX509Credential(org.opensaml.security.x509.BasicX509Credential) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) OpenSamlConfigBean(org.apereo.cas.support.saml.OpenSamlConfigBean) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) KeyInfoCredentialResolver(org.opensaml.xmlsec.keyinfo.KeyInfoCredentialResolver) EntityRoleCriterion(org.opensaml.saml.criterion.EntityRoleCriterion) CriteriaSet(net.shibboleth.utilities.java.support.resolver.CriteriaSet) RequestedSecurityToken(org.opensaml.soap.wsfed.RequestedSecurityToken) UnmarshallerFactory(org.opensaml.core.xml.io.UnmarshallerFactory) EncryptedData(org.opensaml.xmlsec.encryption.EncryptedData) EncryptedElementTypeEncryptedKeyResolver(org.opensaml.saml.saml2.encryption.EncryptedElementTypeEncryptedKeyResolver) IntStream(java.util.stream.IntStream) EncryptedKeyResolver(org.opensaml.xmlsec.encryption.support.EncryptedKeyResolver) Setter(lombok.Setter) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) UsageCriterion(org.opensaml.security.criteria.UsageCriterion) RegisteredServiceProperty(org.apereo.cas.services.RegisteredServiceProperty) RegisteredServiceAccessStrategyUtils(org.apereo.cas.services.RegisteredServiceAccessStrategyUtils) HashMap(java.util.HashMap) SignaturePrevalidator(org.opensaml.xmlsec.signature.support.SignaturePrevalidator) ArrayList(java.util.ArrayList) Decrypter(org.opensaml.saml.saml2.encryption.Decrypter) JcePEMDecryptorProviderBuilder(org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder) X509CertParser(org.bouncycastle.jce.provider.X509CertParser) SAMLSignatureProfileValidator(org.opensaml.saml.security.impl.SAMLSignatureProfileValidator) IDPSSODescriptor(org.opensaml.saml.saml2.metadata.IDPSSODescriptor) XMLObject(org.opensaml.core.xml.XMLObject) X509CertificateObject(org.bouncycastle.jce.provider.X509CertificateObject) SAMLConstants(org.opensaml.saml.common.xml.SAMLConstants) CredentialResolver(org.opensaml.security.credential.CredentialResolver) SignatureTrustEngine(org.opensaml.xmlsec.signature.support.SignatureTrustEngine) ServicesManager(org.apereo.cas.services.ServicesManager) InlineEncryptedKeyResolver(org.opensaml.xmlsec.encryption.support.InlineEncryptedKeyResolver) RequestSecurityTokenResponse(org.opensaml.soap.wsfed.RequestSecurityTokenResponse) Iterator(java.util.Iterator) Credential(org.opensaml.security.credential.Credential) Unmarshaller(org.opensaml.core.xml.io.Unmarshaller) InputStreamReader(java.io.InputStreamReader) RegisteredService(org.apereo.cas.services.RegisteredService) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) Element(org.w3c.dom.Element) Service(org.apereo.cas.authentication.principal.Service) EntityIdCriterion(org.opensaml.core.criterion.EntityIdCriterion) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) BufferedReader(java.io.BufferedReader) SimpleRetrievalMethodEncryptedKeyResolver(org.opensaml.xmlsec.encryption.support.SimpleRetrievalMethodEncryptedKeyResolver) InputStream(java.io.InputStream) ZonedDateTime(java.time.ZonedDateTime) HashMap(java.util.HashMap) List(java.util.List) ArrayList(java.util.ArrayList) XMLObject(org.opensaml.core.xml.XMLObject) X509CertificateObject(org.bouncycastle.jce.provider.X509CertificateObject) Conditions(org.opensaml.saml.saml1.core.Conditions) WsFederationCredential(org.apereo.cas.support.wsfederation.authentication.principal.WsFederationCredential) XSAny(org.opensaml.core.xml.schema.XSAny)

Example 98 with Assertion

use of org.opensaml.saml.saml2.core.Assertion in project cas by apereo.

the class WsFederationHelper method getSecurityTokenFromRequestedToken.

private XMLObject getSecurityTokenFromRequestedToken(final RequestedSecurityToken reqToken, final Collection<WsFederationConfiguration> config) {
    LOGGER.debug("Locating the first occurrence of a security token from the requested security token");
    XMLObject securityToken = getAssertionFromSecurityToken(reqToken);
    if (securityToken instanceof EncryptedData) {
        LOGGER.debug("Security token is encrypted. Attempting to decrypt to extract the assertion");
        final EncryptedData encryptedData = EncryptedData.class.cast(securityToken);
        final Iterator<WsFederationConfiguration> it = config.iterator();
        boolean found = false;
        while (!found && it.hasNext()) {
            try {
                final WsFederationConfiguration c = it.next();
                final Decrypter decrypter = buildAssertionDecrypter(c);
                LOGGER.debug("Built an instance of [{}]", decrypter.getClass().getName());
                securityToken = decrypter.decryptData(encryptedData);
                LOGGER.debug("Decrypted assertion successfully");
                found = true;
            } catch (final Exception e) {
                LOGGER.debug(e.getMessage(), e);
            }
        }
        if (!found) {
            throw new IllegalArgumentException("Could not extract or decrypt an assertion based on the security token provided");
        }
    }
    return securityToken;
}
Also used : XMLObject(org.opensaml.core.xml.XMLObject) Decrypter(org.opensaml.saml.saml2.encryption.Decrypter) EncryptedData(org.opensaml.xmlsec.encryption.EncryptedData) SignatureException(org.opensaml.xmlsec.signature.support.SignatureException) SecurityException(org.opensaml.security.SecurityException)

Example 99 with Assertion

use of org.opensaml.saml.saml2.core.Assertion in project cxf by apache.

the class CustomSaml2Validator method validate.

@Override
public Credential validate(Credential credential, RequestData data) throws WSSecurityException {
    Credential validatedCredential = super.validate(credential, data);
    SamlAssertionWrapper assertion = validatedCredential.getSamlAssertion();
    if (!"sts".equals(assertion.getIssuerString())) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }
    Assertion saml2Assertion = assertion.getSaml2();
    if (saml2Assertion == null) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }
    List<AttributeStatement> attributeStatements = saml2Assertion.getAttributeStatements();
    if (attributeStatements == null || attributeStatements.isEmpty()) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }
    return validatedCredential;
}
Also used : Credential(org.apache.wss4j.dom.validate.Credential) AttributeStatement(org.opensaml.saml.saml2.core.AttributeStatement) Assertion(org.opensaml.saml.saml2.core.Assertion) SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException)

Example 100 with Assertion

use of org.opensaml.saml.saml2.core.Assertion in project verify-hub by alphagov.

the class IdpAuthnResponseTranslatorService method translate.

public InboundResponseFromIdpDto translate(SamlAuthnResponseTranslatorDto samlResponseDto) {
    Response response = stringToOpenSamlResponseTransformer.apply(samlResponseDto.getSamlResponse());
    MdcHelper.addContextToMdc(response);
    try {
        InboundResponseFromIdp idaResponseFromIdp = samlResponseToIdaResponseIssuedByIdpTransformer.apply(response);
        UnknownMethodAlgorithmLogger.probeResponseForMethodAlgorithm(idaResponseFromIdp);
        if (idaResponseFromIdp.getAuthnStatementAssertion().isPresent()) {
            Assertion authnStatementAssertion = stringToAssertionTransformer.apply(idaResponseFromIdp.getAuthnStatementAssertion().get().getUnderlyingAssertionBlob());
            logAnalytics(authnStatementAssertion, AUTHN_STATEMENT);
        }
        Assertion matchingDatasetAssertion = null;
        if (idaResponseFromIdp.getMatchingDatasetAssertion().isPresent()) {
            matchingDatasetAssertion = stringToAssertionTransformer.apply(idaResponseFromIdp.getMatchingDatasetAssertion().get().getUnderlyingAssertionBlob());
            logAnalytics(matchingDatasetAssertion, MATCHING_DATASET);
        }
        InboundResponseFromIdpData inboundResponseFromIdpData = inboundResponseFromIdpDataGenerator.generate(idaResponseFromIdp, samlResponseDto.getMatchingServiceEntityId());
        Optional<LevelOfAssurance> levelOfAssurance = Optional.empty();
        if (!Strings.isNullOrEmpty(inboundResponseFromIdpData.getLevelOfAssurance())) {
            levelOfAssurance = Optional.of(LevelOfAssurance.valueOf(inboundResponseFromIdpData.getLevelOfAssurance()));
        }
        logVerifiedAttributes(idaResponseFromIdp, matchingDatasetAssertion, levelOfAssurance);
        return new InboundResponseFromIdpDto(inboundResponseFromIdpData.getStatus(), inboundResponseFromIdpData.getStatusMessage(), inboundResponseFromIdpData.getIssuer(), inboundResponseFromIdpData.getAuthnStatementAssertionBlob(), inboundResponseFromIdpData.getEncryptedMatchingDatasetAssertion(), inboundResponseFromIdpData.getPersistentId(), inboundResponseFromIdpData.getPrincipalIpAddressAsSeenByIdp(), levelOfAssurance, inboundResponseFromIdpData.getIdpFraudEventId(), inboundResponseFromIdpData.getFraudIndicator());
    } catch (SamlTransformationErrorException e) {
        throw new SamlContextException(response.getID(), response.getIssuer().getValue(), e);
    }
}
Also used : Response(org.opensaml.saml.saml2.core.Response) LevelOfAssurance(uk.gov.ida.hub.samlengine.domain.LevelOfAssurance) SamlContextException(uk.gov.ida.hub.samlengine.exceptions.SamlContextException) InboundResponseFromIdpDto(uk.gov.ida.hub.samlengine.domain.InboundResponseFromIdpDto) SamlTransformationErrorException(uk.gov.ida.saml.core.validation.SamlTransformationErrorException) InboundResponseFromIdp(uk.gov.ida.saml.hub.domain.InboundResponseFromIdp) Assertion(org.opensaml.saml.saml2.core.Assertion) InboundResponseFromIdpData(uk.gov.ida.saml.core.domain.InboundResponseFromIdpData)

Aggregations

Assertion (org.opensaml.saml.saml2.core.Assertion)33 Response (org.opensaml.saml.saml2.core.Response)31 Element (org.w3c.dom.Element)31 SamlAssertionWrapper (org.apache.wss4j.common.saml.SamlAssertionWrapper)26 Document (org.w3c.dom.Document)22 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)20 Status (org.opensaml.saml.saml2.core.Status)20 SAMLCallback (org.apache.wss4j.common.saml.SAMLCallback)18 DateTime (org.joda.time.DateTime)16 Test (org.junit.Test)16 Assertion (org.opensaml.saml.saml1.core.Assertion)13 InputStream (java.io.InputStream)11 Crypto (org.apache.wss4j.common.crypto.Crypto)11 AttributeStatement (org.opensaml.saml.saml2.core.AttributeStatement)11 ZonedDateTime (java.time.ZonedDateTime)10 XMLObject (org.opensaml.core.xml.XMLObject)10 KeyStore (java.security.KeyStore)9 Merlin (org.apache.wss4j.common.crypto.Merlin)9 Assertion (org.jasig.cas.client.validation.Assertion)9 AuthnRequest (org.opensaml.saml.saml2.core.AuthnRequest)9