如何在C#中配置XML解析器以禁用外部实体解析 [英] How to configure the XML parser to disable external entity resolution in c#

查看:757
本文介绍了如何在C#中配置XML解析器以禁用外部实体解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var xDoc = XDocument.Load(fileName);

我在函数中使用以上代码来加载XML文件.从功能上来说,它可以正常工作,但是在Veracode检查之后,它会显示以下Veracode缺陷.

I am using above code in a function to load an XML file. Functionality wise its working fine but it is showing following Veracode Flaw after Veracode check.

说明

该产品处理的XML文档可以包含XML实体,这些XML实体的URL可以解析为外部文档 预期的控制范围,导致产品将不正确的文档嵌入到其输出中.默认情况下, XML实体解析器将尝试解析和检索外部引用.如果攻击者控制的XML可以 提交给这些功能之一,攻击者就可以访问有关内部网络的信息 文件系统或其他敏感数据.这就是XML外部实体(XXE)攻击.

The product processes an XML document that can contain XML entities with URLs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output. By default, the XML entity resolver will attempt to resolve and retrieve external references. If attacker-controlled XML can be submitted to one of these functions, then the attacker could gain access to information about an internal network, local filesystem, or other sensitive data. This is known as an XML eXternal Entity (XXE) attack.

建议

配置XML解析器以禁用外部实体解析.

Configure the XML parser to disable external entity resolution.

解决该问题所需要做的事情.

推荐答案

实施自定义XmlResolver并将其用于读取XML.默认情况下,使用XmlUrlResolver,它将自动下载已解析的引用.

Implement a custom XmlResolver and use it for reading the XML. By default, the XmlUrlResolver is used, which automatically downloads the resolved references.

public class CustomResolver : XmlUrlResolver
{
    public override object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn)
    {
        // base calls XmlUrlResolver.DownloadManager.GetStream(...) here
    }
}

并像这样使用它:

var settings = new XmlReaderSettings { XmlResolver = new CustomResolver() };
var reader = XmlReader.Create(fileName, settings);
var xDoc = XDocument.Load(reader);

这篇关于如何在C#中配置XML解析器以禁用外部实体解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆