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)

security(server): keep server secrets from agent processes

BaaRai04a7ab3c3920
diff --git a/Dockerfile b/Dockerfile
index 1a623e4..7bb5d96 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -196,7 +196,8 @@ COPY --from=build /out/artex /app/artex
# to artex — docker stop only signals PID 1; without forwarding, artex never receives it,
# cannot shut down gracefully, and is hard-killed by SIGKILL after 10 seconds.
COPY start.sh /app/start.sh
-RUN chmod +x /app/artex /app/start.sh && mkdir -p /app/keys
+RUN chmod +x /app/artex /app/start.sh && mkdir -p -m 0700 /app/keys \
+ && chmod 0711 /root
COPY skills/ /app/skills/
# persistence points: data/ (traffic index, task files, transcripts) and keys/ (jwt.key, secret.key, via ARTEX_JWT_KEY_DIR)
VOLUME ["/app/data", "/app/keys"]
diff --git a/SECURITY.md b/SECURITY.md
index 49ccd93..a8e2934 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -49,6 +49,10 @@ Accepted gap: when a task has no allow-list, there is no allow rule to apply (bl
Operators running self-hosted LLM gateways or Ollama on a LAN or Docker bridge can allow specific endpoints with `ARTEX_LLM_PRIVATE_ENDPOINTS`, a comma-separated list of exact `host:port` entries (for example, `127.0.0.1:11434,host.docker.internal:11434,192.168.1.10:11434`). A URL whose `host:port` matches an entry may resolve to a loopback or private address while scheme restrictions, link-local/cloud-metadata blocks, and redirect validation still apply; everything else stays refused. Leaving `ARTEX_LLM_PRIVATE_ENDPOINTS` unset or empty keeps the strict public-only policy.
+## Agent Process Isolation
+
+The server runs as root, but the processes an agent starts (Bash, the interactive shell, custom tools and stdio MCP servers) run as the unprivileged uid and gid set by `-exec-uid` and `-exec-gid` (default 10001). Only the task workspace tree, shared with that group, is writable by them; `keys/` (`jwt.key`, `secret.key`) and the config file are root-only, and the server's environment block no longer carries `ARTEX_PG_DSN`, `ARTEX_SECRET_KEY` or the LLM API keys (Linux). These are a containment layer, not a sandbox: an executor can still read world-readable files under the data directory, reach the loopback API and the database if the network allows it, and use any credential it was given through the platform. Persistence tools (custom tools, MCP servers, skills) need operator approval by default.
+
## What to Expect
This is an open-source project maintained on a best-effort basis. We aim to acknowledge a report within about a week and keep you updated, but we cannot guarantee specific response or fix timeframes.
diff --git a/agent/chat.go b/agent/chat.go
index 65cd595..803daa8 100644
--- a/agent/chat.go
+++ b/agent/chat.go
@@ -152,7 +152,8 @@ func (c *ChatAgent) Chat(ctx context.Context, agentKey, sessionID, message strin
if !sessionDirInside(c.workDir, sessionWorkDir) {
return "", fmt.Errorf("invalid session id %q", sessionID)
}
- _ = os.MkdirAll(sessionWorkDir, 0o755)
+ // 0775 for the same reason as ensureRunDir: the executor group writes here.
+ _ = os.MkdirAll(sessionWorkDir, 0o775)
ctx = intercept.WithReviewWorkingDirectory(ctx, sessionWorkDir)
// Pure assistant: DefaultTools as the base; AugmentTools layers in the key's
diff --git a/agent/worker.go b/agent/worker.go
index c43f94c..b8a29c3 100644
--- a/agent/worker.go
+++ b/agent/worker.go
@@ -324,7 +324,9 @@ func ensureRunDir(base string, taskID, intentID int64) string {
if intentID > 0 {
dir = filepath.Join(dir, "i"+strconv.FormatInt(intentID, 10))
}
- _ = os.MkdirAll(dir, 0o755)
+ // 0775: with the executor group sharing the task tree (server/execpriv.go) the
+ // agent's shell must write here; the umask of the server decides the final bits.
+ _ = os.MkdirAll(dir, 0o775)
return dir
}
diff --git a/cmd/artex/main.go b/cmd/artex/main.go
index 25cb8d9..538e903 100644
--- a/cmd/artex/main.go
+++ b/cmd/artex/main.go
@@ -77,14 +77,34 @@ func printBanner(addr string) {
// main maps run's result onto the process exit code. The body lives in a
// function that can *return* rather than os.Exit, so its own defers still run.
func main() {
+ // Started as the Bash shim or as an MCP drop command: drop the identity and exec
+ // the real program. It returns only for an ordinary start.
+ server.RunExecShimIfRequested(os.Args)
+ // Before any listener or child exists: keep the secrets out of /proc/<pid>/environ.
+ server.SealProcessEnv()
os.Exit(run())
}
+// flagWasSet reports whether the operator passed the named flag.
+func flagWasSet(name string) bool {
+ set := false
+ flag.Visit(func(f *flag.Flag) {
+ if f.Name == name {
+ set = true
+ }
+ })
+ return set
+}
+
func run() int {
var (
addr = flag.String("addr", "127.0.0.1:8787", "HTTP listen address")
dataDir = flag.String("data", filepath.Join(config.BaseDir(), "data"), "runtime data directory: traffic index, task files, transcripts (default: data/ next to the executable)")
proxy = flag.String("proxy", "127.0.0.1:8788", "traffic recording proxy address (empty to disable)")
+ // Identity of every agent process (Bash, the shell, custom tools, MCP stdio).
+ // A negative uid turns the drop off; 0 (root) is refused.
+ execUID = flag.Int("exec-uid", server.DefaultExecUID, "uid that agent processes run as (Bash, shell, custom tools, MCP stdio); -1 turns the drop off")
+ execGID = flag.Int("exec-gid", server.DefaultExecGID, "gid that agent processes run as")
)
flag.Parse()
@@ -152,6 +172,22 @@ func run() int {
TrustedProxies: trustedAddrs,
})
+ // Agent processes run as the executor identity, never as the server's root (see
+ // server/execpriv.go). An explicit option that cannot be applied stops the start.
+ priv, err := server.ResolveExecPrivilege(*execUID, *execGID, flagWasSet("exec-uid") || flagWasSet("exec-gid"))
+ if err != nil {
+ log.Printf("[config] %v", err)
+ return 1
+ }
+ if err := server.PrepareExecPrivilege(priv, *dataDir, config.KeyDir(), config.Path()); err != nil {
+ log.Printf("[config] %v", err)
+ return 1
+ }
+ if err := server.InstallBashShim(priv); err != nil {
+ log.Printf("[config] %v", err)
+ return 1
+ }
+
sigCtx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
ctx, shutdown := shutdownContext(sigCtx)
@@ -163,7 +199,7 @@ func run() int {
}
defer mgr.Close()
- srv := server.New(ctx, mgr, skillDir, *dataDir, keyDir, server.WithSecretScrub(), server.WithTrustedProxies(trusted))
+ srv := server.New(ctx, mgr, skillDir, *dataDir, keyDir, server.WithSecretScrub(), server.WithTrustedProxies(trusted), server.WithExecPrivilege(priv))
// ReadTimeout bounds how long the request headers and body may take to arrive.
// It does not limit how long a handler runs, so an event stream stays open.
// WriteTimeout is left unset: a write deadline would cut that stream.
diff --git a/db/db.go b/db/db.go
index 683323e..2a3955d 100644
--- a/db/db.go
+++ b/db/db.go
@@ -350,6 +350,9 @@ ON CONFLICT (name) DO NOTHING`,
if err := d.seedDefaultInterceptRules(); err != nil {
return fmt.Errorf("seed intercept rules: %w", err)
}
+ if err := d.seedPersistenceApprovalRules(); err != nil {
+ return fmt.Errorf("seed persistence approval rules: %w", err)
+ }
if err := d.seedDefaultInterceptRulesV2(); err != nil {
return fmt.Errorf("seed intercept rules v2: %w", err)
}
diff --git a/db/intercept_persistence_seed.go b/db/intercept_persistence_seed.go
new file mode 100644
index 0000000..71e7166
--- /dev/null
+++ b/db/intercept_persistence_seed.go
@@ -0,0 +1,46 @@
+package db
+
+import "fmt"
+
+// seedPersistenceApprovalRules inserts the built-in approval rules for the platform
+// tools that store something the agents load or run later (custom tools, MCP
+// servers, skill files). Each call of those tools is an ask: the operator approves it
+// in the console. Seeded once, behind its own settings flag, like the other built-in
+// seeds, so a later disable by the operator is never undone on restart. No agent tool
+// reads or edits intercept rules, so an agent cannot lower them.
+func (d *DB) seedPersistenceApprovalRules() error {
+ if v, _, _ := d.GetSetting("intercept_persistence_rules_v1"); v == "done" {
+ return nil
+ }
+ rules := []struct {
+ name string
+ pattern string
+ message string
+ }{
+ {
+ name: "[built-in] Persistent change: custom tool",
+ pattern: `^(?:create_custom_tool|update_custom_tool)$`,
+ message: "Approval needed: the agent asks to create or change a custom tool. It is stored on the platform and its code runs on this server in later calls. Approve only code you have read.",
+ },
+ {
+ name: "[built-in] Persistent change: MCP server",
+ pattern: `^(?:create_mcp|update_mcp)$`,
+ message: "Approval needed: the agent asks to add or change an MCP server. A stdio entry starts its command on this server; an HTTP or SSE entry sends its headers to its URL.",
+ },
+ {
+ name: "[built-in] Persistent change: skill",
+ pattern: `^(?:create_skill|update_skill_file)$`,
+ message: "Approval needed: the agent asks to create or change a skill file. Every agent that sees the skill loads its content as instructions.",
+ },
+ }
+ for _, r := range rules {
+ if _, err := d.Exec(`
+INSERT INTO intercept_rules(name, enabled, priority, match_target, match_type, pattern, action, message, timeout_enabled, timeout_seconds, timeout_action)
+VALUES ($1, true, 95, 'tool_name', 'regex', $2, 'ask', $3, false, 60, 'deny')`,
+ r.name, r.pattern, r.message,
+ ); err != nil {
+ return fmt.Errorf("rule %q: %w", r.name, err)
+ }
+ }
+ return d.SetSetting("intercept_persistence_rules_v1", "done")
+}
diff --git a/guard/guard.go b/guard/guard.go
index 3663722..e10ae6d 100644
--- a/guard/guard.go
+++ b/guard/guard.go
@@ -160,13 +160,19 @@ func (g *Guard) applyIntercept(ctx context.Context, ev hook.Event, cmd string) h
}
scope, gated := g.gateScope(ctx)
rules := !g.targetOnly && g.interceptor != nil && g.interceptor.IsToolEnabled(ev.ToolName)
- if !rules && !gated {
+ // Persistence tools (custom tools, MCP servers, skills) always meet their built-in
+ // approval, in the target-only guard too; see intercept.MatchPersistence.
+ persist := g.interceptor != nil && intercept.IsPersistenceTool(ev.ToolName)
+ if !rules && !gated && !persist {
return hook.Result{}
}
ctx = intercept.WithCall(ctx, ev.ToolName, ev.Input)
var dec intercept.Decision
- if rules {
- var matched bool
+ matched := false
+ if persist {
+ dec, matched = g.interceptor.MatchPersistence(ev.ToolName, ev.Input)
+ }
+ if !matched && rules {
dec, matched = g.interceptor.Match(ev.ToolName, ev.Input)
if !matched {
// No rule matched. Ask the LLM fallback judge (if enabled); when it is off
diff --git a/intercept/persistence.go b/intercept/persistence.go
new file mode 100644
index 0000000..2d63e18
--- /dev/null
+++ b/intercept/persistence.go
@@ -0,0 +1,77 @@
+package intercept
+
+import (
+ "encoding/json"
+ "strings"
+)
+
+// PersistenceTools are the platform tools that store something the agents load or
+// run later: a custom tool (its code runs on the host in later calls), an MCP server
+// (a stdio entry starts its command), a skill file (agents load it as instructions).
+// A prompt-injected page can make an agent call them, so each call needs operator
+// approval. The approval comes from the built-in ask rules seeded in db
+// ("[built-in] Persistent change: ..."). Nothing an agent can call edits those rules;
+// only the console can disable them.
+var PersistenceTools = []string{
+ "create_custom_tool", "update_custom_tool",
+ "create_mcp", "update_mcp",
+ "create_skill", "update_skill_file",
+}
+
+// IsPersistenceTool reports whether name is one of PersistenceTools.
+func IsPersistenceTool(name string) bool {
+ for _, t := range PersistenceTools {
+ if t == name {
+ return true
+ }
+ }
+ return false
+}
+
+// MatchPersistence decides a call of a persistence tool from the loaded rules. Any
+// enabled deny rule that matches wins. Otherwise the first matching built-in ask rule
+// answers, so the approval needs no other rule. User allow rules are not consulted:
+// an allow rule cannot skip the approval.
+func (i *Interceptor) MatchPersistence(toolName string, input []byte) (Decision, bool) {
+ if !IsPersistenceTool(toolName) {
+ return Decision{}, false
+ }
+ rules, err := i.rules()
+ if err != nil {
+ return Decision{}, false
+ }
+ var ask *compiledRule
+ for idx := range rules {
+ r := rules[idx]
+ if !ruleMatches(r, toolName, input) {
+ continue
+ }
+ if r.Action == "deny" {
+ return persistenceDecision(r), true
+ }
+ if ask == nil && r.Action == "ask" && strings.HasPrefix(r.Name, builtinRulePrefix) {
+ ask = &rules[idx]
+ }
+ }
+ if ask == nil {
+ return Decision{}, false
+ }
+ return persistenceDecision(*ask), true
+}
+
+func persistenceDecision(r compiledRule) Decision {
+ msg := r.Message
+ if msg == "" {
+ msg = defaultMessage(r.Action, r.Name)
+ }
+ configJSON, _ := json.Marshal(r.InterceptRule)
+ return Decision{
+ RuleName: r.Name, ConfigDigest: digestInput(configJSON),
+ Action: r.Action,
+ Message: msg,
+ RuleID: r.ID,
+ TimeoutEnabled: r.TimeoutEnabled,
+ TimeoutSeconds: r.TimeoutSeconds,
+ TimeoutAction: r.TimeoutAction,
+ }
+}
diff --git a/intercept/persistence_test.go b/intercept/persistence_test.go
new file mode 100644
index 0000000..4436134
--- /dev/null
+++ b/intercept/persistence_test.go
@@ -0,0 +1,88 @@
+package intercept
+
+import (
+ "testing"
+
+ "github.com/Autumn-27/artex/db"
+)
+
+const customToolApproval = `^(?:create_custom_tool|update_custom_tool)$`
+
+func builtinAsk(enabled bool) db.InterceptRule {
+ return db.InterceptRule{
+ ID: 1, Name: "[built-in] Persistent change: custom tool", Enabled: enabled, Priority: 95,
+ MatchTarget: "tool_name", MatchType: "regex", Pattern: customToolApproval,
+ Action: "ask", Message: "approve the custom tool",
+ }
+}
+
+func TestPersistenceToolsAreSixNamedTools(t *testing.T) {
+ if len(PersistenceTools) != 6 {
+ t.Fatalf("got %d persistence tools, want 6", len(PersistenceTools))
+ }
+ for _, name := range PersistenceTools {
+ if !IsPersistenceTool(name) {
+ t.Fatalf("%s not recognised", name)
+ }
+ }
+ if IsPersistenceTool("Bash") {
+ t.Fatal("Bash is not a persistence tool")
+ }
+}
+
+func TestBuiltinAskAnswersPersistenceCall(t *testing.T) {
+ ic := New(nil)
+ ic.SetRulesForTest([]db.InterceptRule{builtinAsk(true)})
+ dec, ok := ic.MatchPersistence("create_custom_tool", []byte(`{"key":"x"}`))
+ if !ok || dec.Action != "ask" {
+ t.Fatalf("got %+v ok=%v, want an ask", dec, ok)
+ }
+ if dec.RuleName != "[built-in] Persistent change: custom tool" {
+ t.Fatalf("rule name = %q", dec.RuleName)
+ }
+}
+
+func TestPersistenceIgnoresOtherTools(t *testing.T) {
+ ic := New(nil)
+ ic.SetRulesForTest([]db.InterceptRule{builtinAsk(true)})
+ if _, ok := ic.MatchPersistence("Bash", []byte(`{"command":"create_custom_tool"}`)); ok {
+ t.Fatal("a tool outside PersistenceTools must not be answered here")
+ }
+}
+
+// An operator-disabled built-in rule is not loaded, so nothing answers the call.
+func TestDisabledBuiltinAskDoesNotApply(t *testing.T) {
+ ic := New(nil)
+ ic.SetRulesForTest([]db.InterceptRule{builtinAsk(false)})
+ if _, ok := ic.MatchPersistence("create_custom_tool", nil); ok {
+ t.Fatal("a disabled rule must not answer")
+ }
+}
+
+// An allow rule at a higher priority cannot skip the built-in approval.
+func TestUserAllowCannotBypassApproval(t *testing.T) {
+ ic := New(nil)
+ ic.SetRulesForTest([]db.InterceptRule{
+ {ID: 2, Name: "user allow all", Enabled: true, Priority: 500,
+ MatchTarget: "tool_name", MatchType: "regex", Pattern: `.*`, Action: "allow"},
+ builtinAsk(true),
+ })
+ dec, ok := ic.MatchPersistence("update_custom_tool", nil)
+ if !ok || dec.Action != "ask" {
+ t.Fatalf("got %+v ok=%v, want the approval to stand", dec, ok)
+ }
+}
+
+// A user deny that matches a persistence call wins over the built-in approval.
+func TestUserDenyWinsOverApproval(t *testing.T) {
+ ic := New(nil)
+ ic.SetRulesForTest([]db.InterceptRule{
+ {ID: 3, Name: "user deny custom tools", Enabled: true, Priority: 10,
+ MatchTarget: "tool_name", MatchType: "regex", Pattern: `custom_tool`, Action: "deny"},
+ builtinAsk(true),
+ })
+ dec, ok := ic.MatchPersistence("create_custom_tool", nil)
+ if !ok || dec.Action != "deny" {
+ t.Fatalf("got %+v ok=%v, want deny", dec, ok)
+ }
+}
diff --git a/server/assembly.go b/server/assembly.go
index b2ae7d6..9fb0754 100644
--- a/server/assembly.go
+++ b/server/assembly.go
@@ -28,7 +28,7 @@ const mcpUntrustedNote = "\nOutput of this tool may contain attacker-controlled
// hostTools, if set, returns runtime host tools (currently the traffic tools when
// capture is on) to add to EVERY agent's base list — the DB tools table then
// filters them per-agent binding. Empty/nil → no host tools this run (capture off).
-func wireAgentAugment(pg *db.DB, skillDir string, hostTools func() ([]actool.CoreTool, map[string][]string)) {
+func wireAgentAugment(pg *db.DB, skillDir string, hostTools func() ([]actool.CoreTool, map[string][]string), priv ExecPrivilege) {
agent.SetToolAugment(func(ctx context.Context, agentKey string) ([]actool.CoreTool, agent.DeferredInfo, func()) {
a, err := pg.GetAgentByKey(agentKey)
if err != nil || a == nil {
@@ -89,7 +89,7 @@ func wireAgentAugment(pg *db.DB, skillDir string, hostTools func() ([]actool.Cor
if !directVisible && !skillGated {
continue // neither directly visible nor referenced by a visible skill
}
- cl, err := connectMCP(ctx, m)
+ cl, err := connectMCP(ctx, m, priv)
if err != nil {
log.Printf("[mcp] %s connect failed: %v", m.Name, err)
_ = pg.UpdateMCPHealth(m.ID, false, "connect: "+err.Error())
diff --git a/server/assembly_test.go b/server/assembly_test.go
index b6eae9b..b0fe734 100644
--- a/server/assembly_test.go
+++ b/server/assembly_test.go
@@ -48,7 +48,7 @@ func TestAssembleVisibleSkill(t *testing.T) {
t.Fatal(err)
}
- wireAgentAugment(pg, skillDir, nil)
+ wireAgentAugment(pg, skillDir, nil, ExecPrivilege{})
t.Cleanup(func() { agent.SetToolAugment(nil) })
ag, _ := pg.GetAgentByKey("planner")
diff --git a/server/customtool.go b/server/customtool.go
index 09531ae..1dc8999 100644
--- a/server/customtool.go
+++ b/server/customtool.go
@@ -482,7 +482,7 @@ func (s *Server) runScriptTool(ctx context.Context, key string, execRaw json.Raw
}
sessionEnv = tc.Env
}
- body, err := execPython(ctx, interp, key, spec.Code, params, workDir, sessionEnv, timeoutOr(spec.TimeoutMs, 120000))
+ body, err := execPython(ctx, interp, key, spec.Code, params, workDir, sessionEnv, timeoutOr(spec.TimeoutMs, 120000), s.execPriv)
if err != nil {
return actool.Errorf(err.Error()), nil
}
@@ -492,7 +492,7 @@ func (s *Server) runScriptTool(ctx context.Context, key string, execRaw json.Raw
// execPython writes the code to a temp .py under workDir/.tools, runs it via interp
// with the params JSON on stdin + scalar params mirrored to TOOL_<NAME> env, and
// returns combined stdout+stderr (with a timeout/exit note). Standalone + testable.
-func execPython(ctx context.Context, interp, key, code string, params map[string]any, workDir string, sessionEnv []string, timeout time.Duration) (string, error) {
+func execPython(ctx context.Context, interp, key, code string, params map[string]any, workDir string, sessionEnv []string, timeout time.Duration, priv ExecPrivilege) (string, error) {
toolsDir := filepath.Join(workDir, ".tools")
if err := os.MkdirAll(toolsDir, 0o755); err != nil {
return "", err
@@ -508,10 +508,14 @@ func execPython(ctx context.Context, interp, key, code string, params map[string
return "", err
}
f.Close()
+ if err := prepareExecScript(priv, tmp); err != nil {
+ return "", err
+ }
runCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
c := exec.CommandContext(runCtx, interp, tmp)
+ applyExecCredential(c, priv)
c.Dir = workDir
c.Env = append(os.Environ(), sessionEnv...) // session proxy env
for k, v := range params { // scalar params mirrored as TOOL_<NAME>
diff --git a/server/customtool_test.go b/server/customtool_test.go
index 088651a..4984aa3 100644
--- a/server/customtool_test.go
+++ b/server/customtool_test.go
@@ -96,7 +96,7 @@ print("port=" + str(a["port"]))
`
out, err := execPython(context.Background(), interp, "test", code,
map[string]any{"target": "example.com", "port": float64(8080)},
- t.TempDir(), nil, 10*time.Second)
+ t.TempDir(), nil, 10*time.Second, ExecPrivilege{})
if err != nil {
t.Fatalf("execPython error: %v", err)
}
diff --git a/server/envseal.go b/server/envseal.go
new file mode 100644
index 0000000..165552d
--- /dev/null
+++ b/server/envseal.go
@@ -0,0 +1,148 @@
+package server
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "io"
+ "log"
+ "os"
+ "strconv"
+ "strings"
+)
+
+// Sealing the server environment. ScrubSecretEnv removes the secrets from the Go
+// environment, but the kernel keeps the environment block the process was executed
+// with: /proc/<pid>/environ still shows ARTEX_PG_DSN, ARTEX_SECRET_KEY and the API
+// keys to any process that can read it. SealProcessEnv re-executes the server once,
+// with those variables left out of the block; the values travel to the new image
+// through an inherited pipe and are put back into the Go environment there, so the
+// readers that run next see the same configuration.
+//
+// Only Linux has /proc and an exec that keeps the PID, so the handoff is Linux-only
+// (envseal_linux.go). Elsewhere SealProcessEnv logs that the environment is not sealed.
+
+// sealFDEnv names the inherited descriptor that carries the sealed values. It is set
+// only for the re-executed image and removed as soon as that image reads it.
+const sealFDEnv = "ARTEX_SEALED_FD"
+
+// sealMaxPayload keeps the handoff well inside a pipe buffer (64 KiB on Linux), so the
+// write before the exec never blocks. The secrets are a few hundred bytes in practice.
+const sealMaxPayload = 16 << 10
+
+// errSealUnsupported reports a platform where the environment block cannot be replaced.
+var errSealUnsupported = errors.New("replacing the process environment is not supported on this platform")
+
+// SealProcessEnv keeps the secrets out of the process environment block. Call it first
+// in main, before any listener opens or any child starts. In the re-executed image it
+// restores the values; a failure to restore is fatal, since the server cannot run
+// without its configuration.
+func SealProcessEnv() {
+ if raw, ok := os.LookupEnv(sealFDEnv); ok {
+ os.Unsetenv(sealFDEnv)
+ if err := restoreSealedEnv(raw); err != nil {
+ log.Fatalf("[env] sealed environment handoff failed: %v", err)
+ }
+ return
+ }
+ var kvs []string
+ for _, k := range secretEnv {
+ if v, ok := os.LookupEnv(k); ok {
+ kvs = append(kvs, k+"="+v)
+ }
+ }
+ if len(kvs) == 0 {
+ return
+ }
+ payload := encodeSealedEnv(kvs)
+ if len(payload) > sealMaxPayload {
+ log.Printf("[env] server environment not sealed: the secrets are too large for the handoff; they remain readable from /proc/<pid>/environ")
+ return
+ }
+ // reexecSealed returns only when the exec did not happen.
+ err := reexecSealed(withoutSecretEnv(os.Environ()), payload)
+ if errors.Is(err, errSealUnsupported) {
+ log.Printf("[env] server environment not sealed on this platform: secrets remain in the process environment")
+ return
+ }
+ log.Printf("[env] server environment not sealed (%v): secrets remain readable from /proc/<pid>/environ", err)
+}
+
+// restoreSealedEnv reads the handoff from the descriptor named by raw and sets the
+// values in the Go environment.
+func restoreSealedEnv(raw string) error {
+ fd, err := strconv.Atoi(raw)
+ if err != nil || fd < 0 {
+ return fmt.Errorf("bad descriptor %q", raw)
+ }
+ f := os.NewFile(uintptr(fd), "artex-sealed-env")
+ data, err := io.ReadAll(f)
+ f.Close()
+ if err != nil {
+ return err
+ }
+ kvs, err := decodeSealedEnv(data)
+ if err != nil {
+ return err
+ }
+ for _, kv := range kvs {
+ k, v, _ := strings.Cut(kv, "=")
+ if err := os.Setenv(k, v); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// encodeSealedEnv writes NAME=VALUE entries, each terminated by a NUL. Values may be
+// empty or span lines; an environment value cannot contain NUL, so the terminator is
+// unambiguous.
+func encodeSealedEnv(kvs []string) []byte {
+ var b []byte
+ for _, kv := range kvs {
+ b = append(b, kv...)
+ b = append(b, 0)
+ }
+ return b
+}
+
+// decodeSealedEnv parses encodeSealedEnv's output. Only the names in secretEnv are
+// accepted: the handoff carries nothing else, and an unknown name means corruption.
+func decodeSealedEnv(b []byte) ([]string, error) {
+ var kvs []string
+ for len(b) > 0 {
+ i := bytes.IndexByte(b, 0)
+ if i < 0 {
+ return nil, errors.New("sealed environment is not terminated")
+ }
+ entry := string(b[:i])
+ b = b[i+1:]
+ name, _, ok := strings.Cut(entry, "=")
+ if !ok || !isSecretName(name) {
+ return nil, fmt.Errorf("unexpected entry in the sealed environment")
+ }
+ kvs = append(kvs, entry)
+ }
+ return kvs, nil
+}
+
+func isSecretName(name string) bool {
+ for _, k := range secretEnv {
+ if k == name {
+ return true
+ }
+ }
+ return false
+}
+
+// withoutSecretEnv returns the environment block without the secret entries.
+func withoutSecretEnv(env []string) []string {
+ out := make([]string, 0, len(env))
+ for _, kv := range env {
+ name, _, _ := strings.Cut(kv, "=")
+ if !isSecretName(name) {
+ out = append(out, kv)
+ }
+ }
+ return out
+}
diff --git a/server/envseal_linux.go b/server/envseal_linux.go
new file mode 100644
index 0000000..5b3276b
--- /dev/null
+++ b/server/envseal_linux.go
@@ -0,0 +1,50 @@
+//go:build linux
+
+package server
+
+import (
+ "fmt"
+ "os"
+ "strconv"
+ "syscall"
+)
+
+// reexecSealed replaces the server image with the same binary and the given
+// environment block. The payload goes through a pipe whose read end stays open across
+// the exec; its number is passed in sealFDEnv. Only returns on failure.
+func reexecSealed(env []string, payload []byte) error {
+ var fds [2]int
+ // No close-on-exec: the read end must survive the exec. The write end is closed
+ // below before the exec, so the new image sees end-of-file after the payload.
+ if err := syscall.Pipe2(fds[:], 0); err != nil {
+ return fmt.Errorf("pipe: %w", err)
+ }
+ rfd, wfd := fds[0], fds[1]
+ if err := writeFully(wfd, payload); err != nil {
+ syscall.Close(rfd)
+ syscall.Close(wfd)
+ return fmt.Errorf("handoff write: %w", err)
+ }
+ syscall.Close(wfd)
+
+ exe, err := os.Executable()
+ if err != nil {
+ syscall.Close(rfd)
+ return fmt.Errorf("locate the server binary: %w", err)
+ }
+ env = append(env, sealFDEnv+"="+strconv.Itoa(rfd))
+ err = syscall.Exec(exe, os.Args, env)
+ syscall.Close(rfd)
+ return fmt.Errorf("exec: %w", err)
+}
+
+func writeFully(fd int, b []byte) error {
+ for len(b) > 0 {
+ n, err := syscall.Write(fd, b)
+ if err != nil {
+ return err
+ }
+ b = b[n:]
+ }
+ return nil
+}
diff --git a/server/envseal_linux_test.go b/server/envseal_linux_test.go
new file mode 100644
index 0000000..2bae807
--- /dev/null
+++ b/server/envseal_linux_test.go
@@ -0,0 +1,130 @@
+//go:build linux
+
+package server
+
+import (
+ "bytes"
+ "encoding/hex"
+ "fmt"
+ "os"
+ "os/exec"
+ "strings"
+ "testing"
+)
+
+const sealHelperEnv = "ARTEX_SEAL_TEST_HELPER"
+
+// sealHelper is the server's start sequence in miniature: seal, scrub, then report
+// what the kernel environment block and a child process see. It runs in the
+// re-executed image, where SealProcessEnv restores the values from the handoff.
+func sealHelper() {
+ SealProcessEnv()
+ proc, err := os.ReadFile("/proc/self/environ")
+ if err != nil {
+ fmt.Printf("SEAL error %v\n", err)
+ return
+ }
+ fmt.Printf("SEAL proc %x\n", proc)
+ for _, k := range secretEnv {
+ v, ok := os.LookupEnv(k)
+ fmt.Printf("SEAL value %s %x %t\n", k, v, ok)
+ }
+ ScrubSecretEnv()
+ child, err := exec.Command("env").Output()
+ if err != nil {
+ fmt.Printf("SEAL error %v\n", err)
+ return
+ }
+ fmt.Printf("SEAL child %x\n", child)
+ fmt.Println("SEAL done")
+}
+
+// TestSealedEnvironmentHandoff starts the test binary with the secrets in its
+// environment, as the server is started. The kernel environment block of the sealed
+// image and the environment of a child must hold none of the secret names, and the
+// values restored in the process must equal the originals, including empty and
+// multi-line ones.
+func TestSealedEnvironmentHandoff(t *testing.T) {
+ if os.Getenv(sealHelperEnv) == "1" {
+ sealHelper()
+ return
+ }
+ want := map[string]string{
+ "ARTEX_PG_DSN": "postgres://artex:p@[email protected]/artex?sslmode=disable\nsecond line\twith tab",
+ "ARTEX_SECRET_KEY": "",
+ "ANTHROPIC_API_KEY": "sk-ant-test",
+ "OPENAI_API_KEY": "=leading-equals",
+ }
+ env := os.Environ()
+ for k, v := range want {
+ env = append(env, k+"="+v)
+ }
+ env = append(env, sealHelperEnv+"=1")
+ cmd := exec.Command(os.Args[0], "-test.run=^TestSealedEnvironmentHandoff$")
+ cmd.Env = env
+ out, err := cmd.CombinedOutput()
+ if err != nil {
+ t.Fatalf("helper failed: %v\n%s", err, out)
+ }
+
+ var proc, child []byte
+ got := map[string]string{}
+ seen := map[string]bool{}
+ done := false
+ for _, line := range strings.Split(string(out), "\n") {
+ if !strings.HasPrefix(line, "SEAL ") {
+ continue
+ }
+ f := strings.Split(line, " ")
+ switch f[1] {
+ case "error":
+ t.Fatalf("helper: %s", line)
+ case "proc":
+ proc = mustHex(t, f[2])
+ case "child":
+ child = mustHex(t, f[2])
+ case "value":
+ // SEAL value NAME <hex> <present>; the hex part is empty for an empty value.
+ name, present := f[2], f[len(f)-1]
+ hexPart := ""
+ if len(f) == 5 {
+ hexPart = f[3]
+ }
+ if present != "true" {
+ t.Fatalf("%s is not set after sealing", name)
+ }
+ got[name] = string(mustHex(t, hexPart))
+ seen[name] = true
+ case "done":
+ done = true
+ }
+ }
+ if !done {
+ t.Fatalf("helper did not finish:\n%s", out)
+ }
+ for name := range want {
+ if !seen[name] {
+ t.Errorf("%s missing from the helper report", name)
+ }
+ if got[name] != want[name] {
+ t.Errorf("%s restored as %q, want %q", name, got[name], want[name])
+ }
+ }
+ for name := range want {
+ if bytes.Contains(proc, []byte(name+"=")) {
+ t.Errorf("kernel environment block still holds %s", name)
+ }
+ if bytes.Contains(child, []byte(name+"=")) {
+ t.Errorf("child process environment holds %s", name)
+ }
+ }
+}
+
+func mustHex(t *testing.T, s string) []byte {
+ t.Helper()
+ b, err := hex.DecodeString(s)
+ if err != nil {
+ t.Fatalf("bad hex %q: %v", s, err)
+ }
+ return b
+}
diff --git a/server/envseal_other.go b/server/envseal_other.go
new file mode 100644
index 0000000..0f50558
--- /dev/null
+++ b/server/envseal_other.go
@@ -0,0 +1,9 @@
+//go:build !linux
+
+package server
+
+// reexecSealed is not available off Linux: only Linux has the /proc environment this
+// protects, and the handoff depends on an exec that keeps the process in place.
+func reexecSealed(env []string, payload []byte) error {
+ return errSealUnsupported
+}
diff --git a/server/execpriv.go b/server/execpriv.go
new file mode 100644
index 0000000..a553c4e
--- /dev/null
+++ b/server/execpriv.go
@@ -0,0 +1,106 @@
+package server
+
+import (
+ "fmt"
+ "log"
+ "os"
+ "strconv"
+ "sync"
+)
+
+// Agent process privilege. The server keeps running as root (the Docker image does),
+// and every process the agent can start (Bash, the interactive shell, custom tools,
+// stdio MCP servers) runs as the executor identity below instead. Without this a
+// prompt-injected command runs as root in the same container: it reads /app/keys,
+// the config file and /proc/<server-pid>/environ with root's rights.
+//
+// The drop is applied to the child, never to the server: SysProcAttr.Credential for
+// the processes ARTEX starts itself, and for the processes the Norma library starts
+// (Bash, shell, MCP stdio) a shim in the same binary that drops and then execs the
+// real program. See execpriv_unix.go.
+
+// Default executor identity. It is a numeric id, not a system account: the kernel
+// accepts any uid. Override it with -exec-uid and -exec-gid.
+const (
+ DefaultExecUID = 10001
+ DefaultExecGID = 10001
+)
+
+// execDropArg is the argv marker of the MCP drop shim:
+// artex __artex-exec-drop <uid> <gid> -- <command> <args...>.
+const execDropArg = "__artex-exec-drop"
+
+// ExecPrivilege is the identity agent processes run under. The zero value is
+// disabled: children keep the server's identity, which is the state before this
+// change and is logged as such.
+type ExecPrivilege struct {
+ Enabled bool
+ UID uint32
+ GID uint32
+}
+
+// ResolveExecPrivilege turns the -exec-uid and -exec-gid options into an
+// ExecPrivilege. A negative uid disables the drop explicitly. explicit reports
+// whether the operator set either option: an explicit drop that cannot be applied
+// is an error (fail closed), while the default degrades to a single log line.
+func ResolveExecPrivilege(uid, gid int, explicit bool) (ExecPrivilege, error) {
+ if uid < 0 {
+ logExecOnce("[exec] agent processes keep the server's identity (-exec-uid=%d): no privilege drop", uid)
+ return ExecPrivilege{}, nil
+ }
+ if uid == 0 || gid <= 0 || uid > 1<<31-1 || gid > 1<<31-1 {
+ return ExecPrivilege{}, fmt.Errorf("-exec-uid and -exec-gid must name an unprivileged id (got uid %d, gid %d; 0 is root)", uid, gid)
+ }
+ p := ExecPrivilege{Enabled: true, UID: uint32(uid), GID: uint32(gid)}
+ if !execPrivilegeSupported() {
+ return p.unavailable(explicit, "the privilege drop is not supported on this platform")
+ }
+ if !serverIsRoot() {
+ return p.unavailable(explicit, "the server is not root, so it cannot start agent processes as another user")
+ }
+ return p, nil
+}
+
+// unavailable answers a drop that cannot be applied: an error when the operator asked
+// for it, otherwise a disabled privilege with one log line that says so.
+func (p ExecPrivilege) unavailable(explicit bool, why string) (ExecPrivilege, error) {
+ if explicit {
+ return ExecPrivilege{}, fmt.Errorf("agent process isolation cannot be applied: %s", why)
+ }
+ logExecOnce("[exec] same-uid isolation unavailable: %s; agent processes run with the server's identity", why)
+ return ExecPrivilege{}, nil
+}
+
+var execLogOnce sync.Map
+
+// logExecOnce logs a message once per distinct text for the life of the process.
+func logExecOnce(format string, args ...any) {
+ msg := fmt.Sprintf(format, args...)
+ if _, loaded := execLogOnce.LoadOrStore(msg, true); !loaded {
+ log.Print(msg)
+ }
+}
+
+// execIDString renders an executor id for the environment and the shim arguments.
+func execIDString(id uint32) string { return strconv.FormatUint(uint64(id), 10) }
+
+// WithExecPrivilege sets the identity agent processes run under. The binary passes the
+// result of ResolveExecPrivilege; tests and other callers keep the zero value.
+func WithExecPrivilege(p ExecPrivilege) Option {
+ return func(s *Server) { s.execPriv = p }
+}
+
+// execDropCommand returns the command line that runs command as the executor
+// identity. The MCP stdio client starts its command with exec.Command and offers no
+// credential, so the command becomes the server binary in drop mode (RunExecShim).
+func execDropCommand(p ExecPrivilege, command string, args []string) (string, []string, error) {
+ if !p.Enabled {
+ return command, args, nil
+ }
+ self, err := os.Executable()
+ if err != nil {
+ return "", nil, fmt.Errorf("locate the server binary for the privilege drop: %w", err)
+ }
+ out := []string{execDropArg, execIDString(p.UID), execIDString(p.GID), "--", command}
+ return self, append(out, args...), nil
+}
diff --git a/server/execpriv_other.go b/server/execpriv_other.go
new file mode 100644
index 0000000..e1aabd6
--- /dev/null
+++ b/server/execpriv_other.go
@@ -0,0 +1,41 @@
+//go:build !unix
+
+package server
+
+import (
+ "errors"
+ "os/exec"
+)
+
+// Without unix credentials the privilege drop cannot be applied. ResolveExecPrivilege
+// never enables it here, so these stubs only keep the package compiling; the
+// functions that would act on an enabled drop return an error to fail closed.
+
+var errExecUnsupported = errors.New("agent process isolation is not supported on this platform")
+
+func execPrivilegeSupported() bool { return false }
+
+func serverIsRoot() bool { return false }
+
+func applyExecCredential(c *exec.Cmd, p ExecPrivilege) {}
+
+func prepareExecScript(p ExecPrivilege, path string) error { return nil }
+
+// PrepareExecPrivilege fails when a drop is enabled; a disabled one does nothing.
+func PrepareExecPrivilege(p ExecPrivilege, dataDir, keyDir, configPath string) error {
+ if p.Enabled {
+ return errExecUnsupported
+ }
+ return nil
+}
+
+// InstallBashShim fails when a drop is enabled; a disabled one does nothing.
+func InstallBashShim(p ExecPrivilege) error {
+ if p.Enabled {
+ return errExecUnsupported
+ }
+ return nil
+}
+
+// RunExecShimIfRequested does nothing: no shim is ever installed on this platform.
+func RunExecShimIfRequested(argv []string) {}
diff --git a/server/execpriv_test.go b/server/execpriv_test.go
new file mode 100644
index 0000000..e8492ee
--- /dev/null
+++ b/server/execpriv_test.go
@@ -0,0 +1,123 @@
+package server
+
+import (
+ "reflect"
+ "strings"
+ "testing"
+)
+
+func TestResolveExecPrivilegeNegativeUIDDisables(t *testing.T) {
+ p, err := ResolveExecPrivilege(-1, DefaultExecGID, true)
+ if err != nil {
+ t.Fatalf("explicit disable must not fail: %v", err)
+ }
+ if p.Enabled {
+ t.Fatal("negative uid must disable the drop")
+ }
+}
+
+func TestResolveExecPrivilegeRefusesRootIdentity(t *testing.T) {
+ for _, c := range [][2]int{{0, DefaultExecGID}, {DefaultExecUID, 0}} {
+ if _, err := ResolveExecPrivilege(c[0], c[1], true); err == nil {
+ t.Fatalf("uid %d gid %d: root identity must be refused", c[0], c[1])
+ }
+ }
+}
+
+// Without root the drop cannot be applied: an explicit request is a startup error
+// (fail closed), the default degrades to a disabled privilege.
+func TestResolveExecPrivilegeWithoutRoot(t *testing.T) {
+ if serverIsRoot() && execPrivilegeSupported() {
+ t.Skip("needs a process that cannot switch identity")
+ }
+ p, err := ResolveExecPrivilege(DefaultExecUID, DefaultExecGID, false)
+ if err != nil || p.Enabled {
+ t.Fatalf("default request must degrade quietly: enabled=%v err=%v", p.Enabled, err)
+ }
+ if _, err := ResolveExecPrivilege(DefaultExecUID, DefaultExecGID, true); err == nil {
+ t.Fatal("explicit request must fail closed")
+ }
+}
+
+func TestResolveExecPrivilegeAsRoot(t *testing.T) {
+ if !serverIsRoot() || !execPrivilegeSupported() {
+ t.Skip("needs a root process on a platform with credentials")
+ }
+ p, err := ResolveExecPrivilege(DefaultExecUID, DefaultExecGID, true)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !p.Enabled || p.UID != DefaultExecUID || p.GID != DefaultExecGID {
+ t.Fatalf("got %+v", p)
+ }
+}
+
+func TestExecDropCommandDisabledKeepsCommand(t *testing.T) {
+ cmd, args, err := execDropCommand(ExecPrivilege{}, "npx", []string{"-y", "pkg"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if cmd != "npx" || !reflect.DeepEqual(args, []string{"-y", "pkg"}) {
+ t.Fatalf("disabled drop must not rewrite the command: %q %v", cmd, args)
+ }
+}
+
+func TestExecDropCommandWrapsForShim(t *testing.T) {
+ p := ExecPrivilege{Enabled: true, UID: 10001, GID: 10002}
+ _, args, err := execDropCommand(p, "npx", []string{"-y", "pkg"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := []string{execDropArg, "10001", "10002", "--", "npx", "-y", "pkg"}
+ if !reflect.DeepEqual(args, want) {
+ t.Fatalf("args = %v, want %v", args, want)
+ }
+}
+
+func TestWithExecPrivilegeSetsServerField(t *testing.T) {
+ s := &Server{}
+ p := ExecPrivilege{Enabled: true, UID: 10001, GID: 10001}
+ WithExecPrivilege(p)(s)
+ if s.execPriv != p {
+ t.Fatalf("execPriv = %+v, want %+v", s.execPriv, p)
+ }
+}
+
+func TestSealedEnvRoundTripKeepsEmptyAndMultiline(t *testing.T) {
+ in := []string{
+ "ARTEX_PG_DSN=postgres://u:p@h/db?sslmode=disable\nsecond line\ttab",
+ "ARTEX_SECRET_KEY=",
+ "ANTHROPIC_API_KEY=sk-ant-test",
+ "OPENAI_API_KEY==leading-equals",
+ }
+ out, err := decodeSealedEnv(encodeSealedEnv(in))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !reflect.DeepEqual(out, in) {
+ t.Fatalf("round trip changed the values:\n got %q\nwant %q", out, in)
+ }
+}
+
+func TestSealedEnvRejectsForeignNames(t *testing.T) {
+ if _, err := decodeSealedEnv([]byte("PATH=/bin\x00")); err == nil {
+ t.Fatal("a name outside secretEnv must be rejected")
+ }
+ if _, err := decodeSealedEnv([]byte("ANTHROPIC_API_KEY=x")); err == nil {
+ t.Fatal("an unterminated entry must be rejected")
+ }
+}
+
+func TestWithoutSecretEnvDropsOnlySecrets(t *testing.T) {
+ env := []string{"PATH=/bin", "ARTEX_PG_DSN=x", "HOME=/root", "OPENAI_API_KEY=", "ARTEX_SECRET_KEY=y"}
+ got := withoutSecretEnv(env)
+ want := []string{"PATH=/bin", "HOME=/root"}
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("got %v, want %v", got, want)
+ }
+ for _, kv := range got {
+ if isSecretName(strings.SplitN(kv, "=", 2)[0]) {
+ t.Fatalf("secret left in %q", kv)
+ }
+ }
+}
diff --git a/server/execpriv_unix.go b/server/execpriv_unix.go
new file mode 100644
index 0000000..7409058
--- /dev/null
+++ b/server/execpriv_unix.go
@@ -0,0 +1,267 @@
+//go:build unix
+
+package server
+
+import (
+ "errors"
+ "fmt"
+ "io/fs"
+ "log"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "syscall"
+)
+
+// Environment names the Bash shim reads. They carry no secret: the executor id and
+// the real bash path.
+const (
+ envExecBash = "ARTEX_EXEC_BASH"
+ envExecUID = "ARTEX_EXEC_UID"
+ envExecGID = "ARTEX_EXEC_GID"
+)
+
+func execPrivilegeSupported() bool { return true }
+
+func serverIsRoot() bool { return os.Geteuid() == 0 }
+
+// applyExecCredential runs c as the executor identity. The server's own children
+// (custom tools) use it directly; the Norma children go through the shims.
+func applyExecCredential(c *exec.Cmd, p ExecPrivilege) {
+ if !p.Enabled {
+ return
+ }
+ if c.SysProcAttr == nil {
+ c.SysProcAttr = &syscall.SysProcAttr{}
+ }
+ c.SysProcAttr.Credential = &syscall.Credential{Uid: p.UID, Gid: p.GID, Groups: []uint32{p.GID}}
+}
+
+// prepareExecScript lets the executor read a script the server wrote: the file stays
+// root-owned and becomes readable by the executor group only.
+func prepareExecScript(p ExecPrivilege, path string) error {
+ if !p.Enabled {
+ return nil
+ }
+ if err := os.Chown(path, -1, int(p.GID)); err != nil {
+ return err
+ }
+ return os.Chmod(path, 0o640)
+}
+
+// PrepareExecPrivilege sets up the state the executor needs before the server opens
+// its stores. The task and chat workspace trees are shared with the executor group
+// (setgid, group read/write, umask 002) instead of chowned per directory: the
+// workspace is created in many places, and new subdirectories inherit the group. The key files and the
+// config file (which can hold the database DSN) are restricted to root. Nothing
+// else under the data directory changes; directories a root-only path needs are
+// left as they are.
+func PrepareExecPrivilege(p ExecPrivilege, dataDir, keyDir, configPath string) error {
+ if !p.Enabled {
+ return nil
+ }
+ // tasks/ holds the run directories of the task agents, sessions/ the chat
+ // workspaces: the shell of each runs in one of them.
+ for _, sub := range []string{"tasks", "sessions"} {
+ root := filepath.Join(dataDir, sub)
+ if err := os.MkdirAll(root, 0o775); err != nil {
+ return fmt.Errorf("create %s workspace root: %w", sub, err)
+ }
+ if err := shareWithExecGroup(root, int(p.GID)); err != nil {
+ return fmt.Errorf("share %s workspace with the executor group: %w", sub, err)
+ }
+ }
+ tasks := filepath.Join(dataDir, "tasks")
+ for _, name := range []string{"jwt.key", "secret.key"} {
+ if keyDir == "" {
+ break
+ }
+ path := filepath.Join(keyDir, name)
+ if _, err := os.Stat(path); err == nil {
+ if err := os.Chmod(path, 0o600); err != nil {
+ return fmt.Errorf("restrict %s to root: %w", path, err)
+ }
+ }
+ }
+ if configPath != "" {
+ if fi, err := os.Stat(configPath); err == nil && fi.Mode().Perm()&0o077 != 0 {
+ if err := os.Chmod(configPath, 0o600); err != nil {
+ return fmt.Errorf("restrict %s to root: %w", configPath, err)
+ }
+ log.Printf("[exec] %s set to 0600: it can hold the database DSN", configPath)
+ }
+ }
+ // Files and directories the server creates from now on are group-writable, so
+ // the executor can write into the task workspace inside the shared tree.
+ syscall.Umask(0o002)
+ log.Printf("[exec] agent processes run as uid %d gid %d; task workspace %s is shared with that group", p.UID, p.GID, tasks)
+ return nil
+}
+
+// shareWithExecGroup gives the executor group the tree under root: the group owns
+// each entry and gets read/write (and traverse on directories), and directories set
+// the setgid bit so anything created below them keeps the group.
+func shareWithExecGroup(root string, gid int) error {
+ return filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
+ if err != nil {
+ return err
+ }
+ if err := os.Lchown(path, -1, gid); err != nil {
+ return err
+ }
+ if d.Type()&fs.ModeSymlink != 0 {
+ return nil
+ }
+ info, err := d.Info()
+ if err != nil {
+ return err
+ }
+ mode := info.Mode().Perm() | 0o060
+ if d.IsDir() {
+ mode = (info.Mode().Perm() | 0o070) | os.ModeSetgid
+ }
+ return os.Chmod(path, mode)
+ })
+}
+
+// InstallBashShim makes the Bash tool, the interactive shell and background tasks
+// run as the executor. Norma starts them with exec.Command("bash"), which takes no
+// credential, so a symlink named bash to this binary is placed first on PATH. The
+// shim (RunExecShimIfRequested) drops to the executor identity and execs the real
+// bash, which keeps the PID and the process group that Norma tracks.
+func InstallBashShim(p ExecPrivilege) error {
+ if !p.Enabled {
+ return nil
+ }
+ realBash, err := exec.LookPath("bash")
+ if err != nil {
+ return fmt.Errorf("bash is needed for the agent shell: %w", err)
+ }
+ self, err := os.Executable()
+ if err != nil {
+ return fmt.Errorf("locate the server binary: %w", err)
+ }
+ if self, err = filepath.EvalSymlinks(self); err != nil {
+ return fmt.Errorf("resolve the server binary: %w", err)
+ }
+ dir, err := os.MkdirTemp("", "artex-exec-")
+ if err != nil {
+ return fmt.Errorf("create the shim directory: %w", err)
+ }
+ // Root-owned and traversable: the executor can run the shim, cannot change it.
+ if err := os.Chmod(dir, 0o755); err != nil {
+ return err
+ }
+ if err := os.Symlink(self, filepath.Join(dir, "bash")); err != nil {
+ return fmt.Errorf("create the bash shim: %w", err)
+ }
+ if err := os.Setenv(envExecBash, realBash); err != nil {
+ return err
+ }
+ if err := os.Setenv(envExecUID, execIDString(p.UID)); err != nil {
+ return err
+ }
+ if err := os.Setenv(envExecGID, execIDString(p.GID)); err != nil {
+ return err
+ }
+ return os.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
+}
+
+// RunExecShimIfRequested makes the process a privilege-drop shim when it was started
+// as one: as bash through the PATH shim, or as artex __artex-exec-drop for an MCP
+// stdio command. It exits or execs the target; it returns only for an ordinary start.
+func RunExecShimIfRequested(argv []string) {
+ if len(argv) == 0 {
+ return
+ }
+ if filepath.Base(argv[0]) == "bash" && os.Getenv(envExecBash) != "" {
+ runBashShim(argv)
+ }
+ if len(argv) >= 2 && argv[1] == execDropArg {
+ runDropShim(argv[2:])
+ }
+}
+
+func runBashShim(argv []string) {
+ uid, gid, err := execIDsFromEnv()
+ if err != nil {
+ shimFail(err)
+ }
+ if err := dropTo(uid, gid); err != nil {
+ shimFail(err)
+ }
+ shimExec(os.Getenv(envExecBash), argv)
+}
+
+// runDropShim handles: <uid> <gid> -- <command> <args...>.
+func runDropShim(args []string) {
+ if len(args) < 3 || args[2] != "--" {
+ shimFail(errors.New("drop shim needs <uid> <gid> -- <command> [args]"))
+ }
+ uid, errU := strconv.Atoi(args[0])
+ gid, errG := strconv.Atoi(args[1])
+ if errU != nil || errG != nil || len(args) < 4 {
+ shimFail(errors.New("drop shim: malformed identity or command"))
+ }
+ command := args[3]
+ target := command
+ if !strings.Contains(command, "/") {
+ resolved, err := exec.LookPath(command)
+ if err != nil {
+ shimFail(fmt.Errorf("command %q: %w", command, err))
+ }
+ target = resolved
+ }
+ if err := dropTo(uid, gid); err != nil {
+ shimFail(err)
+ }
+ shimExec(target, args[3:])
+}
+
+func execIDsFromEnv() (int, int, error) {
+ uid, errU := strconv.Atoi(os.Getenv(envExecUID))
+ gid, errG := strconv.Atoi(os.Getenv(envExecGID))
+ if errU != nil || errG != nil {
+ return 0, 0, errors.New("executor identity missing from the environment")
+ }
+ return uid, gid, nil
+}
+
+// dropTo switches the calling process to uid and gid, for good: the supplementary
+// groups, gid and uid all change, and the result is checked. A process already
+// running as the executor (a nested bash) passes straight through.
+func dropTo(uid, gid int) error {
+ if os.Getuid() == uid && os.Getgid() == gid {
+ return nil
+ }
+ if os.Geteuid() != 0 {
+ return fmt.Errorf("cannot switch to uid %d: the process is not root", uid)
+ }
+ if err := syscall.Setgroups([]int{gid}); err != nil {
+ return fmt.Errorf("setgroups: %w", err)
+ }
+ if err := syscall.Setgid(gid); err != nil {
+ return fmt.Errorf("setgid %d: %w", gid, err)
+ }
+ if err := syscall.Setuid(uid); err != nil {
+ return fmt.Errorf("setuid %d: %w", uid, err)
+ }
+ if os.Getuid() != uid || os.Geteuid() != uid || os.Getgid() != gid {
+ return fmt.Errorf("privilege drop to %d:%d did not take effect", uid, gid)
+ }
+ return nil
+}
+
+// shimExec replaces the process with target. It returns only on failure, and then
+// the shim stops: a command must never run with the server's identity by mistake.
+func shimExec(target string, argv []string) {
+ err := syscall.Exec(target, argv, os.Environ())
+ shimFail(fmt.Errorf("exec %s: %w", target, err))
+}
+
+func shimFail(err error) {
+ fmt.Fprintf(os.Stderr, "artex: agent process not started: %v\n", err)
+ os.Exit(126)
+}
diff --git a/server/mcpdiscover.go b/server/mcpdiscover.go
index a517035..1355973 100644
--- a/server/mcpdiscover.go
+++ b/server/mcpdiscover.go
@@ -21,13 +21,18 @@ type mcpClient interface {
}
// connectMCP dials one MCP server per its transport. Callers must Close the client.
-func connectMCP(ctx context.Context, m *db.MCPServer) (mcpClient, error) {
+func connectMCP(ctx context.Context, m *db.MCPServer, priv ExecPrivilege) (mcpClient, error) {
switch m.Transport {
case "stdio":
if m.Command == "" {
return nil, fmt.Errorf("stdio transport is missing a command")
}
- return mcp.NewStdioClient(ctx, m.Name, m.Command, jsonStrMap(m.Env), jsonStrSlice(m.Args)...)
+ // The stdio command runs as the executor identity (see execpriv.go).
+ command, args, err := execDropCommand(priv, m.Command, jsonStrSlice(m.Args))
+ if err != nil {
+ return nil, err
+ }
+ return mcp.NewStdioClient(ctx, m.Name, command, jsonStrMap(m.Env), args...)
case "http":
if m.URL == "" {
return nil, fmt.Errorf("http transport is missing a URL")
@@ -47,7 +52,7 @@ func connectMCP(ctx context.Context, m *db.MCPServer) (mcpClient, error) {
// discoverAndCacheMCP connects to one MCP, lists its tools, and persists the tool
// names to mcp_tools_cache so the UI shows them without a live connection.
func (s *Server) discoverAndCacheMCP(ctx context.Context, m *db.MCPServer) error {
- cl, err := connectMCP(ctx, m)
+ cl, err := connectMCP(ctx, m, s.execPriv)
if err != nil {
_ = s.m.pg.UpdateMCPHealth(m.ID, false, err.Error())
return err
diff --git a/server/server.go b/server/server.go
index c53c264..6ffd703 100644
--- a/server/server.go
+++ b/server/server.go
@@ -53,6 +53,8 @@ type Server struct {
scrubSecrets bool // drop ARTEX_PG_DSN and the API keys from the environment once read (binary only)
+ execPriv ExecPrivilege // identity agent processes run under; zero keeps the server's own
+
setupMu sync.Mutex
setupToken string // one-time token POST /api/auth/init requires; empty when none is active
// pwdVersion is auth.password_version, a counter. Zero means no password
@@ -267,7 +269,7 @@ func New(ctx context.Context, m *Manager, skillDir string, dataDir string, keyDi
}
return a.TaskTimeoutWrapupMaxTurns, true
})
- wireAgentAugment(m.pg, s.skillDir, s.hostTools) // wire visible skills/MCP + traffic/orchestration host tools into the agent toolset
+ wireAgentAugment(m.pg, s.skillDir, s.hostTools, s.execPriv) // wire visible skills/MCP + traffic/orchestration host tools into the agent toolset
domainReg := buildDomainReg(m.Assets())
wireTools(m.pg, domainReg) // built-in tools table: filter per agent + override description/schema + inject defaults
seedPrompts(m.pg) // seed built-in agent default prompt bodies into agent_prompts (only when empty)
diff --git a/server/testmain_test.go b/server/testmain_test.go
index 9aece34..13dd97a 100644
--- a/server/testmain_test.go
+++ b/server/testmain_test.go
@@ -18,7 +18,11 @@ func TestMain(m *testing.M) {
// serializing go test ./... across packages.
db.SuffixTestDatabase("server")
// Fixed test key via env: NewManager's InitSecrets then writes no key file.
- os.Setenv("ARTEX_SECRET_KEY", "MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY=")
+ // Not in the sealed-environment helper process (envseal_linux_test.go): it must see
+ // the empty ARTEX_SECRET_KEY the parent test set.
+ if os.Getenv("ARTEX_SEAL_TEST_HELPER") != "1" {
+ os.Setenv("ARTEX_SECRET_KEY", "MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY=")
+ }
dsn, _, err := db.DSN()
if err != nil {
os.Exit(m.Run())