Example usage for javax.xml.parsers DocumentBuilderFactory setAttribute

List of usage examples for javax.xml.parsers DocumentBuilderFactory setAttribute

Introduction

In this page you can find the example usage for javax.xml.parsers DocumentBuilderFactory setAttribute.

Prototype

public abstract void setAttribute(String name, Object value) throws IllegalArgumentException;

Source Link

Document

Allows the user to set specific attributes on the underlying implementation.

Usage

From source file:org.wso2.carbon.identity.saml.inbound.util.SAMLSSOUtil.java

/**
 * Constructing the AuthnRequest Object from a String
 *
 * @param authReqStr Decoded AuthReq String
 * @return AuthnRequest Object/*from  ww  w .  j a v a  2s. com*/
 * @throws
 */
public static XMLObject unmarshall(String authReqStr) throws IdentityException {
    InputStream inputStream = null;
    try {
        doBootstrap();
        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());
        inputStream = new ByteArrayInputStream(authReqStr.trim().getBytes(StandardCharsets.UTF_8));
        Document document = docBuilder.parse(inputStream);
        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 IdentityException.error("Error in constructing AuthRequest from the encoded String ", e);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                log.error("Error while closing the stream", e);
            }
        }
    }
}

From source file:org.wso2.carbon.identity.sso.saml.util.SAMLSSOUtil.java

/**
 * Constructing the AuthnRequest Object from a String
 *
 * @param authReqStr Decoded AuthReq String
 * @return AuthnRequest Object/*from  ww  w. j ava 2  s. co  m*/
 * @throws org.wso2.carbon.identity.base.IdentityException
 */
public static XMLObject unmarshall(String authReqStr) throws IdentityException {
    InputStream inputStream = null;
    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());
        inputStream = new ByteArrayInputStream(authReqStr.trim().getBytes(StandardCharsets.UTF_8));
        Document document = docBuilder.parse(inputStream);
        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 IdentityException("Error in constructing AuthRequest from the encoded String ", e);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                log.error("Error while closing the stream", e);
            }
        }
    }
}

From source file:org.wso2.carbon.identity.user.registration.UserRegistrationService.java

/**
 * * This method provides a secured document builder which will secure XXE attacks.
 *
 * @return DocumentBuilder//from ww w . ja v  a 2  s  .  c  o m
 * @throws ParserConfigurationException
 */
private DocumentBuilder getSecuredDocumentBuilder() throws ParserConfigurationException {

    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 documentBuilder = documentBuilderFactory.newDocumentBuilder();
    documentBuilder.setEntityResolver(new CarbonEntityResolver());
    return documentBuilder;

}

From source file:org.wso2.carbon.jaggeryapp.template.deployer.internal.util.JaggeryappTemplateDeployerHelper.java

public static DocumentBuilderFactory getSecuredDocumentBuilder() {

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    documentBuilderFactory.setXIncludeAware(false);
    documentBuilderFactory.setExpandEntityReferences(false);
    try {/*  ww  w  .  j a  va 2s .com*/
        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);
    } 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);
    }

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

From source file:org.wso2.carbon.policyeditor.PolicyEditorService.java

/**
 * Formats a given unformatted XML string
 *
 * @param xml/*from  w  ww . j  a  v  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 ww. ja  va2s .com*/
 * @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.utils.CarbonUtils.java

/**
 *
 * @param xmlConfiguration InputStream that carries xml configuration
 * @return returns a InputStream that has evaluated system variables in input
 * @throws CarbonException//from   ww  w.  ja va 2  s.c om
 */
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.identity.iml.dsl.mediators.SAMLRequestProcessor.java

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

    IMLUtils.doBootstrap();/*from w  ww  . j a va 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(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  av  a 2 s .  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.zaproxy.zap.utils.ZapXmlConfiguration.java

@Override
protected DocumentBuilder createDocumentBuilder() throws ParserConfigurationException {
    DocumentBuilderFactory factory = XmlUtils.newXxeDisabledDocumentBuilderFactory();

    // Same behaviour as base method:
    if (isValidating()) {
        factory.setValidating(true);//from  www.j  a v a2  s  .co m
        if (isSchemaValidation()) {
            factory.setNamespaceAware(true);
            factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
                    "http://www.w3.org/2001/XMLSchema");
        }
    }

    DocumentBuilder result = factory.newDocumentBuilder();
    result.setEntityResolver(getEntityResolver());

    if (isValidating()) {
        result.setErrorHandler(new DefaultHandler() {

            @Override
            public void error(SAXParseException ex) throws SAXException {
                throw ex;
            }
        });
    }
    return result;
}