c# - 将模式文件打包到 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"));
}
因此,我不想在初始化期间直接从文件系统中读取它们,而是将它们作为某种资源读取。
所以类似于翻译文件。在编译时创建,在运行时不可更改
解决方案
当然这是可能的。我这样做是为了保护他们。
首先将它们声明为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);
}
}
推荐阅读
- javascript - 将 AJAX 响应设置为 javascript 变量以供重用
- python - Spark窗口函数,根据数据集中的值创建排名列
- java - 复制文件或替换 SQLite 数据库在所有版本的 Android 中都可以正常工作,除了 Android Pie
- xml - 如何使用 xslt 基于属性值删除重复的 xml 节点
- reactjs - CORS 策略已阻止从源“http://localhost:3500”访问“http://localhost:8000/api/user-context”获取
- javascript - 识别刚刚登录的用户
- hibernate - 我如何加入两个不同的班级而不是创建标准的班级?
- ios - 使用自定义边框在 UITextField 上浮动 UILabel
- python - Python2.7 无法导入 Pandas
- jenkins - Jenkins Openconnect 插件或其他方式在管道中连接到 VPN