首页 > 解决方案 > 将模式文件打包到 dll 中以防止它们被篡改

问题描述

我有一个与C#-Validating xml file against local .xsd security issues类似的问题。

但我的观点首先不是安全问题。我希望保护我的模式文件免受“愚蠢用户”的侵害,而不是真正的攻击者。

是否有可能在编译时将我的 xsd 文件打包到 dll 中,并在运行时从那里使用它(而不仅仅是从文件系统中读取文本文件)?

如果它在 dll 中,“愚蠢的用户”将无法随意编辑文件,对于攻击者,我们甚至可以更进一步,使用强命名和数字签名保护 dll。

internal class XmlValidator : Validator
{
    private static XmlSchemaSet _schemas;

    /// <summary>
    /// Initializes a new instance of the <see cref="XmlValidator"/> class.
    /// </summary>
    internal XmlValidator()
    {
        string path;
            path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
        }
        else
        {
            path = @".\";
        }

        // Add schemas
        _schemas = new XmlSchemaSet();
        _schemas.Add("http://myschema/schema1", Path.Combine(path, "Schemas", "schema-v1.0.xsd"));
        _schemas.Add("http://myschema/schema11", Path.Combine(path, "Schemas", "chema-v1.1.xsd"));

    }

因此,我不想在初始化期间直接从文件系统中读取它们,而是将它们作为某种资源读取。

所以类似于翻译文件。在编译时创建,在运行时不可更改

标签: c#xsd-validation

解决方案


当然这是可能的。我这样做是为了保护他们。

首先将它们声明为Embedded Resource

在此处输入图像描述

在代码中使用它

public void LoadXsd()
{
    string resourceName = "DefaultNamespace.specs.info.IErrorInfo.xsd";
    Assembly assembly = Assembly.GetExecutingAssembly();
    XmlSchema xsd = XmlSchema.Read(assembly.GetManifestResourceStream(resourceName), _XsdSchema_ValidationEventHandler);

    XmlSchemaSet schemaSet = new XmlSchemaSet();
    schemaSet.Add(xsd);
}

private void _XsdSchema_ValidationEventHandler(object sender, ValidationEventArgs e)
{
    _Logger.Error($"XSD validation error: {e.Message}");
}

也可以一次加载它们:

public void LoadAllXsdFiles()
{
    XmlSchemaSet schemaSet = new XmlSchemaSet();
    var assembly = Assembly.GetExecutingAssembly();
    var allXsdFiles = assembly.GetManifestResourceNames().Where(r => r.EndsWith(".xsd"));
    foreach (string xsdFile in allXsdFiles)
    {
        XmlSchema xsd = XmlSchema.Read(assembly.GetManifestResourceStream(xsdFile), _XsdSchema_ValidationEventHandler);
        schemaSet.Add(xsd);
    }
}

推荐阅读