Skip to content

armgit / ARTEX

Public Imported from GitHub
0

ARTEX - AI autonomous penetration testing system (English translation; upstream: Autumn-27/ARTEX, AGPL-3.0)

server: give agent processes a fixed allowlisted environment

BaaRai2e8f4fea382f
diff --git a/server/customtool.go b/server/customtool.go
index 1ad163a..0903d57 100644
--- a/server/customtool.go
+++ b/server/customtool.go
@@ -525,8 +525,9 @@ func execPython(ctx context.Context, interp, key, code string, params map[string
defer cancel()
c := exec.CommandContext(runCtx, interp, tmp)
c.Dir = workDir
- c.Env = append(os.Environ(), sessionEnv...) // session proxy env
- for k, v := range params { // scalar params mirrored as TOOL_<NAME>
+ // The allowlist as the executor (execenv_unix.go), then the session proxy env.
+ c.Env = append(agentProcessEnv(priv), sessionEnv...)
+ for k, v := range params { // scalar params mirrored as TOOL_<NAME>
if sv, ok := scalarStr(v); ok {
c.Env = append(c.Env, "TOOL_"+strings.ToUpper(k)+"="+sv)
}
diff --git a/server/execenv_unix.go b/server/execenv_unix.go
new file mode 100644
index 0000000..7ce71b6
--- /dev/null
+++ b/server/execenv_unix.go
@@ -0,0 +1,128 @@
+//go:build unix
+
+package server
+
+import (
+ "os"
+ "sort"
+ "strings"
+)
+
+// Environment of the agent processes. When a process crosses from the server's
+// identity to the executor's (the Bash shim, the MCP drop shim, a custom tool), its
+// environment is rebuilt from the fixed allowlist below instead of being inherited
+// from the server. ScrubSecretEnv and SealProcessEnv still remove the known secrets
+// from the server's own environment; they are a deny list, and a credential under
+// any other name (a variable an operator or an image adds) would reach the agent.
+// The allowlist is the boundary: nothing outside it crosses, whatever its name.
+//
+// What an agent process sets for its own children afterwards (a nested bash, an
+// exported variable) is its own business: the environment is rebuilt only when the
+// identity changes.
+
+// executorEnvNames are the server variables an agent process keeps: the search
+// path and locale, the temp directory, the non-interactive defaults Norma sets, the
+// proxy and CA trust variables the agents pass to their shells (agent.proxyEnv),
+// the browser location of the image (Dockerfile), and the shim's own non-secret
+// variables. HOME and XDG_CACHE_HOME are replaced by the executor's home.
+var executorEnvNames = nameSet(
+ "PATH", "HOME", "XDG_CACHE_HOME",
+ "LANG", "LANGUAGE", "TERM", "TZ", "TMPDIR",
+ "PAGER", "GIT_PAGER", "SYSTEMD_PAGER", "DEBIAN_FRONTEND",
+ "HTTP_PROXY", "HTTPS_PROXY", "http_proxy", "https_proxy",
+ "ALL_PROXY", "all_proxy", "NO_PROXY", "no_proxy", "NODE_USE_ENV_PROXY",
+ "SSL_CERT_FILE", "CURL_CA_BUNDLE", "REQUESTS_CA_BUNDLE", "GIT_SSL_CAINFO", "NODE_EXTRA_CA_CERTS",
+ "PLAYWRIGHT_BROWSERS_PATH",
+ envExecBash, envExecUID, envExecGID, envExecHome,
+)
+
+func nameSet(names ...string) map[string]bool {
+ m := make(map[string]bool, len(names))
+ for _, n := range names {
+ m[n] = true
+ }
+ return m
+}
+
+// executorEnvPrefixes are kept by prefix: the locale categories.
+var executorEnvPrefixes = []string{"LC_"}
+
+// envExecKeep lists, comma-separated, names the drop shim keeps besides the
+// allowlist: the variables an MCP stdio server is given in its configuration. It is
+// not kept itself.
+const envExecKeep = "ARTEX_EXEC_KEEP"
+
+// executorEnvAllowed reports whether the variable name crosses to an agent process.
+func executorEnvAllowed(name string) bool {
+ if executorEnvNames[name] {
+ return true
+ }
+ for _, p := range executorEnvPrefixes {
+ if strings.HasPrefix(name, p) {
+ return true
+ }
+ }
+ return false
+}
+
+// executorEnv returns the entries of env an agent process keeps: the allowlisted
+// names and the names in keep, in their order. Malformed entries are dropped.
+func executorEnv(env []string, keep map[string]bool) []string {
+ out := make([]string, 0, len(env))
+ for _, kv := range env {
+ name, _, ok := strings.Cut(kv, "=")
+ if !ok || name == "" {
+ continue
+ }
+ if executorEnvAllowed(name) || keep[name] {
+ out = append(out, kv)
+ }
+ }
+ return out
+}
+
+// sealExecutorEnv replaces the environment of the calling process, a shim about to
+// become an agent process, with executorEnv of it and the names in envExecKeep.
+func sealExecutorEnv() error {
+ keep := map[string]bool{}
+ for _, n := range strings.Split(os.Getenv(envExecKeep), ",") {
+ if n = strings.TrimSpace(n); n != "" {
+ keep[n] = true
+ }
+ }
+ env := executorEnv(os.Environ(), keep)
+ os.Clearenv()
+ for _, kv := range env {
+ k, v, _ := strings.Cut(kv, "=")
+ if err := os.Setenv(k, v); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// agentProcessEnv is the base environment of a custom tool: the allowlist when it
+// runs as the executor, the server's environment otherwise.
+func agentProcessEnv(p ExecPrivilege) []string {
+ if !p.Enabled {
+ return os.Environ()
+ }
+ return executorEnv(os.Environ(), nil)
+}
+
+// withExecKeep adds envExecKeep to the configured environment of an MCP stdio
+// server that runs as the executor, so the drop shim keeps those variables.
+func withExecKeep(p ExecPrivilege, env map[string]string) map[string]string {
+ if !p.Enabled || len(env) == 0 {
+ return env
+ }
+ names := make([]string, 0, len(env))
+ out := make(map[string]string, len(env)+1)
+ for k, v := range env {
+ names = append(names, k)
+ out[k] = v
+ }
+ sort.Strings(names)
+ out[envExecKeep] = strings.Join(names, ",")
+ return out
+}
diff --git a/server/execenv_unix_test.go b/server/execenv_unix_test.go
new file mode 100644
index 0000000..d74145f
--- /dev/null
+++ b/server/execenv_unix_test.go
@@ -0,0 +1,75 @@
+//go:build unix
+
+package server
+
+import (
+ "os"
+ "strings"
+ "testing"
+)
+
+// The allowlist keeps the named and prefixed variables and the extra names, and
+// drops everything else, secrets under known and unknown names alike.
+func TestExecutorEnvAllowlist(t *testing.T) {
+ env := []string{
+ "PATH=/usr/bin", "LANG=C.UTF-8", "LC_ALL=C", "HTTP_PROXY=http://127.0.0.1:8788",
+ "SSL_CERT_FILE=/ca.pem", "PLAYWRIGHT_BROWSERS_PATH=/pw", envExecHome + "=/data/exec-home",
+ "ARTEX_PG_DSN=postgres://artex:pw@postgres/artex", "OPENAI_API_KEY=sk-x",
+ "MY_COMPANY_TOKEN=t0k3n", "ARTEX_NOISE_PROFILE=quiet", "MCP_TOKEN=abc",
+ envExecKeep + "=MCP_TOKEN", "malformed", "=empty-name",
+ }
+ got := strings.Join(executorEnv(env, map[string]bool{"MCP_TOKEN": true}), "|")
+ want := strings.Join([]string{
+ "PATH=/usr/bin", "LANG=C.UTF-8", "LC_ALL=C", "HTTP_PROXY=http://127.0.0.1:8788",
+ "SSL_CERT_FILE=/ca.pem", "PLAYWRIGHT_BROWSERS_PATH=/pw", envExecHome + "=/data/exec-home",
+ "MCP_TOKEN=abc",
+ }, "|")
+ if got != want {
+ t.Fatalf("executorEnv =\n%s\nwant\n%s", got, want)
+ }
+ for _, k := range secretEnv {
+ if executorEnvAllowed(k) {
+ t.Errorf("secret variable %s is on the allowlist", k)
+ }
+ }
+}
+
+// withExecKeep names the configured variables for the shim, only for an executor.
+func TestWithExecKeep(t *testing.T) {
+ env := map[string]string{"B_TOKEN": "2", "A_TOKEN": "1"}
+ got := withExecKeep(ExecPrivilege{Enabled: true, UID: 10001, GID: 10001}, env)
+ if got[envExecKeep] != "A_TOKEN,B_TOKEN" || got["A_TOKEN"] != "1" || got["B_TOKEN"] != "2" || len(got) != 3 {
+ t.Fatalf("withExecKeep = %v", got)
+ }
+ if _, ok := env[envExecKeep]; ok {
+ t.Fatal("withExecKeep changed its argument")
+ }
+ if got := withExecKeep(ExecPrivilege{}, env); len(got) != 2 {
+ t.Fatalf("a disabled drop must leave the env as is: %v", got)
+ }
+ if got := withExecKeep(ExecPrivilege{Enabled: true}, nil); got != nil {
+ t.Fatalf("no configured env: %v", got)
+ }
+}
+
+// agentProcessEnv filters only for an executor.
+func TestAgentProcessEnv(t *testing.T) {
+ t.Setenv("ARTEX_ISOLATION_CANARY", "canary")
+ has := func(env []string) bool {
+ for _, kv := range env {
+ if strings.HasPrefix(kv, "ARTEX_ISOLATION_CANARY=") {
+ return true
+ }
+ }
+ return false
+ }
+ if !has(agentProcessEnv(ExecPrivilege{})) {
+ t.Fatal("with the drop disabled the server environment is passed as before")
+ }
+ if has(agentProcessEnv(ExecPrivilege{Enabled: true, UID: 10001, GID: 10001})) {
+ t.Fatal("an executor process must not inherit a variable outside the allowlist")
+ }
+ if len(agentProcessEnv(ExecPrivilege{Enabled: true})) == 0 && os.Getenv("PATH") != "" {
+ t.Fatal("PATH must cross")
+ }
+}
diff --git a/server/execpriv_other.go b/server/execpriv_other.go
index 16aadf6..b2980a2 100644
--- a/server/execpriv_other.go
+++ b/server/execpriv_other.go
@@ -4,6 +4,7 @@ package server
import (
"errors"
+ "os"
"os/exec"
)
@@ -19,6 +20,10 @@ func serverIsRoot() bool { return false }
func applyExecCredential(c *exec.Cmd, p ExecPrivilege) {}
+func agentProcessEnv(p ExecPrivilege) []string { return os.Environ() }
+
+func withExecKeep(p ExecPrivilege, env map[string]string) map[string]string { return env }
+
func prepareExecScript(p ExecPrivilege, path string) error { return nil }
func shareRestoredTaskDir(p ExecPrivilege, taskDir string) error { return nil }
diff --git a/server/execpriv_root_linux_test.go b/server/execpriv_root_linux_test.go
index 7e24db0..487627d 100644
--- a/server/execpriv_root_linux_test.go
+++ b/server/execpriv_root_linux_test.go
@@ -738,6 +738,111 @@ func TestNormaTaskDirPlantedByExecutorAsRoot(t *testing.T) {
}
}
+// envNames returns the variable names of an `env` listing.
+func envNames(out string) map[string]string {
+ m := map[string]string{}
+ for _, line := range strings.Split(out, "\n") {
+ if k, v, ok := strings.Cut(line, "="); ok && k != "" && !strings.ContainsAny(k, " \t") {
+ m[k] = v
+ }
+ }
+ return m
+}
+
+// checkExecutorEnv asserts what crosses to an executor process: no variable
+// outside the allowlist (the canary and a secret name set in the server), the
+// executor's HOME, and the extra names wanted.
+func checkExecutorEnv(t *testing.T, path, out, home string, want ...string) {
+ t.Helper()
+ got := envNames(out)
+ for k := range got {
+ if !executorEnvAllowed(k) && !strings.HasPrefix(k, "TOOL_") && k != "PWD" && k != "SHLVL" && k != "_" && k != "OLDPWD" && !slicesContains(want, k) {
+ t.Errorf("%s: %s crossed to the executor", path, k)
+ }
+ }
+ for _, k := range []string{"ARTEX_ISOLATION_CANARY", "OPENAI_API_KEY", envExecKeep} {
+ if _, ok := got[k]; ok {
+ t.Errorf("%s: %s reached the executor", path, k)
+ }
+ }
+ if got["HOME"] != home {
+ t.Errorf("%s: HOME=%q, want %q", path, got["HOME"], home)
+ }
+ for _, k := range append([]string{"PATH"}, want...) {
+ if _, ok := got[k]; !ok {
+ t.Errorf("%s: %s missing from the executor environment:\n%s", path, k, out)
+ }
+ }
+}
+
+func slicesContains(s []string, v string) bool {
+ for _, x := range s {
+ if x == v {
+ return true
+ }
+ }
+ return false
+}
+
+// Each executor path starts its process with the allowlisted environment: a
+// variable of the server outside the allowlist does not cross, whatever its name;
+// what the caller passes on purpose (Bash env, custom-tool parameters, the
+// configured env of an MCP server) does. A nested shell keeps what the agent set.
+func TestExecutorEnvAllowlistAsRoot(t *testing.T) {
+ f := newExecRootFixture(t)
+ t.Setenv("ARTEX_ISOLATION_CANARY", "canary-value")
+ t.Setenv("OPENAI_API_KEY", "sk-canary")
+ if err := InstallBashShim(f.priv); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { os.RemoveAll(filepath.SplitList(os.Getenv("PATH"))[0]) })
+
+ // Bash (Norma: exec.Command("bash") with the server env and the agent's BashEnv).
+ in, _ := json.Marshal(map[string]string{"command": "env; echo NESTED=$(AGENT_SET=1 bash -c 'echo $AGENT_SET')"})
+ res, err := actool.NewBash().Call(context.Background(), in, &actool.ToolContext{WorkingDir: f.work, Env: []string{"HTTP_PROXY=http://127.0.0.1:9"}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ out := res.Flatten()
+ checkExecutorEnv(t, "bash shim", out, f.home, "HTTP_PROXY", "PAGER", "NESTED")
+ if !strings.Contains(out, "NESTED=1") {
+ t.Errorf("a nested shell lost the variable the agent set:\n%s", out)
+ }
+
+ // Custom tool.
+ py, err := exec.LookPath("python3")
+ if err != nil {
+ t.Fatalf("python3 is needed for the custom-tool path: %v", err)
+ }
+ out, err = execPython(context.Background(), py, "probe", `import os
+for k, v in os.environ.items():
+ print(k + "=" + v)`, map[string]any{"x": "1"}, f.work, []string{"HTTP_PROXY=http://127.0.0.1:9"}, 30*time.Second, f.priv)
+ if err != nil {
+ t.Fatal(err)
+ }
+ checkExecutorEnv(t, "custom tool", out, f.home, "HTTP_PROXY", "TOOL_X")
+
+ // MCP stdio: mcp.NewStdioClient sets the server env plus the configured one.
+ command, args, err := execDropCommand(f.priv, "env", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ c := exec.Command(command, args...)
+ c.Dir = f.work
+ c.Env = os.Environ()
+ for k, v := range withExecKeep(f.priv, map[string]string{"MCP_TOKEN": "configured"}) {
+ c.Env = append(c.Env, k+"="+v)
+ }
+ b, err := c.CombinedOutput()
+ if err != nil {
+ t.Fatalf("%v\n%s", err, b)
+ }
+ checkExecutorEnv(t, "mcp stdio", string(b), f.home, "MCP_TOKEN")
+ if envNames(string(b))["MCP_TOKEN"] != "configured" {
+ t.Errorf("mcp stdio: the configured MCP_TOKEN did not cross:\n%s", b)
+ }
+}
+
// PrepareExecPrivilege gives the agent's file tools the executor identity: through
// it, a root-only file is refused by the kernel.
func TestPrepareExecPrivilegeSetsFileToolIdentityAsRoot(t *testing.T) {
diff --git a/server/execpriv_unix.go b/server/execpriv_unix.go
index 2c3c76f..c23334c 100644
--- a/server/execpriv_unix.go
+++ b/server/execpriv_unix.go
@@ -608,10 +608,14 @@ func runBashShim(argv []string) {
}
// enterExecutor drops to uid and gid. When this call performs the switch (not in a
-// nested shell already running as the executor, whose HOME the agent may have set),
-// HOME and XDG_CACHE_HOME move to the executor's home first.
+// nested shell already running as the executor, whose environment the agent may
+// have set), the environment is first rebuilt from the allowlist (execenv_unix.go)
+// and HOME and XDG_CACHE_HOME move to the executor's home.
func enterExecutor(uid, gid int) error {
if os.Getuid() != uid || os.Getgid() != gid {
+ if err := sealExecutorEnv(); err != nil {
+ return err
+ }
for _, kv := range execHomeEnv() {
k, v, _ := strings.Cut(kv, "=")
if err := os.Setenv(k, v); err != nil {
diff --git a/server/mcpdiscover.go b/server/mcpdiscover.go
index 1355973..d7e08ce 100644
--- a/server/mcpdiscover.go
+++ b/server/mcpdiscover.go
@@ -32,7 +32,9 @@ func connectMCP(ctx context.Context, m *db.MCPServer, priv ExecPrivilege) (mcpCl
if err != nil {
return nil, err
}
- return mcp.NewStdioClient(ctx, m.Name, command, jsonStrMap(m.Env), args...)
+ // The drop shim rebuilds the environment from the allowlist; the configured
+ // variables of the server are named so it keeps them.
+ return mcp.NewStdioClient(ctx, m.Name, command, withExecKeep(priv, jsonStrMap(m.Env)), args...)
case "http":
if m.URL == "" {
return nil, fmt.Errorf("http transport is missing a URL")