View Javadoc
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    *
9    *      https://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package org.apache.commons.xml.secure;
19  
20  import static org.junit.jupiter.api.Assertions.assertEquals;
21  import static org.junit.jupiter.api.Assertions.assertFalse;
22  import static org.junit.jupiter.api.Assertions.assertInstanceOf;
23  import static org.junit.jupiter.api.Assertions.assertNotNull;
24  import static org.junit.jupiter.api.Assertions.assertNull;
25  import static org.junit.jupiter.api.Assertions.assertSame;
26  import static org.junit.jupiter.api.Assertions.assertThrows;
27  import static org.junit.jupiter.api.Assertions.assertTrue;
28  import static org.mockito.Mockito.mock;
29  import static org.mockito.Mockito.when;
30  
31  import java.lang.reflect.Field;
32  
33  import javax.xml.XMLConstants;
34  import javax.xml.parsers.DocumentBuilder;
35  import javax.xml.parsers.DocumentBuilderFactory;
36  import javax.xml.parsers.ParserConfigurationException;
37  
38  import org.w3c.dom.Document;
39  import org.xml.sax.InputSource;
40  
41  import org.junit.jupiter.api.Assumptions;
42  import org.junit.jupiter.api.Tag;
43  import org.junit.jupiter.api.Test;
44  import org.junit.jupiter.api.condition.DisabledInNativeImage;
45  
46  @Tag("dom")
47  class SecureDocumentBuilderFactoryTest {
48  
49      /**
50       * Test JAXP provider that delegates builder creation to a Mockito mock.
51       */
52      public static final class MockDocumentBuilderFactory extends DocumentBuilderFactory {
53  
54          private static DocumentBuilderFactory delegate;
55  
56          @Override
57          public Object getAttribute(final String name) {
58              return null;
59          }
60  
61          @Override
62          public boolean getFeature(final String name) {
63              return false;
64          }
65  
66          @Override
67          public DocumentBuilder newDocumentBuilder() throws ParserConfigurationException {
68              return delegate.newDocumentBuilder();
69          }
70  
71          @Override
72          public void setAttribute(final String name, final Object value) {
73              // no-op
74          }
75  
76          @Override
77          public void setFeature(final String name, final boolean value) {
78              // no-op
79          }
80      }
81  
82      /**
83       * System property naming the {@link DocumentBuilderFactory} implementation, the JVM's mechanism for reconfiguring the default parser.
84       */
85      private static final String FACTORY_ID = "javax.xml.parsers.DocumentBuilderFactory";
86  
87      /**
88       * Gets the implementation a secure factory delegates to, so the selection tests can observe which parser implementation a lookup picked.
89       *
90       * @param factory a secure factory returned by one of the {@code new*Instance} methods; never {@code null}.
91       * @return The wrapped factory.
92       */
93      private static DocumentBuilderFactory getDelegate(final DocumentBuilderFactory factory) throws ReflectiveOperationException {
94          final Field delegate = factory.getClass().getDeclaredField("delegate");
95          delegate.setAccessible(true);
96          return (DocumentBuilderFactory) delegate.get(factory);
97      }
98  
99      /**
100      * Sets the {@value #FACTORY_ID} system property to select the implementation {@link DocumentBuilderFactory#newInstance()} returns.
101      *
102      * @param factoryClassName The implementation class name to install, or {@code null} to clear the property and restore the platform lookup.
103      * @return The previous property value, {@code null} if it was not set; pass it back here to restore the original lookup.
104      */
105     private static String setFactoryIdProperty(final String factoryClassName) {
106         final String previous = System.getProperty(FACTORY_ID);
107         if (factoryClassName == null) {
108             System.clearProperty(FACTORY_ID);
109         } else {
110             System.setProperty(FACTORY_ID, factoryClassName);
111         }
112         return previous;
113     }
114 
115     @Test
116     void createsBuildersDirectly() {
117         final DocumentBuilder builder = SecureDocumentBuilderFactory.newNSDocumentBuilder();
118         assertTrue(builder.isNamespaceAware());
119         if (AttackTestSupport.DOM_RESOLVES_INTERNAL_ENTITIES) {
120             assertInstanceOf(SecureDocumentBuilder.class, builder);
121         }
122     }
123 
124     @Test
125     void createsSecureBuildersFromEveryStaticEntryPoint() throws Exception {
126         Assumptions.assumeTrue(AttackTestSupport.DOM_RESOLVES_INTERNAL_ENTITIES, "the platform DOM is left unwrapped: it does not resolve user-defined entities");
127         assertInstanceOf(SecureDocumentBuilder.class, SecureDocumentBuilderFactory.newInstance().newDocumentBuilder());
128         assertInstanceOf(SecureDocumentBuilder.class, SecureDocumentBuilderFactory.newDefaultInstance().newDocumentBuilder());
129         assertInstanceOf(SecureDocumentBuilder.class, SecureDocumentBuilderFactory.newNSInstance().newDocumentBuilder());
130         assertInstanceOf(SecureDocumentBuilder.class, SecureDocumentBuilderFactory.newDefaultNSInstance().newDocumentBuilder());
131     }
132 
133     @Test
134     void explicitFactoryClassSelectsThatImplementation() throws Exception {
135         Assumptions.assumeFalse(AttackTestSupport.IS_ANDROID, "Skipped on Android: the platform factory is used unwrapped");
136         final Class<?> discovered = DocumentBuilderFactory.newInstance().getClass();
137         final DocumentBuilderFactory factory = SecureDocumentBuilderFactory.newNSInstance(discovered.getName(), null);
138         assertEquals(discovered, getDelegate(factory).getClass());
139         assertTrue(factory.isNamespaceAware());
140     }
141 
142     @Test
143     void forwardsEverySupportedFactoryConfiguration() throws Exception {
144         Assumptions.assumeTrue(AttackTestSupport.DOM_RESOLVES_INTERNAL_ENTITIES, "the platform DOM is left unwrapped: it does not resolve user-defined entities");
145         final DocumentBuilderFactory factory = SecureDocumentBuilderFactory.newInstance();
146         factory.setCoalescing(true);
147         factory.setExpandEntityReferences(false);
148         factory.setIgnoringComments(true);
149         factory.setIgnoringElementContentWhitespace(true);
150         factory.setNamespaceAware(true);
151         factory.setValidating(false);
152         factory.setXIncludeAware(false);
153         factory.setSchema(null);
154         factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
155         factory.setAttribute(TestConstants.JAXP_SCHEMA_LANGUAGE, XMLConstants.W3C_XML_SCHEMA_NS_URI);
156         assertEquals(XMLConstants.W3C_XML_SCHEMA_NS_URI, factory.getAttribute(TestConstants.JAXP_SCHEMA_LANGUAGE));
157         assertTrue(factory.isCoalescing());
158         assertFalse(factory.isExpandEntityReferences());
159         assertTrue(factory.isIgnoringComments());
160         assertTrue(factory.isIgnoringElementContentWhitespace());
161         assertTrue(factory.isNamespaceAware());
162         assertFalse(factory.isValidating());
163         assertFalse(factory.isXIncludeAware());
164         assertNull(factory.getSchema());
165         assertTrue(factory.getFeature(XMLConstants.FEATURE_SECURE_PROCESSING));
166         assertNotNull(factory.newDocumentBuilder());
167     }
168 
169     @Test
170     // Mockito generates the mock classes and its plugin proxies at run time, which a closed-world native image cannot do.
171     @DisabledInNativeImage
172     void newDocumentBuilderWrapsDeclaredExceptions() throws Exception {
173         Assumptions.assumeFalse(AttackTestSupport.IS_ANDROID, "Skipped on Android: parser selection is pinned to the platform implementation");
174         final String previous = setFactoryIdProperty(MockDocumentBuilderFactory.class.getName());
175         try {
176             final ParserConfigurationException cause = new ParserConfigurationException("test");
177             MockDocumentBuilderFactory.delegate = mock(DocumentBuilderFactory.class);
178             when(MockDocumentBuilderFactory.delegate.newDocumentBuilder()).thenThrow(cause);
179             assertSame(cause, assertThrows(IllegalStateException.class, SecureDocumentBuilderFactory::newNSDocumentBuilder).getCause());
180         } finally {
181             setFactoryIdProperty(previous);
182             MockDocumentBuilderFactory.delegate = null;
183         }
184     }
185 
186     @Test
187     void newNSInstanceFollowsParserSelection() throws Exception {
188         Assumptions.assumeFalse(AttackTestSupport.IS_ANDROID, "Skipped on Android: the platform factory is used unwrapped");
189         final Class<?> discovered = DocumentBuilderFactory.newInstance().getClass();
190         // no property: the JDK built-in default, unless an override is requested
191         assertEquals(SecureDocumentBuilderFactory.JDK_DOCUMENT_BUILDER_FACTORY,
192                 getDelegate(SecureDocumentBuilderFactory.newNSInstance(false)).getClass().getName());
193         assertEquals(discovered, getDelegate(SecureDocumentBuilderFactory.newNSInstance(true)).getClass());
194         // the factory id property is the JDK's own default reconfiguration; both selections honor it
195         final String previous = setFactoryIdProperty(discovered.getName());
196         try {
197             assertEquals(discovered, getDelegate(SecureDocumentBuilderFactory.newNSInstance(false)).getClass());
198             assertEquals(discovered, getDelegate(SecureDocumentBuilderFactory.newNSInstance(true)).getClass());
199         } finally {
200             setFactoryIdProperty(previous);
201         }
202     }
203 
204     @Test
205     void xincludeTrueWithFile() throws Exception {
206         Assumptions.assumeTrue(AttackTestSupport.DOM_SUPPORTS_XINCLUDE, "the platform DOM does not support XInclude");
207         final DocumentBuilderFactory factory = SecureDocumentBuilderFactory.newInstance();
208         factory.setNamespaceAware(true);
209         factory.setXIncludeAware(true);
210         final DocumentBuilder builder = factory.newDocumentBuilder();
211         builder.setEntityResolver((publicId, systemId) -> systemId != null && systemId.endsWith("referenced.xml")
212                 ? new InputSource(AttackTestSupport.resourceUrl("referenced.xml").toString())
213                 : null);
214         final Document document = builder.parse(AttackTestSupport.resourceUrl("with-xinclude.xml").toString());
215         assertEquals("All your base are belong to us", document.getDocumentElement().getTextContent().trim());
216     }
217 
218     @Test
219     void xincludeFalseWithFile() throws Exception {
220         Assumptions.assumeTrue(AttackTestSupport.DOM_SUPPORTS_XINCLUDE, "the platform DOM does not support XInclude");
221         final DocumentBuilderFactory factory = SecureDocumentBuilderFactory.newInstance();
222         factory.setNamespaceAware(true);
223         factory.setXIncludeAware(false);
224         final Document document = factory.newDocumentBuilder().parse(AttackTestSupport.resourceUrl("with-xinclude.xml").toString());
225         assertEquals("", document.getDocumentElement().getTextContent().trim());
226     }
227 
228 }