You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

XMLHelper.java 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. /* ====================================================================
  2. Licensed to the Apache Software Foundation (ASF) under one or more
  3. contributor license agreements. See the NOTICE file distributed with
  4. this work for additional information regarding copyright ownership.
  5. The ASF licenses this file to You under the Apache License, Version 2.0
  6. (the "License"); you may not use this file except in compliance with
  7. the License. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. ==================================================================== */
  15. package org.apache.poi.util;
  16. import static javax.xml.XMLConstants.ACCESS_EXTERNAL_DTD;
  17. import static javax.xml.XMLConstants.ACCESS_EXTERNAL_SCHEMA;
  18. import static javax.xml.XMLConstants.ACCESS_EXTERNAL_STYLESHEET;
  19. import static javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING;
  20. import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI;
  21. import static javax.xml.stream.XMLInputFactory.IS_NAMESPACE_AWARE;
  22. import static javax.xml.stream.XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES;
  23. import static javax.xml.stream.XMLInputFactory.IS_VALIDATING;
  24. import static javax.xml.stream.XMLInputFactory.SUPPORT_DTD;
  25. import static javax.xml.stream.XMLOutputFactory.IS_REPAIRING_NAMESPACES;
  26. import java.io.StringReader;
  27. import java.lang.reflect.Method;
  28. import java.util.concurrent.TimeUnit;
  29. import javax.xml.parsers.DocumentBuilder;
  30. import javax.xml.parsers.DocumentBuilderFactory;
  31. import javax.xml.parsers.ParserConfigurationException;
  32. import javax.xml.parsers.SAXParserFactory;
  33. import javax.xml.stream.XMLEventFactory;
  34. import javax.xml.stream.XMLInputFactory;
  35. import javax.xml.stream.XMLOutputFactory;
  36. import javax.xml.transform.OutputKeys;
  37. import javax.xml.transform.Transformer;
  38. import javax.xml.transform.TransformerConfigurationException;
  39. import javax.xml.transform.TransformerException;
  40. import javax.xml.transform.TransformerFactory;
  41. import javax.xml.validation.SchemaFactory;
  42. import org.apache.logging.log4j.Level;
  43. import org.apache.logging.log4j.LogManager;
  44. import org.apache.logging.log4j.Logger;
  45. import org.xml.sax.ErrorHandler;
  46. import org.xml.sax.InputSource;
  47. import org.xml.sax.SAXException;
  48. import org.xml.sax.SAXParseException;
  49. import org.xml.sax.XMLReader;
  50. /**
  51. * Helper methods for working with javax.xml classes.
  52. *
  53. * @see <a href="https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html">OWASP XXE</a>
  54. */
  55. @Internal
  56. public final class XMLHelper {
  57. static final String FEATURE_LOAD_DTD_GRAMMAR = "http://apache.org/xml/features/nonvalidating/load-dtd-grammar";
  58. static final String FEATURE_LOAD_EXTERNAL_DTD = "http://apache.org/xml/features/nonvalidating/load-external-dtd";
  59. static final String FEATURE_DISALLOW_DOCTYPE_DECL = "http://apache.org/xml/features/disallow-doctype-decl";
  60. static final String FEATURE_PARAMETER_ENTITIES = "http://xml.org/sax/features/external-parameter-entities";
  61. static final String FEATURE_EXTERNAL_ENTITIES = "http://xml.org/sax/features/external-general-entities";
  62. static final String PROPERTY_ENTITY_EXPANSION_LIMIT = "http://www.oracle.com/xml/jaxp/properties/entityExpansionLimit";
  63. static final String PROPERTY_SECURITY_MANAGER = "http://apache.org/xml/properties/security-manager";
  64. static final String METHOD_ENTITY_EXPANSION_XERCES = "setEntityExpansionLimit";
  65. static final String[] SECURITY_MANAGERS = {
  66. //"com.sun.org.apache.xerces.internal.util.SecurityManager",
  67. "org.apache.xerces.util.SecurityManager"
  68. };
  69. private static final Logger LOG = LogManager.getLogger(XMLHelper.class);
  70. private static long lastLog;
  71. // DocumentBuilderFactory.newDocumentBuilder is thread-safe
  72. private static final DocumentBuilderFactory documentBuilderFactory = getDocumentBuilderFactory();
  73. private static final SAXParserFactory saxFactory = getSaxParserFactory();
  74. @FunctionalInterface
  75. private interface SecurityFeature {
  76. void accept(String name, boolean value) throws ParserConfigurationException, SAXException, TransformerException;
  77. }
  78. @FunctionalInterface
  79. private interface SecurityProperty {
  80. void accept(String name, Object value) throws SAXException;
  81. }
  82. private XMLHelper() {
  83. }
  84. /**
  85. * Creates a new DocumentBuilderFactory, with sensible defaults
  86. */
  87. @SuppressWarnings({"squid:S2755"})
  88. public static DocumentBuilderFactory getDocumentBuilderFactory() {
  89. DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  90. factory.setNamespaceAware(true);
  91. // this doesn't appear to work, and we still need to limit
  92. // entity expansions to 1 in trySet(XercesSecurityManager)
  93. factory.setExpandEntityReferences(false);
  94. factory.setValidating(false);
  95. trySet(factory::setFeature, FEATURE_SECURE_PROCESSING, true);
  96. trySet(factory::setAttribute, ACCESS_EXTERNAL_SCHEMA, "");
  97. trySet(factory::setAttribute, ACCESS_EXTERNAL_DTD, "");
  98. trySet(factory::setFeature, FEATURE_EXTERNAL_ENTITIES, false);
  99. trySet(factory::setFeature, FEATURE_PARAMETER_ENTITIES, false);
  100. trySet(factory::setFeature, FEATURE_LOAD_EXTERNAL_DTD, false);
  101. trySet(factory::setFeature, FEATURE_LOAD_DTD_GRAMMAR, false);
  102. trySet(factory::setFeature, FEATURE_DISALLOW_DOCTYPE_DECL, true);
  103. trySet((n, b) -> factory.setXIncludeAware(b), "XIncludeAware", false);
  104. Object manager = getXercesSecurityManager();
  105. if (manager == null || !trySet(factory::setAttribute, PROPERTY_SECURITY_MANAGER, manager)) {
  106. // separate old version of Xerces not found => use the builtin way of setting the property
  107. // Note: when entity_expansion_limit==0, there is no limit!
  108. trySet(factory::setAttribute, PROPERTY_ENTITY_EXPANSION_LIMIT, 1);
  109. }
  110. return factory;
  111. }
  112. /**
  113. * Creates a new document builder, with sensible defaults
  114. *
  115. * @throws IllegalStateException If creating the DocumentBuilder fails, e.g.
  116. * due to {@link ParserConfigurationException}.
  117. */
  118. public static DocumentBuilder newDocumentBuilder() {
  119. try {
  120. DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
  121. documentBuilder.setEntityResolver(XMLHelper::ignoreEntity);
  122. documentBuilder.setErrorHandler(new DocHelperErrorHandler());
  123. return documentBuilder;
  124. } catch (ParserConfigurationException e) {
  125. throw new IllegalStateException("cannot create a DocumentBuilder", e);
  126. }
  127. }
  128. @SuppressWarnings("squid:S2755")
  129. public static SAXParserFactory getSaxParserFactory() {
  130. try {
  131. SAXParserFactory factory = SAXParserFactory.newInstance();
  132. factory.setValidating(false);
  133. factory.setNamespaceAware(true);
  134. trySet(factory::setFeature, FEATURE_SECURE_PROCESSING, true);
  135. trySet(factory::setFeature, FEATURE_LOAD_DTD_GRAMMAR, false);
  136. trySet(factory::setFeature, FEATURE_LOAD_EXTERNAL_DTD, false);
  137. trySet(factory::setFeature, FEATURE_EXTERNAL_ENTITIES, false);
  138. trySet(factory::setFeature, FEATURE_DISALLOW_DOCTYPE_DECL, true);
  139. return factory;
  140. } catch (RuntimeException | Error re) { // NOSONAR
  141. // this also catches NoClassDefFoundError, which may be due to a local class path issue
  142. // This may occur if the code is run inside a web container or a restricted JVM
  143. // See bug 61170: https://bz.apache.org/bugzilla/show_bug.cgi?id=61170
  144. logThrowable(re, "Failed to create SAXParserFactory", "-");
  145. throw re;
  146. } catch (Exception e) {
  147. logThrowable(e, "Failed to create SAXParserFactory", "-");
  148. throw new RuntimeException("Failed to create SAXParserFactory", e);
  149. }
  150. }
  151. /**
  152. * Creates a new SAX XMLReader, with sensible defaults
  153. */
  154. public static XMLReader newXMLReader() throws SAXException, ParserConfigurationException {
  155. XMLReader xmlReader = saxFactory.newSAXParser().getXMLReader();
  156. xmlReader.setEntityResolver(XMLHelper::ignoreEntity);
  157. trySet(xmlReader::setFeature, FEATURE_SECURE_PROCESSING, true);
  158. trySet(xmlReader::setFeature, FEATURE_EXTERNAL_ENTITIES, false);
  159. Object manager = getXercesSecurityManager();
  160. if (manager == null || !trySet(xmlReader::setProperty, PROPERTY_SECURITY_MANAGER, manager)) {
  161. // separate old version of Xerces not found => use the builtin way of setting the property
  162. trySet(xmlReader::setProperty, PROPERTY_ENTITY_EXPANSION_LIMIT, 1);
  163. }
  164. return xmlReader;
  165. }
  166. /**
  167. * Creates a new StAX XMLInputFactory, with sensible defaults
  168. */
  169. @SuppressWarnings({"squid:S2755"})
  170. public static XMLInputFactory newXMLInputFactory() {
  171. XMLInputFactory factory = XMLInputFactory.newInstance();
  172. trySet(factory::setProperty, IS_NAMESPACE_AWARE, true);
  173. trySet(factory::setProperty, IS_VALIDATING, false);
  174. trySet(factory::setProperty, SUPPORT_DTD, false);
  175. trySet(factory::setProperty, IS_SUPPORTING_EXTERNAL_ENTITIES, false);
  176. return factory;
  177. }
  178. /**
  179. * Creates a new StAX XMLOutputFactory, with sensible defaults
  180. */
  181. public static XMLOutputFactory newXMLOutputFactory() {
  182. XMLOutputFactory factory = XMLOutputFactory.newInstance();
  183. trySet(factory::setProperty, IS_REPAIRING_NAMESPACES, true);
  184. return factory;
  185. }
  186. /**
  187. * Creates a new StAX XMLEventFactory, with sensible defaults
  188. */
  189. public static XMLEventFactory newXMLEventFactory() {
  190. // this method seems safer on Android than getFactory()
  191. return XMLEventFactory.newInstance();
  192. }
  193. @SuppressWarnings({"squid:S4435","java:S2755"})
  194. public static TransformerFactory getTransformerFactory() {
  195. TransformerFactory factory = TransformerFactory.newInstance();
  196. trySet(factory::setFeature, FEATURE_SECURE_PROCESSING, true);
  197. quietSet(factory::setAttribute, ACCESS_EXTERNAL_DTD, "");
  198. trySet(factory::setAttribute, ACCESS_EXTERNAL_STYLESHEET, "");
  199. quietSet(factory::setAttribute, ACCESS_EXTERNAL_SCHEMA, "");
  200. return factory;
  201. }
  202. public static Transformer newTransformer() throws TransformerConfigurationException {
  203. Transformer serializer = getTransformerFactory().newTransformer();
  204. // TODO set encoding from a command argument
  205. serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
  206. serializer.setOutputProperty(OutputKeys.INDENT, "no");
  207. serializer.setOutputProperty(OutputKeys.METHOD, "xml");
  208. return serializer;
  209. }
  210. @SuppressWarnings("java:S2755")
  211. public static SchemaFactory getSchemaFactory() {
  212. SchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
  213. trySet(factory::setFeature, FEATURE_SECURE_PROCESSING, true);
  214. trySet(factory::setProperty, ACCESS_EXTERNAL_DTD, "");
  215. trySet(factory::setProperty, ACCESS_EXTERNAL_STYLESHEET, "");
  216. trySet(factory::setProperty, ACCESS_EXTERNAL_SCHEMA, "");
  217. return factory;
  218. }
  219. private static Object getXercesSecurityManager() {
  220. // Try built-in JVM one first, standalone if not
  221. for (String securityManagerClassName : SECURITY_MANAGERS) {
  222. try {
  223. Object mgr = Class.forName(securityManagerClassName).getDeclaredConstructor().newInstance();
  224. Method setLimit = mgr.getClass().getMethod(METHOD_ENTITY_EXPANSION_XERCES, Integer.TYPE);
  225. setLimit.invoke(mgr, 1);
  226. // Stop once one can be setup without error
  227. return mgr;
  228. } catch (ClassNotFoundException ignored) {
  229. // continue without log, this is expected in some setups
  230. } catch (Throwable e) { // NOSONAR - also catch things like NoClassDefError here
  231. logThrowable(e, "SAX Feature unsupported", securityManagerClassName);
  232. }
  233. }
  234. return null;
  235. }
  236. @SuppressWarnings("UnusedReturnValue")
  237. private static boolean trySet(SecurityFeature feature, String name, boolean value) {
  238. try {
  239. feature.accept(name, value);
  240. return true;
  241. } catch (Exception e) {
  242. logThrowable(e, "SAX Feature unsupported", name);
  243. } catch (Error ame) {
  244. logThrowable(ame, "Cannot set SAX feature because outdated XML parser in classpath", name);
  245. }
  246. return false;
  247. }
  248. private static boolean trySet(SecurityProperty property, String name, Object value) {
  249. try {
  250. property.accept(name, value);
  251. return true;
  252. } catch (Exception e) {
  253. logThrowable(e, "SAX Feature unsupported", name);
  254. } catch (Error ame) {
  255. // ignore all top error object - GraalVM in native mode is not coping with java.xml error message resources
  256. logThrowable(ame, "Cannot set SAX feature because outdated XML parser in classpath", name);
  257. }
  258. return false;
  259. }
  260. private static boolean quietSet(SecurityProperty property, String name, Object value) {
  261. try {
  262. property.accept(name, value);
  263. return true;
  264. } catch (Exception|Error e) {
  265. // ok to ignore
  266. }
  267. return false;
  268. }
  269. private static void logThrowable(Throwable t, String message, String name) {
  270. if (System.currentTimeMillis() > lastLog + TimeUnit.MINUTES.toMillis(5)) {
  271. LOG.atWarn().withThrowable(t).log("{} [log suppressed for 5 minutes]{}", message, name);
  272. lastLog = System.currentTimeMillis();
  273. }
  274. }
  275. private static class DocHelperErrorHandler implements ErrorHandler {
  276. public void warning(SAXParseException exception) {
  277. printError(Level.WARN, exception);
  278. }
  279. public void error(SAXParseException exception) {
  280. printError(Level.ERROR, exception);
  281. }
  282. public void fatalError(SAXParseException exception) throws SAXException {
  283. printError(Level.FATAL, exception);
  284. throw exception;
  285. }
  286. /**
  287. * Prints the error message.
  288. */
  289. private void printError(Level type, SAXParseException ex) {
  290. String systemId = ex.getSystemId();
  291. if (systemId != null) {
  292. int index = systemId.lastIndexOf('/');
  293. if (index != -1) {
  294. systemId = systemId.substring(index + 1);
  295. }
  296. }
  297. String message = (systemId == null ? "" : systemId) +
  298. ':' + ex.getLineNumber() +
  299. ':' + ex.getColumnNumber() +
  300. ':' + ex.getMessage();
  301. LOG.atLevel(type).withThrowable(ex).log(message);
  302. }
  303. }
  304. private static InputSource ignoreEntity(String publicId, String systemId) {
  305. return new InputSource(new StringReader(""));
  306. }
  307. }