How to disable DTD fetching using JAXB2.0

前端 未结 5 1891
执念已碎
执念已碎 2020-12-02 17:54

I\'m trying to use JAXB to unmashall some XML which I used xjc to create in the first place. I don\'t want to do any validation on the unmarshalling, but even though I have

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-02 18:11

    In answer to the question "How to disable DTD fetching using JAXB2.0".

    @sameer-puri links to https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#SAXTransformerFactory which answers the question as follows:

    JAXB Unmarshaller

    Since a javax.xml.bind.Unmarshaller parses XML and does not support any flags for disabling XXE, it's imperative to parse the untrusted XML through a configurable secure parser first, generate a source object as a result, and pass the source object to the Unmarshaller. For example:

    //Disable XXE
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setFeature("http://xml.org/sax/features/external-general-entities", false);
    spf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
    spf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    
    //Do unmarshall operation
    Source xmlSource = new SAXSource(spf.newSAXParser().getXMLReader(),
                                    new InputSource(new StringReader(xml)));
    JAXBContext jc = JAXBContext.newInstance(Object.class);
    Unmarshaller um = jc.createUnmarshaller();
    um.unmarshal(xmlSource);
    

提交回复
热议问题