Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to fix 'Disable XML external entity (XXE) processing' vulnerabilities in java

I ran my java code against sonarqube and I got 'Disable XML external entity (XXE) processing' as vulnerability. I spend some time on google to resolve the issue. I have been trying alot of approach but nothing is working for me. I don't know what I'm missing

My Code:

        final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        docFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        docFactory.setFeature(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
        docFactory.setFeature(XMLInputFactory.SUPPORT_DTD, false);

        docFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        docFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
        docFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
        docFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

        final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        final Document doc = docBuilder.parse(filepath);

I'm using java 1.8, Any help is appreciated. Thanks

like image 587
cheetoo Avatar asked Jun 26 '19 16:06

cheetoo


2 Answers

I end up adding all of the following attributes in order to avoid Sonar complaining about this vulnerability:

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        //REDHAT
        //https://www.blackhat.com/docs/us-15/materials/us-15-Wang-FileCry-The-New-Age-Of-XXE-java-wp.pdf
        factory.setAttribute(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
        factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");

        //OWASP
        //https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html
        factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
        factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
        // Disable external DTDs as well
        factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        // and these as well, per Timothy Morgan's 2014 paper: "XML Schema, DTD, and Entity Attacks"
        factory.setXIncludeAware(false);
        factory.setExpandEntityReferences(false);

        DocumentBuilder builder = factory.newDocumentBuilder();
like image 122
chomp Avatar answered Oct 06 '22 18:10

chomp


Java 9+ solution:

For me changing DocumentBuilderFactory.newInstance() to DocumentBuilderFactory.newDefaultInstance() was enough to red rid of this warning.

like image 41
Line Avatar answered Oct 06 '22 19:10

Line