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

This rule detects **Code Injection (CWE-94)** where untrusted input is used to generate, compile or execute code or evaluable expressions. Typical dangerous sinks include `CSharpCodeProvider.CompileAssemblyFromSource`, `CSharpScript.EvaluateAsync`, `DataTable.Compute` where the invoked member is taken directly from user input. Why this is dangerous: - User-controlled input that is compiled or executed can run arbitrary code in the application context. - Attackers can read files, delete data, escalate privileges or perform other malicious actions. Examples of vulnerable code: 1) Direct compilation of user input (CodeDOM) — **vulnerable**

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