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:eu.europa.esig.dss.DSSXMLUtils.java

public static TransformerFactory getSecureTransformerFactory() {
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    try {//from w  w  w  . j a va 2s .c om
        transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    } catch (TransformerConfigurationException e) {
        throw new DSSException(e);
    }
    return transformerFactory;
}

From source file:com.collabnet.ccf.core.transformer.DynamicXsltProcessor.java

/**
 * Hook to perform any validation of the component properties required by
 * the implementation. Default behaviour should be a no-op.
 *///  www  . ja  va 2 s . c o m
@SuppressWarnings("unchecked")
public void validate(List exceptions) {
    // we have to make this map thread safe because it will be
    // updated asynchronously
    xsltFileNameTransformerMap = Collections.synchronizedMap(new HashMap<String, List<Transformer>>());
    if (isListenForFileUpdates()) {
        try {
            fsManager = VFS.getManager();
        } catch (FileSystemException e) {
            exceptions
                    .add(new ValidationException("could not initialize file manager: " + e.getMessage(), this));
            return;
        }
        fileMonitor = new DefaultFileMonitor(new FileListener() {
            public void fileChanged(org.apache.commons.vfs.FileChangeEvent arg0) throws Exception {
                xsltFileNameTransformerMap.clear();
            }

            public void fileCreated(FileChangeEvent arg0) throws Exception {
                xsltFileNameTransformerMap.clear();
            }

            public void fileDeleted(FileChangeEvent arg0) throws Exception {
                xsltFileNameTransformerMap.clear();
            }
        });
    }

    String xsltDir = this.getXsltDir();
    String xsltFile = this.getXsltFile();
    if (!StringUtils.isEmpty(xsltDir)) {
        File xsltDirFile = new File(xsltDir);
        if (xsltDirFile.exists() && xsltDirFile.isDirectory()) {
            log.debug("xsltDir property " + xsltDir + " is a valid directory");
            if (listenForFileUpdates) {
                FileObject fileObject = null;
                try {
                    fileObject = fsManager.resolveFile(xsltDirFile.getAbsolutePath());
                } catch (FileSystemException e) {
                    exceptions.add(new ValidationException(
                            "xsltDir property " + xsltDir + " is not a valid directory: " + e.getMessage(),
                            this));
                    return;
                }
                fileMonitor.setRecursive(true);
                fileMonitor.addFile(fileObject);
                fileMonitor.start();
            }
            if (scriptProcessors.isEmpty()) {
                log.warn("No scripts supplied, so dynamic XSLT processor will not change data at all");
            }
        } else {
            exceptions.add(new ValidationException(
                    "xsltDir property " + xsltDir + " is not a valid directory...!", this));
            return;
        }
    } else if (!StringUtils.isEmpty(xsltFile)) {
        File xsltFileFile = new File(xsltFile);
        if (xsltFileFile.exists() && xsltFileFile.isFile()) {
            log.debug("xsltFile property " + xsltFile + " is a valid file");
            if (listenForFileUpdates) {
                FileObject fileObject = null;
                try {
                    fileObject = fsManager.resolveFile(xsltFileFile.getAbsolutePath());
                } catch (FileSystemException e) {
                    exceptions.add(new ValidationException(
                            "xsltFile property " + xsltFile + " is not a valid file...:" + e.getMessage(),
                            this));
                    return;
                }
                fileMonitor.addFile(fileObject);
                fileMonitor.start();
            }
        } else {
            exceptions.add(new ValidationException("xsltFile property " + xsltFile + " is not a valid file...!",
                    this));
            return;
        }
    }
    factory = TransformerFactory.newInstance();
    if (isOnlyAllowWhiteListedJavaFunctionCalls()) {
        try {
            secureFactory = TransformerFactory.newInstance();
            secureFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
            secureFactory.setErrorListener(new XsltValidationErrorListener());
        } catch (TransformerConfigurationException e) {
            exceptions.add(new ValidationException(
                    "Setting secure processing feature on XSLT processor failed, bailing out since this feature is required by onlyAllowWhiteListedJavaFunctions property",
                    this));
            return;
        }
    }
}

From source file:com.vmware.identity.samlservice.impl.SamlServiceImpl.java

@Override
public SignableSAMLObject decodeSamlRequest(HttpServletRequest request)
        throws MessageDecodingException, SecurityException {
    log.debug("Decoding SAML object: {}", request);
    Validate.notNull(request);/*from  w w  w  .j  av  a2  s.c  o  m*/

    Hashtable<String, Boolean> features = new Hashtable<String, Boolean>();
    Hashtable<String, Object> attributes = new Hashtable<String, Object>();

    BasicParserPool ParserPool = new BasicParserPool();

    features.put(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    ParserPool.setBuilderFeatures(features);

    attributes.put(FEATURE_EXTERNAL_GENERAL_ENTITIES, false);
    attributes.put(FEATURE_EXTERNAL_PARAMETER_ENTITIES, false);
    attributes.put(FEATURE_LOAD_EXTERNAL_DTD, false);
    ParserPool.setBuilderAttributes(attributes);

    final HTTPRedirectDeflateDecoder decode = new HTTPRedirectDeflateDecoder(ParserPool);
    decode.setURIComparator(comparator);
    final HttpServletRequestAdapter adapter = new HttpServletRequestAdapter(request);
    @SuppressWarnings("rawtypes")
    final BasicSAMLMessageContext context = new BasicSAMLMessageContext();
    context.setInboundMessageTransport(adapter);
    decode.decode(context);
    // Save the SAML Request as a SAML Object
    return (SignableSAMLObject) context.getInboundMessage();
}

From source file:eu.eidas.auth.engine.AbstractSAMLEngine.java

/**
 * Build the default set of parser features to use.
 * The default features set are://from  w w w  . ja v a 2s .com
 * <ul>
 * <li>{@link javax.xml.XMLConstants#FEATURE_SECURE_PROCESSING} = true</li>
 * <li>http://apache.org/xml/features/disallow-doctype-decl = true</li>
 * Reference : https://www.owasp.org/index.php/XML_External_Entity_%28XXE%29_Processing
 * </ul>
 */
protected static Map<String, Boolean> buildDefaultFeature() {
    Map<String, Boolean> features = new HashMap<String, Boolean>();
    features.put(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);

    // Ignore the external DTD completely
    // Note: this is for Xerces only:
    features.put("http://apache.org/xml/features/nonvalidating/load-external-dtd", Boolean.FALSE);
    // 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
    features.put("http://apache.org/xml/features/disallow-doctype-decl", Boolean.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
    features.put("http://xml.org/sax/features/external-general-entities", Boolean.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
    features.put("http://xml.org/sax/features/external-parameter-entities", Boolean.FALSE);

    return features;
}

From source file:nl.nn.adapterframework.validation.xerces_2_11.XMLSchemaFactory.java

public boolean getFeature(String name) throws SAXNotRecognizedException, SAXNotSupportedException {
    if (name == null) {
        throw new NullPointerException(JAXPValidationMessageFormatter
                .formatMessage(fXMLSchemaLoader.getLocale(), "FeatureNameNull", null));
    }/*w w  w.  ja  v  a 2s.  c  o m*/
    if (name.startsWith(JAXP_SOURCE_FEATURE_PREFIX)) {
        // Indicates to the caller that this SchemaFactory supports a specific JAXP Source.
        if (name.equals(StreamSource.FEATURE) || name.equals(SAXSource.FEATURE)
                || name.equals(DOMSource.FEATURE) || name.equals(StAXSource.FEATURE)) {
            return true;
        }
    }
    if (name.equals(XMLConstants.FEATURE_SECURE_PROCESSING)) {
        return (fSecurityManager != null);
    } else if (name.equals(USE_GRAMMAR_POOL_ONLY)) {
        return fUseGrammarPoolOnly;
    }
    try {
        return fXMLSchemaLoader.getFeature(name);
    } catch (XMLConfigurationException e) {
        String identifier = e.getIdentifier();
        if (e.getType() == XMLConfigurationException.NOT_RECOGNIZED) {
            throw new SAXNotRecognizedException(SAXMessageFormatter.formatMessage(fXMLSchemaLoader.getLocale(),
                    "feature-not-recognized", new Object[] { identifier }));
        } else {
            throw new SAXNotSupportedException(SAXMessageFormatter.formatMessage(fXMLSchemaLoader.getLocale(),
                    "feature-not-supported", new Object[] { identifier }));
        }
    }
}

From source file:nl.nn.adapterframework.validation.xerces_2_11.XMLSchemaFactory.java

public void setFeature(String name, boolean value) throws SAXNotRecognizedException, SAXNotSupportedException {
    if (name == null) {
        throw new NullPointerException(JAXPValidationMessageFormatter
                .formatMessage(fXMLSchemaLoader.getLocale(), "FeatureNameNull", null));
    }/*from   ww  w. j  a  v a 2s.  co  m*/
    if (name.startsWith(JAXP_SOURCE_FEATURE_PREFIX)) {
        if (name.equals(StreamSource.FEATURE) || name.equals(SAXSource.FEATURE)
                || name.equals(DOMSource.FEATURE) || name.equals(StAXSource.FEATURE)) {
            throw new SAXNotSupportedException(SAXMessageFormatter.formatMessage(fXMLSchemaLoader.getLocale(),
                    "feature-read-only", new Object[] { name }));
        }
    }
    if (name.equals(XMLConstants.FEATURE_SECURE_PROCESSING)) {
        fSecurityManager = value ? new SecurityManager() : null;
        fXMLSchemaLoader.setProperty(SECURITY_MANAGER, fSecurityManager);
        return;
    } else if (name.equals(USE_GRAMMAR_POOL_ONLY)) {
        fUseGrammarPoolOnly = value;
        return;
    }
    try {
        fXMLSchemaLoader.setFeature(name, value);
    } catch (XMLConfigurationException e) {
        String identifier = e.getIdentifier();
        if (e.getType() == XMLConfigurationException.NOT_RECOGNIZED) {
            throw new SAXNotRecognizedException(SAXMessageFormatter.formatMessage(fXMLSchemaLoader.getLocale(),
                    "feature-not-recognized", new Object[] { identifier }));
        } else {
            throw new SAXNotSupportedException(SAXMessageFormatter.formatMessage(fXMLSchemaLoader.getLocale(),
                    "feature-not-supported", new Object[] { identifier }));
        }
    }
}

From source file:nl.nn.adapterframework.validation.xerces_2_11.XMLSchemaFactory.java

private void propagateFeatures(AbstractXMLSchema schema) {
    schema.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, fSecurityManager != null);
    String[] features = fXMLSchemaLoader.getRecognizedFeatures();
    for (int i = 0; i < features.length; ++i) {
        boolean state = fXMLSchemaLoader.getFeature(features[i]);
        schema.setFeature(features[i], state);
    }/*from   www  .j  a v  a2s.c  o m*/
}

From source file:org.adeptnet.auth.saml.SAMLClient.java

private DocumentBuilder createDocumentBuilder(boolean validating, boolean disAllowDocTypeDeclarations)
        throws ParserConfigurationException {
    final DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
    dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
    if (disAllowDocTypeDeclarations) {
        dfactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
    }//from  www  . j a va  2s. c om
    dfactory.setValidating(validating);
    dfactory.setNamespaceAware(true);

    return dfactory.newDocumentBuilder();
}

From source file:org.apache.nifi.minifi.FlowParser.java

/**
 * Generates a {@link Document} from the flow configuration file provided
 */// w ww  . jav  a2  s.  c  o m
public Document parse(final File flowConfigurationFile) {
    if (flowConfigurationFile == null) {
        logger.debug("Flow Configuration file was null");
        return null;
    }

    // if the flow doesn't exist or is 0 bytes, then return null
    final Path flowPath = flowConfigurationFile.toPath();
    try {
        if (!Files.exists(flowPath) || Files.size(flowPath) == 0) {
            logger.warn("Flow Configuration does not exist or was empty");
            return null;
        }
    } catch (IOException e) {
        logger.error("An error occurred determining the size of the Flow Configuration file");
        return null;
    }

    // otherwise create the appropriate input streams to read the file
    try (final InputStream in = Files.newInputStream(flowPath, StandardOpenOption.READ);
            final InputStream gzipIn = new GZIPInputStream(in)) {

        final byte[] flowBytes = IOUtils.toByteArray(gzipIn);
        if (flowBytes == null || flowBytes.length == 0) {
            logger.warn("Could not extract root group id because Flow Configuration File was empty");
            return null;
        }

        final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        docFactory.setNamespaceAware(true);
        docFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);

        // parse the flow
        final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        docBuilder.setErrorHandler(new LoggingXmlParserErrorHandler("Flow Configuration", logger));
        final Document document = docBuilder.parse(new ByteArrayInputStream(flowBytes));
        return document;

    } catch (final SAXException | ParserConfigurationException | IOException ex) {
        logger.error("Unable to parse flow {} due to {}", new Object[] { flowPath.toAbsolutePath(), ex });
        return null;
    }
}