C#-CWE-94¶
Code Injection / Improper Control of Generation of Code (CWE-94): executing or compiling untrusted input as code or expressions
Required inputs: CSharpAST
public static void EvalFail(string userInput)
{
string code = $@"
using System;
public class EvalClass {
public int Eval() {
return {{{{userInput}}}};
}
}";
var provider = new CSharpCodeProvider();
var parameters = new CompilerParameters { GenerateInMemory = true };
var results = provider.CompileAssemblyFromSource(parameters, code);
}
2) DataTable.Compute with raw expressions — **vulnerable**
public static void DataTableComputeFail(string expr)
{
var table = new System.Data.DataTable();
var result = table.Compute(expr, null);
}
Recommended mitigations / fixes:
- **Avoid** compiling or directly executing user-provided code. Prefer domain-specific evaluators that restrict functionality (e.g., arithmetic expression parsers).
- **Validate or whitelist** inputs. If you must support user selection of operations, map user input to a predefined list of safe operations/handlers.
- **Sanitize** and strictly validate expressions before passing them to any evaluator; better: do not use general-purpose evaluators on untrusted input.
- **Use sandboxing** where available (restrict assemblies, types and APIs accessible to script), but treat sandboxing as a last resort and still validate input.Possible Messages
Key |
Text |
Severity |
Disabled |
|---|---|---|---|
tainted_call |
Untrusted input used to generate or execute code. |
None |
False |
Options
This rule shares the following common options: excludes, includes, justification_checker, post_processing, provider, severity
The following places define options that affect this rule: Stylechecks, Analysis-GlobalOptions
This rule has no individual options.