ARTEX - AI autonomous penetration testing system (English translation; upstream: Autumn-27/ARTEX, AGPL-3.0)
Go aiai-agentsautonomous-agentsbug-bountydockergolanglinuxllmmcpnextjspenetration-testingpentestpostgresqlreareactred-teamsecuritysecurity-automationsqlitetypescript
agent: run the file tools as the executor identity
BaaRai2b7739aaf511
diff --git a/agent/bbot_ingest_tool.go b/agent/bbot_ingest_tool.goindex e03d83a..135b5c6 100644--- a/agent/bbot_ingest_tool.go+++ b/agent/bbot_ingest_tool.go@@ -56,10 +56,19 @@ func bbotIntelFact(ev bbotEvent) factItem {// reads the file as root while the agent names the path, so an absolute path// outside the working directory, "..", a symlink and a hard-linked file are// refused. Without a data directory or a working directory it fails closed.-func openBbotOutput(base, dir, p string) (*os.File, error) {+func openBbotOutput(base, dir, p string) (f *os.File, err error) {if strings.TrimSpace(base) == "" {return nil, errors.New("no data directory for this run")}+ // The open runs as the executor when the privilege drop is active+ // (filetools_identity.go); the descriptor is then read by the server.+ if idErr := RunAsFileToolIdentity(func() { f, err = openBbotOutputIn(base, dir, p) }); idErr != nil {+ return nil, idErr+ }+ return f, err+}++func openBbotOutputIn(base, dir, p string) (*os.File, error) {w, err := openWorkRoot(base, dir)if err != nil {return nil, errdiff --git a/agent/filetools.go b/agent/filetools.goindex affc1a1..ce81d21 100644--- a/agent/filetools.go+++ b/agent/filetools.go@@ -69,12 +69,32 @@ func (t *confinedFileTool) Call(_ context.Context, in json.RawMessage, tc *actooif tc != nil {dir = tc.WorkingDir}- w, err := openWorkRoot(t.base, dir)- if err != nil {- return actool.Errorf(fmt.Sprintf("Error: %s cannot run: %v", t.Name(), err)), nil+ var (+ res actool.Result+ err error+ capture bool+ )+ // Every file system access of the call, from opening the working directory on,+ // runs as the executor when the privilege drop is active (filetools_identity.go).+ idErr := RunAsFileToolIdentity(func() {+ w, oerr := openWorkRoot(t.base, dir)+ if oerr != nil {+ res = actool.Errorf(fmt.Sprintf("Error: %s cannot run: %v", t.Name(), oerr))+ return+ }+ defer w.Close()+ res, err = t.run(w, in, tc)+ capture = w.captured+ })+ if idErr != nil {+ return actool.Errorf(fmt.Sprintf("Error: %s cannot run: %v", t.Name(), idErr)), nil}- defer w.Close()- return t.run(w, in, tc)+ if capture && err == nil {+ // Bounded here, with the server's identity: an output over the cap is spilled+ // to the root-owned spill directory, which the executor cannot write.+ res = actool.Text(actool.Capture(tc, res.Flatten()))+ }+ return res, err}// workRoot is the run's working directory opened as an os.Root. dir is the path the@@ -82,6 +102,15 @@ func (t *confinedFileTool) Call(_ context.Context, in json.RawMessage, tc *actootype workRoot struct {*os.Rootdir string+ // captured is set by capture: the result text still has to go through+ // actool.Capture once the call has left the file tool identity.+ captured bool+}++// capture returns s unbounded and marks the call for actool.Capture in Call.+func (w *workRoot) capture(s string) string {+ w.captured = true+ return s}var (@@ -480,7 +509,7 @@ func runConfinedLS(w *workRoot, input json.RawMessage, tc *actool.ToolContext) (}fmt.Fprintf(&b, "%s\t%d bytes\n", e.Name(), size)}- return actool.Text(actool.Capture(tc, b.String())), nil+ return actool.Text(w.capture(b.String())), nil}// ---------- Glob ----------@@ -544,7 +573,7 @@ func runConfinedGlob(w *workRoot, input json.RawMessage, tc *actool.ToolContext)b.WriteString(m.path)b.WriteByte('\n')}- return actool.Text(actool.Capture(tc, b.String())), nil+ return actool.Text(w.capture(b.String())), nil}// globMatch is the SDK Glob matcher: a pattern without "/" matches the base name,@@ -707,7 +736,7 @@ func runConfinedGrep(w *workRoot, input json.RawMessage, tc *actool.ToolContext)if more > 0 {out += fmt.Sprintf("... [%d more result(s) — page with offset=%d, or head_limit=0 for all] ...\n", more, in.Offset+len(kept))}- return actool.Text(actool.Capture(tc, out)), nil+ return actool.Text(w.capture(out)), nil}// grepFileTypes maps a ripgrep-style file type to its globs (the SDK's subset).diff --git a/agent/filetools_identity.go b/agent/filetools_identity.gonew file mode 100644index 0000000..be2344d--- /dev/null+++ b/agent/filetools_identity.go@@ -0,0 +1,36 @@+package agent++import "sync/atomic"++// File tool identity. The confined file tools (filetools.go) and the ingest tools+// open the paths the agent names inside the server process, which is root in the+// Docker image. With the executor privilege drop active (server/execpriv.go) the+// server sets the executor identity here, and each of those calls then reaches the+// file system as that uid and gid, with that gid as its only group: the kernel+// checks every open, create and directory read against the executor's rights, the+// rights of the agent's shell, on top of the os.Root confinement. Linux only; see+// filetools_identity_linux.go.++// FileToolIdentity is the uid and gid the file tools access files as.+type FileToolIdentity struct{ UID, GID uint32 }++var fileToolIdentity atomic.Pointer[FileToolIdentity]++// SetFileToolIdentity sets the identity of the file tools; nil restores the+// server's own identity.+func SetFileToolIdentity(id *FileToolIdentity) { fileToolIdentity.Store(id) }++// FileToolIdentitySupported reports whether the file tools can run as another+// identity on this platform.+func FileToolIdentitySupported() bool { return fileIdentitySupported }++// RunAsFileToolIdentity runs fn with the file tool identity, or directly when none+// is set. When it returns an error, fn did not run.+func RunAsFileToolIdentity(fn func()) error {+ id := fileToolIdentity.Load()+ if id == nil {+ fn()+ return nil+ }+ return runWithFileIdentity(*id, fn)+}diff --git a/agent/filetools_identity_linux.go b/agent/filetools_identity_linux.gonew file mode 100644index 0000000..e4a8fcb--- /dev/null+++ b/agent/filetools_identity_linux.go@@ -0,0 +1,63 @@+//go:build linux++package agent++import (+ "fmt"+ "runtime"++ "golang.org/x/sys/unix"+)++const fileIdentitySupported = true++// runWithFileIdentity runs fn on a thread of its own whose file system uid, file+// system gid and supplementary groups are those of id. On Linux these ids belong to+// the thread: setfsuid, setfsgid and the raw setgroups of x/sys/unix change the+// calling thread only (the syscall package's Setgroups changes every thread and is+// not used). The thread is locked to its goroutine and never unlocked, so the Go+// runtime ends it when the goroutine returns: no other goroutine ever runs with the+// changed ids, and nothing has to be restored. A file system uid other than 0 also+// clears the file capabilities of the thread (CAP_DAC_OVERRIDE, CAP_DAC_READ_SEARCH,+// CAP_FOWNER, CAP_CHOWN and the others of capabilities(7)), so root's override does+// not apply to fn. A panic in fn is raised again in the caller.+func runWithFileIdentity(id FileToolIdentity, fn func()) error {+ done := make(chan error, 1)+ var panicked any+ go func() {+ runtime.LockOSThread()+ if err := enterFileIdentity(id); err != nil {+ done <- err+ return+ }+ defer func() {+ panicked = recover()+ done <- nil+ }()+ fn()+ }()+ err := <-done+ if panicked != nil {+ panic(panicked)+ }+ return err+}++// enterFileIdentity sets the ids of the calling thread and reads them back.+// setfsuid and setfsgid report no error: each returns the previous id, and an+// invalid id (-1) changes nothing and returns the current one.+func enterFileIdentity(id FileToolIdentity) error {+ uid, gid := int(id.UID), int(id.GID)+ if err := unix.Setgroups([]int{gid}); err != nil {+ return fmt.Errorf("file tool identity: setgroups: %w", err)+ }+ _, _ = unix.SetfsgidRetGid(gid)+ _, _ = unix.SetfsuidRetUid(uid)+ curGID, _ := unix.SetfsgidRetGid(-1)+ curUID, _ := unix.SetfsuidRetUid(-1)+ groups, err := unix.Getgroups()+ if err != nil || curUID != uid || curGID != gid || len(groups) != 1 || groups[0] != gid {+ return fmt.Errorf("file tool identity %d:%d did not take effect (fsuid %d, fsgid %d, groups %v)", uid, gid, curUID, curGID, groups)+ }+ return nil+}diff --git a/agent/filetools_identity_other.go b/agent/filetools_identity_other.gonew file mode 100644index 0000000..75cbc12--- /dev/null+++ b/agent/filetools_identity_other.go@@ -0,0 +1,14 @@+//go:build !linux++package agent++import "errors"++const fileIdentitySupported = false++// runWithFileIdentity: per-thread file system ids exist on Linux only. The server+// sets no identity where FileToolIdentitySupported is false; one set anyway fails+// closed.+func runWithFileIdentity(FileToolIdentity, func()) error {+ return errors.New("the file tools cannot run as another identity on this platform")+}diff --git a/agent/filetools_identity_root_linux_test.go b/agent/filetools_identity_root_linux_test.gonew file mode 100644index 0000000..cd20615--- /dev/null+++ b/agent/filetools_identity_root_linux_test.go@@ -0,0 +1,193 @@+//go:build linux++package agent++import (+ "context"+ "encoding/json"+ "errors"+ "io/fs"+ "os"+ "path/filepath"+ "strings"+ "sync"+ "syscall"+ "testing"++ actool "github.com/Autumn-27/norma/tool"+)++// The executor identity of the server's default (server.DefaultExecUID/GID).+const testExecID = 10001++// fileIdentityFixture lays out a data directory like the server's with the drop+// active: tasks/1/main is a run directory root:<exec gid> 2775 below root:root 0755+// parents, and holds a file the server wrote root:root 0600.+type fileIdentityFixture struct {+ base, work, rootOnly string+ tools map[string]actool.CoreTool+ tc *actool.ToolContext+}++func newFileIdentityFixture(t *testing.T) *fileIdentityFixture {+ t.Helper()+ if os.Geteuid() != 0 {+ t.Skip("needs root")+ }+ // Not t.TempDir(): the executor has to traverse the directory. TestMain made the+ // temp directory 1777.+ base, err := os.MkdirTemp("", "artex-fileid-")+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { os.RemoveAll(base) })+ work := filepath.Join(base, "tasks", "1", "main")+ for _, d := range []string{base, filepath.Join(base, "tasks"), filepath.Join(base, "tasks", "1")} {+ if err := os.MkdirAll(d, 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.Chmod(d, 0o755); err != nil {+ t.Fatal(err)+ }+ }+ if err := os.Mkdir(work, 0o775); err != nil {+ t.Fatal(err)+ }+ if err := os.Chown(work, 0, testExecID); err != nil {+ t.Fatal(err)+ }+ if err := os.Chmod(work, 0o775|os.ModeSetgid); err != nil {+ t.Fatal(err)+ }+ rootOnly := filepath.Join(work, "root-only.txt")+ if err := os.WriteFile(rootOnly, []byte(confinedSecret+"\n"), 0o600); err != nil {+ t.Fatal(err)+ }+ if err := os.Chown(rootOnly, 0, 0); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(work, "shared.txt"), []byte("hello shared\n"), 0o664); err != nil {+ t.Fatal(err)+ }+ if err := os.Chown(filepath.Join(work, "shared.txt"), 0, testExecID); err != nil {+ t.Fatal(err)+ }+ tools := map[string]actool.CoreTool{}+ for _, tl := range defaultTools(base) {+ tools[tl.Name()] = tl+ }+ t.Cleanup(func() { SetFileToolIdentity(nil) })+ return &fileIdentityFixture{base: base, work: work, rootOnly: rootOnly, tools: tools, tc: &actool.ToolContext{WorkingDir: work}}+}++func (f *fileIdentityFixture) call(t *testing.T, tool string, in map[string]any) actool.Result {+ t.Helper()+ raw, _ := json.Marshal(in)+ res, err := f.tools[tool].Call(context.Background(), raw, f.tc)+ if err != nil {+ t.Fatalf("%s(%s): %v", tool, raw, err)+ }+ return res+}++// With the executor identity set, the file tools reach the run directory with the+// executor's rights: a root-only file inside it is refused by the kernel, Grep does+// not see it, a file the tools create belongs to the executor, and the shared file+// stays readable. Without the identity (the server's root) the same file is read,+// which is the state the identity changes.+func TestFileToolsRunAsExecutorAsRoot(t *testing.T) {+ f := newFileIdentityFixture(t)++ // Root, no identity: the root-only file is read.+ if res := f.call(t, "Read", map[string]any{"file_path": "root-only.txt"}); res.IsError || !strings.Contains(res.Flatten(), confinedSecret) {+ t.Fatalf("without the identity root reads the file: %s", res.Flatten())+ }++ SetFileToolIdentity(&FileToolIdentity{UID: testExecID, GID: testExecID})++ res := f.call(t, "Read", map[string]any{"file_path": "root-only.txt"})+ if !res.IsError || strings.Contains(res.Flatten(), confinedSecret) || !strings.Contains(res.Flatten(), "permission denied") {+ t.Errorf("Read of a root-only file as the executor: error=%v %s", res.IsError, res.Flatten())+ }+ for _, in := range []map[string]any{+ {"pattern": "TOPSECRET", "output_mode": "content"},+ {"pattern": "TOPSECRET", "path": "root-only.txt", "output_mode": "content"},+ } {+ if out := f.call(t, "Grep", in).Flatten(); strings.Contains(out, confinedSecret) {+ t.Errorf("Grep %v printed the root-only file: %s", in, out)+ }+ }+ res = f.call(t, "Edit", map[string]any{"file_path": "root-only.txt", "old_string": confinedSecret, "new_string": "pwned"})+ if !res.IsError {+ t.Errorf("Edit of a root-only file as the executor was not refused: %s", res.Flatten())+ }+ if res := f.call(t, "Read", map[string]any{"file_path": "shared.txt"}); res.IsError || !strings.Contains(res.Flatten(), "hello shared") {+ t.Errorf("Read of a file shared with the executor group: %s", res.Flatten())+ }+ if res := f.call(t, "Write", map[string]any{"file_path": "made.txt", "content": "x\n"}); res.IsError {+ t.Fatalf("Write as the executor: %s", res.Flatten())+ }+ fi, err := os.Stat(filepath.Join(f.work, "made.txt"))+ if err != nil {+ t.Fatal(err)+ }+ if st := fi.Sys().(*syscall.Stat_t); st.Uid != testExecID || st.Gid != testExecID {+ t.Errorf("made.txt belongs to %d:%d, want the executor %d:%d", st.Uid, st.Gid, testExecID, testExecID)+ }+ if b, err := os.ReadFile(f.rootOnly); err != nil || string(b) != confinedSecret+"\n" {+ t.Fatalf("root-only file changed or unreadable by the test: %q %v", b, err)+ }+}++// The ingest tools open the agent's file the same way.+func TestIngestOpenRunsAsExecutorAsRoot(t *testing.T) {+ f := newFileIdentityFixture(t)+ SetFileToolIdentity(&FileToolIdentity{UID: testExecID, GID: testExecID})+ if file, err := openBbotOutput(f.base, f.work, "root-only.txt"); err == nil || !errors.Is(err, fs.ErrPermission) {+ if file != nil {+ file.Close()+ }+ t.Errorf("ingest_bbot open of a root-only file: %v, want permission denied", err)+ }+ if file, err := openScanOutputInBase(f.base, f.work, "root-only.txt"); err == nil || !errors.Is(err, fs.ErrPermission) {+ if file != nil {+ file.Close()+ }+ t.Errorf("ingest_scan_output open of a root-only file: %v, want permission denied", err)+ }+ file, err := openBbotOutput(f.base, f.work, "shared.txt")+ if err != nil {+ t.Fatalf("ingest_bbot open of a shared file: %v", err)+ }+ file.Close()+}++// The identity never leaks to the calling goroutine or to other goroutines: after+// many concurrent calls the test, still root, reads the root-only file, and its own+// thread keeps file system uid 0.+func TestFileToolIdentityDoesNotLeakAsRoot(t *testing.T) {+ f := newFileIdentityFixture(t)+ SetFileToolIdentity(&FileToolIdentity{UID: testExecID, GID: testExecID})+ var wg sync.WaitGroup+ for i := 0; i < 64; i++ {+ wg.Add(1)+ go func() {+ defer wg.Done()+ raw, _ := json.Marshal(map[string]any{"file_path": "root-only.txt"})+ res, err := f.tools["Read"].Call(context.Background(), raw, f.tc)+ if err != nil || !res.IsError {+ t.Errorf("concurrent Read as the executor: err=%v error=%v %s", err, res.IsError, res.Flatten())+ }+ }()+ }+ wg.Wait()+ for i := 0; i < 16; i++ {+ if _, err := os.ReadFile(f.rootOnly); err != nil {+ t.Fatalf("the server lost root's access after the file tool calls: %v", err)+ }+ }+ SetFileToolIdentity(nil)+ if res := f.call(t, "Read", map[string]any{"file_path": "root-only.txt"}); res.IsError {+ t.Fatalf("with the identity cleared root reads the file again: %s", res.Flatten())+ }+}diff --git a/agent/filetools_identity_test.go b/agent/filetools_identity_test.gonew file mode 100644index 0000000..bab1838--- /dev/null+++ b/agent/filetools_identity_test.go@@ -0,0 +1,34 @@+package agent++import (+ "os"+ "runtime"+ "testing"+)++// Without an identity fn runs directly.+func TestRunAsFileToolIdentityWithoutIdentity(t *testing.T) {+ SetFileToolIdentity(nil)+ ran := false+ if err := RunAsFileToolIdentity(func() { ran = true }); err != nil || !ran {+ t.Fatalf("err=%v ran=%v", err, ran)+ }+}++// A process that cannot change its ids (not root, or not Linux) gets an error and fn+// does not run: the file tools fail closed instead of running as the server.+func TestRunAsFileToolIdentityFailsClosed(t *testing.T) {+ if runtime.GOOS == "linux" && os.Geteuid() == 0 {+ t.Skip("root can change its ids")+ }+ SetFileToolIdentity(&FileToolIdentity{UID: 10001, GID: 10001})+ t.Cleanup(func() { SetFileToolIdentity(nil) })+ ran := false+ if err := RunAsFileToolIdentity(func() { ran = true }); err == nil || ran {+ t.Fatalf("err=%v ran=%v, want an error and fn not run", err, ran)+ }+ f := newConfinedFixture(t)+ if res := f.call(t, "Read", map[string]any{"file_path": "in.txt"}); !res.IsError {+ t.Fatalf("Read ran without its identity: %s", res.Flatten())+ }+}diff --git a/agent/scan_ingest_tool.go b/agent/scan_ingest_tool.goindex c589703..2f3f7cb 100644--- a/agent/scan_ingest_tool.go+++ b/agent/scan_ingest_tool.go@@ -115,16 +115,25 @@ func openScanOutput(root, path string) (*os.File, error) {return openScanOutputFromWorkRoot(&workRoot{Root: r, dir: absRoot}, path)}-func openScanOutputInBase(base, dir, path string) (*os.File, error) {+func openScanOutputInBase(base, dir, path string) (f *os.File, err error) {if strings.TrimSpace(base) == "" {return openScanOutput(dir, path)}- w, err := openWorkRoot(base, dir)- if err != nil {- return nil, err+ // The open runs as the executor when the privilege drop is active+ // (filetools_identity.go); the descriptor is then read by the server.+ idErr := RunAsFileToolIdentity(func() {+ w, oerr := openWorkRoot(base, dir)+ if oerr != nil {+ err = oerr+ return+ }+ defer w.Close()+ f, err = openScanOutputFromWorkRoot(w, path)+ })+ if idErr != nil {+ return nil, idErr}- defer w.Close()- return openScanOutputFromWorkRoot(w, path)+ return f, err}// ingestScanOutput parses a scanner output file written by the agent's owndiff --git a/go.mod b/go.modindex b95f4b9..ebbf876 100644--- a/go.mod+++ b/go.mod@@ -72,7 +72,7 @@ require (golang.org/x/exp v0.0.0-20250106191152-7588d65b2ba8 // indirectgolang.org/x/mod v0.42.0 // indirectgolang.org/x/sync v0.25.0 // indirect- golang.org/x/sys v0.50.0 // indirect+ golang.org/x/sys v0.50.0golang.org/x/tools v0.52.0 // indirectgopkg.in/yaml.v3 v3.0.1 // indirectmodernc.org/libc v1.72.3 // indirectdiff --git a/server/execpriv_root_linux_test.go b/server/execpriv_root_linux_test.goindex 219ebf3..7e24db0 100644--- a/server/execpriv_root_linux_test.go+++ b/server/execpriv_root_linux_test.go@@ -74,7 +74,7 @@ func newExecRootFixture(t *testing.T) *execRootFixture {t.Fatal(err)}// PrepareExecPrivilege sets them process-wide.- t.Cleanup(func() { agent.SetRunDirMaker(nil); agent.SetSpillDirMaker(nil, nil) })+ t.Cleanup(func() { agent.SetRunDirMaker(nil); agent.SetSpillDirMaker(nil, nil); agent.SetFileToolIdentity(nil) })if err := PrepareExecPrivilege(&priv, dataDir, "", ""); err != nil {t.Fatal(err)}@@ -738,6 +738,22 @@ func TestNormaTaskDirPlantedByExecutorAsRoot(t *testing.T) {}}+// 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) {+ f := newExecRootFixture(t)+ var readErr error+ if err := agent.RunAsFileToolIdentity(func() { _, readErr = os.ReadFile(f.secret) }); err != nil {+ t.Fatal(err)+ }+ if !errors.Is(readErr, fs.ErrPermission) {+ t.Fatalf("read of a root-only file with the file tool identity: %v, want permission denied", readErr)+ }+ if _, err := os.ReadFile(f.secret); err != nil {+ t.Fatalf("the server itself must still read the file: %v", err)+ }+}+// applyExecCredential sets the credential and the executor's HOME; the later env// entry wins in exec.Cmd. Runs without root: nothing is started.func TestApplyExecCredentialSetsExecutorHome(t *testing.T) {diff --git a/server/execpriv_unix.go b/server/execpriv_unix.goindex 87b2c28..2c3c76f 100644--- a/server/execpriv_unix.go+++ b/server/execpriv_unix.go@@ -277,6 +277,13 @@ func PrepareExecPrivilege(p *ExecPrivilege, dataDir, keyDir, configPath string)func(base, dir string) error { return makeSpillDir(base, dir, gid) },func(dir string) error { return shareSpillFiles(dir, gid) },)+ // The file tools open the paths the agent names inside the server: they do it as+ // the executor too (agent/filetools_identity.go).+ if agent.FileToolIdentitySupported() {+ agent.SetFileToolIdentity(&agent.FileToolIdentity{UID: p.UID, GID: p.GID})+ } else {+ log.Printf("[exec] the agent's file tools keep the server's identity on this platform: only their path confinement applies")+ }if err := prepareExecHome(*p, dataDir); err != nil {return fmt.Errorf("prepare the executor home: %w", err)}