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.wso2.carbon.policyeditor.PolicyEditorService.java

/**
 * Formats a given unformatted XML string
 *
 * @param xml// w  w w.jav a  2s . c om
 * @return A CDATA wrapped, formatted XML String
 */
public String formatXML(String xml) {

    try {
        // create the factory
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        docFactory.setIgnoringComments(true);
        docFactory.setNamespaceAware(true);
        docFactory.setExpandEntityReferences(false);
        SecurityManager securityManager = new SecurityManager();
        securityManager.setEntityExpansionLimit(ENTITY_EXPANSION_LIMIT);
        docFactory.setAttribute(SECURITY_MANAGER_PROPERTY, securityManager);
        DocumentBuilder docBuilder;
        Document xmlDoc;

        // now use the factory to create the document builder
        docFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        docBuilder = docFactory.newDocumentBuilder();
        docBuilder.setEntityResolver(new CarbonEntityResolver());
        xmlDoc = docBuilder.parse(new ByteArrayInputStream(xml.getBytes(Charsets.UTF_8)));

        OutputFormat format = new OutputFormat(xmlDoc);
        format.setLineWidth(0);
        format.setIndenting(true);
        format.setIndent(2);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        XMLSerializer serializer = new XMLSerializer(baos, format);
        serializer.serialize(xmlDoc);

        xml = baos.toString("UTF-8");

    } catch (ParserConfigurationException pce) {
        throw new IllegalArgumentException("Failed to setup repository: ");
    } catch (Exception e) {
        log.error(e);
    }

    return "<![CDATA[" + xml + "]]>";
}

From source file:org.wso2.carbon.task.ui.internal.TaskManagementHelper.java

/**
 * This method provides a secured document builder which will secure XXE attacks.
 *
 * @param setIgnoreComments whether to set setIgnoringComments in DocumentBuilderFactory.
 * @return DocumentBuilder/*from   w w w.  j a v  a2 s . co  m*/
 * @throws javax.xml.parsers.ParserConfigurationException
 */
public static DocumentBuilder getSecuredDocumentBuilder(boolean setIgnoreComments)
        throws ParserConfigurationException {
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setIgnoringComments(setIgnoreComments);
    documentBuilderFactory.setNamespaceAware(true);
    documentBuilderFactory.setExpandEntityReferences(false);
    documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    documentBuilderFactory.setXIncludeAware(false);
    org.apache.xerces.util.SecurityManager securityManager = new SecurityManager();
    securityManager.setEntityExpansionLimit(0);
    documentBuilderFactory.setAttribute(Constants.XERCES_PROPERTY_PREFIX + Constants.SECURITY_MANAGER_PROPERTY,
            securityManager);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    documentBuilder.setEntityResolver(new EntityResolver() {
        @Override
        public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
            throw new SAXException("Possible XML External Entity (XXE) attack. Skipping entity resolving");
        }
    });
    return documentBuilder;
}

From source file:org.wso2.carbon.tools.wsdlvalidator.WsdlValidator.java

/**
 * Load XML data to a temporary file.//w w  w.  j av  a  2s  .  c  om
 *
 * @param document XML DOM
 * @return URL of the file
 * @throws IOException          on error writing to file
 * @throws TransformerException on transforming error
 */
private URL loadXMLToFile(Document document) throws TransformerException, IOException {
    DOMSource source = new DOMSource(document);
    File tempFile = File.createTempFile("temp", ".txt");
    tempFile.deleteOnExit();
    FileWriter writer = new FileWriter(tempFile);
    StreamResult result = new StreamResult(writer);
    TransformerFactory transformerFactory;
    try {
        transformerFactory = TransformerFactory
                .newInstance("com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl", null);
    } catch (NoSuchMethodError e) {
        log.info("TransformerFactory.newInstance(String, ClassLoader) method not found. "
                + "Using TransformerFactory.newInstance()");
        transformerFactory = TransformerFactory.newInstance();
    }
    transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    Transformer transformer = transformerFactory.newTransformer();
    transformer.transform(source, result);
    return tempFile.toURI().toURL();
}

From source file:org.wso2.carbon.utils.CarbonUtils.java

/**
 *
 * @param xmlConfiguration InputStream that carries xml configuration
 * @return returns a InputStream that has evaluated system variables in input
 * @throws CarbonException/*from  w w  w.ja va 2s .  c o m*/
 */
public static InputStream replaceSystemVariablesInXml(InputStream xmlConfiguration) throws CarbonException {
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder;
    Document doc;
    try {
        documentBuilderFactory.setNamespaceAware(true);
        documentBuilderFactory.setExpandEntityReferences(false);
        documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        SecurityManager securityManager = new SecurityManager();
        securityManager.setEntityExpansionLimit(CarbonConstants.ENTITY_EXPANSION_LIMIT_0);
        documentBuilderFactory.setAttribute(CarbonConstants.SECURITY_MANAGER_PROPERTY, securityManager);
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
        documentBuilder.setEntityResolver(new CarbonEntityResolver());
        doc = documentBuilder.parse(xmlConfiguration);
    } catch (Exception e) {
        throw new CarbonException("Error in building Document", e);
    }
    NodeList nodeList = null;
    if (doc != null) {
        nodeList = doc.getElementsByTagName("*");
    }
    if (nodeList != null) {
        for (int i = 0; i < nodeList.getLength(); i++) {
            resolveLeafNodeValue(nodeList.item(i));
        }
    }
    return toInputStream(doc);
}

From source file:org.wso2.carbon.webapp.authenticator.framework.AuthenticationFrameworkUtil.java

public static Document convertToDocument(File file) throws AuthenticatorFrameworkException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);/*www  .  j  a v  a 2s .c o  m*/
    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 AuthenticatorFrameworkException(
                "Error occurred while parsing file, while converting " + "to a org.w3c.dom.Document", e);
    }
}

From source file:org.wso2.carbon.wsdl2form.Util.java

/**
 * Load XML data to a temporary file./*from w ww  .  j  av a2  s. c  o m*/
 *
 * @param document XML URL
 * @return URL of the file
 * @throws IOException          on error writing to file
 */
private static File loadXMLToFile(Document document) throws IOException {
    DOMSource source = new DOMSource(document);
    File tempFile = File.createTempFile("temp", ".txt");
    tempFile.deleteOnExit();
    try (FileWriter writer = new FileWriter(tempFile)) {
        StreamResult result = new StreamResult(writer);
        TransformerFactory transformerFactory = getTransformerFactory();
        transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        Transformer transformer = transformerFactory.newTransformer();
        transformer.transform(source, result);
    } catch (IOException e) {
        String msg = "Error occurred when creating FileWriter";
        log.error(msg, e);
        throw new AxisFault(msg, e);
    } catch (TransformerException e) {
        String msg = "Error occurred when transforming the document safely";
        log.error(msg, e);
        throw new AxisFault(msg, e);
    }
    return tempFile;
}

From source file:org.wso2.identity.iml.dsl.mediators.SAMLRequestProcessor.java

private AuthnRequest SAMLRequestParser(String samlRequest) throws ParserConfigurationException, SAXException,
        ConfigurationException, IOException, UnmarshallingException {

    IMLUtils.doBootstrap();// w  w w . j a  v  a2  s  .  co m
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    documentBuilderFactory.setExpandEntityReferences(false);
    documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);

    org.apache.xerces.util.SecurityManager securityManager = new SecurityManager();
    securityManager.setEntityExpansionLimit(0);

    documentBuilderFactory.setAttribute(SECURITY_MANAGER_PROPERTY, securityManager);
    DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder();
    docBuilder.setEntityResolver((publicId, systemId) -> {
        throw new SAXException(
                "SAML request contains invalid elements. Possible XML External Entity " + "(XXE) attack.");
    });

    try (InputStream inputStream = new ByteArrayInputStream(
            samlRequest.trim().getBytes(StandardCharsets.UTF_8))) {

        Document document = docBuilder.parse(inputStream);
        Element element = document.getDocumentElement();

        UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
        Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element);

        AuthnRequest authnRequest = (AuthnRequest) unmarshaller.unmarshall(element);
        return authnRequest;
    }

}

From source file:org.wso2.identity.scenarios.commons.SAML2SSOTestBase.java

private XMLObject unmarshall(String saml2SSOString) throws Exception {

    doBootstrap();/*from   w  w w. j  a va 2s.com*/
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    documentBuilderFactory.setXIncludeAware(false);
    documentBuilderFactory.setExpandEntityReferences(false);
    try {
        documentBuilderFactory
                .setFeature(Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_GENERAL_ENTITIES_FEATURE, false);
        documentBuilderFactory.setFeature(
                Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_PARAMETER_ENTITIES_FEATURE, false);
        documentBuilderFactory.setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.LOAD_EXTERNAL_DTD_FEATURE,
                false);
        documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);

    } 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
                + " or secure-processing.");
    }

    org.apache.xerces.util.SecurityManager securityManager = new SecurityManager();
    securityManager.setEntityExpansionLimit(ENTITY_EXPANSION_LIMIT);
    documentBuilderFactory.setAttribute(Constants.XERCES_PROPERTY_PREFIX + Constants.SECURITY_MANAGER_PROPERTY,
            securityManager);

    documentBuilderFactory.setIgnoringComments(true);
    Document document = getDocument(documentBuilderFactory, saml2SSOString);
    if (isSignedWithComments(document)) {
        documentBuilderFactory.setIgnoringComments(false);
        document = getDocument(documentBuilderFactory, saml2SSOString);
    }
    Element element = document.getDocumentElement();
    UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
    Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element);
    return unmarshaller.unmarshall(element);
}

From source file:org.wso2.mobile.utils.utilities.ZipFileReading.java

public static Document loadXMLFromString(String xml) throws Exception {

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    InputSource is = new InputSource(new StringReader(xml));
    return builder.parse(is);
}

From source file:org.wso2.pc.integration.tests.publisher.processes.AssociateBPMNTestCase.java

private Element getAssociateProcess(String processType) throws Exception {
    Element associateProcessElement = null;
    WSRegistryServiceClient wsRegistryServiceClient = registryProviderUtil.getWSRegistry(automationContext);
    String xml = new String(wsRegistryServiceClient.getContent("/_system/governance/bpmn/TestProcess1/1.0"));
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
    Document document = builder.parse(new InputSource(new StringReader(xml)));
    Element root = document.getDocumentElement();
    if (root.getElementsByTagName(processType) != null)
        associateProcessElement = (Element) root.getElementsByTagName(processType).item(0);
    return associateProcessElement;
}