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.assertNotEquals;
23  import static org.junit.jupiter.api.Assertions.assertTrue;
24  import static org.junit.jupiter.api.Assumptions.assumeFalse;
25  import static org.junit.jupiter.api.Assumptions.assumeTrue;
26  
27  import java.io.StringWriter;
28  
29  import javax.xml.transform.Transformer;
30  import javax.xml.transform.TransformerFactory;
31  import javax.xml.transform.stream.StreamResult;
32  import javax.xml.validation.SchemaFactory;
33  import javax.xml.xpath.XPathFactory;
34  
35  import org.junit.jupiter.api.Tag;
36  import org.junit.jupiter.api.Test;
37  import org.junit.jupiter.api.condition.DisabledInNativeImage;
38  import org.xml.sax.XMLReader;
39  
40  /**
41   * Tests that {@code jdk.xml.overrideDefaultParser} selects which secure parser family performs the source rewrites on factories that recognize the feature.
42   *
43   * <p>
44   * The wrapped implementations' internal parsers are never used (the wrappers parse every source themselves), so instead of configuring the delegate, the
45   * wrappers read the feature: {@code false} (the JDK's default) pins the platform's built-in parser, {@code true} (or a delegate that does not recognize the
46   * feature) keeps the pluggable lookup. Both choices are secure, so the feature carries no security weight. The tests pin the JDK implementations through
47   * {@code newDefaultInstance()}, so they discriminate in every JVM execution; under test-jdk-xerces the two parser families genuinely differ.
48   * </p>
49   */
50  @Tag("trax")
51  @Tag("xpath")
52  @Tag("schema")
53  class OverrideDefaultParserTest {
54  
55      private static final String FEATURE = SecureSAXParserFactory.OVERRIDE_DEFAULT_PARSER;
56  
57      /**
58       * Package prefix of the JDK's built-in parsers, the family a {@code false} feature value pins.
59       */
60      private static final String JDK_INTERNAL_PREFIX = "com.sun.org.apache.xerces.internal.";
61  
62      /**
63       * {@code true} where the runtime's factories know {@value SecureSAXParserFactory#OVERRIDE_DEFAULT_PARSER}; JDK 8 gained it in 8u162.
64       */
65      private static final boolean SUPPORTS_FEATURE = probeFeature();
66  
67      /**
68       * Skips a test on a runtime whose factories do not recognize the feature, where there is no selection to observe.
69       */
70      private static void assumeFeatureSupported() {
71          assumeTrue(SUPPORTS_FEATURE, "runtime does not recognize " + FEATURE);
72      }
73  
74      private static boolean probeFeature() {
75          try {
76              TransformerFactory.newInstance().setFeature(FEATURE, true);
77              return true;
78          } catch (final Exception e) {
79              return false;
80          }
81      }
82  
83      private static String transform(final TransformerFactory factory, final String text) throws Exception {
84          final Transformer transformer = factory.newTransformer(AttackTestSupport.streamSource(AttackTestSupport.xsltBody(text)));
85          final StringWriter out = new StringWriter();
86          transformer.transform(AttackTestSupport.streamSource(AttackTestSupport.xmlBody("ignored")), new StreamResult(out));
87          return out.toString();
88      }
89  
90      private static boolean xercesOnClasspath() {
91          try {
92              Class.forName("org.apache.xerces.jaxp.SAXParserFactoryImpl");
93              return true;
94          } catch (final ClassNotFoundException e) {
95              return false;
96          }
97      }
98  
99      @Test
100     void schemaFactoryReadsFeatureAtCreation() throws Exception {
101         assumeFalse(AttackTestSupport.IS_ANDROID);
102         assumeFeatureSupported();
103         final SchemaFactory factory = SecureSchemaFactory.newDefaultInstance();
104         assertFalse(factory.getFeature(FEATURE));
105         assertFalse(((SecureSchema) factory.newSchema(AttackTestSupport.streamSource(AttackTestSupport.BENIGN_SCHEMA))).overrideDefaultParser);
106         factory.setFeature(FEATURE, true);
107         assertTrue(((SecureSchema) factory.newSchema(AttackTestSupport.streamSource(AttackTestSupport.BENIGN_SCHEMA))).overrideDefaultParser);
108     }
109 
110     @Test
111     void secureReaderFollowsFlag() throws Exception {
112         assumeFalse(AttackTestSupport.IS_ANDROID);
113         final XMLReader pinned = ((SecureXMLReader) SecureSAXParserFactory.newXMLReader(false)).getDelegate();
114         assertTrue(pinned.getClass().getName().startsWith(JDK_INTERNAL_PREFIX), pinned.getClass().getName());
115         final XMLReader pluggable = ((SecureXMLReader) SecureSAXParserFactory.newXMLReader(true)).getDelegate();
116         final XMLReader lookedUp = ((SecureXMLReader) SecureSAXParserFactory.newNSInstance().newSAXParser().getXMLReader()).getDelegate();
117         assertEquals(lookedUp.getClass(), pluggable.getClass());
118         if (xercesOnClasspath()) {
119             // The two families genuinely differ only where a third-party parser wins the lookup (the test-jdk-xerces execution).
120             assertNotEquals(pinned.getClass(), pluggable.getClass());
121         }
122     }
123 
124     @Test
125     void transformerFactoryReadsFeatureAtCreation() throws Exception {
126         assumeFalse(AttackTestSupport.IS_ANDROID);
127         assumeFeatureSupported();
128         final TransformerFactory factory = SecureTransformerFactory.newDefaultInstance();
129         assertFalse(factory.getFeature(FEATURE));
130         assertFalse(((SecureTemplates) factory.newTemplates(AttackTestSupport.streamSource(AttackTestSupport.xsltBody("probe")))).overrideDefaultParser);
131         factory.setFeature(FEATURE, true);
132         assertTrue(((SecureTemplates) factory.newTemplates(AttackTestSupport.streamSource(AttackTestSupport.xsltBody("probe")))).overrideDefaultParser);
133     }
134 
135     @Test
136     // The JDK default TrAX pinned by newDefaultInstance() is XSLTC, which defines the compiled translet class at run time — impossible in a closed-world
137     // native image (the reason the native profile substitutes Xalan). The capture tests above stay enabled: newTemplates never loads the translet.
138     @DisabledInNativeImage
139     void transformSucceedsUnderBothParserFamilies() throws Exception {
140         assumeFalse(AttackTestSupport.IS_ANDROID);
141         assumeFeatureSupported();
142         final TransformerFactory factory = SecureTransformerFactory.newDefaultInstance();
143         // Feature false (the JDK's default): stylesheet and source parse through the pinned platform parser.
144         assertTrue(transform(factory, "pinned").contains("pinned"));
145         factory.setFeature(FEATURE, true);
146         // Feature true: same result through the pluggable lookup.
147         assertTrue(transform(factory, "pluggable").contains("pluggable"));
148     }
149 
150     @Test
151     void xPathFactoryReadsFeatureAtCreation() throws Exception {
152         assumeFalse(AttackTestSupport.IS_ANDROID);
153         assumeFeatureSupported();
154         final XPathFactory factory = SecureXPathFactory.newDefaultInstance();
155         assertFalse(factory.getFeature(FEATURE));
156         assertFalse(((SecureXPath) factory.newXPath()).overrideDefaultParser);
157         factory.setFeature(FEATURE, true);
158         assertTrue(((SecureXPath) factory.newXPath()).overrideDefaultParser);
159     }
160 }