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.assertFalse;
21  import static org.junit.jupiter.api.Assertions.assertTrue;
22  import static org.junit.jupiter.api.Assertions.fail;
23  
24  import javax.xml.parsers.DocumentBuilderFactory;
25  import javax.xml.parsers.ParserConfigurationException;
26  import javax.xml.xpath.XPathExpressionException;
27  import javax.xml.xpath.XPathFactory;
28  
29  import org.junit.jupiter.api.Tag;
30  import org.junit.jupiter.api.Test;
31  
32  /**
33   * Tests whether Saxon's XPath 3.1 URI-fetching functions can pull external resources into the result.
34   *
35   * <p>
36   * Saxon ships several XPath 3.1 functions that open arbitrary URIs during evaluation. None require a context node; each is triggered purely by the string
37   * URI it receives. They are <em>not</em> classified as extension functions in Saxon's vocabulary, so disabling {@code ALLOW_EXTERNAL_FUNCTIONS} is not enough
38   * to block them; a complete securing has to close the URI-resolution path.
39   * </p>
40   *
41   * <p>
42   * Each fixture under {@code src/test/resources/leaked/} contains the {@link #MARKER} string. The tests dispatch the URI-fetching function at the file's URL
43   * and check whether the marker reaches the result.
44   * </p>
45   *
46   * <p>
47   * Cases covered, each as a pair (unconfigured Saxon factory expected to leak, secure Saxon factory expected to block):
48   * </p>
49   *
50   * <ul>
51   *   <li>{@code doc(uri)} reading {@code referenced.xml}.</li>
52   *   <li>{@code json-doc(uri)} reading {@code referenced.json}.</li>
53   *   <li>{@code unparsed-text(uri)} reading {@code referenced.txt}.</li>
54   * </ul>
55   *
56   * <p>
57   * The JDK's built-in XPathFactory and Xalan have no equivalent vectors. The class is tagged {@code xpath3}, so under the surefire group filters it only
58   * runs in the {@code test-saxon} execution where Saxon is on the classpath.
59   * </p>
60   */
61  @Tag("xpath3")
62  class SaxonXPathExternalCallsTest {
63  
64      private static final String MARKER = "All your base are belong to us";
65      private static final String SAXON_XPATH_FACTORY_CLASS = "net.sf.saxon.xpath.XPathFactoryImpl";
66  
67      private static void assertCallExcludesMarker(final XPathFactory factory, final String expression) {
68          final String result;
69          try {
70              result = evaluateAsString(factory, expression);
71          } catch (final Exception e) {
72              return; // secure blocked at evaluation; acceptable outcome.
73          }
74          assertFalse(result.contains(MARKER),
75                  "Securing did not block the external reference; result contained marker '" + MARKER + "'.\nFull result:\n" + result);
76      }
77  
78      private static void assertCallLeaksMarker(final XPathFactory factory, final String expression) {
79          final String result;
80          try {
81              result = evaluateAsString(factory, expression);
82          } catch (final Exception e) {
83              fail("Unconfigured Saxon XPath should resolve the external resource, but threw: " + e);
84              return;
85          }
86          assertTrue(result.contains(MARKER),
87                  "Expected marker '" + MARKER + "' in result, got: " + result);
88      }
89  
90      private static String docExpression() {
91          return "doc('" + AttackTestSupport.resourceUrl("referenced.xml") + "')/leaked";
92      }
93  
94      private static String evaluateAsString(final XPathFactory factory, final String expression)
95              throws ParserConfigurationException, XPathExpressionException {
96          return factory.newXPath().evaluate(expression,
97                  DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
98      }
99  
100     private static String jsonDocExpression() {
101         return "json-doc('" + AttackTestSupport.resourceUrl("referenced.json") + "')?leaked";
102     }
103 
104     /**
105      * Instantiates Saxon's {@code XPathFactoryImpl} reflectively.
106      *
107      * <p>
108      * Saxon 12.9 ships no {@code META-INF/services} entry for
109      * {@link XPathFactory}, so {@link XPathFactory#newInstance(String)} cannot find it; direct instantiation bypasses that lookup.
110      * </p>
111      */
112     private static XPathFactory saxonXPathFactory() {
113         try {
114             return (XPathFactory) Class.forName(SAXON_XPATH_FACTORY_CLASS).getDeclaredConstructor().newInstance();
115         } catch (final ReflectiveOperationException e) {
116             throw new AssertionError("Cannot instantiate " + SAXON_XPATH_FACTORY_CLASS, e);
117         }
118     }
119 
120     private static XPathFactory secureSaxonXPathFactory() {
121         return SaxonProvider.configure(saxonXPathFactory());
122     }
123 
124     private static String unparsedTextExpression() {
125         return "unparsed-text('" + AttackTestSupport.resourceUrl("referenced.txt") + "')";
126     }
127 
128     @Test
129     void secureXPathBlocksDoc() {
130         assertCallExcludesMarker(secureSaxonXPathFactory(), docExpression());
131     }
132 
133     @Test
134     void secureXPathBlocksJsonDoc() {
135         assertCallExcludesMarker(secureSaxonXPathFactory(), jsonDocExpression());
136     }
137 
138     @Test
139     void secureXPathBlocksUnparsedText() {
140         assertCallExcludesMarker(secureSaxonXPathFactory(), unparsedTextExpression());
141     }
142 
143     @Test
144     void unconfiguredXPathLeaksDoc() {
145         assertCallLeaksMarker(saxonXPathFactory(), docExpression());
146     }
147 
148     @Test
149     void unconfiguredXPathLeaksJsonDoc() {
150         assertCallLeaksMarker(saxonXPathFactory(), jsonDocExpression());
151     }
152 
153     @Test
154     void unconfiguredXPathLeaksUnparsedText() {
155         assertCallLeaksMarker(saxonXPathFactory(), unparsedTextExpression());
156     }
157 }