Search in sources :

Example 1 with XmlSignatureException

use of org.apache.camel.component.xmlsecurity.api.XmlSignatureException in project camel by apache.

the class XmlSignatureProcessor method getSchema.

protected Schema getSchema(Message message) throws SAXException, XmlSignatureException, IOException {
    String schemaResourceUri = getSchemaResourceUri(message);
    if (schemaResourceUri == null || schemaResourceUri.isEmpty()) {
        return null;
    }
    InputStream is = ResourceHelper.resolveResourceAsInputStream(getConfiguration().getCamelContext().getClassResolver(), schemaResourceUri);
    if (is == null) {
        throw new XmlSignatureException("XML Signature component is wrongly configured: No XML schema found for specified schema resource URI " + schemaResourceUri);
    }
    byte[] bytes = null;
    try {
        bytes = IOConverter.toBytes(is);
    } finally {
        // and make sure to close the input stream after the schema has been loaded
        IOHelper.close(is);
    }
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    schemaFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    schemaFactory.setResourceResolver(new DefaultLSResourceResolver(getConfiguration().getCamelContext(), getConfiguration().getSchemaResourceUri()));
    LOG.debug("Instantiating schema for validation");
    return schemaFactory.newSchema(new BytesSource(bytes));
}
Also used : SchemaFactory(javax.xml.validation.SchemaFactory) BytesSource(org.apache.camel.BytesSource) XmlSignatureException(org.apache.camel.component.xmlsecurity.api.XmlSignatureException) InputStream(java.io.InputStream) DefaultLSResourceResolver(org.apache.camel.component.validator.DefaultLSResourceResolver)

Example 2 with XmlSignatureException

use of org.apache.camel.component.xmlsecurity.api.XmlSignatureException in project camel by apache.

the class XmlSignerProcessor method getTextNode.

private Node getTextNode(Message inMessage, InputStream is) throws IOException, ParserConfigurationException, XmlSignatureException {
    LOG.debug("Message body to be signed is plain text");
    String encoding = getMessageEncoding(inMessage);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    IOHelper.copyAndCloseInput(is, bos);
    try {
        String text = new String(bos.toByteArray(), encoding);
        return XmlSignatureHelper.newDocumentBuilder(true).newDocument().createTextNode(text);
    } catch (UnsupportedEncodingException e) {
        throw new XmlSignatureException(String.format("The message encoding %s is not supported.", encoding), e);
    }
}
Also used : XmlSignatureException(org.apache.camel.component.xmlsecurity.api.XmlSignatureException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ByteArrayOutputStream(java.io.ByteArrayOutputStream)

Example 3 with XmlSignatureException

use of org.apache.camel.component.xmlsecurity.api.XmlSignatureException in project camel by apache.

the class XmlSignerProcessor method sign.

protected Document sign(final Message out) throws Exception {
    try {
        XMLSignatureFactory fac;
        // not work
        try {
            fac = XMLSignatureFactory.getInstance("DOM", "ApacheXMLDSig");
        } catch (NoSuchProviderException ex) {
            fac = XMLSignatureFactory.getInstance("DOM");
        }
        final Node node = getMessageBodyNode(out);
        if (getConfiguration().getKeyAccessor() == null) {
            throw new XmlSignatureNoKeyException("Key accessor is missing for XML signature generation. Specify a key accessor in the configuration.");
        }
        final KeySelector keySelector = getConfiguration().getKeyAccessor().getKeySelector(out);
        if (keySelector == null) {
            throw new XmlSignatureNoKeyException("Key selector is missing for XML signature generation. Specify a key selector in the configuration.");
        }
        SignatureType signatureType = determineSignatureType(out);
        final List<String> contentReferenceUris = getContentReferenceUris(out, signatureType, node);
        Node lastParent = null;
        // only in the detached case there can be several
        for (final String contentReferenceUri : contentReferenceUris) {
            // the method KeyAccessor.getKeyInfo must be called after the method KeyAccessor.getKeySelector, this is part of the interface contract!
            // and this method must be called within the loop over the content reference URIs, because for each signature the key info ID must be different
            final KeyInfo keyInfo = getConfiguration().getKeyAccessor().getKeyInfo(out, node, fac.getKeyInfoFactory());
            String signatureId = getConfiguration().getSignatureId();
            if (signatureId == null) {
                signatureId = "_" + UUID.randomUUID().toString();
            } else if (signatureId.isEmpty()) {
                // indicator that no signature Id attribute shall be generated
                signatureId = null;
            }
            // parent only relevant for enveloped or detached signature
            Node parent = getParentOfSignature(out, node, contentReferenceUri, signatureType);
            if (parent == null) {
                // for enveloping signature, create new document 
                parent = XmlSignatureHelper.newDocumentBuilder(Boolean.TRUE).newDocument();
            }
            lastParent = parent;
            XmlSignatureProperties.Input input = new InputBuilder().contentDigestAlgorithm(getDigestAlgorithmUri()).keyInfo(keyInfo).message(out).messageBodyNode(node).parent(parent).signatureAlgorithm(getConfiguration().getSignatureAlgorithm()).signatureFactory(fac).signatureId(signatureId).contentReferenceUri(contentReferenceUri).signatureType(signatureType).prefixForXmlSignatureNamespace(getConfiguration().getPrefixForXmlSignatureNamespace()).build();
            XmlSignatureProperties.Output properties = getSignatureProperties(input);
            // the signature properties can overwrite the signature Id
            if (properties != null && properties.getSignatureId() != null && !properties.getSignatureId().isEmpty()) {
                signatureId = properties.getSignatureId();
            }
            List<? extends XMLObject> objects = getObjects(input, properties);
            List<? extends Reference> refs = getReferences(input, properties, getKeyInfoId(keyInfo));
            SignedInfo si = createSignedInfo(fac, refs);
            DOMSignContext dsc = createAndConfigureSignContext(parent, keySelector);
            XMLSignature signature = fac.newXMLSignature(si, keyInfo, objects, signatureId, null);
            // generate the signature
            signature.sign(dsc);
        }
        return XmlSignatureHelper.getDocument(lastParent);
    } catch (XMLSignatureException se) {
        if (se.getCause() instanceof InvalidKeyException) {
            throw new XmlSignatureInvalidKeyException(se.getMessage(), se);
        } else {
            throw new XmlSignatureException(se);
        }
    } catch (GeneralSecurityException e) {
        // like NoSuchAlgorithmException, InvalidAlgorithmParameterException, NoSuchProviderException
        throw new XmlSignatureException(e);
    }
}
Also used : XmlSignatureInvalidKeyException(org.apache.camel.component.xmlsecurity.api.XmlSignatureInvalidKeyException) XMLSignatureFactory(javax.xml.crypto.dsig.XMLSignatureFactory) XmlSignatureProperties(org.apache.camel.component.xmlsecurity.api.XmlSignatureProperties) Node(org.w3c.dom.Node) GeneralSecurityException(java.security.GeneralSecurityException) SignatureType(org.apache.camel.component.xmlsecurity.api.SignatureType) KeySelector(javax.xml.crypto.KeySelector) InvalidKeyException(java.security.InvalidKeyException) XmlSignatureInvalidKeyException(org.apache.camel.component.xmlsecurity.api.XmlSignatureInvalidKeyException) SignedInfo(javax.xml.crypto.dsig.SignedInfo) XmlSignatureException(org.apache.camel.component.xmlsecurity.api.XmlSignatureException) KeyInfo(javax.xml.crypto.dsig.keyinfo.KeyInfo) XmlSignatureNoKeyException(org.apache.camel.component.xmlsecurity.api.XmlSignatureNoKeyException) DOMSignContext(javax.xml.crypto.dsig.dom.DOMSignContext) XMLSignature(javax.xml.crypto.dsig.XMLSignature) NoSuchProviderException(java.security.NoSuchProviderException) XMLSignatureException(javax.xml.crypto.dsig.XMLSignatureException)

Example 4 with XmlSignatureException

use of org.apache.camel.component.xmlsecurity.api.XmlSignatureException in project camel by apache.

the class XmlSignerProcessor method getContentReferenceUrisForDetachedCase.

private List<String> getContentReferenceUrisForDetachedCase(Message message, Node messageBodyNode) throws XmlSignatureException, XPathExpressionException {
    List<XPathFilterParameterSpec> xpathsToIdAttributes = getXpathToIdAttributes(message);
    if (xpathsToIdAttributes.isEmpty()) {
        // should not happen, has already been checked earlier
        throw new IllegalStateException("List of XPATHs to ID attributes is empty in detached signature case");
    }
    List<ComparableNode> result = new ArrayList<ComparableNode>(xpathsToIdAttributes.size());
    for (XPathFilterParameterSpec xp : xpathsToIdAttributes) {
        XPathExpression exp;
        try {
            exp = XmlSignatureHelper.getXPathExpression(xp);
        } catch (XPathExpressionException e) {
            throw new XmlSignatureException("The configured xpath expression " + xp.getXPath() + " is invalid.", e);
        }
        NodeList list = (NodeList) exp.evaluate(messageBodyNode, XPathConstants.NODESET);
        if (list == null) {
            //assume optional element, XSD validation has been done before
            LOG.warn("No ID attribute found for xpath expression {}. Therfore this xpath expression will be ignored.", xp.getXPath());
            continue;
        }
        int length = list.getLength();
        for (int i = 0; i < length; i++) {
            Node node = list.item(i);
            if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
                Attr attr = (Attr) node;
                String value = attr.getValue();
                // check that attribute is ID attribute
                Element element = messageBodyNode.getOwnerDocument().getElementById(value);
                if (element == null) {
                    throw new XmlSignatureException("Wrong configured xpath expression for ID attributes: The evaluation of the xpath expression " + xp.getXPath() + " resulted in an attribute which is not of type ID. The attribute value is " + value + ".");
                }
                result.add(new ComparableNode(element, "#" + value));
                LOG.debug("ID attribute with value {} found for xpath {}", value, xp.getXPath());
            } else {
                throw new XmlSignatureException("Wrong configured xpath expression for ID attributes: The evaluation of the xpath expression " + xp.getXPath() + " returned a node which was not of type Attribute.");
            }
        }
    }
    if (result.size() == 0) {
        throw new XmlSignatureException("No element to sign found in the detached case. No node found for the configured xpath expressions " + toString(xpathsToIdAttributes) + ". Either the configuration of the XML signature component is wrong or the incoming message has not the correct structure.");
    }
    // sort so that elements with deeper hierarchy level are treated first
    Collections.sort(result);
    return ComparableNode.getReferenceUris(result);
}
Also used : XPathExpression(javax.xml.xpath.XPathExpression) XPathExpressionException(javax.xml.xpath.XPathExpressionException) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) XPathFilterParameterSpec(javax.xml.crypto.dsig.spec.XPathFilterParameterSpec) ArrayList(java.util.ArrayList) Attr(org.w3c.dom.Attr) XmlSignatureException(org.apache.camel.component.xmlsecurity.api.XmlSignatureException)

Example 5 with XmlSignatureException

use of org.apache.camel.component.xmlsecurity.api.XmlSignatureException in project camel by apache.

the class XmlSignerProcessor method getParentForEnvelopedCase.

protected Element getParentForEnvelopedCase(Document doc, Message inMessage) throws Exception {
    //NOPMD
    if (getConfiguration().getParentXpath() != null) {
        XPathFilterParameterSpec xp = getConfiguration().getParentXpath();
        XPathExpression exp;
        try {
            exp = XmlSignatureHelper.getXPathExpression(xp);
        } catch (XPathExpressionException e) {
            throw new XmlSignatureException("The parent XPath " + getConfiguration().getParentXpath().getXPath() + " is wrongly configured: The XPath " + xp.getXPath() + " is invalid.", e);
        }
        NodeList list = (NodeList) exp.evaluate(doc.getDocumentElement(), XPathConstants.NODESET);
        if (list == null || list.getLength() == 0) {
            throw new XmlSignatureException("The parent XPath " + xp.getXPath() + " returned no result. Check the configuration of the XML signer component.");
        }
        int length = list.getLength();
        for (int i = 0; i < length; i++) {
            Node node = list.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                // return the first element
                return (Element) node;
            }
        }
        throw new XmlSignatureException("The parent XPath " + xp.getXPath() + " returned no element. Check the configuration of the XML signer component.");
    } else {
        // parent local name is not null!
        NodeList parents = doc.getElementsByTagNameNS(getConfiguration().getParentNamespace(), getConfiguration().getParentLocalName());
        if (parents == null || parents.getLength() == 0) {
            throw new XmlSignatureFormatException(String.format("Incoming message has wrong format: The parent element with the local name %s and the namespace %s was not found in the message to build an enveloped XML signature.", getConfiguration().getParentLocalName(), getConfiguration().getParentNamespace()));
        }
        // return the first element
        return (Element) parents.item(0);
    }
}
Also used : XPathExpression(javax.xml.xpath.XPathExpression) XmlSignatureException(org.apache.camel.component.xmlsecurity.api.XmlSignatureException) XmlSignatureFormatException(org.apache.camel.component.xmlsecurity.api.XmlSignatureFormatException) XPathExpressionException(javax.xml.xpath.XPathExpressionException) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) XPathFilterParameterSpec(javax.xml.crypto.dsig.spec.XPathFilterParameterSpec)

Aggregations

XmlSignatureException (org.apache.camel.component.xmlsecurity.api.XmlSignatureException)8 Element (org.w3c.dom.Element)3 Node (org.w3c.dom.Node)3 XPathFilterParameterSpec (javax.xml.crypto.dsig.spec.XPathFilterParameterSpec)2 XPathExpression (javax.xml.xpath.XPathExpression)2 XPathExpressionException (javax.xml.xpath.XPathExpressionException)2 SignatureType (org.apache.camel.component.xmlsecurity.api.SignatureType)2 NodeList (org.w3c.dom.NodeList)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 InputStream (java.io.InputStream)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 GeneralSecurityException (java.security.GeneralSecurityException)1 InvalidKeyException (java.security.InvalidKeyException)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 NoSuchProviderException (java.security.NoSuchProviderException)1 ArrayList (java.util.ArrayList)1 KeySelector (javax.xml.crypto.KeySelector)1 Reference (javax.xml.crypto.dsig.Reference)1 SignedInfo (javax.xml.crypto.dsig.SignedInfo)1 Transform (javax.xml.crypto.dsig.Transform)1