程序集路径注入¶
ID: cs/assembly-path-injection
Kind: path-problem
Security severity: 8.2
Severity: error
Precision: high
Tags:
- security
- external/cwe/cwe-114
Query suites:
- csharp-code-scanning.qls
- csharp-security-extended.qls
- csharp-security-and-quality.qls
C# 支持通过使用 System.Reflection.Assembly
API 按路径运行时加载程序集。如果外部用户可以影响用于加载程序集的路径,则应用程序可能会被欺骗加载并非预期加载的程序集,并执行任意代码。
建议¶
避免根据用户提供的输入加载程序集。如果无法做到这一点,请确保在将路径与 Assembly
一起使用之前对其进行验证。例如,将提供的输入与已知安全程序集的白名单进行比较,或确认该路径仅限于仅包含安全程序集的单个目录。
示例¶
在此示例中,提供了描述程序集路径的用户输入,该输入在未经验证的情况下被加载。这是有问题的,因为它允许用户加载系统上安装的任何程序集,如果攻击者可以在系统上的其他位置上传自定义 DLL,则问题尤其严重。
using System;
using System.Web;
using System.Reflection;
public class AssemblyPathInjectionHandler : IHttpHandler {
public void ProcessRequest(HttpContext ctx) {
string assemblyPath = ctx.Request.QueryString["assemblyPath"];
// BAD: Load assembly based on user input
var badAssembly = Assembly.LoadFile(assemblyPath);
// Method called on loaded assembly. If the user can control the loaded assembly, then this
// could result in a remote code execution vulnerability
MethodInfo m = badAssembly.GetType("Config").GetMethod("GetCustomPath");
Object customPath = m.Invoke(null, null);
// ...
}
}
在更正后的版本中,针对两个选项之一验证用户输入,并且仅当用户输入与其中一个选项匹配时才加载程序集。
using System;
using System.Web;
using System.Reflection;
public class AssemblyPathInjectionHandler : IHttpHandler {
public void ProcessRequest(HttpContext ctx) {
string configType = ctx.Request.QueryString["configType"];
if (configType.equals("configType1") || configType.equals("configType2")) {
// GOOD: Loaded assembly is one of the two known safe options
var safeAssembly = Assembly.LoadFile(@"C:\SafeLibraries\" + configType + ".dll");
// Code execution is limited to one of two known and vetted assemblies
MethodInfo m = safeAssembly.GetType("Config").GetMethod("GetCustomPath");
Object customPath = m.Invoke(null, null);
// ...
}
}
}
参考资料¶
Microsoft:System.Reflection.Assembly。
常见弱点枚举:CWE-114。