Search in sources :

Example 41 with Assertion

use of org.opensaml.saml.saml1.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 42 with Assertion

use of org.opensaml.saml.saml1.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 43 with Assertion

use of org.opensaml.saml.saml1.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)

Example 44 with Assertion

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

the class IdpAssertionMetricsCollectorTest method shouldRegisterIdpNameFromAssertion.

@Test
public void shouldRegisterIdpNameFromAssertion() {
    MetricRegistry metricRegistry = new MetricRegistry();
    IdpAssertionMetricsCollector idpAssertionMetricsCollector = new IdpAssertionMetricsCollector(metricRegistry);
    Assertion anAssertion = anAssertion().withIssuer(anIssuer().withIssuerId("testIdP").build()).buildUnencrypted();
    idpAssertionMetricsCollector.update(anAssertion);
    assertThat(metricRegistry.getGauges().keySet()).contains("notOnOrAfter.testIdP");
}
Also used : MetricRegistry(com.codahale.metrics.MetricRegistry) AssertionBuilder.anAssertion(uk.gov.ida.saml.core.test.builders.AssertionBuilder.anAssertion) Assertion(org.opensaml.saml.saml2.core.Assertion) Test(org.junit.Test)

Example 45 with Assertion

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

the class IdpAssertionMetricsCollectorTest method shouldCollectNotOnOrAfterValueFromAssertion.

@Test
public void shouldCollectNotOnOrAfterValueFromAssertion() {
    DateTimeFreezer.freezeTime();
    MetricRegistry metricRegistry = new MetricRegistry();
    IdpAssertionMetricsCollector idpAssertionMetricsCollector = new IdpAssertionMetricsCollector(metricRegistry);
    DateTime notOnOrAfter = DateTime.now().plusMinutes(15);
    Assertion anAssertion = anAssertion().withIssuer(anIssuer().withIssuerId("testIdP").build()).withSubject(aSubject().withSubjectConfirmation(aSubjectConfirmation().withSubjectConfirmationData(aSubjectConfirmationData().withNotOnOrAfter(notOnOrAfter).build()).build()).build()).buildUnencrypted();
    idpAssertionMetricsCollector.update(anAssertion);
    Gauge actual = metricRegistry.getGauges().get("notOnOrAfter.testIdP");
    assertThat(actual.getValue()).isEqualTo(15L);
}
Also used : MetricRegistry(com.codahale.metrics.MetricRegistry) AssertionBuilder.anAssertion(uk.gov.ida.saml.core.test.builders.AssertionBuilder.anAssertion) Assertion(org.opensaml.saml.saml2.core.Assertion) DateTime(org.joda.time.DateTime) Gauge(com.codahale.metrics.Gauge) Test(org.junit.Test)

Aggregations

Assertion (org.opensaml.saml.saml2.core.Assertion)33 Test (org.junit.Test)16 Assertion (org.opensaml.saml.saml1.core.Assertion)13 AssertionBuilder.anAssertion (uk.gov.ida.saml.core.test.builders.AssertionBuilder.anAssertion)9 Response (org.opensaml.saml.saml2.core.Response)8 DateTime (org.joda.time.DateTime)6 Assertion (org.opensaml.saml2.core.Assertion)6 Element (org.w3c.dom.Element)6 PassthroughAssertion (uk.gov.ida.saml.core.domain.PassthroughAssertion)6 Subject (org.opensaml.saml.saml2.core.Subject)5 MetricRegistry (com.codahale.metrics.MetricRegistry)4 ZonedDateTime (java.time.ZonedDateTime)4 ArrayList (java.util.ArrayList)4 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)4 SamlAssertionWrapper (org.apache.wss4j.common.saml.SamlAssertionWrapper)4 Credential (org.apache.wss4j.dom.validate.Credential)4 Service (org.apereo.cas.authentication.principal.Service)4 RegisteredService (org.apereo.cas.services.RegisteredService)4 WsFederationCredential (org.apereo.cas.support.wsfederation.authentication.principal.WsFederationCredential)4 XMLObject (org.opensaml.core.xml.XMLObject)4