Java Code Examples for javax.xml.parsers.DocumentBuilderFactory#setFeature()

The following examples show how to use javax.xml.parsers.DocumentBuilderFactory#setFeature() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: cs-actions   File: XmlUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static DocumentBuilder getDocumentBuilder(boolean secure) throws ParserConfigurationException {
    String feature;
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    feature = "http://xml.org/sax/features/external-general-entities";
    factory.setFeature(feature, false);
    feature = "http://xml.org/sax/features/external-parameter-entities";
    factory.setFeature(feature, false);
    feature = "http://apache.org/xml/features/nonvalidating/load-external-dtd";
    factory.setFeature(feature, false);
    feature = "http://apache.org/xml/features/disallow-doctype-decl";
    factory.setFeature(feature, true);
    factory.setXIncludeAware(false);
    factory.setExpandEntityReferences(false);
    factory.setNamespaceAware(true);
    factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, secure);
    return factory.newDocumentBuilder();
}
 
Example 2
private B2BParserHelper(){
    
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setValidating(false); // It's not needed to validate here
    builderFactory.setIgnoringElementContentWhitespace(true); 

    try {
        // This is a funky one. Without setting this "load-external-dtd" feature, even though we're
        // explicitly setting non-validating, the parser will still reach out and retrieve that DTD. If
        // the xml.cxml.org site happens to be down, it'll hang or fail on that dependency.
        //
        // http://xerces.apache.org/xerces2-j/features.html#nonvalidating.load-external-dtd
        builderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        
        builder = builderFactory.newDocumentBuilder(); // Create the parser
    } catch(ParserConfigurationException e) {
        throw new RuntimeException(e);
    } 
    
}
 
Example 3
/**
 * This method provides a secured document builder which will secure XXE attacks.
 *
 * @param setIgnoreComments whether to set setIgnoringComments in DocumentBuilderFactory.
 * @return DocumentBuilder
 * @throws ParserConfigurationException
 */
private static DocumentBuilder getSecuredDocumentBuilder(boolean setIgnoreComments) throws
                                                                                    ParserConfigurationException {
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setIgnoringComments(setIgnoreComments);
    documentBuilderFactory.setNamespaceAware(true);
    documentBuilderFactory.setXIncludeAware(false);
    documentBuilderFactory.setExpandEntityReferences(false);
    documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    SecurityManager securityManager = new SecurityManager();
    securityManager.setEntityExpansionLimit(0);
    documentBuilderFactory.setAttribute(Constants.XERCES_PROPERTY_PREFIX +
            Constants.SECURITY_MANAGER_PROPERTY, securityManager);
    documentBuilder.setEntityResolver(new EntityResolver() {
        @Override
        public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
            throw new SAXException("Possible XML External Entity (XXE) attack. Skip resolving entity");
        }
    });
    return documentBuilder;
}
 
Example 4
public boolean parse(String input) throws SAXException {
  try {
    DocumentBuilderFactory domfactory = DocumentBuilderFactory.newInstance();
    domfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    DocumentBuilder dombuilder = domfactory.newDocumentBuilder();
    StringReader rdr = new StringReader(input);
    InputSource src = new InputSource(rdr);
    Document doc = dombuilder.parse(src);
    doc.getDocumentElement().normalize();
    rdr.close();
    parseresponse(doc.getDocumentElement());
    return true;
  } catch (ParserConfigurationException | IOException e) {
    throw new SAXException(e);
  }
}
 
Example 5
public XmlCoverageProvider(Set<File> coverageReports, Set<String> includeFiles) {
    super(includeFiles);
    this.coverageReports = coverageReports;
    this.xmlCoverageHandlers = Arrays.asList(new CoberturaXmlCoverageHandler(),
            new CloverXmlCoverageHandler(),
            new JacocoXmlCoverageHandler());

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(false);
    dbf.setNamespaceAware(true);
    DocumentBuilder localDb = null;
    try {
        dbf.setFeature("http://xml.org/sax/features/namespaces", false);
        dbf.setFeature("http://xml.org/sax/features/validation", false);
        dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
        dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        localDb = dbf.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
    db = localDb;
    cc = new CoverageCounters();
}
 
Example 6
private void fixAdditionalRepositories(Document pom) throws Exception {
    if (project.getFile() != null) {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
        dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        DocumentBuilder builder = dbf.newDocumentBuilder();
        Document originalPom = builder.parse(project.getFile());

        XPath xpath = XPathFactory.newInstance().newXPath();
        Node repositories = (Node) xpath.compile("/project/repositories").evaluate(originalPom, XPathConstants.NODE);
        if (repositories != null) {
            pom.getDocumentElement().appendChild(pom.createComment(GENERATED_SECTION_START));
            pom.getDocumentElement().appendChild(pom.importNode(repositories, true));
            pom.getDocumentElement().appendChild(pom.createComment(GENERATED_SECTION_END));
        }
    } else {
        getLog().warn("Cannot access the project pom file to retrieve repositories");
    }
}
 
Example 7
/**
 * Creates a XML document builder.
 * 
 * @return a XML document builder
 * @throws JRException
 */
public static DocumentBuilder createDocumentBuilder(boolean isNamespaceAware) throws JRException
{
	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	dbf.setValidating(false);
	dbf.setIgnoringComments(true);
	dbf.setNamespaceAware(isNamespaceAware);
	try
	{
		if (!allowDoctype())
		{
			dbf.setFeature(FEATURE_DISALLOW_DOCTYPE, true);
		}
		
		return dbf.newDocumentBuilder();
	}
	catch (ParserConfigurationException e)
	{
		throw 
		new JRException(
			EXCEPTION_MESSAGE_KEY_DOCUMENT_BUILDER_FACTORY_CREATION_FAILURE,
			null,
			e);
	}
}
 
Example 8
Source Project: anno4j   File: DocumentFragmentTest.java    License: Apache License 2.0 5 votes vote down vote up
private Document parse(String xml) throws Exception {
	TransformerFactory factory = TransformerFactory.newInstance();
	DocumentBuilderFactory builder = DocumentBuilderFactory.newInstance();
	builder.setNamespaceAware(true);
	builder.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
	Source source = new StreamSource(new StringReader(xml));
	Document doc = builder.newDocumentBuilder().newDocument();
	DOMResult result = new DOMResult(doc);
	factory.newTransformer().transform(source, result);
	return doc;
}
 
Example 9
public static void unsafeManualConfig3() throws ParserConfigurationException, IOException, SAXException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setFeature("http://xml.org/sax/features/external-general-entities",true);
    dbf.setFeature("http://xml.org/sax/features/external-parameter-entities",true);
    //dbf.setXIncludeAware(false);
    dbf.setExpandEntityReferences(false);
    DocumentBuilder db = dbf.newDocumentBuilder();

    Document doc = db.parse(getInputFile());
    print(doc);
}
 
Example 10
Source Project: openjdk-8   File: XmlUtil.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static DocumentBuilderFactory newDocumentBuilderFactory(boolean secureXmlProcessing) {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    try {
        factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, isXMLSecurityDisabled(secureXmlProcessing));
    } catch (ParserConfigurationException e) {
        LOGGER.log(Level.WARNING, "Factory [{0}] doesn't support secure xml processing!", new Object[] { factory.getClass().getName() } );
    }
    return factory;
}
 
Example 11
public static Document convertToDocument(File file) throws DeviceManagementException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    try {
        factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        DocumentBuilder docBuilder = factory.newDocumentBuilder();
        return docBuilder.parse(file);
    } catch (Exception e) {
        throw new DeviceManagementException("Error occurred while parsing file, while converting " +
                "to a org.w3c.dom.Document", e);
    }
}
 
Example 12
Source Project: takes   File: RsPrettyXml.java    License: MIT License 5 votes vote down vote up
/**
 * Parses the input stream and returns DocumentType built without loading
 * any external DTD schemas.
 * @param body The body to be parsed.
 * @return The documents DocumentType.
 * @throws IOException if something goes wrong.
 */
private static DocumentType getDocType(final InputStream body)
    throws IOException {
    final DocumentBuilderFactory factory =
        DocumentBuilderFactory.newInstance();
    try {
        factory.setFeature(RsPrettyXml.LOAD_EXTERNAL_DTD, false);
        final DocumentBuilder builder = factory.newDocumentBuilder();
        return builder.parse(body).getDoctype();
    } catch (final ParserConfigurationException | SAXException ex) {
        throw new IOException(ex);
    }
}
 
Example 13
public static Document convertToDocument(File file) throws PolicyManagementException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    try {
        factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        DocumentBuilder docBuilder = factory.newDocumentBuilder();
        return docBuilder.parse(file);
    } catch (Exception e) {
        throw new PolicyManagementException("Error occurred while parsing file, while converting " +
                "to a org.w3c.dom.Document : " + e.getMessage(), e);
    }
}
 
Example 14
Source Project: carbon-device-mgt   File: Utils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This class build the iot-api-config.xml file.
 *
 * @param file The file object of iot-api-config.xml.
 * @return Document instance of the file
 * @throws APIMCertificateMGTException
 */
private static Document convertToDocument(File file) throws APIMCertificateMGTException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    try {
        factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        DocumentBuilder docBuilder = factory.newDocumentBuilder();
        return docBuilder.parse(file);
    } catch (Exception e) {
        throw new APIMCertificateMGTException("Error occurred while parsing file, while converting " +
                "to a org.w3c.dom.Document", e);
    }
}
 
Example 15
Source Project: hop   File: XmlParserFactoryProducer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates an instance of {@link DocumentBuilderFactory} class with enabled {@link XMLConstants#FEATURE_SECURE_PROCESSING} property.
 * Enabling this feature prevents from some XXE attacks (e.g. XML bomb)
 * See PPP-3506 for more details.
 *
 * @throws ParserConfigurationException if feature can't be enabled
 */
public static DocumentBuilderFactory createSecureDocBuilderFactory() throws ParserConfigurationException {
  DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
  docBuilderFactory.setFeature( XMLConstants.FEATURE_SECURE_PROCESSING, true );
  docBuilderFactory.setFeature( "http://apache.org/xml/features/disallow-doctype-decl", true );

  return docBuilderFactory;
}
 
Example 16
public static void unsafeManualConfig2() throws ParserConfigurationException, IOException, SAXException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setFeature("http://xml.org/sax/features/external-general-entities",true);
    //dbf.setFeature("http://xml.org/sax/features/external-parameter-entities",true);
    dbf.setXIncludeAware(false);
    dbf.setExpandEntityReferences(false);
    DocumentBuilder db = dbf.newDocumentBuilder();

    Document doc = db.parse(getInputFile());
    print(doc);
}
 
Example 17
public DocumentBuilderFactory getDocumentBuilderFactory() {
  DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();

  try {
    String feature = "http://apache.org/xml/features/disallow-doctype-decl";
    domFactory.setFeature(feature, true);

    // Disable #external-general-entities
    feature = "http://xml.org/sax/features/external-general-entities";
    domFactory.setFeature(feature, false);

    // Disable #external-parameter-entities
    feature = "http://xml.org/sax/features/external-parameter-entities";
    domFactory.setFeature(feature, false);

    // Disable external DTDs as well
    feature = "http://apache.org/xml/features/nonvalidating/load-external-dtd";
    domFactory.setFeature(feature, false);

    // and these as well
    domFactory.setXIncludeAware(false);
    domFactory.setExpandEntityReferences(false);
    domFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
  } catch (ParserConfigurationException e) {
    LOG.error(e.getMessage());
  }

  return domFactory;
}
 
Example 18
public static Element stringToElement(String xml) {
	if (xml == null || xml.trim().length() == 0) {
		return null;
	}
	try {
		DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
		docFactory.setNamespaceAware(false);
		docFactory.setXIncludeAware(false);
		docFactory.setExpandEntityReferences(false);

		docFactory.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_GENERAL_ENTITIES_FEATURE, false);

		docFactory.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_PARAMETER_ENTITIES_FEATURE, false);

		docFactory.setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.LOAD_EXTERNAL_DTD_FEATURE, false);

		SecurityManager securityManager = new SecurityManager();
		securityManager.setEntityExpansionLimit(0);
		docFactory.setAttribute(Constants.XERCES_PROPERTY_PREFIX + Constants.SECURITY_MANAGER_PROPERTY,
				securityManager);

		DocumentBuilder db = docFactory.newDocumentBuilder();
		return db.parse(new ByteArrayInputStream(xml.getBytes())).getDocumentElement();
	} catch (Exception e) {
		throw new RuntimeException(e.getMessage(), e);
	}
}
 
Example 19
Source Project: hottub   File: XmlUtil.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static DocumentBuilderFactory newDocumentBuilderFactory(boolean secureXmlProcessing) {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    try {
        factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, isXMLSecurityDisabled(secureXmlProcessing));
    } catch (ParserConfigurationException e) {
        LOGGER.log(Level.WARNING, "Factory [{0}] doesn't support secure xml processing!", new Object[] { factory.getClass().getName() } );
    }
    return factory;
}
 
Example 20
Source Project: org.hl7.fhir.core   File: XmlParser.java    License: Apache License 2.0 4 votes vote down vote up
public Element parse(InputStream stream) throws Exception {
	Document doc = null;
	try {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		// xxe protection
		factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
		factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
		factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
		factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
		factory.setXIncludeAware(false);
		factory.setExpandEntityReferences(false);

		factory.setNamespaceAware(true);
		if (policy == ValidationPolicy.EVERYTHING) {
			// use a slower parser that keeps location data
			TransformerFactory transformerFactory = TransformerFactory.newInstance();
			Transformer nullTransformer = transformerFactory.newTransformer();
			DocumentBuilder docBuilder = factory.newDocumentBuilder();
			doc = docBuilder.newDocument();
			DOMResult domResult = new DOMResult(doc);
			SAXParserFactory spf = SAXParserFactory.newInstance();
			spf.setNamespaceAware(true);
			spf.setValidating(false);
			SAXParser saxParser = spf.newSAXParser();
			XMLReader xmlReader = saxParser.getXMLReader();
			// xxe protection
			spf.setFeature("http://xml.org/sax/features/external-general-entities", false);
			spf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
			xmlReader.setFeature("http://xml.org/sax/features/external-general-entities", false);
			xmlReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);

			XmlLocationAnnotator locationAnnotator = new XmlLocationAnnotator(xmlReader, doc);
			InputSource inputSource = new InputSource(stream);
			SAXSource saxSource = new SAXSource(locationAnnotator, inputSource);
			nullTransformer.transform(saxSource, domResult);
		} else {
			DocumentBuilder builder = factory.newDocumentBuilder();
			doc = builder.parse(stream);
		}
	} catch (Exception e) {
		logError(0, 0, "(syntax)", IssueType.INVALID, e.getMessage(), IssueSeverity.FATAL);
		doc = null;
	}
	if (doc == null)
		return null;
	else
		return parse(doc);
}