Example usage for javax.xml XMLConstants FEATURE_SECURE_PROCESSING

List of usage examples for javax.xml XMLConstants FEATURE_SECURE_PROCESSING

Introduction

In this page you can find the example usage for javax.xml XMLConstants FEATURE_SECURE_PROCESSING.

Prototype

String FEATURE_SECURE_PROCESSING

To view the source code for javax.xml XMLConstants FEATURE_SECURE_PROCESSING.

Click Source Link

Document

Feature for secure processing.

Usage

From source file:org.apache.nifi.processors.standard.TransformXml.java

private Templates newTemplates(final ProcessContext context, final String path)
        throws TransformerConfigurationException, LookupFailureException {
    final Boolean secureProcessing = context.getProperty(SECURE_PROCESSING).asBoolean();
    TransformerFactory factory = TransformerFactory.newInstance();
    final boolean isFilename = context.getProperty(XSLT_FILE_NAME).isSet();

    if (secureProcessing) {
        factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        // don't be overly DTD-unfriendly forcing http://apache.org/xml/features/disallow-doctype-decl
        factory.setFeature(//from   www.  j  a va  2 s . c o m
                "http://saxon.sf.net/feature/parserFeature?uri=http://xml.org/sax/features/external-parameter-entities",
                false);
        factory.setFeature(
                "http://saxon.sf.net/feature/parserFeature?uri=http://xml.org/sax/features/external-general-entities",
                false);
    }

    if (isFilename) {
        return factory.newTemplates(new StreamSource(path));
    } else {
        final String coordinateKey = lookupService.get().getRequiredKeys().iterator().next();
        final Optional<String> attributeValue = lookupService.get()
                .lookup(Collections.singletonMap(coordinateKey, path));
        if (attributeValue.isPresent() && StringUtils.isNotBlank(attributeValue.get())) {
            return factory.newTemplates(new StreamSource(
                    new ByteArrayInputStream(attributeValue.get().getBytes(StandardCharsets.UTF_8))));
        } else {
            throw new TransformerConfigurationException(
                    "No XSLT definition is associated to " + path + " in the lookup controller service.");
        }
    }
}

From source file:org.apache.rahas.TrustUtil.java

/**
 * Create DocumentBuilderFactory with the XXE and XEE prevention measurements
 *
 * @return DocumentBuilderFactory instance
 *///from   w  ww  .  j  av  a 2  s.  co  m
public static DocumentBuilderFactory getSecuredDocumentBuilderFactory() {

    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);
        dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    } catch (ParserConfigurationException e) {
        logger.error("Failed to load XML Processor Feature " + Constants.EXTERNAL_GENERAL_ENTITIES_FEATURE
                + " or " + Constants.EXTERNAL_PARAMETER_ENTITIES_FEATURE + " or "
                + Constants.LOAD_EXTERNAL_DTD_FEATURE + "or secure-processing.");
    }

    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.apache.rampart.util.Axis2Util.java

/**
 * Create DocumentBuilderFactory with the XXE prevention measurements
 *
 * @return DocumentBuilderFactory instance
 *//*  w  w w  . j a v  a 2s .c  o m*/
public static DocumentBuilderFactory getSecuredDocumentBuilderFactory() {

    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);
        dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    } catch (ParserConfigurationException e) {
        logger.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.apache.ranger.utils.install.XmlConfigChanger.java

public void run() throws ParserConfigurationException, SAXException, IOException, TransformerException {

    loadInstallProperties();/*from ww  w. j a  v a 2 s . c o  m*/

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    doc = builder.parse(inpFile);

    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new FileReader(confFile));

        String line = null;

        @SuppressWarnings("unused")
        int lineNo = 0;
        Properties variables = new Properties();
        while ((line = reader.readLine()) != null) {

            lineNo++;

            line = line.trim();

            if (line.isEmpty())
                continue;
            if (line.startsWith("#")) {
                continue;
            }

            if (line.contains("#")) {
                int len = line.indexOf("#");
                line = line.substring(0, len);
            }

            String[] tokens = line.split("\\s+");

            String propName = tokens[0];

            String propValue = null;

            try {
                if (propnameContainsVariables(propName)) {
                    propName = replaceProp(propName, variables);
                }
                propValue = replaceProp(tokens[1], installProperties);
            } catch (ValidationException e) {
                // throw new RuntimeException("Unable to replace tokens in the line: \n[" + line + "]\n in file [" + confFile.getAbsolutePath() + "] line number:["  + lineNo + "]" );
                throw new RuntimeException(e);
            }

            String actionType = tokens[2];
            String options = (tokens.length > 3 ? tokens[3] : null);
            boolean createIfNotExists = (options != null && options.contains("create-if-not-exists"));

            if ("add".equals(actionType)) {
                addProperty(propName, propValue);
            } else if ("mod".equals(actionType)) {
                modProperty(propName, propValue, createIfNotExists);
            } else if ("del".equals(actionType)) {
                delProperty(propName);
            } else if ("append".equals(actionType)) {
                String curVal = getProperty(propName);
                if (curVal == null) {
                    if (createIfNotExists) {
                        addProperty(propName, propValue);
                    }
                } else {
                    String appendDelimitor = (tokens.length > 4 ? tokens[4] : " ");
                    if (!curVal.contains(propValue)) {
                        String newVal = null;
                        if (curVal.length() == 0) {
                            newVal = propValue;
                        } else {
                            newVal = curVal + appendDelimitor + propValue;
                        }
                        modProperty(propName, newVal, createIfNotExists);
                    }
                }
            } else if ("delval".equals(actionType)) {
                String curVal = getProperty(propName);
                if (curVal != null) {
                    String appendDelimitor = (tokens.length > 4 ? tokens[4] : " ");
                    if (curVal.contains(propValue)) {
                        String[] valTokens = curVal.split(appendDelimitor);
                        StringBuilder sb = new StringBuilder();
                        for (String v : valTokens) {
                            if (!v.equals(propValue)) {
                                if (sb.length() > 0) {
                                    sb.append(appendDelimitor);
                                }
                                sb.append(v);
                            }
                        }
                        String newVal = sb.toString();
                        modProperty(propName, newVal, createIfNotExists);
                    }
                }
            } else if ("var".equals(actionType)) {
                variables.put(propName, propValue);
            } else {
                throw new RuntimeException(
                        "Unknown Command Found: [" + actionType + "], Supported Types:  add modify del append");
            }

        }

        TransformerFactory tfactory = TransformerFactory.newInstance();
        Transformer transformer = tfactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

        DOMSource source = new DOMSource(doc);
        FileOutputStream out = new FileOutputStream(outFile);
        StreamResult result = new StreamResult(out);
        transformer.transform(source, result);
        out.close();

    } finally {
        if (reader != null) {
            reader.close();
        }
    }

}

From source file:org.fao.geonet.utils.Xml.java

private static SAXBuilder getSAXBuilderWithoutXMLResolver(boolean validate) {
    SAXBuilder builder = new SAXBuilder(validate);
    builder.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    return builder;
}

From source file:org.kitodo.production.editor.XMLEditor.java

/**
 * Constructor./* ww w.j a  v a  2  s .  com*/
 */
public XMLEditor() {
    try {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        logger.error("ERROR: unable to instantiate document builder: " + e.getMessage());
    }
}

From source file:org.kitodo.production.plugin.importer.massimport.PicaMassImport.java

/**
 * Get OPAC address./*  w w w.  j  av a 2  s .  c  o  m*/
 *
 * @return the address of the opac catalogue
 */
private String getOpacAddress() throws ImportPluginException {

    String address;

    try (FileInputStream istream = new FileInputStream(KitodoConfigFile.OPAC_CONFIGURATION.getFile())) {

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);

        DocumentBuilder builder = factory.newDocumentBuilder();

        Document xmlDocument = builder.parse(istream);

        XPath xPath = XPathFactory.newInstance().newXPath();

        Node node = (Node) xPath
                .compile("/opacCatalogues/catalogue[@title='" + this.getOpacCatalogue() + "']/config")
                .evaluate(xmlDocument, XPathConstants.NODE);

        address = node.getAttributes().getNamedItem("address").getNodeValue();

    } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException e) {
        logger.error(e.getMessage(), e);
        throw new ImportPluginException(e);
    }
    return address;
}

From source file:org.kitodo.production.services.data.ImportService.java

private Document transformXmlByXslt(String xmlString, File stylesheetFile) {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    try {/*from  w ww.ja va  2  s.  c  om*/
        factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    } catch (ParserConfigurationException e) {
        throw new IllegalArgumentException(e.getMessage(), e);
    }
    factory.setNamespaceAware(true);
    try {
        SAXBuilder saxBuilder = new SAXBuilder();
        DOMOutputter outputter = new DOMOutputter();
        StreamSource transformSource = new StreamSource(stylesheetFile);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        File outputFile = File.createTempFile("transformed", "xml");
        try (FileOutputStream outputStream = new FileOutputStream(outputFile)) {
            Transformer xsltTransformer = transformerFactory.newTransformer(transformSource);
            TransformerHandler handler = ((SAXTransformerFactory) SAXTransformerFactory.newInstance())
                    .newTransformerHandler();
            handler.setResult(new StreamResult(outputStream));
            Result saxResult = new SAXResult(handler);
            SAXSource saxSource = new SAXSource(new InputSource(new StringReader(xmlString)));
            xsltTransformer.transform(saxSource, saxResult);
        }
        return outputter.output(saxBuilder.build(outputFile));
    } catch (JDOMException | IOException | TransformerException e) {
        throw new ConfigException("Error in transforming the response in intern format : ", e);
    }
}

From source file:org.openstreetmap.josm.tools.Utils.java

/**
 * Returns a new secure DOM builder, supporting XML namespaces.
 * @return a new secure DOM builder, supporting XML namespaces
 * @throws ParserConfigurationException if a parser cannot be created which satisfies the requested configuration.
 * @since 10404/*from   w ww  .  j  ava 2 s .c om*/
 */
public static DocumentBuilder newSafeDOMBuilder() throws ParserConfigurationException {
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    builderFactory.setNamespaceAware(true);
    builderFactory.setValidating(false);
    return builderFactory.newDocumentBuilder();
}

From source file:org.openstreetmap.josm.tools.Utils.java

/**
 * Returns a new secure SAX parser, supporting XML namespaces.
 * @return a new secure SAX parser, supporting XML namespaces
 * @throws ParserConfigurationException if a parser cannot be created which satisfies the requested configuration.
 * @throws SAXException for SAX errors./*from  w  w  w. ja v  a2s. c o  m*/
 * @since 8287
 */
public static SAXParser newSafeSAXParser() throws ParserConfigurationException, SAXException {
    SAXParserFactory parserFactory = SAXParserFactory.newInstance();
    parserFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    parserFactory.setNamespaceAware(true);
    return parserFactory.newSAXParser();
}