Securing a Transformer Factory
Securing Transformer Factory
The use of XML Hardener for securing TransformerFactory is analogical to the other factories for DOM and SAX parsing
-
To secure the TransformerFactory, import the following facade:
-
As a result, the returned TransformerFactory is immediately secured and is instance of HardenedTransformerFactory.
There are also white and mapper lists, as well as features for factory access, resetting the factory and switching it to learning mode.
Example
Sample Code
DocumentBuilder builder = this.dbFactory.newDocumentBuilder();
Source xsltSource = new DOMSource(builder.parse(new File(CURRENT_WORK_FOLDER, rootXsl)));
Source source = new DOMSource(builder.parse(new File(CURRENT_WORK_FOLDER, xmlFile)));
securedTrFactory = HardenedFacade.secureTransformerFactory(this.transformerFactory);
transformerFactory.setFeature(HardenerConstants.USE_WHITELIST_FEATURE, true);
try {
Utils.addToWhiteListForXslt(transformerFactory, importXsl1, rootXsl);
Utils.addToWhiteListForXslt(transformerFactory, importXsl2, rootXsl);
} catch (URISyntaxException e) {
e.printStackTrace();
}
Transformer transformer = transformerFactory.newTransformer(xsltSource);
StringWriter writer = new StringWriter();
Result output = new StreamResult(writer);
transformer.transform(source, output);
The method with parameters TransformerFactory and String namespace is used for external configuration file. The second parameter identifies which exactly configuration file to be used.
public static TransformerFactory secureTransformerFactory(final TransformerFactory factory, final String callerNamespace)
throws TransformerConfigurationException
Call as less as possible the secureTransformerFactory method because there are some resource consuming operations, which might affect the performance of your application. Try to reuse the TransformerFactory instance across classes instead.