Search in sources :

Example 6 with InvalidCanonicalizerException

use of org.apache.xml.security.c14n.InvalidCanonicalizerException in project cxf by apache.

the class AsymmetricBindingHandler method doEncryption.

private WSSecBase doEncryption(AbstractTokenWrapper recToken, List<WSEncryptionPart> encrParts, boolean externalRef, 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);
        Crypto crypto = getEncryptionCrypto();
        final SecurityToken securityToken;
        try {
            securityToken = getSecurityToken();
            if (!isRequestor() && securityToken != null && recToken.getToken() instanceof SamlToken) {
                String tokenType = securityToken.getTokenType();
                if (WSS4JConstants.WSS_SAML_TOKEN_TYPE.equals(tokenType) || WSS4JConstants.SAML_NS.equals(tokenType)) {
                    encr.setCustomEKTokenValueType(WSS4JConstants.WSS_SAML_KI_VALUE_TYPE);
                    encr.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
                    encr.setCustomEKTokenId(securityToken.getId());
                } else if (WSS4JConstants.WSS_SAML2_TOKEN_TYPE.equals(tokenType) || WSS4JConstants.SAML2_NS.equals(tokenType)) {
                    encr.setCustomEKTokenValueType(WSS4JConstants.WSS_SAML2_KI_VALUE_TYPE);
                    encr.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
                    encr.setCustomEKTokenId(securityToken.getId());
                } else {
                    setKeyIdentifierType(encr, encrToken);
                }
            } else {
                setKeyIdentifierType(encr, encrToken);
            }
        } catch (TokenStoreException ex) {
            LOG.log(Level.FINE, ex.getMessage(), ex);
            throw new Fault(ex);
        }
        // 
        if (!isRequestor() && securityToken != null && securityToken.getX509Certificate() != null) {
            encr.setUseThisCert(securityToken.getX509Certificate());
        } else if (!isRequestor() && securityToken != null && securityToken.getKey() instanceof PublicKey) {
            encr.setUseThisPublicKey((PublicKey) securityToken.getKey());
            encr.setKeyIdentifierType(WSConstants.KEY_VALUE);
        } else {
            setEncryptionUser(encr, encrToken, false, crypto);
        }
        if (!encr.isCertSet() && encr.getUseThisPublicKey() == null && crypto == null) {
            unassertPolicy(recToken, "Missing security configuration. " + "Make sure jaxws:client element is configured " + "with a " + SecurityConstants.ENCRYPT_PROPERTIES + " value.");
        }
        AlgorithmSuite algorithmSuite = abinding.getAlgorithmSuite();
        AlgorithmSuiteType algType = algorithmSuite.getAlgorithmSuiteType();
        encr.setSymmetricEncAlgorithm(algType.getEncryption());
        encr.setKeyEncAlgo(algType.getAsymmetricKeyWrap());
        encr.setMGFAlgorithm(algType.getMGFAlgo());
        encr.setDigestAlgorithm(algType.getEncryptionDigest());
        encr.prepare(crypto, symmetricKey);
        Element encryptedKeyElement = encr.getEncryptedKeyElement();
        List<Element> attachments = encr.getAttachmentEncryptedDataElements();
        // Encrypt, get hold of the ref list and add it
        if (externalRef) {
            Element refList = encr.encryptForRef(null, encrParts, symmetricKey);
            if (refList != null) {
                insertBeforeBottomUp(refList);
            }
            if (attachments != null) {
                for (Element attachment : attachments) {
                    this.insertBeforeBottomUp(attachment);
                }
            }
            if (refList != null || (attachments != null && !attachments.isEmpty())) {
                this.addEncryptedKeyElement(encryptedKeyElement);
            }
        } else {
            Element refList = encr.encryptForRef(null, encrParts, symmetricKey);
            if (refList != null || (attachments != null && !attachments.isEmpty())) {
                this.addEncryptedKeyElement(encryptedKeyElement);
            }
            // Add internal refs
            if (refList != null) {
                encryptedKeyElement.appendChild(refList);
            }
            if (attachments != null) {
                for (Element attachment : attachments) {
                    this.addEncryptedKeyElement(attachment);
                }
            }
        }
        // Put BST before EncryptedKey element
        if (encr.getBSTTokenId() != null) {
            encr.prependBSTElementToHeader();
        }
        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) SamlToken(org.apache.wss4j.policy.model.SamlToken) AlgorithmSuiteType(org.apache.wss4j.policy.model.AlgorithmSuite.AlgorithmSuiteType) PublicKey(java.security.PublicKey) Element(org.w3c.dom.Element) Fault(org.apache.cxf.interceptor.Fault) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) 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) InvalidCanonicalizerException(org.apache.xml.security.c14n.InvalidCanonicalizerException) AttachmentCallbackHandler(org.apache.cxf.ws.security.wss4j.AttachmentCallbackHandler) TokenStoreException(org.apache.cxf.ws.security.tokenstore.TokenStoreException)

Example 7 with InvalidCanonicalizerException

use of org.apache.xml.security.c14n.InvalidCanonicalizerException in project cxf by apache.

the class WSS4JInInterceptor method handleMessageInternal.

@SuppressWarnings("deprecation")
private void handleMessageInternal(SoapMessage msg) throws Fault {
    boolean utWithCallbacks = MessageUtils.getContextualBoolean(msg, SecurityConstants.VALIDATE_TOKEN, true);
    translateProperties(msg);
    RequestData reqData = new CXFRequestData();
    WSSConfig config = (WSSConfig) msg.getContextualProperty(WSSConfig.class.getName());
    WSSecurityEngine engine;
    if (config != null) {
        engine = new WSSecurityEngine();
        engine.setWssConfig(config);
    } else {
        engine = getSecurityEngine(utWithCallbacks);
        if (engine == null) {
            engine = new WSSecurityEngine();
        }
        config = engine.getWssConfig();
    }
    reqData.setWssConfig(config);
    // Add Audience Restrictions for SAML
    reqData.setAudienceRestrictions(SAMLUtils.getAudienceRestrictions(msg, true));
    SOAPMessage doc = getSOAPMessage(msg);
    boolean doDebug = LOG.isLoggable(Level.FINE);
    SoapVersion version = msg.getVersion();
    try {
        reqData.setEncryptionSerializer(new StaxSerializer());
    } catch (InvalidCanonicalizerException e) {
        throw new SoapFault(new Message("SECURITY_FAILED", LOG), e, version.getReceiver());
    }
    if (doDebug) {
        LOG.fine("WSS4JInInterceptor: enter handleMessage()");
    }
    /*
         * The overall try, just to have a finally at the end to perform some
         * housekeeping.
         */
    try {
        reqData.setMsgContext(msg);
        reqData.setAttachmentCallbackHandler(new AttachmentCallbackHandler(msg));
        setAlgorithmSuites(msg, reqData);
        reqData.setCallbackHandler(getCallback(reqData, utWithCallbacks));
        computeAction(msg, reqData);
        String action = getAction(msg, version);
        List<Integer> actions = WSSecurityUtil.decodeAction(action);
        String actor = (String) getOption(ConfigurationConstants.ACTOR);
        if (actor == null) {
            actor = (String) msg.getContextualProperty(SecurityConstants.ACTOR);
        }
        reqData.setActor(actor);
        // Configure replay caching
        configureReplayCaches(reqData, actions, msg);
        TLSSessionInfo tlsInfo = msg.get(TLSSessionInfo.class);
        if (tlsInfo != null) {
            Certificate[] tlsCerts = tlsInfo.getPeerCertificates();
            reqData.setTlsCerts(tlsCerts);
        }
        /*
             * Get and check the Signature specific parameters first because
             * they may be used for encryption too.
             */
        doReceiverAction(actions, reqData);
        // explicitly specified by the user)
        if (getString(ConfigurationConstants.EXPAND_XOP_INCLUDE_FOR_SIGNATURE, msg) == null && getString(ConfigurationConstants.EXPAND_XOP_INCLUDE, msg) == null) {
            reqData.setExpandXopInclude(AttachmentUtil.isMtomEnabled(msg));
        }
        /*get chance to check msg context enableRevocation setting
             *when use policy based ws-security where the WSHandler configuration
             *isn't available
             */
        boolean enableRevocation = reqData.isRevocationEnabled() || PropertyUtils.isTrue(SecurityUtils.getSecurityPropertyValue(SecurityConstants.ENABLE_REVOCATION, msg));
        reqData.setEnableRevocation(enableRevocation);
        Element soapBody = SAAJUtils.getBody(doc);
        if (soapBody != null) {
            engine.setCallbackLookup(new CXFCallbackLookup(soapBody.getOwnerDocument(), soapBody));
        }
        Element elem = WSSecurityUtil.getSecurityHeader(doc.getSOAPHeader(), actor, version.getVersion() != 1.1);
        elem = (Element) DOMUtils.getDomElement(elem);
        Node originalNode = null;
        if (elem != null) {
            originalNode = elem.cloneNode(true);
        }
        WSHandlerResult wsResult = engine.processSecurityHeader(elem, reqData);
        importNewDomToSAAJ(doc, elem, originalNode, wsResult);
        Element header = SAAJUtils.getHeader(doc);
        Element body = SAAJUtils.getBody(doc);
        header = (Element) DOMUtils.getDomElement(header);
        body = (Element) DOMUtils.getDomElement(body);
        if (!(wsResult.getResults() == null || wsResult.getResults().isEmpty())) {
            // security header found
            if (reqData.isEnableSignatureConfirmation()) {
                checkSignatureConfirmation(reqData, wsResult);
            }
            checkActions(msg, wsResult.getResults(), actions);
            doResults(msg, actor, header, body, wsResult, utWithCallbacks);
        } else {
            // no security header found
            if (doc.getSOAPPart().getEnvelope().getBody().hasFault() && isRequestor(msg)) {
                LOG.warning("The request is a SOAP Fault, but it is not secured");
                // We allow lax action matching here for backwards compatibility
                // with manually configured WSS4JInInterceptors that previously
                // allowed faults to pass through even if their actions aren't
                // a strict match against those configured.  In the WS-SP case,
                // we will want to still call doResults as it handles asserting
                // certain assertions that do not require a WS-S header such as
                // a sp:TransportBinding assertion.  In the case of WS-SP,
                // the unasserted assertions will provide confirmation that
                // security was not sufficient.
                // checkActions(msg, reqData, wsResult, actions);
                doResults(msg, actor, header, body, wsResult, utWithCallbacks);
            } else {
                checkActions(msg, wsResult.getResults(), actions);
                doResults(msg, actor, header, body, wsResult, utWithCallbacks);
            }
        }
        if (SAAJUtils.getBody(doc) != null) {
            advanceBody(msg, body);
        }
        SAAJInInterceptor.replaceHeaders(doc, msg);
        if (doDebug) {
            LOG.fine("WSS4JInInterceptor: exit handleMessage()");
        }
        msg.put(SECURITY_PROCESSED, Boolean.TRUE);
    } catch (WSSecurityException e) {
        throw WSS4JUtils.createSoapFault(msg, version, e);
    } catch (XMLStreamException e) {
        throw new SoapFault(new Message("STAX_EX", LOG), e, version.getSender());
    } catch (SOAPException e) {
        throw new SoapFault(new Message("SAAJ_EX", LOG), e, version.getSender());
    }
}
Also used : SoapFault(org.apache.cxf.binding.soap.SoapFault) SoapMessage(org.apache.cxf.binding.soap.SoapMessage) Message(org.apache.cxf.common.i18n.Message) SOAPMessage(javax.xml.soap.SOAPMessage) Element(org.w3c.dom.Element) Node(org.w3c.dom.Node) SOAPMessage(javax.xml.soap.SOAPMessage) WSHandlerResult(org.apache.wss4j.dom.handler.WSHandlerResult) WSSConfig(org.apache.wss4j.dom.engine.WSSConfig) RequestData(org.apache.wss4j.dom.handler.RequestData) SOAPException(javax.xml.soap.SOAPException) TLSSessionInfo(org.apache.cxf.security.transport.TLSSessionInfo) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) SoapVersion(org.apache.cxf.binding.soap.SoapVersion) XMLStreamException(javax.xml.stream.XMLStreamException) InvalidCanonicalizerException(org.apache.xml.security.c14n.InvalidCanonicalizerException) WSSecurityEngine(org.apache.wss4j.dom.engine.WSSecurityEngine) Certificate(java.security.cert.Certificate)

Example 8 with InvalidCanonicalizerException

use of org.apache.xml.security.c14n.InvalidCanonicalizerException in project santuario-java by apache.

the class Reference method getNodesetBeforeFirstCanonicalization.

/**
 * This method returns the XMLSignatureInput which represents the node set before
 * some kind of canonicalization is applied for the first time.
 * @return Gets a the node doing everything till the first c14n is needed
 *
 * @throws XMLSignatureException
 */
public XMLSignatureInput getNodesetBeforeFirstCanonicalization() throws XMLSignatureException {
    try {
        XMLSignatureInput input = this.getContentsBeforeTransformation();
        cacheDereferencedElement(input);
        XMLSignatureInput output = input;
        Transforms transforms = this.getTransforms();
        if (transforms != null) {
            for (int i = 0; i < transforms.getLength(); i++) {
                Transform t = transforms.item(i);
                String uri = t.getURI();
                if (uri.equals(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS) || uri.equals(Transforms.TRANSFORM_C14N_EXCL_WITH_COMMENTS) || uri.equals(Transforms.TRANSFORM_C14N_OMIT_COMMENTS) || uri.equals(Transforms.TRANSFORM_C14N_WITH_COMMENTS) || uri.equals(Transforms.TRANSFORM_C14N11_OMIT_COMMENTS) || uri.equals(Transforms.TRANSFORM_C14N11_WITH_COMMENTS)) {
                    break;
                }
                output = t.performTransform(output, null);
            }
            output.setSourceURI(input.getSourceURI());
        }
        return output;
    } catch (IOException ex) {
        throw new XMLSignatureException(ex);
    } catch (ResourceResolverException ex) {
        throw new XMLSignatureException(ex);
    } catch (CanonicalizationException ex) {
        throw new XMLSignatureException(ex);
    } catch (InvalidCanonicalizerException ex) {
        throw new XMLSignatureException(ex);
    } catch (TransformationException ex) {
        throw new XMLSignatureException(ex);
    } catch (XMLSecurityException ex) {
        throw new XMLSignatureException(ex);
    }
}
Also used : TransformationException(org.apache.xml.security.transforms.TransformationException) CanonicalizationException(org.apache.xml.security.c14n.CanonicalizationException) InvalidCanonicalizerException(org.apache.xml.security.c14n.InvalidCanonicalizerException) Transforms(org.apache.xml.security.transforms.Transforms) IOException(java.io.IOException) ResourceResolverException(org.apache.xml.security.utils.resolver.ResourceResolverException) Transform(org.apache.xml.security.transforms.Transform) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException)

Aggregations

InvalidCanonicalizerException (org.apache.xml.security.c14n.InvalidCanonicalizerException)8 CanonicalizationException (org.apache.xml.security.c14n.CanonicalizationException)4 XMLSecurityException (org.apache.xml.security.exceptions.XMLSecurityException)4 Element (org.w3c.dom.Element)4 IOException (java.io.IOException)3 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)3 TransformationException (org.apache.xml.security.transforms.TransformationException)3 PublicKey (java.security.PublicKey)2 AttachmentCallbackHandler (org.apache.cxf.ws.security.wss4j.AttachmentCallbackHandler)2 StaxSerializer (org.apache.cxf.ws.security.wss4j.StaxSerializer)2 Crypto (org.apache.wss4j.common.crypto.Crypto)2 WSSecEncrypt (org.apache.wss4j.dom.message.WSSecEncrypt)2 AbstractToken (org.apache.wss4j.policy.model.AbstractToken)2 AlgorithmSuite (org.apache.wss4j.policy.model.AlgorithmSuite)2 Transforms (org.apache.xml.security.transforms.Transforms)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 OutputStream (java.io.OutputStream)1 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)1 Certificate (java.security.cert.Certificate)1