@@ -42,9 +42,12 @@ This file is part of the iText (R) project.
42
42
*/
43
43
package com .itextpdf .kernel .utils ;
44
44
45
- import java .io .IOException ;
46
- import java .io .InputStream ;
47
- import java .io .OutputStream ;
45
+ import org .w3c .dom .Document ;
46
+ import org .xml .sax .EntityResolver ;
47
+ import org .xml .sax .InputSource ;
48
+ import org .xml .sax .SAXException ;
49
+
50
+ import javax .xml .XMLConstants ;
48
51
import javax .xml .parsers .DocumentBuilder ;
49
52
import javax .xml .parsers .DocumentBuilderFactory ;
50
53
import javax .xml .parsers .ParserConfigurationException ;
@@ -54,12 +57,18 @@ This file is part of the iText (R) project.
54
57
import javax .xml .transform .TransformerFactory ;
55
58
import javax .xml .transform .dom .DOMSource ;
56
59
import javax .xml .transform .stream .StreamResult ;
57
- import org .w3c .dom .Document ;
58
- import org .xml .sax .SAXException ;
60
+ import java .io .IOException ;
61
+ import java .io .InputStream ;
62
+ import java .io .OutputStream ;
63
+ import java .io .StringReader ;
59
64
60
65
class XmlUtils {
61
66
public static void writeXmlDocToStream (Document xmlReport , OutputStream stream ) throws TransformerException {
62
67
TransformerFactory tFactory = TransformerFactory .newInstance ();
68
+ try {
69
+ tFactory .setAttribute (XMLConstants .ACCESS_EXTERNAL_DTD , "" );
70
+ tFactory .setAttribute (XMLConstants .ACCESS_EXTERNAL_STYLESHEET , "" );
71
+ } catch (Exception exc ) {}
63
72
Transformer transformer = tFactory .newTransformer ();
64
73
transformer .setOutputProperty (OutputKeys .INDENT , "yes" );
65
74
DOMSource source = new DOMSource (xmlReport );
@@ -74,6 +83,7 @@ public static boolean compareXmls(InputStream xml1, InputStream xml2) throws Par
74
83
dbf .setIgnoringElementContentWhitespace (true );
75
84
dbf .setIgnoringComments (true );
76
85
DocumentBuilder db = dbf .newDocumentBuilder ();
86
+ db .setEntityResolver (new SafeEmptyEntityResolver ());
77
87
78
88
Document doc1 = db .parse (xml1 );
79
89
doc1 .normalizeDocument ();
@@ -87,4 +97,12 @@ public static boolean compareXmls(InputStream xml1, InputStream xml2) throws Par
87
97
public static Document initNewXmlDocument () throws ParserConfigurationException {
88
98
return DocumentBuilderFactory .newInstance ().newDocumentBuilder ().newDocument ();
89
99
}
100
+
101
+ // Prevents XXE attacks
102
+ private static class SafeEmptyEntityResolver implements EntityResolver {
103
+ public InputSource resolveEntity (String publicId , String systemId ) throws SAXException , IOException {
104
+ return new InputSource (new StringReader ("" ));
105
+ }
106
+ }
107
+
90
108
}
0 commit comments