Dynamic code execution (ARCH341)
Ce contenu n’est pas encore disponible dans votre langue.
Key dotnet.security.dynamic-code-execution · Severity critical · Category security · CWE CWE-95
.NET has no eval, but Roslyn scripting, PowerShell hosting, System.Linq.Dynamic, DataTable.Compute and loading an assembly from bytes all turn a runtime string into running code. A literal script is a design choice; a script that arrives as a variable is remote code execution waiting for its input.
Incorrect
Section titled “Incorrect”public async Task<object> Run(string expression){ return await CSharpScript.EvaluateAsync(expression);}Correct
Section titled “Correct”public decimal Run(Operation op, decimal a, decimal b) => op switch{ Operation.Add => a + b, Operation.Multiply => a * b, _ => throw new ArgumentOutOfRangeException(nameof(op))};Map the input onto a fixed set of operations (enum/switch, expression trees built in code). If scripting is a product feature, sandbox it and allowlist the script sources.