Example usage for javax.xml.parsers DocumentBuilder setEntityResolver

List of usage examples for javax.xml.parsers DocumentBuilder setEntityResolver

Introduction

In this page you can find the example usage for javax.xml.parsers DocumentBuilder setEntityResolver.

Prototype


public abstract void setEntityResolver(EntityResolver er);

Source Link

Document

Specify the EntityResolver to be used to resolve entities present in the XML document to be parsed.

Usage

From source file:org.unitime.commons.hibernate.util.HibernateUtil.java

public static void configureHibernateFromRootDAO(String cfgName, Configuration cfg) {
    try {/*from  ww  w .  j a v a 2 s  .  c om*/
        EntityResolver entityResolver = new EntityResolver() {
            public InputSource resolveEntity(String publicId, String systemId) {
                if (publicId.equals("-//Hibernate/Hibernate Mapping DTD 3.0//EN")) {
                    return new InputSource(HibernateUtil.class.getClassLoader()
                            .getResourceAsStream("org/hibernate/hibernate-mapping-3.0.dtd"));
                } else if (publicId.equals("-//Hibernate/Hibernate Mapping DTD//EN")) {
                    return new InputSource(HibernateUtil.class.getClassLoader()
                            .getResourceAsStream("org/hibernate/hibernate-mapping-3.0.dtd"));
                } else if (publicId.equals("-//Hibernate/Hibernate Configuration DTD 3.0//EN")) {
                    return new InputSource(HibernateUtil.class.getClassLoader()
                            .getResourceAsStream("org/hibernate/hibernate-configuration-3.0.dtd"));
                } else if (publicId.equals("-//Hibernate/Hibernate Configuration DTD//EN")) {
                    return new InputSource(HibernateUtil.class.getClassLoader()
                            .getResourceAsStream("org/hibernate/hibernate-configuration-3.0.dtd"));
                }
                return null;
            }
        };

        cfg.setEntityResolver(entityResolver);
        sLog.debug("  -- added entity resolver");

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        sLog.debug("  -- document factory created");
        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setEntityResolver(entityResolver);
        sLog.debug("  -- document builder created");
        Document document = builder
                .parse(ConfigHelper.getConfigStream(cfgName == null ? "hibernate.cfg.xml" : cfgName));

        String dialect = ApplicationProperty.DatabaseDialect.value();
        if (dialect != null)
            setProperty(document, "dialect", dialect);

        String default_schema = ApplicationProperty.DatabaseSchema.value();
        if (default_schema != null)
            setProperty(document, "default_schema", default_schema);

        String idgen = ApplicationProperty.DatabaseUniqueIdGenerator.value();
        if (idgen != null)
            setProperty(document, "tmtbl.uniqueid.generator", idgen);

        if (ApplicationProperty.HibernateClusterEnabled.isFalse())
            setProperty(document, "net.sf.ehcache.configurationResourceName", "ehcache-nocluster.xml");

        for (Enumeration e = ApplicationProperties.getProperties().propertyNames(); e.hasMoreElements();) {
            String name = (String) e.nextElement();
            if (name.startsWith("hibernate.") || name.startsWith("connection.")
                    || name.startsWith("tmtbl.hibernate.")) {
                String value = ApplicationProperties.getProperty(name);
                if ("NULL".equals(value))
                    removeProperty(document, name);
                else
                    setProperty(document, name, value);
                if (!name.equals("connection.password"))
                    sLog.debug("  -- set " + name + ": " + value);
                else
                    sLog.debug("  -- set " + name + ": *****");
            }
        }

        cfg.configure(document);
        sLog.debug("  -- hibernate configured");

        HibernateUtil.fixSchemaInFormulas(cfg);
        sLog.debug("  -- %SCHEMA% in formulas changed to " + cfg.getProperty("default_schema"));

        UniqueIdGenerator.configure(cfg);
        sLog.debug("  -- UniquId generator configured");
    } catch (Exception e) {
        sLog.error("Unable to configure hibernate, reason: " + e.getMessage(), e);
    }
}

From source file:org.wso2.carbon.dataservices.core.XSLTTransformer.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.c  om*/
 * @throws javax.xml.parsers.ParserConfigurationException
 */
private 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);
    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. Skip resolving entity");
        }
    });
    return documentBuilder;
}

From source file:org.wso2.carbon.datasource.utils.DataSourceUtils.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 av a2  s . com
 * @throws ParserConfigurationException
 */
private 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);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    documentBuilder.setEntityResolver((publicId, systemId) -> {
        throw new SAXException("Possible XML External Entity (XXE) attack. Skip resolving entity");
    });
    return documentBuilder;
}

From source file:org.wso2.carbon.datasource.utils.DataSourceUtils.java

/**
 * Replaces system variables in the input xml configuration.
 *
 * @param xmlConfiguration InputStream that carries xml configuration
 * @return returns a InputStream that has evaluated system variables in input
 * @throws DataSourceException//w  ww.j  av  a  2  s  .c o m
 */
public static InputStream replaceSystemVariablesInXml(InputStream xmlConfiguration) throws DataSourceException {
    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(ENTITY_EXPANSION_LIMIT);
        //            documentBuilderFactory.setAttribute(SECURITY_MANAGER_PROPERTY, securityManager);
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
        documentBuilder.setEntityResolver((publicId, systemId) -> {
            throw new SAXException("Possible XML External Entity (XXE) attack. Skip resolving entity");
        });
        doc = documentBuilder.parse(xmlConfiguration);
    } catch (ParserConfigurationException | IOException | SAXException e) {
        throw new DataSourceException("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.identity.application.authenticator.passive.sts.manager.PassiveSTSManager.java

/**
 * @param samlString//from w w w  .  j av  a 2  s  .  c om
 * @return
 * @throws PassiveSTSException
 */
private XMLObject unmarshall(String samlString) throws PassiveSTSException {

    String samlStr = decodeHTMLCharacters(samlString);
    try {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);

        documentBuilderFactory.setExpandEntityReferences(false);
        documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        SecurityManager securityManager = new SecurityManager();
        securityManager.setEntityExpansionLimit(ENTITY_EXPANSION_LIMIT);
        documentBuilderFactory.setAttribute(SECURITY_MANAGER_PROPERTY, securityManager);

        DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder();
        docBuilder.setEntityResolver(new CarbonEntityResolver());
        ByteArrayInputStream is = new ByteArrayInputStream(samlStr.getBytes(Charset.forName("UTF-8")));
        Document document = docBuilder.parse(is);
        Element element = document.getDocumentElement();

        NodeList nodeList = element.getElementsByTagNameNS("http://docs.oasis-open.org/ws-sx/ws-trust/200512",
                "RequestedSecurityToken");
        if (nodeList == null || nodeList.getLength() == 0) {
            throw new PassiveSTSException("Security Token is not found in the Response");
        }

        if (nodeList.getLength() > 1) {
            log.warn("More than one Security Token is found in the Response");
        }

        Element node = (Element) nodeList.item(0).getFirstChild();
        UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
        Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(node);
        return unmarshaller.unmarshall(node);
    } catch (ParserConfigurationException e) {
        throw new PassiveSTSException(
                PassiveSTSConstants.ERROR_IN_UNMARSHALLING_SAML_REQUEST_FROM_THE_ENCODED_STRING, e);
    } catch (UnmarshallingException e) {
        throw new PassiveSTSException(
                PassiveSTSConstants.ERROR_IN_UNMARSHALLING_SAML_REQUEST_FROM_THE_ENCODED_STRING, e);
    } catch (SAXException e) {
        throw new PassiveSTSException(
                PassiveSTSConstants.ERROR_IN_UNMARSHALLING_SAML_REQUEST_FROM_THE_ENCODED_STRING, e);
    } catch (IOException e) {
        throw new PassiveSTSException(
                PassiveSTSConstants.ERROR_IN_UNMARSHALLING_SAML_REQUEST_FROM_THE_ENCODED_STRING, e);
    }

}

From source file:org.wso2.carbon.identity.application.authenticator.samlsso.manager.DefaultSAML2SSOManager.java

private XMLObject unmarshall(String samlString) throws SAMLSSOException {

    try {/*from ww w .jav  a 2s  .  c o 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(ENTITY_EXPANSION_LIMIT);
        documentBuilderFactory.setAttribute(SECURITY_MANAGER_PROPERTY, securityManager);

        DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder();
        docBuilder.setEntityResolver(new CarbonEntityResolver());
        ByteArrayInputStream is = new ByteArrayInputStream(samlString.getBytes());
        Document document = docBuilder.parse(is);
        Element element = document.getDocumentElement();
        UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
        Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element);
        return unmarshaller.unmarshall(element);
    } catch (ParserConfigurationException e) {
        throw new SAMLSSOException("Error in unmarshalling SAML Request from the encoded String", e);
    } catch (UnmarshallingException e) {
        throw new SAMLSSOException("Error in unmarshalling SAML Request from the encoded String", e);
    } catch (SAXException e) {
        throw new SAMLSSOException("Error in unmarshalling SAML Request from the encoded String", e);
    } catch (IOException e) {
        throw new SAMLSSOException("Error in unmarshalling SAML Request from the encoded String", e);
    }

}

From source file:org.wso2.carbon.identity.auth.saml2.common.SAML2AuthUtils.java

public static XMLObject unmarshall(String samlString) throws IdentityRuntimeException {

    try {//ww w  .j  a  v  a 2 s .c  o  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 org.apache.xerces.util.SecurityManager();
        securityManager.setEntityExpansionLimit(ENTITY_EXPANSION_LIMIT);
        documentBuilderFactory.setAttribute(SECURITY_MANAGER_PROPERTY, securityManager);

        DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder();
        docBuilder.setEntityResolver(new CarbonEntityResolver());
        ByteArrayInputStream is = new ByteArrayInputStream(samlString.getBytes(StandardCharsets.UTF_8));
        Document document = docBuilder.parse(is);
        Element element = document.getDocumentElement();
        UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
        Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element);
        return unmarshaller.unmarshall(element);
    } catch (ParserConfigurationException e) {
        throw new IdentityRuntimeException("Error in unmarshalling SAML Request from the encoded String", e);
    } catch (UnmarshallingException e) {
        throw new IdentityRuntimeException("Error in unmarshalling SAML Request from the encoded String", e);
    } catch (SAXException e) {
        throw new IdentityRuntimeException("Error in unmarshalling SAML Request from the encoded String", e);
    } catch (IOException e) {
        throw new IdentityRuntimeException("Error in unmarshalling SAML Request from the encoded String", e);
    }
}

From source file:org.wso2.carbon.identity.authenticator.saml2.sso.common.Util.java

/**
 * Constructing the XMLObject Object from a String
 *
 * @param authReqStr/*w  ww . j  a v a2  s.  c om*/
 * @return Corresponding XMLObject which is a SAML2 object
 * @throws SAML2SSOUIAuthenticatorException
 */
public static XMLObject unmarshall(String authReqStr) throws SAML2SSOUIAuthenticatorException {

    try {
        doBootstrap();
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);

        documentBuilderFactory.setExpandEntityReferences(false);
        documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        SecurityManager securityManager = new SecurityManager();
        securityManager.setEntityExpansionLimit(ENTITY_EXPANSION_LIMIT);
        documentBuilderFactory.setAttribute(SECURITY_MANAGER_PROPERTY, securityManager);

        DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder();
        docBuilder.setEntityResolver(new CarbonEntityResolver());
        Document document = docBuilder.parse(new ByteArrayInputStream(authReqStr.trim().getBytes()));
        Element element = document.getDocumentElement();
        UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
        Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element);
        return unmarshaller.unmarshall(element);
    } catch (Exception e) {
        log.error("Error in constructing AuthRequest from the encoded String", e);
        throw new SAML2SSOUIAuthenticatorException(
                "Error in constructing AuthRequest from " + "the encoded String ", e);
    }
}

From source file:org.wso2.carbon.identity.authenticator.saml2.sso.util.Util.java

/**
 * Constructing the XMLObject Object from a String
 *
 * @param authReqStr/*from  w w w  .  j  a  v  a  2 s. co m*/
 * @return Corresponding XMLObject which is a SAML2 object
 * @throws org.wso2.carbon.identity.authenticator.saml2.sso.SAML2SSOAuthenticatorException
 */
public static XMLObject unmarshall(String authReqStr) throws SAML2SSOAuthenticatorException {

    XMLObject response;
    try {
        doBootstrap();
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);

        documentBuilderFactory.setExpandEntityReferences(false);
        documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        SecurityManager securityManager = new SecurityManager();
        securityManager.setEntityExpansionLimit(ENTITY_EXPANSION_LIMIT);
        documentBuilderFactory.setAttribute(SECURITY_MANAGER_PROPERTY, securityManager);

        DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder();
        docBuilder.setEntityResolver(new CarbonEntityResolver());
        Document document = docBuilder.parse(new ByteArrayInputStream(authReqStr.trim().getBytes()));
        Element element = document.getDocumentElement();
        UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
        Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element);
        response = unmarshaller.unmarshall(element);
        // Check for duplicate samlp:Response
        NodeList list = response.getDOM().getElementsByTagNameNS(SAMLConstants.SAML20P_NS, "Response");
        if (list.getLength() > 0) {
            log.error("Invalid schema for the SAML2 reponse");
            throw new SAML2SSOAuthenticatorException("Error occured while processing saml2 response");
        }
        return response;
    } catch (ParserConfigurationException e) {
        log.error("Error occured while processing saml2 response");
        throw new SAML2SSOAuthenticatorException("Error occured while processing saml2 response", e);
    } catch (SAXException e) {
        log.error("Error occured while processing saml2 response");
        throw new SAML2SSOAuthenticatorException("Error occured while processing saml2 response", e);
    } catch (IOException e) {
        log.error("Error occured while processing saml2 response");
        throw new SAML2SSOAuthenticatorException("Error occured while processing saml2 response", e);
    } catch (UnmarshallingException e) {
        log.error("Error occured while processing saml2 response");
        throw new SAML2SSOAuthenticatorException("Error occured while processing saml2 response", e);
    }

}

From source file:org.wso2.carbon.identity.core.util.IdentityUtil.java

/**
 * Constructing the SAML or XACML Objects from a String
 *
 * @param xmlString Decoded SAML or XACML String
 * @return SAML or XACML Object//  w w w. j  a v a 2  s. c  o m
 * @throws org.wso2.carbon.identity.base.IdentityException
 */
public static XMLObject unmarshall(String xmlString) throws IdentityException {

    try {
        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(ENTITY_EXPANSION_LIMIT);
        documentBuilderFactory.setAttribute(SECURITY_MANAGER_PROPERTY, securityManager);

        DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder();
        docBuilder.setEntityResolver(new CarbonEntityResolver());
        Document document = docBuilder
                .parse(new ByteArrayInputStream(xmlString.trim().getBytes(Charsets.UTF_8)));
        Element element = document.getDocumentElement();
        UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
        Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element);
        return unmarshaller.unmarshall(element);
    } catch (ParserConfigurationException | UnmarshallingException | SAXException | IOException e) {
        String message = "Error in constructing XML Object from the encoded String";
        throw new IdentityException(message, e);
    }
}