Search in sources :

Example 11 with CryptoLoader

use of org.apache.cxf.rs.security.common.CryptoLoader in project cxf by apache.

the class Saml2BearerGrantHandler method validateToken.

protected void validateToken(Message message, SamlAssertionWrapper assertion) {
    try {
        RequestData data = new RequestData();
        if (assertion.isSigned()) {
            WSSConfig cfg = WSSConfig.getNewInstance();
            data.setWssConfig(cfg);
            data.setCallbackHandler(RSSecurityUtils.getCallbackHandler(message, this.getClass()));
            try {
                data.setSigVerCrypto(new CryptoLoader().getCrypto(message, SecurityConstants.SIGNATURE_CRYPTO, SecurityConstants.SIGNATURE_PROPERTIES));
            } catch (IOException ex) {
                throw new OAuthServiceException(OAuthConstants.INVALID_GRANT);
            }
            boolean enableRevocation = false;
            String enableRevocationStr = (String) org.apache.cxf.rt.security.utils.SecurityUtils.getSecurityPropertyValue(SecurityConstants.ENABLE_REVOCATION, message);
            if (enableRevocationStr != null) {
                enableRevocation = Boolean.parseBoolean(enableRevocationStr);
            }
            data.setEnableRevocation(enableRevocation);
            Signature sig = assertion.getSignature();
            WSDocInfo docInfo = new WSDocInfo(sig.getDOM().getOwnerDocument());
            data.setWsDocInfo(docInfo);
            KeyInfo keyInfo = sig.getKeyInfo();
            SAMLKeyInfo samlKeyInfo = SAMLUtil.getCredentialFromKeyInfo(keyInfo.getDOM(), new WSSSAMLKeyInfoProcessor(data), data.getSigVerCrypto());
            assertion.verifySignature(samlKeyInfo);
            assertion.parseSubject(new WSSSAMLKeyInfoProcessor(data), data.getSigVerCrypto(), data.getCallbackHandler());
        } else if (getTLSCertificates(message) == null) {
            throw new OAuthServiceException(OAuthConstants.INVALID_GRANT);
        }
        if (samlValidator != null) {
            Credential credential = new Credential();
            credential.setSamlAssertion(assertion);
            samlValidator.validate(credential, data);
        }
        samlOAuthValidator.validate(message, assertion);
    } catch (Exception ex) {
        throw new OAuthServiceException(OAuthConstants.INVALID_GRANT, ex);
    }
}
Also used : WSDocInfo(org.apache.wss4j.dom.WSDocInfo) Credential(org.apache.wss4j.dom.validate.Credential) OAuthServiceException(org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException) CryptoLoader(org.apache.cxf.rs.security.common.CryptoLoader) IOException(java.io.IOException) Base64Exception(org.apache.cxf.common.util.Base64Exception) OAuthServiceException(org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException) IOException(java.io.IOException) SAMLKeyInfo(org.apache.wss4j.common.saml.SAMLKeyInfo) WSSConfig(org.apache.wss4j.dom.engine.WSSConfig) KeyInfo(org.opensaml.xmlsec.signature.KeyInfo) SAMLKeyInfo(org.apache.wss4j.common.saml.SAMLKeyInfo) RequestData(org.apache.wss4j.dom.handler.RequestData) Signature(org.opensaml.xmlsec.signature.Signature) WSSSAMLKeyInfoProcessor(org.apache.wss4j.dom.saml.WSSSAMLKeyInfoProcessor)

Example 12 with CryptoLoader

use of org.apache.cxf.rs.security.common.CryptoLoader in project cxf by apache.

the class AbstractSamlInHandler method validateToken.

protected void validateToken(Message message, SamlAssertionWrapper assertion) {
    try {
        RequestData data = new RequestData();
        data.setMsgContext(message);
        // Add Audience Restrictions for SAML
        configureAudienceRestriction(message, data);
        if (assertion.isSigned()) {
            WSSConfig cfg = WSSConfig.getNewInstance();
            data.setWssConfig(cfg);
            data.setCallbackHandler(RSSecurityUtils.getCallbackHandler(message, this.getClass()));
            try {
                data.setSigVerCrypto(new CryptoLoader().getCrypto(message, SecurityConstants.SIGNATURE_CRYPTO, SecurityConstants.SIGNATURE_PROPERTIES));
            } catch (IOException ex) {
                throwFault("Crypto can not be loaded", ex);
            }
            boolean enableRevocation = false;
            String enableRevocationStr = (String) org.apache.cxf.rt.security.utils.SecurityUtils.getSecurityPropertyValue(SecurityConstants.ENABLE_REVOCATION, message);
            if (enableRevocationStr != null) {
                enableRevocation = Boolean.parseBoolean(enableRevocationStr);
            }
            data.setEnableRevocation(enableRevocation);
            Signature sig = assertion.getSignature();
            WSDocInfo docInfo = new WSDocInfo(sig.getDOM().getOwnerDocument());
            data.setWsDocInfo(docInfo);
            SAMLKeyInfo samlKeyInfo = null;
            KeyInfo keyInfo = sig.getKeyInfo();
            if (keyInfo != null) {
                samlKeyInfo = SAMLUtil.getCredentialFromKeyInfo(keyInfo.getDOM(), new WSSSAMLKeyInfoProcessor(data), data.getSigVerCrypto());
            } else if (!keyInfoMustBeAvailable) {
                samlKeyInfo = createKeyInfoFromDefaultAlias(data.getSigVerCrypto());
            }
            assertion.verifySignature(samlKeyInfo);
            assertion.parseSubject(new WSSSAMLKeyInfoProcessor(data), data.getSigVerCrypto(), data.getCallbackHandler());
        } else if (getTLSCertificates(message) == null) {
            throwFault("Assertion must be signed", null);
        }
        if (samlValidator != null) {
            Credential credential = new Credential();
            credential.setSamlAssertion(assertion);
            samlValidator.validate(credential, data);
        }
        checkSubjectConfirmationData(message, assertion);
        setSecurityContext(message, assertion);
    } catch (Exception ex) {
        throwFault("Assertion can not be validated", ex);
    }
}
Also used : WSDocInfo(org.apache.wss4j.dom.WSDocInfo) Credential(org.apache.wss4j.dom.validate.Credential) CryptoLoader(org.apache.cxf.rs.security.common.CryptoLoader) IOException(java.io.IOException) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) IOException(java.io.IOException) SAMLKeyInfo(org.apache.wss4j.common.saml.SAMLKeyInfo) WSSConfig(org.apache.wss4j.dom.engine.WSSConfig) KeyInfo(org.opensaml.xmlsec.signature.KeyInfo) SAMLKeyInfo(org.apache.wss4j.common.saml.SAMLKeyInfo) RequestData(org.apache.wss4j.dom.handler.RequestData) Signature(org.opensaml.xmlsec.signature.Signature) WSSSAMLKeyInfoProcessor(org.apache.wss4j.dom.saml.WSSSAMLKeyInfoProcessor)

Example 13 with CryptoLoader

use of org.apache.cxf.rs.security.common.CryptoLoader in project cxf by apache.

the class SAMLUtils method createAssertion.

public static SamlAssertionWrapper createAssertion(Message message, CallbackHandler handler) throws Fault {
    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(handler, samlCallback);
    try {
        SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);
        if (samlCallback.isSignAssertion()) {
            // --- This code will be moved to a common utility class
            Crypto crypto = new CryptoLoader().getCrypto(message, SecurityConstants.SIGNATURE_CRYPTO, SecurityConstants.SIGNATURE_PROPERTIES);
            String user = RSSecurityUtils.getUserName(message, crypto, SecurityConstants.SIGNATURE_USERNAME);
            if (StringUtils.isEmpty(user)) {
                return assertion;
            }
            String password = RSSecurityUtils.getPassword(message, user, WSPasswordCallback.SIGNATURE, SAMLUtils.class);
            assertion.signAssertion(user, password, crypto, false, samlCallback.getCanonicalizationAlgorithm(), samlCallback.getSignatureAlgorithm(), samlCallback.getSignatureDigestAlgorithm());
        }
        return assertion;
    } catch (Exception ex) {
        StringWriter sw = new StringWriter();
        ex.printStackTrace(new PrintWriter(sw));
        LOG.warning(sw.toString());
        throw new Fault(new RuntimeException(ex.getMessage() + ", stacktrace: " + sw.toString()));
    }
}
Also used : Crypto(org.apache.wss4j.common.crypto.Crypto) StringWriter(java.io.StringWriter) CryptoLoader(org.apache.cxf.rs.security.common.CryptoLoader) SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) SAMLCallback(org.apache.wss4j.common.saml.SAMLCallback) Fault(org.apache.cxf.interceptor.Fault) PrintWriter(java.io.PrintWriter)

Example 14 with CryptoLoader

use of org.apache.cxf.rs.security.common.CryptoLoader in project cxf by apache.

the class SamlCallbackHandler method handle.

public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
    Message m = PhaseInterceptorChain.getCurrentMessage();
    for (int i = 0; i < callbacks.length; i++) {
        if (callbacks[i] instanceof SAMLCallback) {
            SAMLCallback callback = (SAMLCallback) callbacks[i];
            if (saml2) {
                callback.setSamlVersion(Version.SAML_20);
            } else {
                callback.setSamlVersion(Version.SAML_11);
            }
            callback.setIssuer("https://idp.example.org/SAML2");
            String subjectName = null;
            if (m != null) {
                subjectName = (String) m.getContextualProperty("saml.subject.name");
            }
            if (subjectName == null) {
                subjectName = "uid=sts-client,o=mock-sts.com";
            }
            String subjectQualifier = "www.mock-sts.com";
            if (!saml2 && SAML2Constants.CONF_SENDER_VOUCHES.equals(confirmationMethod)) {
                confirmationMethod = SAML1Constants.CONF_SENDER_VOUCHES;
            }
            SubjectBean subjectBean = new SubjectBean(subjectName, subjectQualifier, confirmationMethod);
            if (SAML2Constants.CONF_HOLDER_KEY.equals(confirmationMethod)) {
                try {
                    CryptoLoader loader = new CryptoLoader();
                    Crypto crypto = loader.getCrypto(m, SecurityConstants.SIGNATURE_CRYPTO, SecurityConstants.SIGNATURE_PROPERTIES);
                    X509Certificate cert = RSSecurityUtils.getCertificates(crypto, RSSecurityUtils.getUserName(m, crypto, SecurityConstants.SIGNATURE_USERNAME))[0];
                    KeyInfoBean keyInfo = new KeyInfoBean();
                    keyInfo.setCertificate(cert);
                    subjectBean.setKeyInfo(keyInfo);
                } catch (Exception ex) {
                    throw new RuntimeException(ex);
                }
            }
            callback.setSubject(subjectBean);
            ConditionsBean conditions = new ConditionsBean();
            AudienceRestrictionBean audienceRestriction = new AudienceRestrictionBean();
            audienceRestriction.setAudienceURIs(Collections.singletonList("https://sp.example.com/SAML2"));
            conditions.setAudienceRestrictions(Collections.singletonList(audienceRestriction));
            callback.setConditions(conditions);
            AuthDecisionStatementBean authDecBean = new AuthDecisionStatementBean();
            authDecBean.setDecision(Decision.INDETERMINATE);
            authDecBean.setResource("https://sp.example.com/SAML2");
            ActionBean actionBean = new ActionBean();
            actionBean.setContents("Read");
            authDecBean.setActions(Collections.singletonList(actionBean));
            callback.setAuthDecisionStatementData(Collections.singletonList(authDecBean));
            AuthenticationStatementBean authBean = new AuthenticationStatementBean();
            authBean.setSubject(subjectBean);
            authBean.setAuthenticationInstant(new DateTime());
            authBean.setSessionIndex("123456");
            // AuthnContextClassRef is not set
            authBean.setAuthenticationMethod("urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport");
            callback.setAuthenticationStatementData(Collections.singletonList(authBean));
            AttributeStatementBean attrBean = new AttributeStatementBean();
            attrBean.setSubject(subjectBean);
            List<String> roles = null;
            if (m != null) {
                roles = CastUtils.cast((List<?>) m.getContextualProperty("saml.roles"));
            }
            if (roles == null) {
                roles = Collections.singletonList("user");
            }
            List<AttributeBean> claims = new ArrayList<>();
            AttributeBean roleClaim = new AttributeBean();
            roleClaim.setSimpleName("subject-role");
            roleClaim.setQualifiedName(SAMLClaim.SAML_ROLE_ATTRIBUTENAME_DEFAULT);
            roleClaim.setNameFormat(SAML2Constants.ATTRNAME_FORMAT_UNSPECIFIED);
            roleClaim.setAttributeValues(new ArrayList<>(roles));
            claims.add(roleClaim);
            List<String> authMethods = null;
            if (m != null) {
                authMethods = CastUtils.cast((List<?>) m.getContextualProperty("saml.auth"));
            }
            if (authMethods == null) {
                authMethods = Collections.singletonList("password");
            }
            AttributeBean authClaim = new AttributeBean();
            authClaim.setSimpleName("http://claims/authentication");
            authClaim.setQualifiedName("http://claims/authentication");
            authClaim.setNameFormat("http://claims/authentication-format");
            authClaim.setAttributeValues(new ArrayList<>(authMethods));
            claims.add(authClaim);
            attrBean.setSamlAttributes(claims);
            callback.setAttributeStatementData(Collections.singletonList(attrBean));
            callback.setSignatureAlgorithm(signatureAlgorithm);
            callback.setSignatureDigestAlgorithm(digestAlgorithm);
            callback.setSignAssertion(signAssertion);
        }
    }
}
Also used : KeyInfoBean(org.apache.wss4j.common.saml.bean.KeyInfoBean) AttributeStatementBean(org.apache.wss4j.common.saml.bean.AttributeStatementBean) AudienceRestrictionBean(org.apache.wss4j.common.saml.bean.AudienceRestrictionBean) Message(org.apache.cxf.message.Message) AuthenticationStatementBean(org.apache.wss4j.common.saml.bean.AuthenticationStatementBean) CryptoLoader(org.apache.cxf.rs.security.common.CryptoLoader) ConditionsBean(org.apache.wss4j.common.saml.bean.ConditionsBean) ArrayList(java.util.ArrayList) ActionBean(org.apache.wss4j.common.saml.bean.ActionBean) X509Certificate(java.security.cert.X509Certificate) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) IOException(java.io.IOException) DateTime(org.joda.time.DateTime) SubjectBean(org.apache.wss4j.common.saml.bean.SubjectBean) Crypto(org.apache.wss4j.common.crypto.Crypto) AuthDecisionStatementBean(org.apache.wss4j.common.saml.bean.AuthDecisionStatementBean) SAMLCallback(org.apache.wss4j.common.saml.SAMLCallback) ArrayList(java.util.ArrayList) List(java.util.List) AttributeBean(org.apache.wss4j.common.saml.bean.AttributeBean)

Aggregations

CryptoLoader (org.apache.cxf.rs.security.common.CryptoLoader)14 Crypto (org.apache.wss4j.common.crypto.Crypto)11 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)8 X509Certificate (java.security.cert.X509Certificate)7 IOException (java.io.IOException)5 XMLSecurityException (org.apache.xml.security.exceptions.XMLSecurityException)5 Element (org.w3c.dom.Element)5 XMLStreamException (javax.xml.stream.XMLStreamException)4 PatternSyntaxException (java.util.regex.PatternSyntaxException)3 UnsupportedCallbackException (javax.security.auth.callback.UnsupportedCallbackException)3 SamlAssertionWrapper (org.apache.wss4j.common.saml.SamlAssertionWrapper)3 Document (org.w3c.dom.Document)3 PrivateKey (java.security.PrivateKey)2 PublicKey (java.security.PublicKey)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2 WebApplicationException (javax.ws.rs.WebApplicationException)2 QName (javax.xml.namespace.QName)2 Base64Exception (org.apache.cxf.common.util.Base64Exception)2 WebClient (org.apache.cxf.jaxrs.client.WebClient)2