Search in sources :

Example 11 with SubjectConfirmation

use of org.opensaml.saml.saml2.core.SubjectConfirmation in project pac4j by pac4j.

the class SAML2DefaultResponseValidator method validateSamlSSOResponse.

/**
 * Validates the SAML SSO response by finding a valid assertion with authn statements.
 * Populates the {@link SAML2MessageContext} with a subjectAssertion and a subjectNameIdentifier.
 *
 * @param response  the response
 * @param context   the context
 * @param engine    the engine
 * @param decrypter the decrypter
 */
protected final void validateSamlSSOResponse(final Response response, final SAML2MessageContext context, final SignatureTrustEngine engine, final Decrypter decrypter) {
    final List<SAMLException> errors = new ArrayList<>();
    for (final Assertion assertion : response.getAssertions()) {
        if (!assertion.getAuthnStatements().isEmpty()) {
            try {
                validateAssertion(assertion, context, engine, decrypter);
            } catch (final SAMLException e) {
                logger.error("Current assertion validation failed, continue with the next one", e);
                errors.add(e);
                continue;
            }
            context.setSubjectAssertion(assertion);
            break;
        }
    }
    if (!errors.isEmpty()) {
        throw errors.get(0);
    }
    if (context.getSubjectAssertion() == null) {
        throw new SAMAssertionSubjectException("No valid subject assertion found in response");
    }
    // We do not check EncryptedID here because it has been already decrypted and stored into NameID
    final List<SubjectConfirmation> subjectConfirmations = context.getSubjectConfirmations();
    final NameID nameIdentifier = (NameID) context.getSAMLSubjectNameIdentifierContext().getSubjectNameIdentifier();
    if ((nameIdentifier == null || nameIdentifier.getValue() == null) && context.getBaseID() == null && (subjectConfirmations == null || subjectConfirmations.isEmpty())) {
        throw new SAMLException("Subject NameID, BaseID and EncryptedID cannot be all null at the same time if there are no Subject Confirmations.");
    }
}
Also used : SAMAssertionSubjectException(org.pac4j.saml.exceptions.SAMAssertionSubjectException) SubjectConfirmation(org.opensaml.saml.saml2.core.SubjectConfirmation) NameID(org.opensaml.saml.saml2.core.NameID) ArrayList(java.util.ArrayList) EncryptedAssertion(org.opensaml.saml.saml2.core.EncryptedAssertion) Assertion(org.opensaml.saml.saml2.core.Assertion) SAMLException(org.pac4j.saml.exceptions.SAMLException)

Example 12 with SubjectConfirmation

use of org.opensaml.saml.saml2.core.SubjectConfirmation in project ddf by codice.

the class SamlAssertionValidatorImpl method validateHolderOfKeyConfirmation.

private void validateHolderOfKeyConfirmation(SamlAssertionWrapper assertion, X509Certificate[] x509Certs) throws SecurityServiceException {
    List<String> confirmationMethods = assertion.getConfirmationMethods();
    boolean hasHokMethod = false;
    for (String method : confirmationMethods) {
        if (OpenSAMLUtil.isMethodHolderOfKey(method)) {
            hasHokMethod = true;
        }
    }
    if (hasHokMethod) {
        if (x509Certs != null && x509Certs.length > 0) {
            List<SubjectConfirmation> subjectConfirmations = assertion.getSaml2().getSubject().getSubjectConfirmations();
            for (SubjectConfirmation subjectConfirmation : subjectConfirmations) {
                if (OpenSAMLUtil.isMethodHolderOfKey(subjectConfirmation.getMethod())) {
                    Element dom = subjectConfirmation.getSubjectConfirmationData().getDOM();
                    Node keyInfo = dom.getFirstChild();
                    Node x509Data = keyInfo.getFirstChild();
                    Node dataNode = x509Data.getFirstChild();
                    Node dataText = dataNode.getFirstChild();
                    X509Certificate tlsCertificate = x509Certs[0];
                    if (dataNode.getLocalName().equals("X509Certificate")) {
                        String textContent = dataText.getTextContent();
                        byte[] byteValue = Base64.getMimeDecoder().decode(textContent);
                        try {
                            CertificateFactory cf = CertificateFactory.getInstance("X.509");
                            X509Certificate cert = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(byteValue));
                            // check that the certificate is still valid
                            cert.checkValidity();
                            // if the certs aren't the same, verify
                            if (!tlsCertificate.equals(cert)) {
                                // verify that the cert was signed by the same private key as the TLS cert
                                cert.verify(tlsCertificate.getPublicKey());
                            }
                        } catch (CertificateException | NoSuchAlgorithmException | InvalidKeyException | SignatureException | NoSuchProviderException e) {
                            throw new SecurityServiceException("Unable to validate Holder of Key assertion with certificate.");
                        }
                    } else if (dataNode.getLocalName().equals("X509SubjectName")) {
                        String textContent = dataText.getTextContent();
                        // the assertion.
                        if (!tlsCertificate.getSubjectDN().getName().equals(textContent)) {
                            throw new SecurityServiceException("Unable to validate Holder of Key assertion with subject DN.");
                        }
                    } else if (dataNode.getLocalName().equals("X509IssuerSerial")) {
                        // we have no way to support this confirmation type so we have to throw an error
                        throw new SecurityServiceException("Unable to validate Holder of Key assertion with issuer serial. NOT SUPPORTED");
                    } else if (dataNode.getLocalName().equals("X509SKI")) {
                        String textContent = dataText.getTextContent();
                        byte[] tlsSKI = tlsCertificate.getExtensionValue("2.5.29.14");
                        byte[] assertionSKI = Base64.getMimeDecoder().decode(textContent);
                        if (tlsSKI != null && tlsSKI.length > 0) {
                            ASN1OctetString tlsOs = ASN1OctetString.getInstance(tlsSKI);
                            ASN1OctetString assertionOs = ASN1OctetString.getInstance(assertionSKI);
                            SubjectKeyIdentifier tlsSubjectKeyIdentifier = SubjectKeyIdentifier.getInstance(tlsOs.getOctets());
                            SubjectKeyIdentifier assertSubjectKeyIdentifier = SubjectKeyIdentifier.getInstance(assertionOs.getOctets());
                            // assertion.
                            if (!Arrays.equals(tlsSubjectKeyIdentifier.getKeyIdentifier(), assertSubjectKeyIdentifier.getKeyIdentifier())) {
                                throw new SecurityServiceException("Unable to validate Holder of Key assertion with subject key identifier.");
                            }
                        } else {
                            throw new SecurityServiceException("Unable to validate Holder of Key assertion with subject key identifier.");
                        }
                    }
                }
            }
        } else {
            throw new SecurityServiceException("Holder of Key assertion, must be used with 2-way TLS.");
        }
    }
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) SecurityServiceException(ddf.security.service.SecurityServiceException) Element(org.w3c.dom.Element) Node(org.w3c.dom.Node) CertificateException(java.security.cert.CertificateException) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SignatureException(java.security.SignatureException) SubjectKeyIdentifier(org.bouncycastle.asn1.x509.SubjectKeyIdentifier) InvalidKeyException(java.security.InvalidKeyException) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate) SubjectConfirmation(org.opensaml.saml.saml2.core.SubjectConfirmation) ByteArrayInputStream(java.io.ByteArrayInputStream) NoSuchProviderException(java.security.NoSuchProviderException)

Example 13 with SubjectConfirmation

use of org.opensaml.saml.saml2.core.SubjectConfirmation in project ddf by codice.

the class SamlAssertionValidatorImplTest method createAssertion.

private Assertion createAssertion(boolean sign, boolean validSignature, String issuerString, DateTime notOnOrAfter) throws Exception {
    Assertion assertion = new AssertionBuilder().buildObject();
    assertion.setID(UUID.randomUUID().toString());
    assertion.setIssueInstant(new DateTime());
    Issuer issuer = new IssuerBuilder().buildObject();
    issuer.setValue(issuerString);
    assertion.setIssuer(issuer);
    NameID nameID = new NameIDBuilder().buildObject();
    nameID.setFormat("urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified");
    nameID.setNameQualifier("http://cxf.apache.org/sts");
    nameID.setValue("admin");
    SubjectConfirmation subjectConfirmation = new SubjectConfirmationBuilder().buildObject();
    subjectConfirmation.setMethod("urn:oasis:names:tc:SAML:2.0:cm:bearer");
    Subject subject = new SubjectBuilder().buildObject();
    subject.setNameID(nameID);
    subject.getSubjectConfirmations().add(subjectConfirmation);
    assertion.setSubject(subject);
    Conditions conditions = new ConditionsBuilder().buildObject();
    conditions.setNotBefore(new DateTime().minusDays(3));
    conditions.setNotOnOrAfter(notOnOrAfter);
    assertion.setConditions(conditions);
    AuthnStatement authnStatement = new AuthnStatementBuilder().buildObject();
    authnStatement.setAuthnInstant(new DateTime());
    AuthnContext authnContext = new AuthnContextBuilder().buildObject();
    AuthnContextClassRef authnContextClassRef = new AuthnContextClassRefBuilder().buildObject();
    authnContextClassRef.setAuthnContextClassRef("urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified");
    authnContext.setAuthnContextClassRef(authnContextClassRef);
    authnStatement.setAuthnContext(authnContext);
    assertion.getAuthnStatements().add(authnStatement);
    AttributeStatement attributeStatement = new AttributeStatementBuilder().buildObject();
    Attribute attribute = new AttributeBuilder().buildObject();
    AttributeValueType attributeValue = new AttributeValueTypeImplBuilder().buildObject();
    attributeValue.setValue("admin");
    attribute.setName("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/role");
    attribute.setNameFormat("urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified");
    attribute.getAttributeValues().add(attributeValue);
    attributeStatement.getAttributes().add(attribute);
    assertion.getAttributeStatements().add(attributeStatement);
    if (sign) {
        Signature signature = OpenSAMLUtil.buildSignature();
        signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
        signature.setSignatureAlgorithm(WSS4JConstants.RSA);
        BasicX509Credential signingCredential;
        if (validSignature) {
            signingCredential = new BasicX509Credential(certificate);
            signingCredential.setPrivateKey(privateKey);
            signature.setSigningCredential(signingCredential);
        } else {
            try (InputStream inputStream = getClass().getResourceAsStream("/localhost.crt")) {
                CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
                X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(inputStream);
                signingCredential = new BasicX509Credential(cert);
                signature.setSigningCredential(signingCredential);
            }
        }
        X509KeyInfoGeneratorFactory x509KeyInfoGeneratorFactory = new X509KeyInfoGeneratorFactory();
        x509KeyInfoGeneratorFactory.setEmitEntityCertificate(true);
        KeyInfo keyInfo = x509KeyInfoGeneratorFactory.newInstance().generate(signingCredential);
        signature.setKeyInfo(keyInfo);
        assertion.setSignature(signature);
    }
    return assertion;
}
Also used : Issuer(org.opensaml.saml.saml2.core.Issuer) Attribute(org.opensaml.saml.saml2.core.Attribute) AuthnStatementBuilder(org.opensaml.saml.saml2.core.impl.AuthnStatementBuilder) AuthnContextClassRefBuilder(org.opensaml.saml.saml2.core.impl.AuthnContextClassRefBuilder) CertificateFactory(java.security.cert.CertificateFactory) DateTime(org.joda.time.DateTime) Conditions(org.opensaml.saml.saml2.core.Conditions) AuthnContext(org.opensaml.saml.saml2.core.AuthnContext) NameIDBuilder(org.opensaml.saml.saml2.core.impl.NameIDBuilder) SubjectConfirmation(org.opensaml.saml.saml2.core.SubjectConfirmation) KeyInfo(org.opensaml.xmlsec.signature.KeyInfo) SubjectBuilder(org.opensaml.saml.saml2.core.impl.SubjectBuilder) SubjectConfirmationBuilder(org.opensaml.saml.saml2.core.impl.SubjectConfirmationBuilder) X509KeyInfoGeneratorFactory(org.opensaml.xmlsec.keyinfo.impl.X509KeyInfoGeneratorFactory) AttributeStatementBuilder(org.opensaml.saml.saml2.core.impl.AttributeStatementBuilder) AttributeBuilder(org.opensaml.saml.saml2.core.impl.AttributeBuilder) NameID(org.opensaml.saml.saml2.core.NameID) AttributeValueType(org.opensaml.xacml.ctx.AttributeValueType) InputStream(java.io.InputStream) AuthnContextBuilder(org.opensaml.saml.saml2.core.impl.AuthnContextBuilder) Assertion(org.opensaml.saml.saml2.core.Assertion) AuthnContextClassRef(org.opensaml.saml.saml2.core.AuthnContextClassRef) AssertionBuilder(org.opensaml.saml.saml2.core.impl.AssertionBuilder) Subject(org.opensaml.saml.saml2.core.Subject) X509Certificate(java.security.cert.X509Certificate) ConditionsBuilder(org.opensaml.saml.saml2.core.impl.ConditionsBuilder) BasicX509Credential(org.opensaml.security.x509.BasicX509Credential) AttributeStatement(org.opensaml.saml.saml2.core.AttributeStatement) Signature(org.opensaml.xmlsec.signature.Signature) AuthnStatement(org.opensaml.saml.saml2.core.AuthnStatement) IssuerBuilder(org.opensaml.saml.saml2.core.impl.IssuerBuilder) AttributeValueTypeImplBuilder(org.opensaml.xacml.ctx.impl.AttributeValueTypeImplBuilder)

Example 14 with SubjectConfirmation

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

the class SamlOAuthValidator method validateAuthenticationSubject.

private boolean validateAuthenticationSubject(Message m, Conditions cs, org.opensaml.saml.saml2.core.Subject subject) {
    // We need to find a Bearer Subject Confirmation method
    boolean bearerSubjectConfFound = false;
    if (subject.getSubjectConfirmations() != null) {
        for (SubjectConfirmation subjectConf : subject.getSubjectConfirmations()) {
            if (SAML2Constants.CONF_BEARER.equals(subjectConf.getMethod())) {
                validateSubjectConfirmation(m, cs, subjectConf.getSubjectConfirmationData());
                bearerSubjectConfFound = true;
            }
        }
    }
    return bearerSubjectConfFound;
}
Also used : SubjectConfirmation(org.opensaml.saml.saml2.core.SubjectConfirmation)

Example 15 with SubjectConfirmation

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

the class DuplicateAssertionValidatorTest method createAssertion.

private Assertion createAssertion(String id, DateTime notOnOrAfter) {
    SubjectConfirmationData subjectConfirmationData = aSubjectConfirmationData().withNotOnOrAfter(notOnOrAfter).build();
    SubjectConfirmation subjectConfirmation = aSubjectConfirmation().withSubjectConfirmationData(subjectConfirmationData).build();
    Subject subject = aSubject().withSubjectConfirmation(subjectConfirmation).build();
    return anAssertion().withId(id).withSubject(subject).buildUnencrypted();
}
Also used : SubjectConfirmation(org.opensaml.saml.saml2.core.SubjectConfirmation) SubjectConfirmationBuilder.aSubjectConfirmation(uk.gov.ida.saml.core.test.builders.SubjectConfirmationBuilder.aSubjectConfirmation) SubjectConfirmationData(org.opensaml.saml.saml2.core.SubjectConfirmationData) SubjectConfirmationDataBuilder.aSubjectConfirmationData(uk.gov.ida.saml.core.test.builders.SubjectConfirmationDataBuilder.aSubjectConfirmationData) Subject(org.opensaml.saml.saml2.core.Subject) SubjectBuilder.aSubject(uk.gov.ida.saml.core.test.builders.SubjectBuilder.aSubject)

Aggregations

SubjectConfirmation (org.opensaml.saml.saml2.core.SubjectConfirmation)16 Assertion (org.opensaml.saml.saml2.core.Assertion)8 SubjectConfirmationData (org.opensaml.saml.saml2.core.SubjectConfirmationData)8 Subject (org.opensaml.saml.saml2.core.Subject)7 NameID (org.opensaml.saml.saml2.core.NameID)6 EncryptedAssertion (org.opensaml.saml.saml2.core.EncryptedAssertion)5 Conditions (org.opensaml.saml.saml2.core.Conditions)4 Issuer (org.opensaml.saml.saml2.core.Issuer)4 CertificateFactory (java.security.cert.CertificateFactory)3 X509Certificate (java.security.cert.X509Certificate)3 DateTime (org.joda.time.DateTime)3 AuthnStatement (org.opensaml.saml.saml2.core.AuthnStatement)3 SecurityServiceException (ddf.security.service.SecurityServiceException)2 ByteArrayInputStream (java.io.ByteArrayInputStream)2 InputStream (java.io.InputStream)2 InvalidKeyException (java.security.InvalidKeyException)2 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)2 NoSuchProviderException (java.security.NoSuchProviderException)2 SignatureException (java.security.SignatureException)2 CertificateException (java.security.cert.CertificateException)2