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

## Avoid Dynamic Code Execution

Executing arbitrary strings as code is extremely dangerous. Attackers can run any code on your server. While Go doesn't have a native `eval()` function, similar risks exist with certain libraries or `os/exec`.

**Incorrect (dynamic execution/dangerous OS calls):**

```go
// INSECURE: Executing user-provided command
cmd := exec.Command("bash", "-c", r.URL.Query().Get("cmd"))
cmd.Run()

// INSECURE: Using a dangerous expression library with unsanitized input
result, _ := govau.Eval(r.URL.Query().Get("formula")) 
```

**Correct (safe alternatives):**

```go
// Use switch/mapping for dynamic behavior
var operations = map[string]func(int, int) int{
    "add":      func(a, b int) int { return a + b },
    "subtract": func(a, b int) int { return a - b },
}

opFunc, ok := operations[r.FormValue("op")]
if !ok {
    http.Error(w, "Invalid operation", 400)
    return
}
result := opFunc(a, b)

// Use safe parsers for math
// import "github.com/Knetic/govaluate"
expression, _ := govaluate.NewEvaluable("10 + x")
parameters := make(map[string]interface{})
parameters["x"] = 5
result, _ := expression.Evaluate(parameters)
```

**Tools:** `gosec` (G204), Semgrep, Code Review
