---
title: Avoid Eval Or Dynamic Code Execution
impact: HIGH
impactDescription: prevents remote code execution vulnerabilities
tags: eval, code-execution, rce, injection, security, csharp
---

## Avoid Eval Or Dynamic Code Execution

Dynamic code execution functions allow attackers to execute arbitrary code on the server. In C#, this often involves `Assembly.Load`, `Process.Start` with user input, or dynamic compilation tools like Roslyn scripting.

**Incorrect (dynamic code execution):**

```csharp
// Executing user input as code
using Microsoft.CodeAnalysis.CSharp.Scripting;

string userCode = Request.Form["code"];
var result = await CSharpScript.EvaluateAsync(userCode); // RCE Vulnerability!

// Loading arbitrary assembly
var assembly = Assembly.LoadFile(userInputPath); // Dangerous

// Command Injection via Process.Start
Process.Start("cmd.exe", "/c " + userInput); 
```

**Correct (safe alternatives):**

```csharp
// Use a math parser library for formulas
var result = new DataTable().Compute("1 + 2", null); // Simple math only

// Use Strategy Pattern or Dictionary for dynamic logic
var actions = new Dictionary<string, Action>
{
    { "start", StartService },
    { "stop", StopService }
};

if (actions.TryGetValue(userInput, out var action))
{
    action();
}

// Process.Start with explicit arguments (no shell execute)
var startInfo = new ProcessStartInfo
{
    FileName = "git",
    ArgumentList = { "status" }, // Safe list
    UseShellExecute = false
};
Process.Start(startInfo);
```

**Tools:** Roslyn Analyzers, SonarQube (S1523), Security Code Scan
