I am trying to update an existing method to avoid XXE attack. Below is the existing method:
private String xmlToString(final Node node) {
try {
final Source source = new DOMSource(node);
final StringWriter stringWriter = new StringWriter();
final Result result = new StreamResult(stringWriter);
final TransformerFactory factory = TransformerFactory.newInstance();
final Transformer transformer = factory.newTransformer();
transformer.transform(source, result);
return stringWriter.getBuffer().toString();
} catch (final TransformerConfigurationException e) {
LOG.error("Unable to convert XML node to string", e);
} catch (final TransformerException e) {
LOG.error("Unable to convert XML node to string", e);
}
return null;
}
Here is my modification:
private String xmlToString(final Node node) {
try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
documentBuilderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
documentBuilderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
documentBuilderFactory.setNamespaceAware(true);
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.newDocument();
Node importedNode = document.importNode(node, true);
document.appendChild(importedNode);
final Source source = new DOMSource(document);
final StringWriter stringWriter = new StringWriter();
final Result result = new StreamResult(stringWriter);
final TransformerFactory factory = TransformerFactory.newInstance();
//factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
final Transformer transformer = factory.newTransformer();
transformer.transform(source, result);
return stringWriter.getBuffer().toString();
} catch (final TransformerConfigurationException e) {
LOG.error("Unable to convert XML node to string", e);
} catch (final TransformerException e) {
LOG.error("Unable to convert XML node to string", e);
} catch (ParserConfigurationException e) {
LOG.error("Unable to convert XML node to string", e);
}
return null;
}
I initially added setFeature
property for TransformerFactory
(commented line of code) and saw the following error:
java.lang.UnsupportedOperationException: This class does not support JDK1.5
at weblogic.xml.jaxp.RegistryTransformerFactory.setFeature(RegistryTransformerFactory.java:317)
Then I decided to add DocumentBuilderFactory
to the method and convert the node to document. I saw this link and updated my method.
But, I see the below error:
org.w3c.dom.DOMException: NOT_SUPPORTED_ERR: The implementation does not support the requested type of object or operation.
at org.apache.xerces.dom.CoreDocumentImpl.importNode(Unknown Source)
at org.apache.xerces.dom.CoreDocumentImpl.importNode(Unknown Source)
Can somebody please help me correcting the problem.
Thanks,
NN.