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 16KB

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