CodeQL 文档

缺少 XML 验证

ID: cs/xml/missing-validation
Kind: path-problem
Security severity: 4.3
Severity: recommendation
Precision: high
Tags:
   - security
   - external/cwe/cwe-112
Query suites:
   - csharp-security-extended.qls
   - csharp-security-and-quality.qls

点击查看 CodeQL 存储库中的查询

如果将未经处理的用户输入作为 XML 处理,则应根据已知架构对其进行验证。 如果未进行验证,或者验证依赖于文档本身中指定的架构或 DTD,则 XML 文档可能包含任何形式的任何数据,这可能会使程序稍后做出的假设失效。

建议

用户提供的任何 XML 都应在处理时根据已知架构进行验证。

如果使用 XmlReader.Create,则应始终传递 XmlReaderSettings 的实例,并使用以下属性

  • 必须将 ValidationType 设置为 Schema。 如果未设置此属性,则不会进行任何验证。 如果将其设置为 DTD,则仅根据用户提供的文档本身中指定的 DTD 对文档进行验证 - 恶意用户可以将其指定为任何内容。

  • ValidationFlags 不得包含 ProcessInlineSchemaProcessSchemaLocation。 这些标志允许用户提供自己的内联架构或架构位置进行验证,从而允许恶意用户绕过已知架构验证。

示例

在以下示例中,使用 XmlReader.Create 加载用户提供的文本。 在前三个示例中,验证不足,因为未指定验证,或者仅针对用户提供的 DTD 指定了验证,或者验证允许用户提供内联架构。 在最后一个示例中,提供了已知架构,并使用 XmlReaderSettings 的实例设置了验证。 这可确保根据已知架构正确验证用户输入。

using System;
using System.IO;
using System.Web;
using System.Xml;
using System.Xml.Schema;

public class MissingXmlValidationHandler : IHttpHandler
{

    public void ProcessRequest(HttpContext ctx)
    {
        String userProvidedXml = ctx.Request.QueryString["userProvidedXml"];

        // BAD: User provided XML is processed without any validation,
        //      because there is no settings instance configured.
        XmlReader.Create(new StringReader(userProvidedXml));

        // BAD: User provided XML is processed without any validation,
        //      because the settings instance specifies DTD as the ValidationType
        XmlReaderSettings badSettings = new XmlReaderSettings();
        badSettings.ValidationType = ValidationType.DTD;
        XmlReader.Create(new StringReader(userProvidedXml), badSettings);

        // BAD: User provided XML is processed with validation, but the ProcessInlineSchema
        //      option is specified, so an attacker can provide their own schema to validate
        //      against.
        XmlReaderSettings badInlineSettings = new XmlReaderSettings();
        badInlineSettings.ValidationType = ValidationType.Schema;
        badInlineSettings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
        XmlReader.Create(new StringReader(userProvidedXml), badInlineSettings);

        // GOOD: User provided XML is processed with validation
        XmlReaderSettings goodSettings = new XmlReaderSettings();
        goodSettings.ValidationType = ValidationType.Schema;
        goodSettings.Schemas = new XmlSchemaSet() { { "urn:my-schema", "my.xsd" } };
        XmlReader.Create(new StringReader(userProvidedXml), goodSettings);
    }
}

参考

  • ©GitHub 公司
  • 条款
  • 隐私