Search in sources :

Example 6 with XMLObject

use of javax.xml.crypto.dsig.XMLObject in project camel by apache.

the class TimestampProperty method get.

@Override
public Output get(Input input) throws Exception {
    Transform transform = input.getSignatureFactory().newTransform(CanonicalizationMethod.INCLUSIVE, (TransformParameterSpec) null);
    Reference ref = input.getSignatureFactory().newReference("#propertiesObject", input.getSignatureFactory().newDigestMethod(input.getContentDigestAlgorithm(), null), Collections.singletonList(transform), null, null);
    String doc2 = "<ts:timestamp xmlns:ts=\"http:/timestamp\">" + System.currentTimeMillis() + "</ts:timestamp>";
    InputStream is = new ByteArrayInputStream(doc2.getBytes("UTF-8"));
    Document doc = XmlSignatureHelper.newDocumentBuilder(Boolean.TRUE).parse(is);
    DOMStructure structure = new DOMStructure(doc.getDocumentElement());
    SignatureProperty prop = input.getSignatureFactory().newSignatureProperty(Collections.singletonList(structure), input.getSignatureId(), "property");
    SignatureProperties properties = input.getSignatureFactory().newSignatureProperties(Collections.singletonList(prop), "properties");
    XMLObject propertiesObject = input.getSignatureFactory().newXMLObject(Collections.singletonList(properties), "propertiesObject", null, null);
    XmlSignatureProperties.Output result = new Output();
    result.setReferences(Collections.singletonList(ref));
    result.setObjects(Collections.singletonList(propertiesObject));
    return result;
}
Also used : Reference(javax.xml.crypto.dsig.Reference) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) XmlSignatureProperties(org.apache.camel.component.xmlsecurity.api.XmlSignatureProperties) XMLObject(javax.xml.crypto.dsig.XMLObject) Document(org.w3c.dom.Document) SignatureProperty(javax.xml.crypto.dsig.SignatureProperty) ByteArrayInputStream(java.io.ByteArrayInputStream) DOMStructure(javax.xml.crypto.dom.DOMStructure) XmlSignatureProperties(org.apache.camel.component.xmlsecurity.api.XmlSignatureProperties) SignatureProperties(javax.xml.crypto.dsig.SignatureProperties) Transform(javax.xml.crypto.dsig.Transform)

Example 7 with XMLObject

use of javax.xml.crypto.dsig.XMLObject in project camel by apache.

the class XmlVerifierProcessor method verify.

@SuppressWarnings("unchecked")
protected void verify(InputStream input, final Message out) throws Exception {
    //NOPMD
    LOG.debug("Verification of XML signature document started");
    final Document doc = parseInput(input, out);
    XMLSignatureFactory fac;
    // not work
    try {
        fac = XMLSignatureFactory.getInstance("DOM", "ApacheXMLDSig");
    } catch (NoSuchProviderException ex) {
        fac = XMLSignatureFactory.getInstance("DOM");
    }
    KeySelector selector = getConfiguration().getKeySelector();
    if (selector == null) {
        throw new IllegalStateException("Wrong configuration. Key selector is missing.");
    }
    DOMValidateContext valContext = new DOMValidateContext(selector, doc);
    valContext.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE);
    valContext.setProperty("org.jcp.xml.dsig.validateManifests", Boolean.TRUE);
    if (getConfiguration().getSecureValidation() == Boolean.TRUE) {
        valContext.setProperty("org.apache.jcp.xml.dsig.secureValidation", Boolean.TRUE);
        valContext.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.TRUE);
    }
    setUriDereferencerAndBaseUri(valContext);
    setCryptoContextProperties(valContext);
    NodeList signatureNodes = getSignatureNodes(doc);
    List<XMLObject> collectedObjects = new ArrayList<XMLObject>(3);
    List<Reference> collectedReferences = new ArrayList<Reference>(3);
    int totalCount = signatureNodes.getLength();
    for (int i = 0; i < totalCount; i++) {
        Element signatureNode = (Element) signatureNodes.item(i);
        valContext.setNode(signatureNode);
        final XMLSignature signature = fac.unmarshalXMLSignature(valContext);
        if (getConfiguration().getXmlSignatureChecker() != null) {
            XmlSignatureChecker.Input checkerInput = new CheckerInputBuilder().message(out).messageBodyDocument(doc).keyInfo(signature.getKeyInfo()).currentCountOfSignatures(i + 1).currentSignatureElement(signatureNode).objects(signature.getObjects()).signatureValue(signature.getSignatureValue()).signedInfo(signature.getSignedInfo()).totalCountOfSignatures(totalCount).xmlSchemaValidationExecuted(getSchemaResourceUri(out) != null).build();
            getConfiguration().getXmlSignatureChecker().checkBeforeCoreValidation(checkerInput);
        }
        boolean coreValidity;
        try {
            coreValidity = signature.validate(valContext);
        } catch (XMLSignatureException se) {
            throw getConfiguration().getValidationFailedHandler().onXMLSignatureException(se);
        }
        // Check core validation status
        boolean goon = coreValidity;
        if (!coreValidity) {
            goon = handleSignatureValidationFailed(valContext, signature);
        }
        if (goon) {
            LOG.debug("XML signature {} verified", i + 1);
        } else {
            throw new XmlSignatureInvalidException("XML signature validation failed");
        }
        collectedObjects.addAll(signature.getObjects());
        collectedReferences.addAll(signature.getSignedInfo().getReferences());
    }
    map2Message(collectedReferences, collectedObjects, out, doc);
}
Also used : XMLSignatureFactory(javax.xml.crypto.dsig.XMLSignatureFactory) XmlSignatureInvalidException(org.apache.camel.component.xmlsecurity.api.XmlSignatureInvalidException) Reference(javax.xml.crypto.dsig.Reference) NodeList(org.w3c.dom.NodeList) Element(org.w3c.dom.Element) XmlSignatureChecker(org.apache.camel.component.xmlsecurity.api.XmlSignatureChecker) ArrayList(java.util.ArrayList) XMLObject(javax.xml.crypto.dsig.XMLObject) Document(org.w3c.dom.Document) KeySelector(javax.xml.crypto.KeySelector) XMLSignature(javax.xml.crypto.dsig.XMLSignature) DOMValidateContext(javax.xml.crypto.dsig.dom.DOMValidateContext) NoSuchProviderException(java.security.NoSuchProviderException) XMLSignatureException(javax.xml.crypto.dsig.XMLSignatureException)

Example 8 with XMLObject

use of javax.xml.crypto.dsig.XMLObject in project camel by apache.

the class XmlVerifierProcessor method handleSignatureValidationFailed.

@SuppressWarnings("unchecked")
protected boolean handleSignatureValidationFailed(DOMValidateContext valContext, XMLSignature signature) throws Exception {
    //NOPMD
    ValidationFailedHandler handler = getConfiguration().getValidationFailedHandler();
    LOG.debug("handleSignatureValidationFailed called");
    try {
        handler.start();
        // first check signature value, see
        // https://www.isecpartners.com/media/12012/XMLDSIG_Command_Injection.pdf
        SignatureValue sigValue = signature.getSignatureValue();
        boolean sv = sigValue.validate(valContext);
        if (!sv) {
            handler.signatureValueValidationFailed(sigValue);
        }
        // check the validation status of each Reference
        for (Reference ref : (List<Reference>) signature.getSignedInfo().getReferences()) {
            boolean refValid = ref.validate(valContext);
            if (!refValid) {
                handler.referenceValidationFailed(ref);
            }
        }
        // validate Manifests, if property set
        if (Boolean.TRUE.equals(valContext.getProperty("org.jcp.xml.dsig.validateManifests"))) {
            for (XMLObject xo : (List<XMLObject>) signature.getObjects()) {
                List<XMLStructure> content = xo.getContent();
                for (XMLStructure xs : content) {
                    if (xs instanceof Manifest) {
                        Manifest man = (Manifest) xs;
                        for (Reference ref : (List<Reference>) man.getReferences()) {
                            boolean refValid = ref.validate(valContext);
                            if (!refValid) {
                                handler.manifestReferenceValidationFailed(ref);
                            }
                        }
                    }
                }
            }
        }
        boolean goon = handler.ignoreCoreValidationFailure();
        LOG.debug("Ignore Core Validation failure: {}", goon);
        return goon;
    } finally {
        handler.end();
    }
}
Also used : ValidationFailedHandler(org.apache.camel.component.xmlsecurity.api.ValidationFailedHandler) SignatureValue(javax.xml.crypto.dsig.XMLSignature.SignatureValue) Reference(javax.xml.crypto.dsig.Reference) XMLObject(javax.xml.crypto.dsig.XMLObject) ArrayList(java.util.ArrayList) NodeList(org.w3c.dom.NodeList) List(java.util.List) XMLStructure(javax.xml.crypto.XMLStructure) Manifest(javax.xml.crypto.dsig.Manifest)

Example 9 with XMLObject

use of javax.xml.crypto.dsig.XMLObject in project camel by apache.

the class DefaultXmlSignature2Message method getReferencedSameDocumentObjects.

protected List<XMLObject> getReferencedSameDocumentObjects(List<Reference> relevantReferences, List<XMLObject> relevantObjects) {
    List<XMLObject> referencedObjects = new ArrayList<XMLObject>(1);
    for (Reference ref : relevantReferences) {
        String refUri = getSameDocumentReferenceUri(ref);
        if (refUri == null) {
            continue;
        }
        XMLObject referencedOb = getReferencedObject(relevantObjects, refUri);
        if (referencedOb != null) {
            referencedObjects.add(referencedOb);
            continue;
        }
        // content could also be indirectly referenced via manifest
        addManifestReferencedObjects(relevantObjects, referencedObjects, refUri);
    }
    return referencedObjects;
}
Also used : Reference(javax.xml.crypto.dsig.Reference) ArrayList(java.util.ArrayList) XMLObject(javax.xml.crypto.dsig.XMLObject)

Example 10 with XMLObject

use of javax.xml.crypto.dsig.XMLObject in project camel by apache.

the class DefaultXmlSignature2Message method getDomStructureForMessageBody.

/**
     * Returns the DOM structure which is transformed to a byte array and set to
     * the camel message body.
     * 
     * @param relevantReferences
     *            input from method
     *            {@link #getReferencesForMessageMapping(ReferencesAndObjects)}
     * @param relevantObjects
     *            input from method
     *            {@link #getObjectsForMessageMapping(ReferencesAndObjects)}
     * @return dom structure
     * @throws Exception
     *             if an error occurs
     */
protected DOMStructure getDomStructureForMessageBody(List<Reference> relevantReferences, List<XMLObject> relevantObjects) throws Exception {
    //NOPMD
    List<XMLObject> referencedObjects = getReferencedSameDocumentObjects(relevantReferences, relevantObjects);
    if (referencedObjects.isEmpty()) {
        throw new XmlSignatureException(String.format("Unsupported XML signature document: Content object not found in the enveloping XML signature."));
    }
    if (referencedObjects.size() > 1) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < referencedObjects.size(); i++) {
            XMLObject xmlOb = referencedObjects.get(i);
            sb.append(xmlOb.getId());
            if (i < referencedObjects.size() - 1) {
                sb.append(", ");
            }
        }
        throw new XmlSignatureException(String.format("Unsupported XML signature document: More than one content objects found. Object IDs: %s", sb.toString()));
    }
    @SuppressWarnings("unchecked") List<XMLStructure> structures = referencedObjects.get(0).getContent();
    if (structures.size() == 0) {
        throw new XmlSignatureException("Unsupported XML signature: XML signature is not enveloping; content not found in XML signature: structure list is empty.");
    }
    if (structures.size() > 1) {
        throw new XmlSignatureException("Unsupported XML signature: more than one structure elements in referenced content object.");
    }
    XMLStructure structure = structures.get(0);
    // only dom currently supported
    DOMStructure domStruc = (DOMStructure) structure;
    return domStruc;
}
Also used : DOMStructure(javax.xml.crypto.dom.DOMStructure) XMLObject(javax.xml.crypto.dsig.XMLObject) XMLStructure(javax.xml.crypto.XMLStructure)

Aggregations

XMLObject (javax.xml.crypto.dsig.XMLObject)12 Reference (javax.xml.crypto.dsig.Reference)10 ArrayList (java.util.ArrayList)8 XMLStructure (javax.xml.crypto.XMLStructure)5 DOMStructure (javax.xml.crypto.dom.DOMStructure)5 Manifest (javax.xml.crypto.dsig.Manifest)4 Transform (javax.xml.crypto.dsig.Transform)3 Document (org.w3c.dom.Document)3 Element (org.w3c.dom.Element)3 NodeList (org.w3c.dom.NodeList)3 HashMap (java.util.HashMap)2 List (java.util.List)2 Map (java.util.Map)2 XMLSignature (javax.xml.crypto.dsig.XMLSignature)2 XMLSignatureException (javax.xml.crypto.dsig.XMLSignatureException)2 XMLSignatureFactory (javax.xml.crypto.dsig.XMLSignatureFactory)2 Node (org.w3c.dom.Node)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 File (java.io.File)1