问题
I am very new to JAXB and in our code audit, there was suggestion on preventing XXE attack with JAXB. I found related answer: Prevent XXE Attack with JAXB
My existing code looks like this:
if (properties.getProperty(MANIFEST) != null && !properties.getProperty(MANIFEST).isEmpty()) {
String manifestString = properties.getProperty(MANIFEST);
ByteArrayInputStream is = new ByteArrayInputStream(manifestString.getBytes());
try {
this.manifest = (Manifest) getJaxbContext().createUnmarshaller().unmarshal(is);
}
catch (JAXBException e) {
LOG.warn("There was an error trying to convert xml String to Manifest - {}", e.getMessage(), e);
}
}
Based on the answer, instead of using ByteArrayInputStream, I am supposed to use XMLStreamReader with some properties false.
In suggested answer, it says:
XMLStreamReader xsr = xif.createXMLStreamReader(new StreamSource("src/xxe/input.xml"));
I don't understand what 'src/xxe/input.xml' is and what it needs to be for my solution. Can anyone please explain?
回答1:
The src/xxe/input.xml from the answer in the other question is that question's source location for the XML being processed - namely a filename, accessed as a URL resource.
In your case, your XML is provided in String manifestString - therefore your StreamSource needs to be given this string as its source, not a file location.
This can be done using a StringReader:
import java.io.StringReader
...
StringReader manifestReader = new StringReader(manifestString);
XMLStreamReader xsr = xif.createXMLStreamReader(new StreamSource(manifestReader));
I split the code into 2 lines to make it clearer - but you can collapse them back to one line if you prefer:
XMLStreamReader xsr = xif.createXMLStreamReader(
new StreamSource(new StringReader(manifestString)));
The above code assumes you have already created your context and the xif input factory:
JAXBContext jc = JAXBContext.newInstance(Manifest.class);
XMLInputFactory xif = XMLInputFactory.newFactory();
xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);
Then you can unmarshal in the usual way:
Unmarshaller unmarshaller = jc.createUnmarshaller();
Manifest manifest = (Manifest) unmarshaller.unmarshal(xsr);
来源:https://stackoverflow.com/questions/65295943/prevent-xxe-attack-with-jaxb-xmlstreamreader