How to Prevent XML External Entity Injection on TransformerFactory

。_饼干妹妹 提交于 2019-12-03 10:05:39

问题


My problem:

Fortify 4.2.1 is marking below code as susceptible for XML External Entities attack.

TransformerFactory factory = TransformerFactory.newInstance();
StreamSource xslStream = new StreamSource(inputXSL);
Transformer transformer = factory.newTransformer(xslStream);

Solution I have tried:

  1. Setting TransformerFactory feature for XMLConstants.FEATURE_SECURE_PROCESSING to true.

  2. Looked into possiblities of providing more such features to TransformerFactory, just like we do for DOM and SAX parsers. e.g. disallowing doctype declaration, etc. But TransformerFactoryImpl doesn't seem to be accepting anything else that XMLConstants.FEATURE_SECURE_PROCESSING. Impl Code

Please point me to any resource that you think I might have not gone through or a possible solution to this issue.


回答1:


TransformerFactory trfactory = TransformerFactory.newInstance();
trfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
trfactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
trfactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");

I think this would be sufficient.

Fortify would suggest below features but those doesn't work for TransformerFactory

actory.setFeature("http://xml.org/sax/features/external-general-entities", false);
factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);

We might need to change to a different parser to make use of them.




回答2:


Because of lot of xml parsing engines in the market, each of it has its own mechanism to disable External entity injection. Please refer to the documentation of your engine. Below is an example to prevent it when using a SAX parser.

The funda is to disallow DOCTYPE declaration. However if it is required disabling external general entities and external parameter entities will not trick the underlying SAX parser to XXE injection.

public class MyDocumentBuilderFactory{

    public static DocumentBuilderFactory newDocumentBuilderFactory(){

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();

        try{

            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);

        }catch(ParserConfigurationException exp){
            exp.printStackTrace();
        }

        return documentBuilderFactory;
    }
}


来源:https://stackoverflow.com/questions/32178558/how-to-prevent-xml-external-entity-injection-on-transformerfactory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!