1 /*
2 * Copyright 2010-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License").
5 * You may not use this file except in compliance with the License.
6 * A copy of the License is located at
7 *
8 * http://aws.amazon.com/apache2.0
9 *
10 * or in the "license" file accompanying this file. This file is distributed
11 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
12 * express or implied. See the License for the specific language governing
13 * permissions and limitations under the License.
14 */
15 package com.amazonaws.util;
16
17 import com.amazonaws.internal.SdkThreadLocalsRegistry;
18 import java.io.IOException;
19 import java.io.InputStream;
20 import javax.xml.stream.XMLInputFactory;
21 import org.xml.sax.ContentHandler;
22 import org.xml.sax.InputSource;
23 import org.xml.sax.SAXException;
24 import org.xml.sax.XMLReader;
25 import org.xml.sax.helpers.XMLReaderFactory;
26
27 public class XmlUtils {
28
29 /**
30 * Shared factory for creating XML event readers
31 */
32 private static final ThreadLocal<XMLInputFactory> xmlInputFactory = SdkThreadLocalsRegistry.register(
33 new ThreadLocal<XMLInputFactory>() {
34 @Override
35 protected XMLInputFactory initialValue() {
36 return createXmlInputFactory();
37 }
38 });
39
40 public static XMLReader parse(InputStream in, ContentHandler handler)
41 throws SAXException, IOException {
42
43 XMLReader reader = XMLReaderFactory.createXMLReader();
44 reader.setContentHandler(handler);
45 reader.parse(new InputSource(in));
46 in.close();
47 return reader;
48 }
49
50 /**
51 * @return A {@link ThreadLocal} copy of {@link XMLInputFactory}.
52 */
53 public static XMLInputFactory getXmlInputFactory() {
54 return xmlInputFactory.get();
55 }
56
57 /**
58 * Disables certain dangerous features that attempt to automatically fetch DTDs
59 *
60 * See <a href="https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Prevention_Cheat_Sheet">OWASP XXE Cheat Sheet</a>
61 */
62 private static XMLInputFactory createXmlInputFactory() {
63 XMLInputFactory factory = XMLInputFactory.newInstance();
64 factory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
65 factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
66 return factory;
67 }
68
69 }
70