List of usage examples for javax.xml.parsers DocumentBuilderFactory setExpandEntityReferences
public void setExpandEntityReferences(boolean expandEntityRef)
From source file:org.cytobank.acs.core.TableOfContents.java
/** * <p>Creates a DocumentBuilder with Cytobank's preferred security settings * applied to it. Specifically turning off external entities and external * DTDs to prevent External Entity Exploits (XXE)</p> * * @throws ParserConfigurationException//from ww w. j a v a 2s.co m * @return DocumentBuilder */ protected DocumentBuilder getDocumentBuilder() throws ParserConfigurationException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = null; String FEATURE = null; // This is the PRIMARY defense. If DTDs (doctypes) are disallowed, almost all XML entity attacks are prevented // Xerces 2 only - http://xerces.apache.org/xerces2-j/features.html#disallow-doctype-decl FEATURE = "http://apache.org/xml/features/disallow-doctype-decl"; dbf.setFeature(FEATURE, true); // If you can't completely disable DTDs, then at least do the following: // Xerces 1 - http://xerces.apache.org/xerces-j/features.html#external-general-entities // Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#external-general-entities // JDK7+ - http://xml.org/sax/features/external-general-entities FEATURE = "http://xml.org/sax/features/external-general-entities"; dbf.setFeature(FEATURE, false); // Xerces 1 - http://xerces.apache.org/xerces-j/features.html#external-parameter-entities // Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#external-parameter-entities // JDK7+ - http://xml.org/sax/features/external-parameter-entities FEATURE = "http://xml.org/sax/features/external-parameter-entities"; dbf.setFeature(FEATURE, false); // Disable external DTDs as well FEATURE = "http://apache.org/xml/features/nonvalidating/load-external-dtd"; dbf.setFeature(FEATURE, false); // and these as well, per Timothy Morgan's 2014 paper: "XML Schema, DTD, and Entity Attacks" (see reference below) dbf.setXIncludeAware(false); dbf.setExpandEntityReferences(false); // And, per Timothy Morgan: "If for some reason support for inline DOCTYPEs are a requirement, then // ensure the entity settings are disabled (as shown above) and beware that SSRF attacks // (http://cwe.mitre.org/data/definitions/918.html) and denial // of service attacks (such as billion laughs or decompression bombs via "jar:") are a risk." boolean namespaceAware = true; boolean xsdValidate = false; boolean ignoreWhitespace = false; boolean ignoreComments = false; boolean putCDATAIntoText = false; boolean createEntityRefs = false; dbf.setNamespaceAware(namespaceAware); dbf.setValidating(xsdValidate); dbf.setIgnoringComments(ignoreComments); dbf.setIgnoringElementContentWhitespace(ignoreWhitespace); dbf.setCoalescing(putCDATAIntoText); dbf.setExpandEntityReferences(createEntityRefs); db = dbf.newDocumentBuilder(); return db; }
From source file:org.forgerock.maven.plugins.LinkTester.java
@Override() public void execute() throws MojoExecutionException, MojoFailureException { if (outputFile != null) { if (!outputFile.isAbsolute()) { outputFile = new File(project.getBasedir(), outputFile.getPath()); }// ww w . j a va2 s . com if (outputFile.exists()) { debug("Deleting existing outputFile: " + outputFile); outputFile.delete(); } try { outputFile.createNewFile(); fileWriter = new FileWriter(outputFile); } catch (IOException ioe) { error("Error while creating output file", ioe); } } initializeSkipUrlPatterns(); //Initialize XML parsers and XPath expressions DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setExpandEntityReferences(false); dbf.setXIncludeAware(xIncludeAware); if (validating) { SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); try { Schema schema = sf.newSchema(new URL(DOCBOOK_XSD)); dbf.setSchema(schema); } catch (MalformedURLException murle) { error("Invalid URL provided as schema source", murle); } catch (SAXException saxe) { error("Parsing error occurred while constructing schema for validation", saxe); } } DocumentBuilder db; try { db = dbf.newDocumentBuilder(); db.setErrorHandler(new LoggingErrorHandler(this)); } catch (ParserConfigurationException pce) { throw new MojoExecutionException("Unable to create new DocumentBuilder", pce); } XPathFactory xpf = XPathFactory.newInstance(); XPath xpath = xpf.newXPath(); xpath.setNamespaceContext(new XmlNamespaceContext()); XPathExpression expr; try { expr = xpath.compile("//@xml:id"); } catch (XPathExpressionException xpee) { throw new MojoExecutionException("Unable to compile Xpath expression", xpee); } if (docSources != null) { for (DocSource docSource : docSources) { processDocSource(docSource, db, expr); } } try { if (!skipOlinks) { //we can only check olinks after going through all the documents, otherwise we would see false //positives, because of the not yet processed files for (Map.Entry<String, Collection<String>> entry : (Set<Map.Entry<String, Collection<String>>>) olinks .entrySet()) { for (String val : entry.getValue()) { checkOlink(entry.getKey(), val); } } } if (!failedUrls.isEmpty()) { error("The following files had invalid URLs:\n" + failedUrls.toString()); } if (!timedOutUrls.isEmpty()) { warn("The following files had unavailable URLs (connection or read timed out):\n" + timedOutUrls.toString()); } if (failedUrls.isEmpty() && timedOutUrls.isEmpty() && !failure) { //there are no failed URLs and the parser didn't encounter any errors either info("DocBook links successfully tested, no errors reported."); } } finally { flushReport(); } if (failOnError) { if (failure || !failedUrls.isEmpty()) { throw new MojoFailureException("One or more error occurred during plugin execution"); } } }
From source file:org.gluu.oxtrust.ldap.service.Shibboleth2ConfService.java
/** * @param stream//www . j a va 2s . c o m * @throws IOException * @throws SAXException * @throws ParserConfigurationException */ public synchronized GluuErrorHandler validateMetadata(InputStream stream) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory newFactory = DocumentBuilderFactory.newInstance(); newFactory.setCoalescing(false); newFactory.setExpandEntityReferences(true); newFactory.setIgnoringComments(false); newFactory.setIgnoringElementContentWhitespace(false); newFactory.setNamespaceAware(true); newFactory.setValidating(false); DocumentBuilder xmlParser = newFactory.newDocumentBuilder(); Document xmlDoc = xmlParser.parse(stream); String schemaDir = System.getProperty("catalina.home") + File.separator + "conf" + File.separator + "shibboleth2" + File.separator + "idp" + File.separator + "schema" + File.separator; Schema schema = SchemaBuilder.buildSchema(SchemaLanguage.XML, schemaDir); Validator validator = schema.newValidator(); GluuErrorHandler handler = new GluuErrorHandler(); validator.setErrorHandler(handler); validator.validate(new DOMSource(xmlDoc)); return handler; }
From source file:org.gluu.saml.Response.java
public void loadXml(String xml) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory fty = DocumentBuilderFactory.newInstance(); fty.setNamespaceAware(true);/*www.j av a 2 s .c om*/ // Fix XXE vulnerability fty.setXIncludeAware(false); fty.setExpandEntityReferences(false); fty.setFeature("http://xml.org/sax/features/external-parameter-entities", false); fty.setFeature("http://xml.org/sax/features/external-general-entities", false); fty.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); DocumentBuilder builder = fty.newDocumentBuilder(); ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes()); xmlDoc = builder.parse(bais); }
From source file:org.gss_project.gss.server.rest.Webdav.java
/** * Return JAXP document builder instance. * * @return the DocumentBuilder//from www. j a v a2 s . com * @throws ServletException */ private DocumentBuilder getDocumentBuilder() throws ServletException { DocumentBuilder documentBuilder = null; DocumentBuilderFactory documentBuilderFactory = null; try { documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); documentBuilderFactory.setExpandEntityReferences(false); documentBuilder = documentBuilderFactory.newDocumentBuilder(); documentBuilder.setEntityResolver(new WebdavResolver(getServletContext())); } catch (ParserConfigurationException e) { throw new ServletException("Error while creating a document builder"); } return documentBuilder; }
From source file:org.icatproject.idav.methods.AbstractMethod.java
/** * Return JAXP document builder instance. *///from w ww . java 2 s.c om protected DocumentBuilder getDocumentBuilder() throws ServletException { DocumentBuilder documentBuilder = null; DocumentBuilderFactory documentBuilderFactory = null; try { documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); // disable XML External Entities to prevent XML XXE attacks as described at: // https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Prevention_Cheat_Sheet documentBuilderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false); documentBuilderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); documentBuilderFactory.setXIncludeAware(false); documentBuilderFactory.setExpandEntityReferences(false); // documentBuilder = documentBuilderFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { String msg = "Failed to create an XML DocumentBuilder which satisfies the configuration requested: " + e.getMessage(); LOG.error(msg); throw new ServletException(msg); } return documentBuilder; }
From source file:org.jaggeryjs.modules.sso.common.util.Util.java
/** * Create DocumentBuilderFactory with the XXE prevention measurements * * @return DocumentBuilderFactory instance *//*w w w.j a v a 2 s . c om*/ public static DocumentBuilderFactory getSecuredDocumentBuilder() { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setXIncludeAware(false); dbf.setExpandEntityReferences(false); try { dbf.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_GENERAL_ENTITIES_FEATURE, false); dbf.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_PARAMETER_ENTITIES_FEATURE, false); dbf.setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.LOAD_EXTERNAL_DTD_FEATURE, false); } catch (ParserConfigurationException e) { log.error("Failed to load XML Processor Feature " + Constants.EXTERNAL_GENERAL_ENTITIES_FEATURE + " or " + Constants.EXTERNAL_PARAMETER_ENTITIES_FEATURE + " or " + Constants.LOAD_EXTERNAL_DTD_FEATURE); } SecurityManager securityManager = new SecurityManager(); securityManager.setEntityExpansionLimit(ENTITY_EXPANSION_LIMIT); dbf.setAttribute(Constants.XERCES_PROPERTY_PREFIX + Constants.SECURITY_MANAGER_PROPERTY, securityManager); return dbf; }
From source file:org.sakaiproject.dav.DavServlet.java
/** * Return JAXP document builder instance. *//* w w w . j a v a2 s.co m*/ protected DocumentBuilder getDocumentBuilder() throws ServletException { DocumentBuilder documentBuilder = null; DocumentBuilderFactory documentBuilderFactory = null; try { documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); documentBuilderFactory.setExpandEntityReferences(false); documentBuilderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false); documentBuilderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); documentBuilder = documentBuilderFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new ServletException("Sakaidavservlet.jaxpfailed"); } return documentBuilder; }
From source file:org.springframework.ide.eclipse.internal.uaa.UaaManager.java
/** * Starts up this {@link UaaManager} instance. */// w w w . ja v a2 s.c o m public void start() { // Since we run in an restricted environment we need to obtain the builder factory from the OSGi service // registry instead of trying to create a new one from the API DocumentBuilderFactory documentBuilderFactory = UaaUtils.getDocumentBuilderFactory(); documentBuilderFactory.setExpandEntityReferences(false); XmlUtils.setDocumentBuilderFactory(documentBuilderFactory); try { initProductDescriptions(getDefaultDetectedProducts(), getDefaultDetectedProductsSignaturer()); } catch (IOException e) { } // Add Transmission listener so that we can download the list of detected products periodically. service.addTransmissionEventListener(new TransmissionEventListener() { public void afterTransmission(TransmissionType type, boolean success) { if (type == TransmissionType.DOWNLOAD && success) { InputStream configuration = null; InputStream configurationSignature = null; try { configuration = service.getTransmissionService().download(UAA_URL); configurationSignature = service.getTransmissionService().download(SIGNATURE_URL); initProductDescriptions(configuration, configurationSignature); } catch (IOException e) { } finally { // Safely close the streams if (configuration != null) { try { configuration.close(); } catch (IOException e) { } } if (configurationSignature != null) { try { configurationSignature.close(); } catch (IOException e) { } } } } } public void beforeTransmission(TransmissionType type) { } }); // After starting up and reporting the initial state we should send the data Job transmissionJob = new Job("Initializing Spring UAA") { @Override protected IStatus run(IProgressMonitor monitor) { if (service instanceof TransmissionAwareUaaService) { ((TransmissionAwareUaaService) service).requestTransmission(); } return Status.OK_STATUS; } }; transmissionJob.setSystem(true); transmissionJob.setPriority(Job.DECORATE); // Schedule this for 10 minutes into the running instance transmissionJob.schedule(10L * 60L * 1000L); }
From source file:org.wso2.appserver.webapp.security.utils.SSOUtils.java
/** * Generates a {@code javax.xml.parsers.DocumentBuilder} instance based on the specified configurations. * * @param expandEntityReferences true if the parser is to expand entity reference nodes, else false * @param namespaceAware true if the parser provides support for XML namespaces, else false * @param entityResolver the {@link EntityResolver} to be used within the parser, if {@code entityResolver} * is set to null default implementation is used * @return the generated {@link DocumentBuilder} instance * @throws SSOException if an error occurs when generating the new DocumentBuilder */// w w w . j a va 2s. c o m private static DocumentBuilder getDocumentBuilder(boolean expandEntityReferences, boolean namespaceAware, EntityResolver entityResolver) throws SSOException { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); if (!expandEntityReferences) { documentBuilderFactory.setExpandEntityReferences(false); } if (namespaceAware) { documentBuilderFactory.setNamespaceAware(true); } DocumentBuilder docBuilder; try { docBuilder = documentBuilderFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new SSOException("Error when generating the new DocumentBuilder", e); } Optional.ofNullable(entityResolver).ifPresent(docBuilder::setEntityResolver); return docBuilder; }