Search in sources :

Example 76 with WSSecurityException

use of org.apache.wss4j.common.ext.WSSecurityException in project cxf by apache.

the class SAMLTokenValidator method validateToken.

/**
 * Validate a Token using the given TokenValidatorParameters.
 */
public TokenValidatorResponse validateToken(TokenValidatorParameters tokenParameters) {
    LOG.fine("Validating SAML Token");
    STSPropertiesMBean stsProperties = tokenParameters.getStsProperties();
    Crypto sigCrypto = stsProperties.getSignatureCrypto();
    CallbackHandler callbackHandler = stsProperties.getCallbackHandler();
    TokenValidatorResponse response = new TokenValidatorResponse();
    ReceivedToken validateTarget = tokenParameters.getToken();
    validateTarget.setState(STATE.INVALID);
    response.setToken(validateTarget);
    if (!validateTarget.isDOMElement()) {
        return response;
    }
    try {
        Element validateTargetElement = (Element) validateTarget.getToken();
        SamlAssertionWrapper assertion = new SamlAssertionWrapper(validateTargetElement);
        if (!assertion.isSigned()) {
            LOG.log(Level.WARNING, "The received assertion is not signed, and therefore not trusted");
            return response;
        }
        RequestData requestData = new RequestData();
        requestData.setSigVerCrypto(sigCrypto);
        WSSConfig wssConfig = WSSConfig.getNewInstance();
        requestData.setWssConfig(wssConfig);
        requestData.setCallbackHandler(callbackHandler);
        requestData.setMsgContext(tokenParameters.getMessageContext());
        requestData.setSubjectCertConstraints(certConstraints.getCompiledSubjectContraints());
        requestData.setWsDocInfo(new WSDocInfo(validateTargetElement.getOwnerDocument()));
        // Verify the signature
        Signature sig = assertion.getSignature();
        KeyInfo keyInfo = sig.getKeyInfo();
        SAMLKeyInfo samlKeyInfo = SAMLUtil.getCredentialFromKeyInfo(keyInfo.getDOM(), new WSSSAMLKeyInfoProcessor(requestData), sigCrypto);
        assertion.verifySignature(samlKeyInfo);
        SecurityToken secToken = null;
        byte[] signatureValue = assertion.getSignatureValue();
        if (tokenParameters.getTokenStore() != null && signatureValue != null && signatureValue.length > 0) {
            int hash = Arrays.hashCode(signatureValue);
            secToken = tokenParameters.getTokenStore().getToken(Integer.toString(hash));
            if (secToken != null && secToken.getTokenHash() != hash) {
                secToken = null;
            }
        }
        if (secToken != null && secToken.isExpired()) {
            if (LOG.isLoggable(Level.FINE)) {
                LOG.fine("Token: " + secToken.getId() + " is in the cache but expired - revalidating");
            }
            secToken = null;
        }
        Principal principal = null;
        if (secToken == null) {
            // Validate the assertion against schemas/profiles
            validateAssertion(assertion);
            // Now verify trust on the signature
            Credential trustCredential = new Credential();
            trustCredential.setPublicKey(samlKeyInfo.getPublicKey());
            trustCredential.setCertificates(samlKeyInfo.getCerts());
            trustCredential = validator.validate(trustCredential, requestData);
            principal = trustCredential.getPrincipal();
            // Finally check that subject DN of the signing certificate matches a known constraint
            X509Certificate cert = null;
            if (trustCredential.getCertificates() != null) {
                cert = trustCredential.getCertificates()[0];
            }
            if (!certConstraints.matches(cert)) {
                return response;
            }
        }
        if (principal == null) {
            principal = new SAMLTokenPrincipalImpl(assertion);
        }
        // Parse roles from the validated token
        if (samlRoleParser != null) {
            Set<Principal> roles = samlRoleParser.parseRolesFromAssertion(principal, null, assertion);
            response.setRoles(roles);
        }
        // Get the realm of the SAML token
        String tokenRealm = null;
        SAMLRealmCodec codec = samlRealmCodec;
        if (codec == null) {
            codec = stsProperties.getSamlRealmCodec();
        }
        if (codec != null) {
            tokenRealm = codec.getRealmFromToken(assertion);
            // verify the realm against the cached token
            if (secToken != null) {
                Map<String, Object> props = secToken.getProperties();
                if (props != null) {
                    String cachedRealm = (String) props.get(STSConstants.TOKEN_REALM);
                    if (cachedRealm != null && !tokenRealm.equals(cachedRealm)) {
                        return response;
                    }
                }
            }
        }
        response.setTokenRealm(tokenRealm);
        if (!validateConditions(assertion, validateTarget)) {
            return response;
        }
        // Store the successfully validated token in the cache
        if (secToken == null) {
            storeTokenInCache(tokenParameters.getTokenStore(), assertion, tokenParameters.getPrincipal(), tokenRealm);
        }
        // Add the SamlAssertionWrapper to the properties, as the claims are required to be transformed
        Map<String, Object> addProps = new HashMap<>(1);
        addProps.put(SamlAssertionWrapper.class.getName(), assertion);
        response.setAdditionalProperties(addProps);
        response.setPrincipal(principal);
        validateTarget.setState(STATE.VALID);
        LOG.fine("SAML Token successfully validated");
    } catch (WSSecurityException ex) {
        LOG.log(Level.WARNING, "", ex);
    }
    return response;
}
Also used : CallbackHandler(javax.security.auth.callback.CallbackHandler) HashMap(java.util.HashMap) Element(org.w3c.dom.Element) SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) SAMLRealmCodec(org.apache.cxf.sts.token.realm.SAMLRealmCodec) 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) ReceivedToken(org.apache.cxf.sts.request.ReceivedToken) SAMLTokenPrincipalImpl(org.apache.wss4j.common.principal.SAMLTokenPrincipalImpl) WSDocInfo(org.apache.wss4j.dom.WSDocInfo) Credential(org.apache.wss4j.dom.validate.Credential) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) X509Certificate(java.security.cert.X509Certificate) SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) Crypto(org.apache.wss4j.common.crypto.Crypto) STSPropertiesMBean(org.apache.cxf.sts.STSPropertiesMBean) Signature(org.opensaml.xmlsec.signature.Signature) WSSSAMLKeyInfoProcessor(org.apache.wss4j.dom.saml.WSSSAMLKeyInfoProcessor) Principal(java.security.Principal)

Example 77 with WSSecurityException

use of org.apache.wss4j.common.ext.WSSecurityException in project cxf by apache.

the class SCTCanceller method cancelToken.

/**
 * Cancel a Token using the given TokenCancellerParameters.
 */
public TokenCancellerResponse cancelToken(TokenCancellerParameters tokenParameters) {
    LOG.fine("Trying to cancel a SecurityContextToken");
    TokenCancellerResponse response = new TokenCancellerResponse();
    ReceivedToken cancelTarget = tokenParameters.getToken();
    if (tokenParameters.getTokenStore() == null) {
        LOG.log(Level.FINE, "A cache must be configured to use the SCTCanceller");
        return response;
    }
    if (cancelTarget == null) {
        LOG.log(Level.FINE, "Cancel Target is null");
        return response;
    }
    cancelTarget.setState(STATE.NONE);
    response.setToken(cancelTarget);
    if (cancelTarget.isDOMElement()) {
        try {
            Element cancelTargetElement = (Element) cancelTarget.getToken();
            SecurityContextToken sct = new SecurityContextToken(cancelTargetElement);
            String identifier = sct.getIdentifier();
            SecurityToken token = tokenParameters.getTokenStore().getToken(identifier);
            if (token == null) {
                LOG.fine("Identifier: " + identifier + " is not found in the cache");
                return response;
            }
            if (verifyProofOfPossession && !matchKey(tokenParameters, token.getSecret())) {
                throw new STSException("Failed to verify the proof of possession of the key associated with the " + "security context. No matching key found in the request.", STSException.INVALID_REQUEST);
            }
            tokenParameters.getTokenStore().remove(token.getId());
            cancelTarget.setState(STATE.CANCELLED);
            LOG.fine("SecurityContextToken successfully cancelled");
        } catch (WSSecurityException ex) {
            LOG.log(Level.WARNING, "", ex);
        }
    }
    return response;
}
Also used : SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) SecurityContextToken(org.apache.wss4j.dom.message.token.SecurityContextToken) Element(org.w3c.dom.Element) STSException(org.apache.cxf.ws.security.sts.provider.STSException) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) ReceivedToken(org.apache.cxf.sts.request.ReceivedToken)

Example 78 with WSSecurityException

use of org.apache.wss4j.common.ext.WSSecurityException in project cxf by apache.

the class X509TokenValidator method validateToken.

/**
 * Validate a Token using the given TokenValidatorParameters.
 */
public TokenValidatorResponse validateToken(TokenValidatorParameters tokenParameters) {
    LOG.fine("Validating X.509 Token");
    STSPropertiesMBean stsProperties = tokenParameters.getStsProperties();
    CallbackHandler callbackHandler = stsProperties.getCallbackHandler();
    // See CXF-4028
    Crypto crypto = stsProperties.getEncryptionCrypto();
    if (crypto == null) {
        crypto = stsProperties.getSignatureCrypto();
    }
    RequestData requestData = new RequestData();
    requestData.setSigVerCrypto(crypto);
    requestData.setWssConfig(WSSConfig.getNewInstance());
    requestData.setCallbackHandler(callbackHandler);
    requestData.setMsgContext(tokenParameters.getMessageContext());
    requestData.setSubjectCertConstraints(certConstraints.getCompiledSubjectContraints());
    TokenValidatorResponse response = new TokenValidatorResponse();
    ReceivedToken validateTarget = tokenParameters.getToken();
    validateTarget.setState(STATE.INVALID);
    response.setToken(validateTarget);
    final BinarySecurity binarySecurity;
    if (validateTarget.isBinarySecurityToken()) {
        BinarySecurityTokenType binarySecurityType = (BinarySecurityTokenType) validateTarget.getToken();
        // Test the encoding type
        String encodingType = binarySecurityType.getEncodingType();
        if (!BASE64_ENCODING.equals(encodingType)) {
            LOG.fine("Bad encoding type attribute specified: " + encodingType);
            return response;
        }
        // 
        // Turn the received JAXB object into a DOM element
        // 
        Document doc = DOMUtils.getEmptyDocument();
        binarySecurity = new X509Security(doc);
        binarySecurity.setEncodingType(encodingType);
        binarySecurity.setValueType(binarySecurityType.getValueType());
        String data = binarySecurityType.getValue();
        Node textNode = doc.createTextNode(data);
        binarySecurity.getElement().appendChild(textNode);
    } else if (validateTarget.isDOMElement()) {
        try {
            Document doc = DOMUtils.getEmptyDocument();
            binarySecurity = new X509Security(doc);
            binarySecurity.setEncodingType(BASE64_ENCODING);
            X509Data x509Data = new X509Data((Element) validateTarget.getToken(), "");
            if (x509Data.containsCertificate()) {
                X509Certificate cert = x509Data.itemCertificate(0).getX509Certificate();
                ((X509Security) binarySecurity).setX509Certificate(cert);
            }
        } catch (XMLSecurityException ex) {
            LOG.log(Level.WARNING, "", ex);
            return response;
        }
    } else {
        return response;
    }
    // 
    try {
        Credential credential = new Credential();
        credential.setBinarySecurityToken(binarySecurity);
        if (crypto != null) {
            X509Certificate cert = ((X509Security) binarySecurity).getX509Certificate(crypto);
            credential.setCertificates(new X509Certificate[] { cert });
        }
        Credential returnedCredential = validator.validate(credential, requestData);
        Principal principal = returnedCredential.getPrincipal();
        if (principal == null) {
            principal = returnedCredential.getCertificates()[0].getSubjectX500Principal();
        }
        response.setPrincipal(principal);
        validateTarget.setState(STATE.VALID);
        LOG.fine("X.509 Token successfully validated");
    } catch (WSSecurityException ex) {
        LOG.log(Level.WARNING, "", ex);
    }
    return response;
}
Also used : CallbackHandler(javax.security.auth.callback.CallbackHandler) Credential(org.apache.wss4j.dom.validate.Credential) BinarySecurity(org.apache.wss4j.common.token.BinarySecurity) Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) Document(org.w3c.dom.Document) X509Data(org.apache.xml.security.keys.content.X509Data) X509Certificate(java.security.cert.X509Certificate) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException) Crypto(org.apache.wss4j.common.crypto.Crypto) STSPropertiesMBean(org.apache.cxf.sts.STSPropertiesMBean) BinarySecurityTokenType(org.apache.cxf.ws.security.sts.provider.model.secext.BinarySecurityTokenType) RequestData(org.apache.wss4j.dom.handler.RequestData) ReceivedToken(org.apache.cxf.sts.request.ReceivedToken) X509Security(org.apache.wss4j.common.token.X509Security) Principal(java.security.Principal)

Example 79 with WSSecurityException

use of org.apache.wss4j.common.ext.WSSecurityException in project cxf by apache.

the class Saml2CallbackHandler method handle.

public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
    for (int i = 0; i < callbacks.length; i++) {
        if (callbacks[i] instanceof SAMLCallback) {
            SAMLCallback callback = (SAMLCallback) callbacks[i];
            callback.setSamlVersion(Version.SAML_20);
            callback.setIssuer("intermediary");
            String subjectName = "uid=" + principal.getName();
            String confirmationMethod = SAML2Constants.CONF_SENDER_VOUCHES;
            SubjectBean subjectBean = new SubjectBean(subjectName, null, confirmationMethod);
            callback.setSubject(subjectBean);
            AttributeStatementBean attrBean = new AttributeStatementBean();
            if (subjectBean != null) {
                attrBean.setSubject(subjectBean);
            }
            AttributeBean attributeBean = new AttributeBean();
            attributeBean.setQualifiedName("role");
            attributeBean.addAttributeValue("user");
            attrBean.setSamlAttributes(Collections.singletonList(attributeBean));
            callback.setAttributeStatementData(Collections.singletonList(attrBean));
            try {
                String file = "serviceKeystore.properties";
                Crypto crypto = CryptoFactory.getInstance(file);
                callback.setIssuerCrypto(crypto);
                callback.setIssuerKeyName("myservicekey");
                callback.setIssuerKeyPassword("skpass");
                callback.setSignAssertion(true);
            } catch (WSSecurityException e) {
                throw new IOException(e);
            }
        }
    }
}
Also used : SubjectBean(org.apache.wss4j.common.saml.bean.SubjectBean) AttributeStatementBean(org.apache.wss4j.common.saml.bean.AttributeStatementBean) Crypto(org.apache.wss4j.common.crypto.Crypto) SAMLCallback(org.apache.wss4j.common.saml.SAMLCallback) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) AttributeBean(org.apache.wss4j.common.saml.bean.AttributeBean) IOException(java.io.IOException)

Example 80 with WSSecurityException

use of org.apache.wss4j.common.ext.WSSecurityException in project cxf by apache.

the class SymmetricBindingHandler method doEncryption.

private WSSecEncrypt doEncryption(AbstractTokenWrapper recToken, SecurityToken encrTok, boolean attached, List<WSEncryptionPart> encrParts, boolean atEnd, SecretKey symmetricKey) {
    AbstractToken encrToken = recToken.getToken();
    assertPolicy(recToken);
    assertPolicy(encrToken);
    try {
        WSSecEncrypt encr = new WSSecEncrypt(secHeader);
        encr.setEncryptionSerializer(new StaxSerializer());
        encr.setIdAllocator(wssConfig.getIdAllocator());
        encr.setCallbackLookup(callbackLookup);
        encr.setAttachmentCallbackHandler(new AttachmentCallbackHandler(message));
        encr.setStoreBytesInAttachment(storeBytesInAttachment);
        encr.setExpandXopInclude(isExpandXopInclude());
        encr.setWsDocInfo(wsDocInfo);
        String encrTokId = encrTok.getId();
        if (attached) {
            encrTokId = encrTok.getWsuId();
            if (encrTokId == null && (encrToken instanceof SecureConversationToken || encrToken instanceof SecurityContextToken)) {
                encr.setEncKeyIdDirectId(true);
                encrTokId = encrTok.getId();
            } else if (encrTokId == null) {
                encrTokId = encrTok.getId();
            }
            if (encrTokId.startsWith("#")) {
                encrTokId = encrTokId.substring(1);
            }
        } else {
            encr.setEncKeyIdDirectId(true);
        }
        if (encrTok.getTokenType() != null) {
            encr.setCustomReferenceValue(encrTok.getTokenType());
        }
        encr.setEncKeyId(encrTokId);
        AlgorithmSuite algorithmSuite = sbinding.getAlgorithmSuite();
        encr.setSymmetricEncAlgorithm(algorithmSuite.getAlgorithmSuiteType().getEncryption());
        Crypto crypto = getEncryptionCrypto();
        if (crypto != null) {
            setEncryptionUser(encr, encrToken, false, crypto);
        }
        encr.setEncryptSymmKey(false);
        encr.setMGFAlgorithm(algorithmSuite.getAlgorithmSuiteType().getMGFAlgo());
        encr.setDigestAlgorithm(algorithmSuite.getAlgorithmSuiteType().getEncryptionDigest());
        if (encrToken instanceof IssuedToken || encrToken instanceof SpnegoContextToken || encrToken instanceof SecureConversationToken) {
            // Setting the AttachedReference or the UnattachedReference according to the flag
            Element ref;
            if (attached) {
                ref = encrTok.getAttachedReference();
            } else {
                ref = encrTok.getUnattachedReference();
            }
            String tokenType = encrTok.getTokenType();
            if (ref != null) {
                SecurityTokenReference secRef = new SecurityTokenReference(cloneElement(ref), new BSPEnforcer());
                encr.setSecurityTokenReference(secRef);
            } else if (WSS4JConstants.WSS_SAML_TOKEN_TYPE.equals(tokenType) || WSS4JConstants.SAML_NS.equals(tokenType)) {
                encr.setCustomReferenceValue(WSS4JConstants.WSS_SAML_KI_VALUE_TYPE);
                encr.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
            } else if (WSS4JConstants.WSS_SAML2_TOKEN_TYPE.equals(tokenType) || WSS4JConstants.SAML2_NS.equals(tokenType)) {
                encr.setCustomReferenceValue(WSS4JConstants.WSS_SAML2_KI_VALUE_TYPE);
                encr.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
            } else {
                encr.setCustomReferenceValue(tokenType);
                encr.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
            }
        } else if (encrToken instanceof UsernameToken) {
            encr.setCustomReferenceValue(WSS4JConstants.WSS_USERNAME_TOKEN_VALUE_TYPE);
        } else if (encrToken instanceof KerberosToken && !isRequestor()) {
            encr.setCustomReferenceValue(WSS4JConstants.WSS_KRB_KI_VALUE_TYPE);
            encr.setEncKeyId(encrTok.getSHA1());
        } else if (!isRequestor() && encrTok.getSHA1() != null) {
            encr.setCustomReferenceValue(encrTok.getSHA1());
            encr.setKeyIdentifierType(WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER);
        }
        encr.prepare(crypto, symmetricKey);
        if (encr.getBSTTokenId() != null) {
            encr.prependBSTElementToHeader();
        }
        Element refList = encr.encryptForRef(null, encrParts, symmetricKey);
        List<Element> attachments = encr.getAttachmentEncryptedDataElements();
        addAttachmentsForEncryption(atEnd, refList, attachments);
        return encr;
    } catch (InvalidCanonicalizerException | WSSecurityException e) {
        LOG.log(Level.FINE, e.getMessage(), e);
        unassertPolicy(recToken, e);
    }
    return null;
}
Also used : WSSecEncrypt(org.apache.wss4j.dom.message.WSSecEncrypt) KerberosToken(org.apache.wss4j.policy.model.KerberosToken) IssuedToken(org.apache.wss4j.policy.model.IssuedToken) Element(org.w3c.dom.Element) UsernameToken(org.apache.wss4j.policy.model.UsernameToken) WSSecUsernameToken(org.apache.wss4j.dom.message.WSSecUsernameToken) BSPEnforcer(org.apache.wss4j.common.bsp.BSPEnforcer) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) SecureConversationToken(org.apache.wss4j.policy.model.SecureConversationToken) SpnegoContextToken(org.apache.wss4j.policy.model.SpnegoContextToken) AlgorithmSuite(org.apache.wss4j.policy.model.AlgorithmSuite) StaxSerializer(org.apache.cxf.ws.security.wss4j.StaxSerializer) Crypto(org.apache.wss4j.common.crypto.Crypto) AbstractToken(org.apache.wss4j.policy.model.AbstractToken) SecurityTokenReference(org.apache.wss4j.common.token.SecurityTokenReference) SecurityContextToken(org.apache.wss4j.policy.model.SecurityContextToken) InvalidCanonicalizerException(org.apache.xml.security.c14n.InvalidCanonicalizerException) AttachmentCallbackHandler(org.apache.cxf.ws.security.wss4j.AttachmentCallbackHandler)

Aggregations

WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)241 Element (org.w3c.dom.Element)72 Document (org.w3c.dom.Document)53 IOException (java.io.IOException)51 Crypto (org.apache.wss4j.common.crypto.Crypto)50 SamlAssertionWrapper (org.apache.wss4j.common.saml.SamlAssertionWrapper)39 Credential (org.apache.wss4j.dom.validate.Credential)37 RequestData (org.apache.wss4j.dom.handler.RequestData)36 X509Certificate (java.security.cert.X509Certificate)31 Response (org.opensaml.saml.saml2.core.Response)31 SAMLCallback (org.apache.wss4j.common.saml.SAMLCallback)25 DateTime (org.joda.time.DateTime)22 XMLObject (org.opensaml.core.xml.XMLObject)22 XMLStreamException (javax.xml.stream.XMLStreamException)21 SecurityToken (org.apache.cxf.ws.security.tokenstore.SecurityToken)21 Fault (org.apache.cxf.interceptor.Fault)20 SOAPException (javax.xml.soap.SOAPException)19 CallbackHandler (javax.security.auth.callback.CallbackHandler)18 ReceivedToken (org.apache.cxf.sts.request.ReceivedToken)17 InputStream (java.io.InputStream)16