简体   繁体   中英

Document to String using DocumentBuilderFactory?

I am trying to find a way to convert Document to String and found this XML Document to String? post here. But, I want to do the conversion without using TransformerFactory because of XXE Vulnerabilities and by using DocumentBuilderFactory only. I cannot upgrade to jdk8 because of other limitations.

I haven't had any luck so far with it; all the searches are returning the same code shown in the above link.

Is it possible to do this?

This is difficult to do, but since your actual problem is the security vulnerability and not TransformerFactory , that may be a better way to go.

You should be able to configure TransformerFactory to ignore entities to prevent this sort of problem. See: Preventing XXE Injection

Another thing that may work for your security concerns is to use TransformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING) . This should prevent the problems that you're worried about. See also this forum thread on coderanch.

Setting FEATURE_SECURE_PROCESSING may or may not help, depending on what implementation TransformerFactory.getInstance() actually returns.

For example in Java 7 with no additional XML libraries on classpath setting transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); does not help.

You can fix this by providing a Source other than StreamSource (which factory would need to parse using some settings that you do not control).

For example you can use StAXSource like this:

TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); // does not help in Java 7
Transformer transformer = transformerFactory.newTransformer();

// StreamSource is insecure by default:
// Source source = new StreamSource(new StringReader(xxeXml));

// Source configured to be secure:
XMLInputFactory xif = XMLInputFactory.newFactory();
xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);
XMLEventReader xmlEventReader = xif.createXMLEventReader(new StringReader(xxeXml));
Source source = new StAXSource(xmlEventReader);

transformer.transform(
        source,
        new StreamResult(new ByteArrayOutputStream()));

Note the actual TrasformerFactory may not actually support StAXSource , so you need to test your code with the classpath as it would be on production. For example Saxon 9 (old one, I know) does not support StAXSource and the only clean way of "fixing" it that I know is to provide custom net.sf.saxon.Configuration instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM