XmlReaderSettings.MaxCharactersFromEntities 属性

定义

获取或设置一个值,该值指示文档中允许扩展实体产生的最大字符数。

public:
 property long MaxCharactersFromEntities { long get(); void set(long value); };
public long MaxCharactersFromEntities { get; set; }
member this.MaxCharactersFromEntities : int64 with get, set
Public Property MaxCharactersFromEntities As Long

属性值

Int64

扩展实体中允许的最大字符数。 默认值为 0。

示例

下面的代码设置此属性,然后尝试分析包含一个实体的文档,该实体扩展到大于设置限制的大小。 在实际方案中,将此限制设置为足以处理有效文档的值,但足够小,以限制恶意文档的威胁。

string markup =  
@"<!DOCTYPE Root [  
  <!ENTITY anEntity ""Expands to more than 30 characters"">  
  <!ELEMENT Root (#PCDATA)>  
]>  
<Root>Content &anEntity;</Root>";  

XmlReaderSettings settings = new XmlReaderSettings();  
settings.DtdProcessing = DtdProcessing.Parse;  
settings.ValidationType = ValidationType.DTD;  
settings.MaxCharactersFromEntities = 30;  

try  
{  
    XmlReader reader = XmlReader.Create(new StringReader(markup), settings);  
    while (reader.Read()) { }  
}  
catch (XmlException ex)  
{  
    Console.WriteLine(ex.Message);  
}  
Dim markup As String = _  
    "<!DOCTYPE Root [" + Environment.NewLine + _  
    "  <!ENTITY anEntity ""Expands to more than 30 characters"">" + Environment.NewLine + _  
    "  <!ELEMENT Root (#PCDATA)>" + Environment.NewLine + _  
    "]>" + Environment.NewLine + _  
    "<Root>Content &anEntity;</Root>"  

Dim settings As XmlReaderSettings = New XmlReaderSettings()  
settings.DtdProcessing = DtdProcessing.Parse;  
settings.ValidationType = ValidationType.DTD  
settings.MaxCharactersFromEntities = 30  

Try  
    Dim reader As XmlReader = XmlReader.Create(New StringReader(markup), settings)  
    While (reader.Read())  
    End While  
Catch ex As XmlException  
    Console.WriteLine(ex.Message)  
End Try  

该示例产生下面的输出:

There is an error in XML document (MaxCharactersFromEntities, ).  

注解

零 (0) 值表示对扩展实体导致的字符数没有限制。 非零值指定可能由扩展实体产生的最大字符数。

如果读取者尝试读取包含实体的文档,以便展开的大小将超过此属性,将引发一个 XmlException

通过此属性,可以缓解攻击者通过扩展实体尝试超过内存限制的 XML 文档,从而缓解拒绝服务攻击。 通过限制扩展实体生成的字符,可以检测攻击并可靠地恢复。

适用于