Compare commits

..
Author SHA1 Message Date
BaaRai 6322d6aa83 Keep transcripts and noa archives owner-only, stop Norma ripgrep auto-install
Norma writes transcripts and noa archives with 0755 directories and 0644
files, so any other uid on the host, the executor that runs the agent's
commands included, could read every conversation.

LockDownPrivateDataDirs walks <data>/transcripts and <data>/noa under an
os.Root at the data directory: each directory keeps at most 0700 and each
regular file at most 0600, a narrower mode is kept, and every change goes
through the descriptor that was checked. A symlink, a hard-linked file, any
other entry and a directory not owned by the server are refused and left as
they are. cmd/artex runs it with the key directory lockdown, so a refusal or
a failed chmod fails the start unless ARTEX_ALLOW_UNISOLATED=1 is set;
NewManager runs it too and only logs.

Norma's Grep runs an unpinned npm install of @vscode/ripgrep when rg is
missing unless NORMA_RIPGREP_NO_INSTALL is non-empty. NewManager now always
sets it to 1, so an empty value cannot re-enable the install.
2026-12-03 23:24:56 +01:00
BaaRai d0645b6370 Merge pull request #940 from BaaRai/fix/alwaysallow-denylist
fix(intercept): refuse always-allow rules for sqlmap, sqlite3 and nmap
2026-12-03 23:24:03 +01:00
BaaRai 978b497ac4 intercept: deny always-allow for sqlmap, sqlite and nmap 2026-12-03 22:59:00 +01:00
BaaRai ba22ce4015 Merge pull request #944 from BaaRai/fix/customtool-secret-origin
fix(server): bind custom HTTP tool secrets to one origin
2026-12-03 22:58:48 +01:00
BaaRai ad5e4e8484 server: bind custom HTTP tool secrets to one origin 2026-12-03 22:34:47 +01:00
BaaRai c1bd9530fe Merge pull request #942 from BaaRai/fix/enrich-sandbox-egress
fix(enrich): apply the sandbox egress policy to panel HTTP probes
2026-12-03 22:34:35 +01:00
BaaRai 6045a2c80f enrich: apply the sandbox egress policy to panel HTTP probes 2026-12-03 22:11:20 +01:00
BaaRai 2653cf57ca enrich: apply the sandbox egress policy to panel HTTP probes 2026-12-03 22:11:11 +01:00
BaaRai 4a4fa45245 Merge pull request #941 from BaaRai/fix/ask-operator-root
fix(server): anchor ask_operator image reads at the task root
2026-12-03 22:10:59 +01:00
BaaRai aeb094d5ef server: anchor ask_operator image reads at the task root 2026-12-03 21:49:41 +01:00
BaaRai eb05248804 Merge pull request #939 from BaaRai/fix/archive-symlink
fix(server): keep task archive packing inside the payload
2026-12-03 21:49:28 +01:00
BaaRai 130fe9a0c4 server: keep task archive packing inside the payload
writeTaskArchivePackage listed each directory of the staged run tree and
then opened its files by full path as root. Code running as the executor
uid with a working directory inside the moved run tree could swap a
listed directory for a symlink, so later children were read through it
and root-only files outside the payload were copied into the archive,
then handed back to the executor group on restore.

Walk and open the payload through an os.Root anchored at it, so no
lookup can leave the payload, and refuse the archive when an opened file
is not the regular file the walk listed. Add regression tests that swap
a directory or a file for an outside, a ../ or an inside symlink right
before the packer opens it, plus guards for existing symlinks and for
link and nested ../ entries on extraction.
2026-12-03 21:24:40 +01:00
BaaRai e4f6de91d2 Merge pull request #938 from BaaRai/fix/session-background-tools
fix(agent): disable Norma background-task tools in sandboxed sessions
2026-12-03 21:23:51 +01:00
23 changed files with 1800 additions and 110 deletions
+6
View File
@@ -6,6 +6,12 @@ All notable changes to this project are documented in this file. The format is b
### Security
- **Transcripts and noa archives are owner-only, and Norma's Grep no longer installs ripgrep.** Norma writes `<data>/transcripts` and the noa compression archives under `<data>/noa` with 0755 directories and 0644 files, so any other uid on the host, the executor that runs the agent's commands included, could read every conversation (prompts, model output, tool results). At startup every directory in these two trees, the top ones included, now keeps at most its owner bits (0700) and every regular file at most owner read and write (0600); a narrower mode is never widened, and a missing top directory is created 0700. As for the key directory, nothing is changed by path: the trees are walked under an `os.Root` at the data directory, each entry is checked without following symlinks and changed through the descriptor that was checked, and a symlink (`transcripts` or `noa` themselves included), a hard-linked file or any other non-regular entry is refused and left as it is. A refusal or a failed mode change fails the start like a key directory that cannot be locked down: the error joins the isolation self-test, and only `ARTEX_ALLOW_UNISOLATED=1` (or `-dev-insecure-no-isolation`) starts anyway. Only the server reads these trees: the sandbox and Kubernetes workers mount only their task directory, the executor's shells and file tools work inside run directories, and archive export and the workspace file manager read them as the server. Files Norma writes later are still 0644 but sit under 0700 directories. Norma's Grep ran an unpinned `npm install -g @vscode/ripgrep` (install scripts enabled) when `rg` was missing; `NORMA_RIPGREP_NO_INSTALL` is now always set to `1` at startup, so no value, an empty one included, lets a Norma Grep install a package at run time (ARTEX's own Grep never starts ripgrep). Behaviour change: archiving the data directory as a non-root host user (`scripts/backup.sh --with-data`, which already asks for root) cannot read these two trees, and a data directory the server cannot change (for example an NFS export with root squashing, or a tree owned by another uid) fails the start until it is fixed or the opt-out is set.
- **The always-allow denylist refuses `sqlmap`, `sqlite3` and `nmap`.** An argv allow rule covers every flag, and each of these programs has a flag or script hook that runs code chosen by the caller: `sqlmap --eval`, `sqlite3 .shell` and `nmap --script` with a Lua NSE file. After an operator clicked "always allow" on a harmless call, later calls of the same program matched the rule and skipped the fallback judge, so those flags ran arbitrary code. The three names join the code-owned denylist; `sqlite3` is stored as `sqlite` because `argvProgramName` strips the version suffix, and `sqlmap.py`/`sqlmapapi.py` reduce to their bare names through the same extension stripping. Allow rules already stored for these programs stop matching because the denylist is checked again at match time: their calls go back to the judge or to an ask rule, and the rows stay in the rules table.
- **HTTP custom tools bind stored headers and body to one origin.** A tool saved with a masked secret kept it while the literal url template stayed the same, so a template with a parameterized host (`https://{host}/collect`) could send the stored `X-API-Key` and body to an attacker-chosen host. A redirect from the configured host could also replay them to another origin: Go copies custom headers, and 307/308 replay the body. A secret-bearing HTTP tool now needs a fixed scheme, host and port in its url template, the rendered url must stay on that origin, and a redirect to another origin is refused; an edit that keeps a masked value may not add or change the proxy either (clearing it is allowed, the request then goes to the fixed origin). Tools without stored headers or body are unchanged. Every non-empty header value and body counts as stored, so a saved tool with a parameterized url and a constant header (`Content-Type`) or a body template is now refused at save and at run, and a secret-bearing tool whose API redirects to another host, port or scheme (apex to `www`, `http` to `https`, a CDN) now fails on that redirect.
- **Panel-side asset enrichment obeys the sandbox egress policy.** `insert_assets` starts an HTTP probe in the panel process, and the probe dialed through the recording proxy whenever the target gate was off, with no destination check: a worker could submit a service URL for loopback, RFC1918 or the cloud metadata address and read the status, length and title with `list_assets`, or the full body through the traffic store. While `ARTEX_SANDBOX=required`, the probe now uses the task's `sandbox.EgressPolicy` for the URL, every redirect and every connection, resolves and pins the address itself, then hands that address to the target gate's pinned dialer as WebFetch and the http tool do (a probe without a target scope, or one a gated scope does not cover, still dials nothing), and uses neither the recording nor the environment proxy. A task without an approved scope probes nothing, as in the rest of the sandbox.
- **`ask_operator` reads run-directory images through a task-rooted handle.** The copy path resolved the asking run directory with `EvalSymlinks` and then opened the resolved path, so a worker that replaced its run directory with a symlink to `/` made the confinement root `/`: an absolute `image_path` to a symlink named `*.png` could have the panel copy `/proc/1/environ` or `/app/keys/jwt.key` into `tasks/<id>/uploads`, where the worker reads it. The read and the upload write are now both anchored with `os.Root` at `tasks/<id>`; the run directory must be a real directory, no path component may be a symlink, the opened file must be the one `Lstat` saw, and the copy is bounded to 10 MB. Existing `..`, outside-path and non-image refusals are unchanged.
- **Task archives no longer follow a directory swapped for a symlink while the task is packed.** The packer, running as root, listed each directory of the staged run tree and then opened its files by full path, so code running as the executor uid that kept a working directory inside the run tree could replace a listed directory with a symlink (for example to `/app/keys`) and have root-only files such as the session signing key copied into the archive, then read them back from the run directory after a restore. The packer now walks and opens the payload through an `os.Root` anchored at it, so no lookup can leave the payload, and refuses the archive when a file it opens is not the regular file the walk listed (device and inode compared). Symlinks already present in the run tree are still skipped and never followed. Behaviour change: an archive whose run tree changes this way while it is packed fails instead of completing, and the task stays in place.
- **Agent sessions no longer offer Norma's background-task tools.** Norma adds `Monitor`, `TaskOutput`, `TaskStop` and `TaskList` to every session that does not opt out, and only the connection test and the goal decomposer opted out. `Monitor` starts a shell command in the panel process, not through the sandbox that `Bash` uses, so in `ARTEX_SANDBOX=required` mode a worker, planner, chat or main-agent model could run commands in the panel container, outside the task's worker, and read or write other tasks' workspaces and transcripts. Every agent session is now built through one constructor. It turns these tools off while the sandbox is required, and always for a session that has neither `Bash` nor the interactive shell, so an orchestration agent cannot gain a shell through `Monitor`. Sessions that do have `Bash` or `shell_*` keep them when the sandbox is off: their background runs, PTY sessions and the pause kill switch depend on the same task manager. The constructor also turns a nil tool list into an empty one, because Norma reads nil as "use my own default tools" and installs its unconfined `Bash` and file tools; the tool catalogue resolver also returns an empty list instead of nil when the tools table cannot be read, the case of the Auto chat agent, whose base list is empty.
- **The target gate honors operator-approved egress grants.** The gate compared every target with pins only, while the sandbox proxy allowed every port of an operator-approved CIDR grant: a host already inside a granted task or company scope still raised per-port and bare-host approval prompts (pins match `host:port`, and a request naming the host without a port is covered only by a port-0 pin). `CheckTargets` now also consults the grants the operator approved for the task (its approved, unexpanded `task_scope` rows and the entries frozen into `task_scope_egress` by approved company grants, normalized as the proxy allowlist is): a domain matching a granted domain, an address inside a granted CIDR, or a range fully inside one passes as covered by `scope_grant`, recorded once per process and target key as a system-decided allowed row with the target outcome `scope_grant`. Pins, stored exemptions, block rules and human approvals are unchanged: anything outside a grant is decided as before, and task allow rules play no role, as everywhere in the gate. Related to #830, the mirror gap on the network side.
- **Chat-spawned tasks inherit fully operator-approved companies (#830).** Migration `0025_company_scope_approved.sql` made company scope an explicit operator decision, but `spawn_task` still stamped the whole company link `approved_by_operator=false`, so a chat-spawned task started with an empty egress allowlist and every connection was denied until an operator approved scope again per task (the trap #833 warns about). `CreateTaskWithOptions` now checks each LLM-selected company: one whose scope inventory exists and is entirely operator-approved and to which the calling task itself holds an operator-approved link carries standing consent, so its task link is inserted approved (a spawn with no task caller - chat session or direct API - inherits nothing, per review on #841) and its grant frozen into `task_scope_egress`, exactly as an operator selection does; a company holding any agent-written (unapproved) row, and one with no scope rows, stay coverage-only, so `add_company_scope`, the ScopeSentry sync and invented ids still grant nothing without a fresh operator decision. Provenance is preserved: `source` stays `agent` and the approval column records the inherited consent row by row. Related: #830, #833.
+3 -1
View File
@@ -221,7 +221,9 @@ func run() int {
}
// Tighten an existing key directory before running the isolation self-test:
// a host bind mount (typically 0755) masks the image's 0700.
keyLockErr := errors.Join(server.LockDownKeyDir(keyDir), server.LockDownCAKey(*dataDir))
// The transcripts and noa archives (whole conversations) too: Norma leaves
// them 0755/0644, readable by the executor.
keyLockErr := errors.Join(server.LockDownKeyDir(keyDir), server.LockDownCAKey(*dataDir), server.LockDownPrivateDataDirs(*dataDir))
// Before the stores open and any agent runs: check that the isolation above holds
// (server/isolation.go). Startup is fail-closed unless ARTEX_ALLOW_UNISOLATED=1
// (or -dev-insecure-no-isolation) is explicitly set.
+60 -1
View File
@@ -27,6 +27,7 @@ import (
"github.com/Autumn-27/artex/db"
"github.com/Autumn-27/artex/egress"
"github.com/Autumn-27/artex/intercept"
"github.com/Autumn-27/artex/sandbox"
"github.com/miekg/dns"
"github.com/projectdiscovery/dnsx/libs/dnsx"
@@ -67,6 +68,10 @@ type Engine struct {
resolv *dnsx.DNSX
client *http.Client
// sandboxPolicy returns the task's egress policy while the panel runs in
// ARTEX_SANDBOX=required mode, nil otherwise. It is set once, before jobs.
sandboxPolicy func(context.Context) *sandbox.EgressPolicy
jobs chan job
cool sync.Map // dedup/cooldown: "kind:id" -> time.Time (last run)
once sync.Once
@@ -256,6 +261,50 @@ func buildClient(proxy func() string) *http.Client {
}
}
// SetSandboxPolicy installs the source of the task egress policy applied to
// panel-side HTTP probes while ARTEX_SANDBOX=required. It must return nil when
// the sandbox is off; the probe then keeps the recording-proxy path. Set it once
// at construction, before any job is enqueued.
func (e *Engine) SetSandboxPolicy(policy func(context.Context) *sandbox.EgressPolicy) {
e.sandboxPolicy = policy
}
// sandboxClient probes through the task's sandbox egress policy: every connection
// is resolved, checked and pinned by the policy, with no proxy and no environment
// proxy, so a proxy cannot route around it. The pinned address then goes through
// the target gate's pinned dialer, as on the recording-proxy client: a probe
// without a target scope is refused, and a gated scope still needs a pin. This
// is the order the WebFetch and http tool sandbox dialers use. Redirects stay
// off, as on the recording-proxy client.
func sandboxClient(policy *sandbox.EgressPolicy) *http.Client {
gate := intercept.PinnedDialer("enrich", true)
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
DisableKeepAlives: true,
TLSHandshakeTimeout: httpTimeout,
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
host, portStr, err := net.SplitHostPort(addr)
if err != nil {
return nil, fmt.Errorf("sandbox enrich blocked invalid target %q: %w", addr, err)
}
port, err := strconv.Atoi(portStr)
if err != nil || port <= 0 || port > 65535 {
return nil, fmt.Errorf("sandbox enrich blocked invalid port %q", portStr)
}
ip, err := policy.ResolveAndCheck(ctx, host)
if err != nil {
return nil, fmt.Errorf("sandbox enrich blocked: %w", err)
}
return gate(ctx, network, net.JoinHostPort(ip.String(), portStr))
},
}
return &http.Client{
Transport: egress.Dynamic("enrich", tr),
Timeout: httpTimeout,
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
}
}
// ResolveDomain enqueues a DNS resolution for a domain asset (ungated). host is the
// FQDN. No-op for an empty engine.
func (e *Engine) ResolveDomain(id int64, host string) { e.enqueue(job{jobDNS, id, host, nil}) }
@@ -377,7 +426,17 @@ func (e *Engine) doHTTP(ctx context.Context, id int64, rawURL string) {
return
}
intercept.ApplyAssessmentUserAgent(req)
resp, err := e.client.Do(req)
client := e.client
if e.sandboxPolicy != nil {
if policy := e.sandboxPolicy(ctx); policy != nil {
if err := policy.CheckURL(ctx, rawURL); err != nil {
slog.Warn("[enrich] HTTP probe blocked by sandbox egress policy", "url", rawURL, "err", err)
return
}
client = sandboxClient(policy)
}
}
resp, err := client.Do(req)
if err != nil {
return
}
+182
View File
@@ -0,0 +1,182 @@
package enrich
import (
"context"
"errors"
"net"
"net/http"
"net/http/httptest"
"net/netip"
"strconv"
"sync/atomic"
"testing"
"time"
"github.com/Autumn-27/artex/intercept"
"github.com/Autumn-27/artex/sandbox"
)
// A probe scheduled while ARTEX_SANDBOX=required must use the task egress policy,
// not the recording proxy: loopback, IMDS and RFC1918 are refused even when the
// target name is in scope and resolves there.
func TestSandboxPolicyBlocksInternalProbes(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer ln.Close()
accepted := make(chan struct{}, 4)
go func() {
for {
c, err := ln.Accept()
if err != nil {
return
}
accepted <- struct{}{}
c.Close()
}
}()
port := ln.Addr().(*net.TCPAddr).Port
policy, err := sandbox.NewEgressPolicy("t1", []string{"allowed.example"}, nil, nil)
if err != nil {
t.Fatal(err)
}
policy.Resolver = func(context.Context, string) ([]netip.Addr, error) {
return []netip.Addr{netip.MustParseAddr("127.0.0.1")}, nil
}
e := New(nil, nil, 1)
e.SetSandboxPolicy(func(context.Context) *sandbox.EgressPolicy { return policy })
defer e.Close()
for _, target := range []string{
"http://127.0.0.1:" + strconv.Itoa(port) + "/",
"http://169.254.169.254/",
"http://10.0.0.1/",
"http://allowed.example:" + strconv.Itoa(port) + "/",
} {
e.doHTTP(context.Background(), 1, target)
}
select {
case <-accepted:
t.Fatal("a sandboxed probe connected to a forbidden target")
case <-time.After(100 * time.Millisecond):
}
}
// The sandbox dialer resolves and pins the target itself: a name in scope that
// answers a private address is refused before any connection, even when the URL
// check is bypassed.
func TestSandboxDialerPinsResolvedAddress(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer ln.Close()
accepted := make(chan struct{}, 1)
go func() {
c, err := ln.Accept()
if err == nil {
accepted <- struct{}{}
c.Close()
}
}()
port := ln.Addr().(*net.TCPAddr).Port
policy, err := sandbox.NewEgressPolicy("t1", []string{"allowed.example"}, nil, nil)
if err != nil {
t.Fatal(err)
}
policy.Resolver = func(context.Context, string) ([]netip.Addr, error) {
return []netip.Addr{netip.MustParseAddr("127.0.0.1")}, nil
}
if _, err := sandboxClient(policy).Get("http://allowed.example:" + strconv.Itoa(port) + "/"); err == nil {
t.Fatal("the sandbox dialer connected to a name resolving to loopback")
}
select {
case <-accepted:
t.Fatal("the sandbox dialer opened a connection to loopback")
case <-time.After(100 * time.Millisecond):
}
}
// A target explicitly inside the task scope CIDRs still probes normally through
// the sandbox transport.
func TestSandboxClientAllowsScopedTarget(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte("ok"))
}))
defer srv.Close()
policy, err := sandbox.NewEgressPolicy("t1", nil, []string{"127.0.0.1/32"}, nil)
if err != nil {
t.Fatal(err)
}
ctx := intercept.WithTargetScope(context.Background(), intercept.TargetScope{TaskID: "t1"})
req, err := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL, nil)
if err != nil {
t.Fatal(err)
}
resp, err := sandboxClient(policy).Do(req)
if err != nil {
t.Fatalf("scoped target refused: %v", err)
}
resp.Body.Close()
}
// The sandbox policy narrows the target gate, it does not replace it: a target
// inside the sandbox scope is still refused without a target scope, and under a
// gated scope that does not decide it.
func TestSandboxClientKeepsTargetGate(t *testing.T) {
var hits atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
hits.Add(1)
}))
defer srv.Close()
policy, err := sandbox.NewEgressPolicy("t1", nil, []string{"127.0.0.1/32"}, nil)
if err != nil {
t.Fatal(err)
}
gated := intercept.WithTargetScope(context.Background(), intercept.TargetScope{
TaskID: "t1", Enabled: func() bool { return true },
})
for name, ctx := range map[string]context.Context{"no target scope": context.Background(), "gate on": gated} {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL, nil)
if err != nil {
t.Fatal(err)
}
if resp, err := sandboxClient(policy).Do(req); err == nil {
resp.Body.Close()
t.Fatalf("%s: the sandbox client skipped the target gate", name)
}
}
if hits.Load() != 0 {
t.Fatalf("the target received %d request(s)", hits.Load())
}
}
type countingRoundTripper struct{ calls *atomic.Int32 }
func (c countingRoundTripper) RoundTrip(*http.Request) (*http.Response, error) {
c.calls.Add(1)
return nil, errors.New("normal client used")
}
// doHTTP must select the sandbox client when the policy hook is set: the normal
// recording-proxy client would otherwise be used even in required mode.
func TestDoHTTPUsesSandboxClient(t *testing.T) {
var normalCalls atomic.Int32
e := New(nil, nil, 1)
defer e.Close()
e.client = &http.Client{Transport: countingRoundTripper{calls: &normalCalls}}
policy, err := sandbox.NewEgressPolicy("t1", nil, nil, nil)
if err != nil {
t.Fatal(err)
}
e.SetSandboxPolicy(func(context.Context) *sandbox.EgressPolicy { return policy })
e.doHTTP(context.Background(), 1, "http://127.0.0.1:1/")
if n := normalCalls.Load(); n != 0 {
t.Fatalf("doHTTP used the normal client %d time(s) under a sandbox policy", n)
}
}
+3 -3
View File
@@ -19,8 +19,8 @@ func TestArgvAllowKeepsDenyAndTargetGate(t *testing.T) {
Pattern: "--force", Action: "deny", Message: "force push is forbidden"},
{ID: 2, Name: "argv allow curl", Enabled: true, Priority: -1000, MatchTarget: "tool_input", MatchType: "argv",
Pattern: `["curl"]`, Action: "allow"},
{ID: 3, Name: "argv allow nmap", Enabled: true, Priority: -1000, MatchTarget: "tool_input", MatchType: "argv",
Pattern: `["nmap"]`, Action: "allow"},
{ID: 3, Name: "argv allow whois", Enabled: true, Priority: -1000, MatchTarget: "tool_input", MatchType: "argv",
Pattern: `["whois"]`, Action: "allow"},
})
g := NewWithInterceptor(ic)
gate := &fakeGate{t: t, check: unpinnedOnce, request: func(int, []intercept.TargetRequest, *intercept.Decision) intercept.TargetResult {
@@ -29,7 +29,7 @@ func TestArgvAllowKeepsDenyAndTargetGate(t *testing.T) {
g.gate = gate
ctx := gateOn(context.Background(), "7", time.Minute)
if block, msg := pre(g, ctx, "Bash", `{"command":"nmap --force 10.0.0.1"}`); !block || !strings.Contains(msg, "force push is forbidden") {
if block, msg := pre(g, ctx, "Bash", `{"command":"whois --force 10.0.0.1"}`); !block || !strings.Contains(msg, "force push is forbidden") {
t.Fatalf("deny over argv allow: block=%v msg=%q", block, msg)
}
if gate.checks != 0 {
+13 -1
View File
@@ -29,6 +29,9 @@ var alwaysAllowDenylist = func() map[string]bool {
"mvn gradle dotnet apt apt-get dpkg dnf yum rpm pacman apk brew snap flatpak",
// version control and build generators: run hooks, aliases and script files
"git cmake ctest cpack",
// tools whose flags run code chosen by the caller: a prefix covers every flag
// (sqlmapapi: sqlmap's REST API server; argvProgramName strips its .py launcher)
"sqlmap sqlmapapi sqlite nmap",
// orchestration: run images, playbooks and plans
"docker docker-compose podman nerdctl kubectl helm ansible ansible-playbook terraform pulumi vagrant",
// destructive
@@ -44,13 +47,22 @@ var alwaysAllowDenylist = func() map[string]bool {
}()
// argvProgramName normalises a program token for the denylist: the basename,
// in lower case, without a trailing version (python3.11, php8.2, perl5, pip3)
// in lower case, without an interpreter or launcher extension (sqlmap.py,
// sqlite3.exe), without a trailing version (python3.11, php8.2, perl5, pip3)
// and with every mkfs.* variant reduced to mkfs.
func argvProgramName(tok string) string {
name := strings.ToLower(path.Base(tok))
if strings.HasPrefix(name, "mkfs.") {
return "mkfs"
}
// A script or a Windows launcher runs the same program as its bare name:
// sqlmap.py, nmap.exe and sqlite3.exe must not slip past the denylist.
for _, ext := range []string{".exe", ".cmd", ".bat", ".ps1", ".py", ".pl", ".rb", ".sh", ".bash", ".lua", ".php", ".js"} {
if strings.HasSuffix(name, ext) {
name = strings.TrimSuffix(name, ext)
break
}
}
// Strip a trailing run of digits and dots, but only after a letter, so a
// name made only of digits (or ".") is kept as is.
end := len(name)
+18 -7
View File
@@ -14,12 +14,14 @@ func TestArgvAllowDenylist(t *testing.T) {
"env", "/usr/bin/env", "bash", "/bin/sh", "find", "rm", "mkfs", "mkfs.ext4", "/sbin/mkfs.xfs",
"docker", "kubectl", "npm", "sudo", "xargs", "Rscript", ".",
"git", "/usr/bin/git", "cmake", "cmake3", "/usr/bin/cmake", "ctest", "cpack",
"sqlmap", "/usr/bin/sqlmap", "sqlite", "sqlite3", "/usr/bin/sqlite3", "nmap", "/usr/bin/nmap",
"sqlmap.py", "/opt/sqlmap/sqlmap.py", "sqlmapapi", "/opt/sqlmap/sqlmapapi.py", "sqlite3.exe", "nmap.exe", "nmap.sh",
} {
if !ArgvAllowDenied(prog) {
t.Errorf("%q is not denied", prog)
}
}
for _, prog := range []string{"nmap", "curl", "ls", "gh", "x", "7z", "pythonic"} {
for _, prog := range []string{"whois", "curl", "ls", "gh", "x", "7z", "pythonic"} {
if ArgvAllowDenied(prog) {
t.Errorf("%q is denied, want allowable", prog)
}
@@ -34,8 +36,8 @@ func TestAlwaysAllowPrefix(t *testing.T) {
if got, err := AlwaysAllowPrefix("Bash", bash("gh pr list --limit 5")); err != nil || !slices.Equal(got, []string{"gh", "pr", "list"}) {
t.Fatalf("gh pr list: %q %v", got, err)
}
if got, err := AlwaysAllowPrefix("Bash", bash("nmap -p 80 10.0.0.1")); err != nil || !slices.Equal(got, []string{"nmap"}) {
t.Fatalf("nmap: %q %v", got, err)
if got, err := AlwaysAllowPrefix("Bash", bash("whois example.com")); err != nil || !slices.Equal(got, []string{"whois"}) {
t.Fatalf("whois: %q %v", got, err)
}
for name, c := range map[string]struct {
tool string
@@ -58,6 +60,14 @@ func TestAlwaysAllowPrefix(t *testing.T) {
"git config": {"Bash", bash("git config user.name x")},
"cmake": {"Bash", bash("cmake --version")},
"ctest": {"Bash", bash("ctest -N")},
"sqlmap": {"Bash", bash("sqlmap --version")},
"path to sqlmap": {"Bash", bash("/usr/bin/sqlmap -u http://127.0.0.1/")},
"sqlmap.py": {"Bash", bash("/opt/sqlmap/sqlmap.py -u http://127.0.0.1/")},
"sqlmapapi": {"Bash", bash("/opt/sqlmap/sqlmapapi.py --version")},
"sqlite3": {"Bash", bash("sqlite3 -version")},
"sqlite3.exe": {"Bash", bash("sqlite3.exe -version")},
"nmap": {"Bash", bash("nmap -sV -p 80 127.0.0.1")},
"path to nmap": {"Bash", bash("/usr/bin/nmap -p 80 127.0.0.1")},
} {
if got, err := AlwaysAllowPrefix(c.tool, c.input); err == nil {
t.Errorf("%s: prefix %q, want a refusal", name, got)
@@ -92,17 +102,18 @@ func TestArgvDenylistAtMatching(t *testing.T) {
ic := New(nil)
ic.SetRulesForTest([]db.InterceptRule{
argv(1, `["python"]`, "allow"), argv(2, `["python3.11"]`, "allow"), argv(3, `["find"]`, "allow"),
argv(4, `["/usr/bin/env"]`, "allow"), argv(5, `["nmap"]`, "allow"), ask,
argv(4, `["/usr/bin/env"]`, "allow"), argv(5, `["nmap"]`, "allow"), argv(8, `["whois"]`, "allow"),
argv(9, `["sqlmap"]`, "allow"), argv(10, `["sqlite3"]`, "allow"), ask,
})
for _, cmd := range []string{"python x.py", "python3.11 -c 'import os'", "find . -name x", "/usr/bin/env"} {
for _, cmd := range []string{"python x.py", "python3.11 -c 'import os'", "find . -name x", "/usr/bin/env", "nmap -p 80 x", "sqlmap -u http://127.0.0.1/", "sqlite3 -version"} {
input, _ := json.Marshal(map[string]string{"command": cmd})
dec, ok := ic.Match("Bash", input)
if !ok || dec.Action != "ask" || dec.RuleID != 99 {
t.Errorf("%q: %+v %v, want the fallback ask rule", cmd, dec, ok)
}
}
if dec, ok := ic.Match("Bash", []byte(`{"command":"nmap -p 80 x"}`)); !ok || dec.Action != "allow" || dec.RuleID != 5 {
t.Errorf("nmap: %+v %v, want the argv allow", dec, ok)
if dec, ok := ic.Match("Bash", []byte(`{"command":"whois example.com"}`)); !ok || dec.Action != "allow" || dec.RuleID != 8 {
t.Errorf("whois: %+v %v, want the argv allow", dec, ok)
}
ic.SetRulesForTest([]db.InterceptRule{argv(1, `["python"]`, "allow"), argv(6, `["python"]`, "deny"), argv(7, `["find"]`, "ask")})
+19 -19
View File
@@ -231,20 +231,20 @@ func TestArgvAllowRemainsStrict(t *testing.T) {
cmd string
want bool
}{
{"nmap -p 80 x", true},
{"command nmap x", false},
{"nmap x; true", false},
{"bash -c 'nmap x'", false},
{"/usr/bin/nmap x", false},
{"sudo nmap x", false},
{"env FOO=1 nmap x", false},
{"nmap $(id)", false},
{"whois -p 80 x", true},
{"command whois x", false},
{"whois x; true", false},
{"bash -c 'whois x'", false},
{"/usr/bin/whois x", false},
{"sudo whois x", false},
{"env FOO=1 whois x", false},
{"whois $(id)", false},
}
for _, tc := range cases {
t.Run(tc.cmd, func(t *testing.T) {
_, got := matchSingleArgvRule("allow", `["nmap"]`, "Bash", bashInput(tc.cmd))
_, got := matchSingleArgvRule("allow", `["whois"]`, "Bash", bashInput(tc.cmd))
if got != tc.want {
t.Errorf("allow [\"nmap\"] on %q = %v, want %v", tc.cmd, got, tc.want)
t.Errorf("allow [\"whois\"] on %q = %v, want %v", tc.cmd, got, tc.want)
}
})
}
@@ -256,15 +256,15 @@ func TestArgvCompoundMalformedInputDoesNotPanic(t *testing.T) {
[]byte(``),
[]byte(`not json`),
[]byte(`{}`),
bashInput(`nmap 'unterminated`),
bashInput(`nmap $(`),
bashInput(`whois 'unterminated`),
bashInput(`whois $(`),
bashInput(`if then fi; (( (`),
bashInput(`bash -c "unterminated`),
bashInput(`eval "((("`),
}
for _, action := range []string{"deny", "ask", "allow"} {
for _, in := range inputs {
if dec, ok := matchSingleArgvRule(action, `["nmap"]`, "Bash", in); ok {
if dec, ok := matchSingleArgvRule(action, `["whois"]`, "Bash", in); ok {
t.Errorf("%s matched malformed input %q: %+v", action, string(in), dec)
}
}
@@ -274,18 +274,18 @@ func TestArgvCompoundMalformedInputDoesNotPanic(t *testing.T) {
func TestArgvPriorityPreservedWithCompoundDeny(t *testing.T) {
ic := New(nil)
ic.SetRulesForTest([]db.InterceptRule{
{ID: 1, Name: "allow simple nmap", Enabled: true, Priority: 100, MatchTarget: "tool_input", MatchType: "argv", Pattern: `["nmap"]`, Action: "allow"},
{ID: 2, Name: "deny compound nmap", Enabled: true, Priority: 50, MatchTarget: "tool_input", MatchType: "argv", Pattern: `["nmap"]`, Action: "deny"},
{ID: 1, Name: "allow simple whois", Enabled: true, Priority: 100, MatchTarget: "tool_input", MatchType: "argv", Pattern: `["whois"]`, Action: "allow"},
{ID: 2, Name: "deny compound whois", Enabled: true, Priority: 50, MatchTarget: "tool_input", MatchType: "argv", Pattern: `["whois"]`, Action: "deny"},
})
// Simple command hits the higher-priority allow rule.
dec, ok := ic.Match("Bash", bashInput("nmap -p 80 x"))
dec, ok := ic.Match("Bash", bashInput("whois -p 80 x"))
if !ok || dec.Action != "allow" || dec.RuleID != 1 {
t.Fatalf("simple nmap: got (%+v, %v), want allow rule 1", dec, ok)
t.Fatalf("simple whois: got (%+v, %v), want allow rule 1", dec, ok)
}
// Compound command fails the strict allow rule and falls through to the deny rule.
dec, ok = ic.Match("Bash", bashInput("nmap -p 80 x; true"))
dec, ok = ic.Match("Bash", bashInput("whois -p 80 x; true"))
if !ok || dec.Action != "deny" || dec.RuleID != 2 {
t.Fatalf("compound nmap: got (%+v, %v), want deny rule 2", dec, ok)
t.Fatalf("compound whois: got (%+v, %v), want deny rule 2", dec, ok)
}
}
+9 -9
View File
@@ -133,9 +133,9 @@ func TestArgvRejectsWrappers(t *testing.T) {
// no rule and the normal flow (judge, approval) continues.
func TestArgvParseFailureIsNoMatch(t *testing.T) {
ic := New(nil)
ic.SetRulesForTest([]db.InterceptRule{{ID: 1, Name: "argv allow nmap", Enabled: true, MatchTarget: "tool_input",
MatchType: "argv", Pattern: `["nmap"]`, Action: "allow"}})
for _, input := range []string{`{"command":"nmap 'unterminated"}`, `{"command":"nmap $("}`, `{"command":""}`, `{}`, `not json`} {
ic.SetRulesForTest([]db.InterceptRule{{ID: 1, Name: "argv allow whois", Enabled: true, MatchTarget: "tool_input",
MatchType: "argv", Pattern: `["whois"]`, Action: "allow"}})
for _, input := range []string{`{"command":"whois 'unterminated"}`, `{"command":"whois $("}`, `{"command":""}`, `{}`, `not json`} {
if dec, ok := ic.Match("Bash", []byte(input)); ok {
t.Errorf("%s matched: %+v", input, dec)
}
@@ -216,18 +216,18 @@ func TestArgvAllowBelowDeny(t *testing.T) {
ic.SetRulesForTest([]db.InterceptRule{
{ID: 1, Name: "no force flag", Enabled: true, Priority: 50, MatchTarget: "tool_input", MatchType: "regex",
Pattern: `--force`, Action: "deny"},
{ID: 2, Name: "argv allow nmap", Enabled: true, Priority: -1000, MatchTarget: "tool_input", MatchType: "argv",
Pattern: `["nmap"]`, Action: "allow"},
{ID: 2, Name: "argv allow whois", Enabled: true, Priority: -1000, MatchTarget: "tool_input", MatchType: "argv",
Pattern: `["whois"]`, Action: "allow"},
})
dec, ok := ic.Match("Bash", []byte(`{"command":"nmap --force 10.0.0.1"}`))
dec, ok := ic.Match("Bash", []byte(`{"command":"whois --force 10.0.0.1"}`))
if !ok || dec.Action != "deny" || dec.RuleID != 1 {
t.Fatalf("force flag: %+v %v, want the deny rule", dec, ok)
}
dec, ok = ic.Match("Bash", []byte(`{"command":"nmap 10.0.0.1"}`))
dec, ok = ic.Match("Bash", []byte(`{"command":"whois 10.0.0.1"}`))
if !ok || dec.Action != "allow" || dec.RuleID != 2 {
t.Fatalf("nmap: %+v %v, want the argv allow", dec, ok)
t.Fatalf("whois: %+v %v, want the argv allow", dec, ok)
}
if _, ok := ic.Match("Bash", []byte(`{"command":"nmap 10.0.0.1; id"}`)); ok {
if _, ok := ic.Match("Bash", []byte(`{"command":"whois 10.0.0.1; id"}`)); ok {
t.Fatal("a compound command matched the argv rule")
}
if _, ok := compileRule(db.InterceptRule{MatchType: "argv", Pattern: `["-x"]`}); ok {
+112 -49
View File
@@ -170,10 +170,11 @@ func askOperatorActivity(text string, att []chatAttachment, derived []string) db
return a
}
// resolveAskOperatorImage maps image_path onto a regular file inside runDir, the
// run directory of the agent that asks (its CWD). Relative paths are resolved from it.
// ".." segments, paths that EvalSymlinks outside runDir, and non-images are refused.
func resolveAskOperatorImage(runDir, src string) (string, error) {
// askOperatorImageRel maps image_path onto a path relative to the task root.
// Relative paths resolve from runName, the run directory of the agent that asks
// (i<intentID>, or main). An absolute path must be inside that run directory.
// ".." segments, paths outside the run directory and non-images are refused.
func askOperatorImageRel(taskDir, runName, src string) (string, error) {
src = strings.TrimSpace(src)
ext := strings.ToLower(filepath.Ext(src))
if !askOperatorImageExt[ext] {
@@ -182,34 +183,54 @@ func resolveAskOperatorImage(runDir, src string) (string, error) {
if slices.Contains(strings.Split(filepath.ToSlash(src), "/"), "..") {
return "", fmt.Errorf("image_path must stay inside the run directory")
}
if !filepath.IsAbs(src) {
src = filepath.Join(runDir, src)
var rel string
if filepath.IsAbs(src) {
r, err := filepath.Rel(taskDir, filepath.Clean(src))
if err != nil {
return "", fmt.Errorf("image_path must stay inside the run directory")
}
rel = r
} else {
rel = filepath.Join(runName, src)
}
realRoot, err := filepath.EvalSymlinks(runDir)
if err != nil {
return "", fmt.Errorf("image not readable")
}
real, err := filepath.EvalSymlinks(src)
if err != nil {
return "", fmt.Errorf("image not readable")
}
rel, err := filepath.Rel(realRoot, real)
if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
if !filepath.IsLocal(rel) || (rel != runName && !strings.HasPrefix(rel, runName+string(filepath.Separator))) {
return "", fmt.Errorf("image_path must stay inside the run directory")
}
return real, nil
return rel, nil
}
// openAskOperatorImage opens the image at path and requires the opened file to be
// the regular file lst describes, lst being the Lstat of path. Between the
// EvalSymlinks of resolveAskOperatorImage and this open, the agent can replace the
// file with a symlink: Lstat does not follow one and the open does, so the two then
// name different files and the image is refused.
func openAskOperatorImage(path string, lst os.FileInfo) (*os.File, error) {
// askOperatorRejectSymlinks refuses a symlink in any component of rel below the
// task root. os.Root follows links that stay inside the root, so a link from the
// run directory to a sibling would otherwise be read.
func askOperatorRejectSymlinks(root *os.Root, rel string) error {
parts := strings.Split(rel, string(filepath.Separator))
prefix := parts[0]
for i, part := range parts {
if i > 0 {
prefix = filepath.Join(prefix, part)
}
info, err := root.Lstat(prefix)
if err != nil {
return fmt.Errorf("image not readable")
}
if info.Mode()&os.ModeSymlink != 0 {
return fmt.Errorf("image_path must stay inside the run directory")
}
if i < len(parts)-1 && !info.IsDir() {
return fmt.Errorf("image not readable")
}
}
return nil
}
// openAskOperatorImage opens rel under the task root and requires the opened file
// to be the regular file lst describes. The root refuses a path outside the task
// and a symlink that leaves it; Lstat does not follow the last component.
func openAskOperatorImage(root *os.Root, rel string, lst os.FileInfo) (*os.File, error) {
if !lst.Mode().IsRegular() {
return nil, fmt.Errorf("image_path must be a regular file")
}
f, err := os.Open(path)
f, err := root.Open(rel)
if err != nil {
return nil, fmt.Errorf("image not readable")
}
@@ -220,18 +241,22 @@ func openAskOperatorImage(path string, lst os.FileInfo) (*os.File, error) {
return f, nil
}
// askOperatorUploadsDir returns tasks/<id>/uploads, created when absent. A symlink
// or anything else that is not a directory is refused: the copy would be written
// through it.
func askOperatorUploadsDir(taskDir string) (string, error) {
dir := filepath.Join(taskDir, "uploads")
if err := os.Mkdir(dir, 0o755); err != nil && !errors.Is(err, fs.ErrExist) {
return "", err
// askOperatorUploadsRoot returns tasks/<id>/uploads as a root anchored at the
// task directory. A symlink or anything else that is not a directory is refused:
// the copy would be written through it.
func askOperatorUploadsRoot(taskRoot *os.Root) (*os.Root, error) {
if err := taskRoot.Mkdir("uploads", 0o755); err != nil && !errors.Is(err, fs.ErrExist) {
return nil, err
}
if fi, err := os.Lstat(dir); err != nil || !fi.IsDir() {
return "", fmt.Errorf("the task uploads directory is not a directory")
fi, err := taskRoot.Lstat("uploads")
if err != nil || fi.Mode()&os.ModeSymlink != 0 || !fi.IsDir() {
return nil, fmt.Errorf("the task uploads directory is not a directory")
}
return dir, nil
uploads, err := taskRoot.OpenRoot("uploads")
if err != nil {
return nil, fmt.Errorf("the task uploads directory is not a directory")
}
return uploads, nil
}
// askOperatorStageTries bounds the names tried for one staged copy.
@@ -257,33 +282,57 @@ func stageAskOperatorImage(dataDir string, taskID, intentID int64, src string) (
if src == "" {
return nil, nil
}
taskDir := filepath.Join(dataDir, "tasks", strconv.FormatInt(taskID, 10))
resolved, err := resolveAskOperatorImage(agent.EnsureRunDir(dataDir, taskID, intentID), src)
if err != nil {
return nil, err
taskRel := filepath.Join("tasks", strconv.FormatInt(taskID, 10))
runName := "main"
if intentID > 0 {
runName = "i" + strconv.FormatInt(intentID, 10)
}
st, err := os.Lstat(resolved)
// Every lookup is anchored at the task directory: a run directory or an
// intermediate directory swapped for a symlink cannot leave the task.
dataRoot, err := os.OpenRoot(dataDir)
if err != nil {
return nil, fmt.Errorf("image not readable")
}
in, err := openAskOperatorImage(resolved, st)
defer dataRoot.Close()
taskRoot, err := dataRoot.OpenRoot(taskRel)
if err != nil {
return nil, fmt.Errorf("image not readable")
}
defer taskRoot.Close()
runInfo, err := taskRoot.Lstat(runName)
if err != nil || runInfo.Mode()&os.ModeSymlink != 0 || !runInfo.IsDir() {
return nil, fmt.Errorf("image_path must stay inside the run directory")
}
rel, err := askOperatorImageRel(filepath.Join(dataDir, taskRel), runName, src)
if err != nil {
return nil, err
}
if err := askOperatorRejectSymlinks(taskRoot, rel); err != nil {
return nil, err
}
st, err := taskRoot.Lstat(rel)
if err != nil || !st.Mode().IsRegular() {
return nil, fmt.Errorf("image not readable")
}
if st.Size() > askOperatorMaxImage {
return nil, fmt.Errorf("image too large (%s, max 10MB)", humanBytes(st.Size()))
}
in, err := openAskOperatorImage(taskRoot, rel, st)
if err != nil {
return nil, err
}
defer in.Close()
if st.Size() > askOperatorMaxImage {
return nil, fmt.Errorf("image too large (%s, max 10MB)", humanBytes(st.Size()))
}
dir, err := askOperatorUploadsDir(taskDir)
uploads, err := askOperatorUploadsRoot(taskRoot)
if err != nil {
return nil, err
}
ext := strings.ToLower(filepath.Ext(resolved))
defer uploads.Close()
ext := strings.ToLower(filepath.Ext(rel))
var name string
var out *os.File
for try := 1; ; try++ {
name = askOperatorStageName(ext)
out, err = os.OpenFile(filepath.Join(dir, name), os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o640)
out, err = uploads.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o640)
if err == nil {
break
}
@@ -291,9 +340,23 @@ func stageAskOperatorImage(dataDir string, taskID, intentID int64, src string) (
return nil, err
}
}
defer out.Close()
if _, err := io.Copy(out, in); err != nil {
committed := false
defer func() {
if !committed {
_ = out.Close()
_ = uploads.Remove(name)
}
}()
n, err := io.Copy(out, io.LimitReader(in, askOperatorMaxImage+1))
if err != nil {
return nil, err
}
return []chatAttachment{{Name: name, Path: "uploads/" + name, Size: st.Size()}}, nil
if n > askOperatorMaxImage {
return nil, fmt.Errorf("image too large (%s, max 10MB)", humanBytes(n))
}
if err := out.Close(); err != nil {
return nil, err
}
committed = true
return []chatAttachment{{Name: name, Path: "uploads/" + name, Size: n}}, nil
}
+76 -7
View File
@@ -282,16 +282,22 @@ func TestStageAskOperatorImageNeverOverwrites(t *testing.T) {
// elsewhere.
func TestOpenAskOperatorImageRefusesSwap(t *testing.T) {
dir, taskDir := askOperatorRunDirs(t)
root, err := os.OpenRoot(taskDir)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = root.Close() })
src := filepath.Join(taskDir, "i3", "shot.png")
rel := filepath.Join("i3", "shot.png")
outside := filepath.Join(dir, "outside.png")
if err := os.WriteFile(outside, []byte("outside"), 0o644); err != nil {
t.Fatal(err)
}
lst, err := os.Lstat(src)
lst, err := root.Lstat(rel)
if err != nil {
t.Fatal(err)
}
f, err := openAskOperatorImage(src, lst)
f, err := openAskOperatorImage(root, rel, lst)
if err != nil {
t.Fatalf("unchanged file: %v", err)
}
@@ -305,32 +311,95 @@ func TestOpenAskOperatorImageRefusesSwap(t *testing.T) {
if err := os.Rename(other, src); err != nil {
t.Fatal(err)
}
if f, err := openAskOperatorImage(src, lst); err == nil {
if f, err := openAskOperatorImage(root, rel, lst); err == nil {
f.Close()
t.Fatal("opened a file that replaced the checked one")
}
// A symlink to a file outside the run directory takes the path.
// A symlink to a file outside the run directory takes the path. os.Root
// refuses the absolute target because it leaves the task root.
if err := os.Remove(src); err != nil {
t.Fatal(err)
}
if err := os.Symlink(outside, src); err != nil {
t.Skipf("no symlink here: %v", err)
}
if f, err := openAskOperatorImage(src, lst); err == nil {
if f, err := openAskOperatorImage(root, rel, lst); err == nil {
f.Close()
t.Fatal("opened the target of a symlink that replaced the checked file")
}
// The swap came before the Lstat: the last component is a symlink.
if lst, err = os.Lstat(src); err != nil {
if lst, err = root.Lstat(rel); err != nil {
t.Fatal(err)
}
if f, err := openAskOperatorImage(src, lst); err == nil {
if f, err := openAskOperatorImage(root, rel, lst); err == nil {
f.Close()
t.Fatal("opened a path whose last component is a symlink")
}
}
// A run directory replaced by a symlink must not turn the task root into the
// confinement root: the read stays anchored at tasks/<id>.
func TestStageAskOperatorImageRejectsRunDirSymlink(t *testing.T) {
dir, taskDir := askOperatorRunDirs(t)
runDir := filepath.Join(taskDir, "i3")
moved := filepath.Join(taskDir, "i3.real")
if err := os.Rename(runDir, moved); err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
_ = os.Remove(runDir)
_ = os.Rename(moved, runDir)
})
if err := os.Symlink("/", runDir); err != nil {
t.Skipf("no symlink here: %v", err)
}
// taskDir/shot.png is outside the run directory but inside the task. With the
// run directory symlinked to /, the old confinement root resolved to / and
// accepted it; the task root must not move.
outsideRun := filepath.Join(taskDir, "shot.png")
if err := os.WriteFile(outsideRun, []byte("outside the run dir"), 0o644); err != nil {
t.Fatal(err)
}
if att, err := stageAskOperatorImage(dir, 7, 3, outsideRun); err == nil {
t.Fatalf("staged %v through a symlinked run directory", att)
}
if att, err := stageAskOperatorImage(dir, 7, 3, "shot.png"); err == nil {
t.Fatalf("staged %v through a symlinked run directory", att)
}
}
// A symlink inside the run directory must not lead to a sibling run directory.
func TestStageAskOperatorImageRejectsSiblingSymlink(t *testing.T) {
dir, taskDir := askOperatorRunDirs(t)
link := filepath.Join(taskDir, "i3", "sibling")
if err := os.Symlink(filepath.Join("..", "main"), link); err != nil {
t.Skipf("no symlink here: %v", err)
}
if att, err := stageAskOperatorImage(dir, 7, 3, filepath.Join("sibling", "shot.png")); err == nil {
t.Fatalf("staged %v through a sibling symlink", att)
}
}
// uploads/ swapped for a symlink must not redirect the copy outside the task.
func TestStageAskOperatorImageRejectsUploadsSymlink(t *testing.T) {
dir, taskDir := askOperatorRunDirs(t)
outside := t.TempDir()
if err := os.Symlink(outside, filepath.Join(taskDir, "uploads")); err != nil {
t.Skipf("no symlink here: %v", err)
}
if att, err := stageAskOperatorImage(dir, 7, 3, "shot.png"); err == nil {
t.Fatalf("staged %v through a symlinked uploads directory", att)
}
entries, err := os.ReadDir(outside)
if err != nil {
t.Fatal(err)
}
if len(entries) != 0 {
t.Fatalf("wrote %d file(s) outside the task", len(entries))
}
}
// The emitted activity must carry the {text, attachments} Detail shape the
// transcript parser expects, so the operator sees the question with the
// attachment card for the screenshot.
+138 -2
View File
@@ -12,6 +12,7 @@ import (
"fmt"
"io"
"log/slog"
"net"
"net/http"
"net/url"
"os"
@@ -413,8 +414,25 @@ func unmaskToolExec(storedKind string, stored json.RawMessage, kind string, in j
}
oldURL, _ := old["url"].(string)
newURL, _ := e["url"].(string)
if kept && (oldURL != newURL || storedKind != kind) {
return nil, fmt.Errorf("destination changed (url or kind) while a stored secret was kept: re-enter the masked header/proxy/body or clear it; stored secrets are not sent to a new destination")
oldProxy, _ := old["proxy"].(string)
newProxy, _ := e["proxy"].(string)
oldRecording, _ := old["use_recording_proxy"].(bool)
newRecording, _ := e["use_recording_proxy"].(bool)
if kept {
if oldURL != newURL || storedKind != kind || oldRecording != newRecording {
return nil, fmt.Errorf("destination or recording proxy changed while a stored secret was kept: re-enter the masked header/proxy/body or clear it; stored secrets are not sent to a new destination")
}
// Clearing the configured proxy sends the request to the tool's fixed
// destination, not to a third party. Switching to another proxy does not
// have that guarantee.
if newProxy != "" && newProxy != oldProxy {
return nil, fmt.Errorf("proxy changed while a stored secret was kept: re-enter the masked header/body or clear it; stored secrets are not sent to a new proxy")
}
}
if kind == "http" {
if err := validateHTTPToolExec(e); err != nil {
return nil, err
}
}
if !changed {
return in, nil
@@ -698,6 +716,13 @@ func (s *Server) runHTTPTool(ctx context.Context, key string, execRaw json.RawMe
if strings.TrimSpace(rawURL) == "" {
return actool.Errorf("http url is empty"), nil
}
// A tool with stored headers or body may only send them to the origin it was
// configured for: the scheme, host and port of the url template cannot be
// parameters, and the rendered url must stay on that origin.
secretOrigin, originErr := httpToolSecretOrigin(spec, rawURL)
if originErr != nil {
return actool.Errorf(originErr.Error()), nil
}
// ARTEX_SANDBOX=required: the request leaves from the panel process, not from
// the task's worker container and its egress proxy. The task's egress policy,
// the one WebFetch enforces, applies here to the URL, to every redirect hop
@@ -741,6 +766,9 @@ func (s *Server) runHTTPTool(ctx context.Context, key string, execRaw json.RawMe
if sbPolicy != nil {
client.CheckRedirect = sandboxRedirectCheck(sbPolicy, client.CheckRedirect)
}
if secretOrigin != "" {
client.CheckRedirect = secretOriginRedirectCheck(secretOrigin, client.CheckRedirect)
}
// The current egress governor paces every request and redirect hop per host
// under the noise profile (off by default: the base transport itself). It is
// resolved per request, so a changed profile applies to the next call.
@@ -765,6 +793,114 @@ func (s *Server) runHTTPTool(ctx context.Context, key string, execRaw json.RawMe
return actool.Text(actool.Capture(tc, string(b))), nil
}
// httpToolHasSecrets reports whether an HTTP tool carries stored values the API
// masks: any non-empty header value or body.
func httpToolHasSecrets(spec httpExec) bool {
for _, v := range spec.Headers {
if strings.TrimSpace(v) != "" {
return true
}
}
return strings.TrimSpace(spec.Body) != ""
}
// validateHTTPToolExec refuses a secret-bearing HTTP tool whose url authority is
// parameterized. The stored headers and body would otherwise follow the rendered
// host to any third party.
func validateHTTPToolExec(e map[string]any) error {
raw, err := json.Marshal(e)
if err != nil {
return nil
}
var spec httpExec
if json.Unmarshal(raw, &spec) != nil {
return errors.New("invalid HTTP tool exec")
}
if !httpToolHasSecrets(spec) {
return nil
}
if _, ok := fixedHTTPOrigin(spec.URL); !ok {
return errors.New("an HTTP tool with stored headers or body needs a fixed origin: the url scheme, host and port cannot contain parameters")
}
return nil
}
// httpToolSecretOrigin returns the origin a secret-bearing HTTP tool must stay
// on, or "" when the tool carries no stored header or body.
func httpToolSecretOrigin(spec httpExec, rawURL string) (string, error) {
if !httpToolHasSecrets(spec) {
return "", nil
}
fixed, ok := fixedHTTPOrigin(spec.URL)
if !ok {
return "", errors.New("this HTTP tool sends stored headers or body, so its url must have a fixed scheme, host and port (no parameters)")
}
u, err := url.Parse(rawURL)
if err != nil {
return "", errors.New("http url is invalid")
}
rendered, err := canonicalOrigin(u)
if err != nil || rendered != fixed {
return "", fmt.Errorf("this HTTP tool sends stored headers or body, so the rendered url must stay on %s", fixed)
}
return fixed, nil
}
// fixedHTTPOrigin returns the canonical origin of a url template whose scheme,
// host and port are literal. ok is false when a parameter or an invalid url
// makes the destination dynamic.
func fixedHTTPOrigin(template string) (string, bool) {
u, err := url.Parse(strings.TrimSpace(template))
if err != nil || u.Scheme == "" || u.Host == "" {
return "", false
}
if strings.ContainsAny(u.Scheme, "{}") || strings.ContainsAny(u.Host, "{}") ||
(u.User != nil && strings.ContainsAny(u.User.String(), "{}")) {
return "", false
}
origin, err := canonicalOrigin(u)
if err != nil {
return "", false
}
return origin, true
}
// canonicalOrigin normalizes scheme, host case and default port, so a redirect
// is same-origin only when it keeps all three.
func canonicalOrigin(u *url.URL) (string, error) {
scheme := strings.ToLower(strings.TrimSpace(u.Scheme))
if scheme != "http" && scheme != "https" {
return "", fmt.Errorf("scheme %q is not http or https", u.Scheme)
}
host := strings.ToLower(strings.TrimSuffix(u.Hostname(), "."))
if host == "" {
return "", errors.New("url has no host")
}
port := u.Port()
if (scheme == "http" && port == "80") || (scheme == "https" && port == "443") {
port = ""
}
if port != "" {
return scheme + "://" + net.JoinHostPort(host, port), nil
}
if strings.Contains(host, ":") {
return scheme + "://[" + host + "]", nil
}
return scheme + "://" + host, nil
}
// secretOriginRedirectCheck refuses a redirect hop that leaves the origin the
// tool's stored headers and body were configured for.
func secretOriginRedirectCheck(origin string, check func(*http.Request, []*http.Request) error) func(*http.Request, []*http.Request) error {
return func(req *http.Request, via []*http.Request) error {
next, err := canonicalOrigin(req.URL)
if err != nil || next != origin {
return errors.New("redirect to a different origin refused: this HTTP tool sends stored headers or body")
}
return check(req, via)
}
}
// assessmentRedirectCheck sheds the generated identifier on the first redirect
// to another origin. net/http copies headers from the initial request for each
// hop, so check the previous hop to keep the identifier off after that point.
+225
View File
@@ -0,0 +1,225 @@
package server
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"github.com/Autumn-27/artex/agent"
"github.com/Autumn-27/artex/notify"
)
func TestFixedHTTPOrigin(t *testing.T) {
for _, tc := range []struct {
url string
want string
ok bool
}{
{"https://api.example.com/x", "https://api.example.com", true},
{"https://API.Example.com:443/x", "https://api.example.com", true},
{"http://api.example.com:80/x", "http://api.example.com", true},
{"http://api.example.com:8080/x", "http://api.example.com:8080", true},
{"https://api.example.com/{path}", "https://api.example.com", true},
{"https://[::1]:443/x", "https://[::1]", true},
{"https://[::1]:8443/x", "https://[::1]:8443", true},
{"https://{user}@api.example.com/x", "", false},
{"https://{host}/x", "", false},
{"https://api.{domain}/x", "", false},
{"https://api.example.com:{port}/x", "", false},
{"ftp://api.example.com/x", "", false},
{"/relative", "", false},
} {
got, ok := fixedHTTPOrigin(tc.url)
if ok != tc.ok || got != tc.want {
t.Errorf("fixedHTTPOrigin(%q) = %q, %v; want %q, %v", tc.url, got, ok, tc.want, tc.ok)
}
}
}
func TestHTTPToolSecretOrigin(t *testing.T) {
// A tool without stored headers or body may keep a parameterized authority.
if origin, err := httpToolSecretOrigin(httpExec{URL: "https://{host}/collect"}, "https://attacker.example/collect"); err != nil || origin != "" {
t.Fatalf("no-secret tool: origin=%q err=%v", origin, err)
}
// The rendered url must stay on the template origin.
if _, err := httpToolSecretOrigin(httpExec{
URL: "https://api.example.com/x",
Headers: map[string]string{"X-API-Key": "secret"},
}, "https://attacker.example/x"); err == nil {
t.Fatal("rendered url outside the template origin accepted")
}
}
func TestUnmaskToolExecRequiresFixedOriginForSecrets(t *testing.T) {
exec := func(url string, headers map[string]string) json.RawMessage {
b, _ := json.Marshal(map[string]any{"method": "GET", "url": url, "headers": headers})
return b
}
if _, err := unmaskToolExec("", nil, "http", exec("https://{host}/collect", map[string]string{"X-API-Key": "secret"})); err == nil {
t.Fatal("parameterized authority with a stored header accepted")
}
if _, err := unmaskToolExec("", nil, "http", exec("https://api.example.com/collect", map[string]string{"X-API-Key": "secret"})); err != nil {
t.Fatalf("fixed origin refused: %v", err)
}
if _, err := unmaskToolExec("", nil, "http", exec("https://{host}/collect", nil)); err != nil {
t.Fatalf("parameterized authority without secrets refused: %v", err)
}
if _, err := unmaskToolExec("", nil, "http", exec("https://api.example.com/{path}", map[string]string{"X-API-Key": "secret"})); err != nil {
t.Fatalf("path parameter with a fixed origin refused: %v", err)
}
}
func noSandbox(t *testing.T) {
t.Helper()
prev := agent.CurrentSandboxExecutor()
agent.SetSandboxExecutor(nil)
t.Cleanup(func() { agent.SetSandboxExecutor(prev) })
}
func TestHTTPToolRefusesParameterizedAuthorityWithSecrets(t *testing.T) {
noSandbox(t)
raw, _ := json.Marshal(map[string]any{
"method": "GET",
"url": "https://{host}/collect",
"headers": map[string]string{"X-API-Key": "secret"},
})
res, err := (&Server{}).runHTTPTool(context.Background(), "probe", raw, map[string]any{"host": "attacker.example"}, nil)
if err != nil {
t.Fatal(err)
}
if !res.IsError || !strings.Contains(res.Flatten(), "fixed scheme, host and port") {
t.Fatalf("parameterized authority not refused: isError=%v text=%q", res.IsError, res.Flatten())
}
}
func TestUnmaskToolExecRejectsMalformedHTTPExec(t *testing.T) {
raw := json.RawMessage(`{"method":"GET","url":"https://api.example.com/","headers":{"X":1}}`)
if _, err := unmaskToolExec("", nil, "http", raw); err == nil {
t.Fatal("numeric header value accepted")
}
}
func TestUnmaskToolExecRefusesProxyChangeWithSecrets(t *testing.T) {
stored := json.RawMessage(`{"method":"GET","url":"https://api.example.com/collect","headers":{"X-API-Key":"secret"}}`)
masked := func(proxy string, recording bool) json.RawMessage {
m := map[string]any{
"method": "GET",
"url": "https://api.example.com/collect",
"headers": map[string]string{"X-API-Key": notify.MaskedPrefix},
}
if proxy != "" {
m["proxy"] = proxy
}
if recording {
m["use_recording_proxy"] = true
}
b, _ := json.Marshal(m)
return b
}
if _, err := unmaskToolExec("http", stored, "http", masked("http://attacker.example:8080", false)); err == nil {
t.Fatal("proxy change with a kept secret accepted")
}
if _, err := unmaskToolExec("http", stored, "http", masked("", true)); err == nil {
t.Fatal("recording proxy change with a kept secret accepted")
}
if _, err := unmaskToolExec("http", stored, "http", masked("", false)); err != nil {
t.Fatalf("unchanged destination refused: %v", err)
}
storedProxy := json.RawMessage(`{"method":"GET","url":"https://api.example.com/collect","headers":{"X-API-Key":"secret"},"proxy":"http://proxy.example:8080"}`)
if _, err := unmaskToolExec("http", storedProxy, "http", masked("", false)); err != nil {
t.Fatalf("clearing the configured proxy refused: %v", err)
}
}
func TestHTTPToolRefusesParameterizedAuthorityWithBodySecret(t *testing.T) {
noSandbox(t)
raw, _ := json.Marshal(map[string]any{
"method": "POST",
"url": "https://{host}/collect",
"body": "token=secret",
})
res, err := (&Server{}).runHTTPTool(context.Background(), "probe", raw, map[string]any{"host": "attacker.example"}, nil)
if err != nil {
t.Fatal(err)
}
if !res.IsError || !strings.Contains(res.Flatten(), "fixed scheme, host and port") {
t.Fatalf("body-bearing parameterized authority not refused: isError=%v text=%q", res.IsError, res.Flatten())
}
}
func TestHTTPToolSecretStaysOnConfiguredOrigin(t *testing.T) {
noSandbox(t)
for _, code := range []int{http.StatusTemporaryRedirect, http.StatusPermanentRedirect} {
t.Run(http.StatusText(code), func(t *testing.T) {
var outsideHits atomic.Int32
outside := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
outsideHits.Add(1)
_, _ = w.Write([]byte("outside"))
}))
defer outside.Close()
var startHits atomic.Int32
start := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
startHits.Add(1)
if got := r.Header.Get("X-API-Key"); got != "secret" {
t.Errorf("first hop header = %q, want secret", got)
}
http.Redirect(w, r, outside.URL+"/stolen", code)
}))
defer start.Close()
raw, _ := json.Marshal(map[string]any{
"method": "GET",
"url": start.URL + "/start",
"headers": map[string]string{"X-API-Key": "secret"},
})
res, err := (&Server{}).runHTTPTool(context.Background(), "probe", raw, nil, nil)
if err != nil {
t.Fatal(err)
}
if !res.IsError || !strings.Contains(res.Flatten(), "different origin") {
t.Fatalf("cross-origin redirect not refused: isError=%v text=%q", res.IsError, res.Flatten())
}
if n := outsideHits.Load(); n != 0 {
t.Fatalf("outside origin received %d request(s)", n)
}
if n := startHits.Load(); n != 1 {
t.Fatalf("start origin hits = %d, want 1", n)
}
})
}
}
func TestHTTPToolSecretAllowsSameOriginRedirect(t *testing.T) {
noSandbox(t)
var finalHits atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/start" {
http.Redirect(w, r, "/final", http.StatusFound)
return
}
finalHits.Add(1)
_, _ = w.Write([]byte("final"))
}))
defer srv.Close()
raw, _ := json.Marshal(map[string]any{
"method": "GET",
"url": srv.URL + "/start",
"headers": map[string]string{"X-API-Key": "secret"},
})
res, err := (&Server{}).runHTTPTool(context.Background(), "probe", raw, nil, nil)
if err != nil {
t.Fatal(err)
}
if res.IsError {
t.Fatalf("same-origin redirect refused: %s", res.Flatten())
}
if n := finalHits.Load(); n != 1 {
t.Fatalf("final origin hits = %d, want 1", n)
}
}
+19
View File
@@ -0,0 +1,19 @@
package server
import "os"
// privateDataDirs are the data subdirectories only the server process reads:
// Norma's transcripts and the noa compression archives. They hold whole
// conversations (prompts, model output, tool results), and Norma creates the
// directories below them 0755 and the files 0644 (LockDownPrivateDataDirs).
var privateDataDirs = []string{"transcripts", "noa"}
// disableNormaRipgrepInstall stops Norma's Grep from installing ripgrep: with no
// rg on PATH it runs an unpinned `npm install -g @vscode/ripgrep`, install
// scripts included, unless NORMA_RIPGREP_NO_INSTALL is non-empty. ARTEX's own
// Grep never starts ripgrep. The variable is set to "1" whatever its value: an
// empty value, which Norma reads as unset, cannot re-enable the install, and no
// value is meant to.
func disableNormaRipgrepInstall() {
_ = os.Setenv("NORMA_RIPGREP_NO_INSTALL", "1")
}
@@ -0,0 +1,72 @@
//go:build unix
package server
import (
"os"
"path/filepath"
"testing"
)
// mkModeDir creates dir with exactly mode (the umask does not apply).
func mkModeDir(t *testing.T, dir string, mode os.FileMode) {
t.Helper()
if err := os.MkdirAll(dir, 0o700); err != nil {
t.Fatal(err)
}
if err := os.Chmod(dir, mode); err != nil {
t.Fatal(err)
}
}
// newManagerAnyDB starts a manager on dir and closes it. The data directories
// are settled before the database is opened, so the outcome does not depend on
// PostgreSQL.
func newManagerAnyDB(dir string) {
if m, err := NewManager(dir, ""); err == nil {
m.Close()
}
}
// Starting the manager leaves no transcript or noa content readable by another
// uid: directories an earlier version left 0755 become 0700, their 0644 files
// 0600, a narrower file keeps its mode, and noa is created 0700.
func TestNewManagerKeepsTranscriptsAndNoaPrivate(t *testing.T) {
dir := t.TempDir()
tr := filepath.Join(dir, "transcripts")
mkModeDir(t, filepath.Join(tr, "exp1-main"), 0o755)
mkModeDir(t, tr, 0o755)
writeMode(t, filepath.Join(tr, "exp1-worker.jsonl"), 0o644)
writeMode(t, filepath.Join(tr, "exp1-main", "part.jsonl"), 0o644)
writeMode(t, filepath.Join(tr, "read-only.jsonl"), 0o400)
newManagerAnyDB(dir)
wantMode(t, tr, 0o700)
wantMode(t, filepath.Join(tr, "exp1-main"), 0o700)
wantMode(t, filepath.Join(tr, "exp1-worker.jsonl"), 0o600)
wantMode(t, filepath.Join(tr, "exp1-main", "part.jsonl"), 0o600)
wantMode(t, filepath.Join(tr, "read-only.jsonl"), 0o400)
fi, err := os.Stat(filepath.Join(dir, "noa"))
if err != nil || !fi.IsDir() || fi.Mode().Perm() != 0o700 {
t.Fatalf("noa: %v %v, want a 0700 directory", fi, err)
}
}
// A transcripts or noa directory replaced by a symlink is not followed by the
// manager's start: the outside directory and its files keep their modes.
func TestNewManagerDoesNotFollowSymlinkedPrivateDirs(t *testing.T) {
for _, name := range []string{"transcripts", "noa"} {
t.Run(name, func(t *testing.T) {
dir, outside := t.TempDir(), t.TempDir()
mkModeDir(t, outside, 0o755)
writeMode(t, filepath.Join(outside, "f.jsonl"), 0o644)
if err := os.Symlink(outside, filepath.Join(dir, name)); err != nil {
t.Fatal(err)
}
newManagerAnyDB(dir)
wantMode(t, outside, 0o755)
wantMode(t, filepath.Join(outside, "f.jsonl"), 0o644)
})
}
}
+22
View File
@@ -0,0 +1,22 @@
//go:build !unix
package server
import (
"os"
"path/filepath"
)
// LockDownPrivateDataDirs creates the private data directories if missing;
// POSIX mode enforcement is Unix-only, as for LockDownKeyDir.
func LockDownPrivateDataDirs(dataDir string) error {
if dataDir == "" {
return nil
}
for _, name := range privateDataDirs {
if err := os.MkdirAll(filepath.Join(dataDir, name), 0o700); err != nil {
return err
}
}
return nil
}
+172
View File
@@ -0,0 +1,172 @@
//go:build unix
package server
import (
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
"syscall"
"github.com/Autumn-27/artex/traffic"
)
// LockDownPrivateDataDirs keeps <dataDir>/transcripts and <dataDir>/noa
// owner-only. Each directory in them, the top one included, keeps at most its
// owner bits (0700), and each regular file at most owner read and write (0600);
// a mode already narrower is left as it is. A missing top directory is created
// 0700.
//
// As in LockDownKeyDir, nothing is changed by path: the tree is walked under an
// os.Root at dataDir, every directory must be a real directory, not a symlink,
// the one opened being the one checked (traffic.OpenRealDir), and its mode is
// changed through that descriptor before its entries are read. A file is
// checked with Lstat (a regular file with a single link), opened under the
// root without following a symlink, checked again on the descriptor, and its
// mode is changed through that descriptor. A symlink, a hard-linked file or any
// other entry is refused and left as it is, so the server (root) never changes
// the mode of a file outside the tree; the walk goes on and the refusals are
// returned together.
//
// Each directory must be owned by the server's uid, and it is narrowed before
// its entries are read: from then on only the server can add, rename, link or
// unlink an entry in it, which is what a swap between a check and the chmod,
// or a hard link whose other name is unlinked meanwhile, would need. That is
// why a file is changed in place, not replaced by a copy as LockDownKeyDir's
// keys are: the copy would rewrite every transcript at each start. A directory
// owned by another uid is refused and its tree left as it is.
func LockDownPrivateDataDirs(dataDir string) error {
if strings.TrimSpace(dataDir) == "" {
return nil
}
if err := os.MkdirAll(dataDir, 0o755); err != nil {
return fmt.Errorf("create data dir %s: %w", dataDir, err)
}
root, err := os.OpenRoot(dataDir)
if err != nil {
return fmt.Errorf("open data dir %s: %w", dataDir, err)
}
defer root.Close()
var errs []error
for _, name := range privateDataDirs {
shown := filepath.Join(dataDir, name)
if err := root.Mkdir(name, 0o700); err != nil && !errors.Is(err, fs.ErrExist) {
errs = append(errs, fmt.Errorf("create %s: %w", shown, err))
continue
}
dir, err := traffic.OpenRealDir(root, name)
if err != nil {
errs = append(errs, fmt.Errorf("open %s: %w", shown, err))
continue
}
errs = append(errs, lockDownPrivateTree(dir, shown))
dir.Close()
}
return errors.Join(errs...)
}
// lockDownPrivateTree narrows the directory dir (shown in errors) and everything
// in it, as LockDownPrivateDataDirs describes.
func lockDownPrivateTree(dir *os.Root, shown string) error {
d, err := dir.Open(".")
if err != nil {
return fmt.Errorf("open %s: %w", shown, err)
}
defer d.Close()
fi, err := d.Stat()
if err != nil {
return fmt.Errorf("stat %s: %w", shown, err)
}
if st, ok := fi.Sys().(*syscall.Stat_t); !ok || int(st.Uid) != os.Geteuid() {
return fmt.Errorf("%s is not owned by the server's uid %d: left as it is", shown, os.Geteuid())
}
var errs []error
if err := narrowMode(d, 0o700); err != nil {
errs = append(errs, fmt.Errorf("chmod %s: %w", shown, err))
}
entries, err := d.ReadDir(-1)
if err != nil {
return errors.Join(append(errs, fmt.Errorf("read %s: %w", shown, err))...)
}
for _, e := range entries {
name, p := e.Name(), filepath.Join(shown, e.Name())
fi, err := dir.Lstat(name)
if errors.Is(err, fs.ErrNotExist) {
continue
}
switch {
case err != nil:
errs = append(errs, fmt.Errorf("lstat %s: %w", p, err))
case fi.IsDir():
sub, err := traffic.OpenRealDir(dir, name)
if err != nil {
errs = append(errs, fmt.Errorf("open %s: %w", p, err))
continue
}
errs = append(errs, lockDownPrivateTree(sub, p))
sub.Close()
case fi.Mode().IsRegular():
errs = append(errs, lockDownPrivateFile(dir, name, p, fi))
default:
errs = append(errs, fmt.Errorf("%s is not a regular file or a directory (%s): left as it is", p, fi.Mode().Type()))
}
}
return errors.Join(errs...)
}
// lockDownPrivateFile narrows dir/name to at most 0600 through a descriptor,
// provided it is the regular, single-link file want describes.
func lockDownPrivateFile(dir *os.Root, name, shown string, want os.FileInfo) error {
if err := privateSingleLinkFile(shown, want); err != nil {
return err
}
// O_NONBLOCK: should a FIFO replace the file after the Lstat, the open does not
// wait for a writer; the checks below refuse it.
f, err := dir.OpenFile(name, os.O_RDONLY|syscall.O_NOFOLLOW|syscall.O_NONBLOCK|syscall.O_NOCTTY, 0)
if err != nil {
return fmt.Errorf("open %s: %w", shown, err)
}
defer f.Close()
fi, err := f.Stat()
if err != nil {
return fmt.Errorf("stat %s: %w", shown, err)
}
if !os.SameFile(want, fi) {
return fmt.Errorf("%s changed while it was opened: left as it is", shown)
}
if err := privateSingleLinkFile(shown, fi); err != nil {
return err
}
if err := narrowMode(f, 0o600); err != nil {
return fmt.Errorf("chmod %s: %w", shown, err)
}
return nil
}
// privateSingleLinkFile refuses anything but a regular file with a single link:
// a hard link shares its inode, and so its mode, with a file elsewhere.
func privateSingleLinkFile(shown string, fi os.FileInfo) error {
if !fi.Mode().IsRegular() {
return fmt.Errorf("%s is not a regular file (%s): left as it is", shown, fi.Mode().Type())
}
if st, ok := fi.Sys().(*syscall.Stat_t); !ok || st.Nlink != 1 {
return fmt.Errorf("%s is hard-linked: it shares its mode with another file, left as it is", shown)
}
return nil
}
// narrowMode clears the permission bits of f outside allowed, never adding one.
func narrowMode(f *os.File, allowed os.FileMode) error {
fi, err := f.Stat()
if err != nil {
return err
}
perm := fi.Mode().Perm()
if perm&allowed == perm {
return nil
}
return f.Chmod(fi.Mode()&^os.ModePerm | perm&allowed)
}
+149
View File
@@ -0,0 +1,149 @@
//go:build unix
package server
import (
"os"
"path/filepath"
"strings"
"testing"
"time"
)
// Every directory under transcripts and noa keeps at most 0700 and every file
// at most 0600; a narrower mode is never widened; a missing noa is created 0700.
func TestLockDownPrivateDataDirsNarrowsTree(t *testing.T) {
dir := t.TempDir()
tr := filepath.Join(dir, "transcripts")
mkModeDir(t, filepath.Join(tr, "exp1-main"), 0o755)
mkModeDir(t, tr, 0o755)
writeMode(t, filepath.Join(tr, "exp1-worker.jsonl"), 0o644)
writeMode(t, filepath.Join(tr, "exp1-main", "part.jsonl"), 0o664)
writeMode(t, filepath.Join(tr, "script.sh"), 0o755)
writeMode(t, filepath.Join(tr, "read-only.jsonl"), 0o400)
mkModeDir(t, filepath.Join(tr, "narrow"), 0o500)
if err := LockDownPrivateDataDirs(dir); err != nil {
t.Fatal(err)
}
wantMode(t, tr, 0o700)
wantMode(t, filepath.Join(tr, "exp1-main"), 0o700)
wantMode(t, filepath.Join(tr, "exp1-worker.jsonl"), 0o600)
wantMode(t, filepath.Join(tr, "exp1-main", "part.jsonl"), 0o600)
wantMode(t, filepath.Join(tr, "script.sh"), 0o600)
wantMode(t, filepath.Join(tr, "read-only.jsonl"), 0o400)
wantMode(t, filepath.Join(tr, "narrow"), 0o500)
wantMode(t, filepath.Join(dir, "noa"), 0o700)
// A second start finds nothing to change.
if err := LockDownPrivateDataDirs(dir); err != nil {
t.Fatal(err)
}
}
// A symlink or a hard link never leads the chmod outside the tree: transcripts
// or noa replaced by a symlink is refused, and so is a symlinked file, a
// symlinked subdirectory or a hard-linked file inside; the outside modes stay
// as they were, and the rest of the tree is still narrowed.
func TestLockDownPrivateDataDirsRefusesLinks(t *testing.T) {
dir := t.TempDir()
outside := t.TempDir()
outDir := filepath.Join(outside, "dir")
mkModeDir(t, outDir, 0o755)
writeMode(t, filepath.Join(outDir, "secret.jsonl"), 0o644)
outFile := filepath.Join(outside, "file.jsonl")
writeMode(t, outFile, 0o644)
outLinked := filepath.Join(outside, "linked.jsonl")
writeMode(t, outLinked, 0o644)
// transcripts itself is a symlink to an outside directory.
if err := os.Symlink(outDir, filepath.Join(dir, "transcripts")); err != nil {
t.Fatal(err)
}
// noa is real; inside it a symlinked file, a symlinked subdirectory, a
// hard-linked file and an ordinary file.
noa := filepath.Join(dir, "noa")
mkModeDir(t, noa, 0o755)
if err := os.Symlink(outFile, filepath.Join(noa, "link.jsonl")); err != nil {
t.Fatal(err)
}
if err := os.Symlink(outDir, filepath.Join(noa, "linkdir")); err != nil {
t.Fatal(err)
}
if err := os.Link(outLinked, filepath.Join(noa, "hard.jsonl")); err != nil {
t.Fatal(err)
}
writeMode(t, filepath.Join(noa, "own.jsonl"), 0o644)
err := LockDownPrivateDataDirs(dir)
if err == nil {
t.Fatal("links were accepted")
}
for _, want := range []string{"transcripts is not a directory", "link.jsonl is not a regular file or a directory", "linkdir is not a regular file or a directory", "hard.jsonl is hard-linked"} {
if !strings.Contains(err.Error(), want) {
t.Errorf("error %q does not mention %q", err, want)
}
}
wantMode(t, outDir, 0o755)
wantMode(t, filepath.Join(outDir, "secret.jsonl"), 0o644)
wantMode(t, outFile, 0o644)
wantMode(t, outLinked, 0o644)
wantMode(t, noa, 0o700)
wantMode(t, filepath.Join(noa, "own.jsonl"), 0o600)
if fi, err := os.Lstat(filepath.Join(dir, "transcripts")); err != nil || fi.Mode()&os.ModeSymlink == 0 {
t.Errorf("the transcripts symlink was replaced: %v %v", fi, err)
}
}
// While the lockdown runs, a file and a subdirectory under noa keep being
// swapped for symlinks to a file and a directory elsewhere, and back. The
// outside file and directory keep their modes however the swaps land.
func TestLockDownPrivateDataDirsSymlinkSwapRace(t *testing.T) {
if testing.Short() {
t.Skip("long race test")
}
outside := t.TempDir()
victim := filepath.Join(outside, "host-file")
writeMode(t, victim, 0o644)
victimDir := filepath.Join(outside, "host-dir")
mkModeDir(t, victimDir, 0o755)
dir := t.TempDir()
noa := filepath.Join(dir, "noa")
mkModeDir(t, noa, 0o700)
file, sub := filepath.Join(noa, "s.jsonl"), filepath.Join(noa, "sess")
ownFile, ownDir, link := filepath.Join(noa, "own.tmp"), filepath.Join(noa, "own.dir"), filepath.Join(noa, "link.tmp")
race := func() {
_ = os.WriteFile(ownFile, []byte("own"), 0o644)
_ = os.Rename(ownFile, file)
_ = os.Symlink(victim, link)
_ = os.Rename(link, file)
_ = os.Mkdir(ownDir, 0o755)
_ = os.Rename(ownDir, sub)
_ = os.Symlink(victimDir, link)
_ = os.Remove(sub) // the directory, now empty, or nothing
_ = os.Rename(link, sub)
_ = os.Remove(sub)
}
stop, done := make(chan struct{}), make(chan struct{})
go func() {
defer close(done)
for {
select {
case <-stop:
return
default:
}
race()
}
}()
start := time.Now()
iter := 0
for ; iter < keyDirRaceIter && time.Since(start) < keyDirRaceBudget; iter++ {
_ = LockDownPrivateDataDirs(dir)
if !wantUntouched(t, victim, 0o644, "key") || !wantUntouched(t, victimDir, 0o755, "") {
break
}
}
close(stop)
<-done
t.Logf("%d iterations in %v, outside file and directory unchanged", iter, time.Since(start).Round(time.Millisecond))
}
+5 -5
View File
@@ -7,7 +7,7 @@ import (
)
func TestValidateArgvRuleReq(t *testing.T) {
base := interceptRuleReq{Name: "r", MatchTarget: "tool_input", MatchType: "argv", Pattern: `["nmap"]`, Action: "allow"}
base := interceptRuleReq{Name: "r", MatchTarget: "tool_input", MatchType: "argv", Pattern: `["whois"]`, Action: "allow"}
if err := validateInterceptRuleReq(base); err != nil {
t.Fatalf("valid argv rule refused: %v", err)
}
@@ -15,8 +15,8 @@ func TestValidateArgvRuleReq(t *testing.T) {
"tool_name target": func(r *interceptRuleReq) { r.MatchTarget = "tool_name" },
"empty pattern": func(r *interceptRuleReq) { r.Pattern = "" },
"empty token": func(r *interceptRuleReq) { r.Pattern = `["git",""]` },
"flag token": func(r *interceptRuleReq) { r.Pattern = `["nmap","-C"]` },
"metacharacter": func(r *interceptRuleReq) { r.Pattern = `["nmap;id"]` },
"flag token": func(r *interceptRuleReq) { r.Pattern = `["whois","-C"]` },
"metacharacter": func(r *interceptRuleReq) { r.Pattern = `["whois;id"]` },
"nine tokens": func(r *interceptRuleReq) { r.Pattern = `["a","b","c","d","e","f","g","h","i"]` },
"not an array": func(r *interceptRuleReq) { r.Pattern = `git push` },
} {
@@ -31,7 +31,7 @@ func TestValidateArgvRuleReq(t *testing.T) {
// The manual rule form refuses an argv allow rule for a denylisted program,
// with the message of the "always allow" endpoint; deny and ask stay creatable.
func TestValidateArgvAllowDenylist(t *testing.T) {
for _, pattern := range []string{`["python"]`, `["python3.11"]`, `["/usr/bin/env"]`, `["find"]`, `["docker","run"]`, `["git","push"]`, `["cmake"]`} {
for _, pattern := range []string{`["python"]`, `["python3.11"]`, `["/usr/bin/env"]`, `["find"]`, `["docker","run"]`, `["git","push"]`, `["cmake"]`, `["nmap"]`, `["sqlmap"]`, `["sqlite3"]`} {
req := interceptRuleReq{Name: "r", MatchTarget: "tool_input", MatchType: "argv", Pattern: pattern, Action: "allow"}
tokens, _ := intercept.ParseArgvPattern(pattern)
want := intercept.CheckArgvAllow(tokens)
@@ -45,7 +45,7 @@ func TestValidateArgvAllowDenylist(t *testing.T) {
}
}
}
for _, pattern := range []string{`["nmap"]`, `["curl"]`} {
for _, pattern := range []string{`["whois"]`, `["curl"]`} {
req := interceptRuleReq{Name: "r", MatchTarget: "tool_input", MatchType: "argv", Pattern: pattern, Action: "allow"}
if err := validateInterceptRuleReq(req); err != nil {
t.Errorf("allow %s refused: %v", pattern, err)
+19
View File
@@ -25,6 +25,7 @@ import (
"github.com/Autumn-27/artex/enrich"
"github.com/Autumn-27/artex/guard"
"github.com/Autumn-27/artex/intercept"
"github.com/Autumn-27/artex/sandbox"
"github.com/Autumn-27/artex/traffic"
"github.com/Autumn-27/artex/traffic/rewrite"
actool "github.com/Autumn-27/norma/tool"
@@ -416,6 +417,8 @@ func (m *Manager) Enrich() *enrich.Engine { return m.enrich }
// NewManager connects to PostgreSQL and, if proxyAddr is non-empty, starts the
// traffic-recording proxy. PostgreSQL is required (it is the single data source).
func NewManager(dir, proxyAddr string) (*Manager, error) {
// Before any agent or tool exists (datadir_private.go).
disableNormaRipgrepInstall()
cfg, err := config.Load()
if err != nil {
return nil, err
@@ -432,6 +435,13 @@ func NewManager(dir, proxyAddr string) (*Manager, error) {
if err := os.MkdirAll(dir, 0o755); err != nil {
return nil, err
}
// cmd/artex runs this before the isolation self-test and fails the start on
// an error unless the operator opts out (ARTEX_ALLOW_UNISOLATED=1), as for the
// key directory. Here it covers every other way a Manager is built, and only
// logs: the start decision is made there.
if err := LockDownPrivateDataDirs(dir); err != nil {
log.Printf("[data] keep transcripts and noa owner-only: %v", err)
}
dsn, source, err := pgdb.DSN()
if err != nil {
return nil, err
@@ -582,6 +592,15 @@ func NewManager(dir, proxyAddr string) (*Manager, error) {
}
}
m.enrich = enrich.New(m.assets, m.ProxyAddr, 4)
// Panel-side asset probes are agent-triggered: while the sandbox is required,
// they leave through the task's sandbox egress policy, as WebFetch and custom
// HTTP tools do, instead of the recording proxy that has no destination check.
m.enrich.SetSandboxPolicy(func(ctx context.Context) *sandbox.EgressPolicy {
if !agent.SandboxRequired() {
return nil
}
return agent.SandboxEgressPolicy(ctx)
})
// Reconcile the seeded browser MCP with the persisted capture state, so a
// restart with capture already on keeps Playwright routed through the proxy.
m.syncBrowserMCPProxy()
+75
View File
@@ -0,0 +1,75 @@
//go:build unix
package server
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"github.com/Autumn-27/norma/tool"
)
const normaRipgrepChildEnv = "ARTEX_TEST_NORMA_RIPGREP_CHILD"
// Norma's Grep never installs ripgrep once a manager exists, whatever
// NORMA_RIPGREP_NO_INSTALL held before: unset, empty or blank. Norma resolves
// ripgrep once per process, so each case runs in a fresh test process whose
// PATH holds only a fake npm that records its arguments: no rg, no real npm,
// and the tests run without a network.
func TestNewManagerStopsNormaRipgrepInstall(t *testing.T) {
if os.Getenv(normaRipgrepChildEnv) == "1" {
normaRipgrepChild(t)
return
}
for name, value := range map[string]*string{"unset": nil, "empty": new(string), "blank": normaStrPtr(" ")} {
t.Run(name, func(t *testing.T) {
bin := t.TempDir()
record := filepath.Join(t.TempDir(), "npm-calls")
npm := "#!/bin/sh\necho \"$*\" >> " + record + "\nexit 1\n"
if err := os.WriteFile(filepath.Join(bin, "npm"), []byte(npm), 0o755); err != nil {
t.Fatal(err)
}
var env []string
for _, kv := range os.Environ() {
k, _, _ := strings.Cut(kv, "=")
switch k {
case "PATH", "NORMA_RIPGREP_NO_INSTALL", "NORMA_DISABLE_RIPGREP", "ARTEX_PG_DSN":
continue
}
env = append(env, kv)
}
// An unreachable database: the child's TestMain and NewManager give up
// on it at once instead of waiting for this suite's advisory lock.
env = append(env, "PATH="+bin, normaRipgrepChildEnv+"=1",
"ARTEX_PG_DSN=postgres://artex@127.0.0.1:1/none?sslmode=disable&connect_timeout=2")
if value != nil {
env = append(env, "NORMA_RIPGREP_NO_INSTALL="+*value)
}
cmd := exec.Command(os.Args[0], "-test.run=^TestNewManagerStopsNormaRipgrepInstall$", "-test.count=1")
cmd.Env = env
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("child: %v\n%s", err, out)
}
if !strings.Contains(string(out), `RG env="1" path=""`) {
t.Errorf("child did not end with the install disabled and no ripgrep:\n%s", out)
}
if calls, err := os.ReadFile(record); err == nil {
t.Errorf("npm was run: %q", calls)
}
})
}
}
func normaStrPtr(s string) *string { return &s }
// normaRipgrepChild builds a manager, then resolves ripgrep the way Norma's Grep
// does on its first call.
func normaRipgrepChild(t *testing.T) {
newManagerAnyDB(t.TempDir())
fmt.Printf("RG env=%q path=%q\n", os.Getenv("NORMA_RIPGREP_NO_INSTALL"), tool.RipgrepPath())
}
+64 -6
View File
@@ -28,6 +28,11 @@ const (
maxArchiveBytes = int64(1 << 47) // 128 TiB safety ceiling for corrupt headers.
)
// taskArchiveBeforeOpenHook is an optional test hook invoked with the payload-relative
// name of each regular file immediately before writeTaskArchivePackage opens it,
// allowing deterministic TOCTOU regression tests (always nil in production).
var taskArchiveBeforeOpenHook func(name string)
type archiveFileMove struct {
Source string `json:"source"`
Relative string `json:"relative"`
@@ -700,15 +705,24 @@ func writeTaskArchivePackage(path, payloadDir string, snapshot *pgdb.TaskArchive
if err != nil {
return 0, 0, "", err
}
// Code running as the executor uid can keep a working directory inside the moved run
// directory and swap a directory for a symlink after it was listed. Walk and open
// through a root anchored at the payload so no lookup can leave it, and check that
// each opened file is the one the walk saw.
root, err := os.OpenRoot(payloadDir)
if err != nil {
return 0, 0, "", err
}
defer root.Close()
tarWriter := tar.NewWriter(encoder)
walkErr := filepath.WalkDir(payloadDir, func(current string, entry fs.DirEntry, walkErr error) error {
walkErr := walkTaskArchiveRoot(root, ".", func(relative string, entry fs.DirEntry, walkErr error) error {
if walkErr != nil {
return walkErr
}
relative, err := filepath.Rel(payloadDir, current)
if err != nil || relative == "." {
return err
if relative == "." {
return nil
}
current := filepath.Join(payloadDir, filepath.FromSlash(relative))
info, err := entry.Info()
if err != nil {
return err
@@ -730,7 +744,7 @@ func writeTaskArchivePackage(path, payloadDir string, snapshot *pgdb.TaskArchive
if err != nil {
return err
}
header.Name = filepath.ToSlash(relative)
header.Name = relative
if err := tarWriter.WriteHeader(header); err != nil {
return err
}
@@ -738,10 +752,21 @@ func writeTaskArchivePackage(path, payloadDir string, snapshot *pgdb.TaskArchive
return nil
}
originalSize += info.Size()
input, err := os.Open(current)
if taskArchiveBeforeOpenHook != nil {
taskArchiveBeforeOpenHook(relative)
}
input, err := root.Open(filepath.FromSlash(relative))
if err != nil {
return err
}
opened, err := input.Stat()
if err == nil && (!opened.Mode().IsRegular() || !os.SameFile(info, opened)) {
err = fmt.Errorf("task archive entry %s changed while it was packed", relative)
}
if err != nil {
_ = input.Close()
return err
}
_, copyErr := io.Copy(tarWriter, input)
closeErr := input.Close()
return errors.Join(copyErr, closeErr)
@@ -780,6 +805,39 @@ func writeTaskArchivePackage(path, payloadDir string, snapshot *pgdb.TaskArchive
return originalSize, compressedSize, checksum, nil
}
// walkTaskArchiveRoot walks dir inside root like fs.WalkDir, in lexical order, with
// slash-separated names. It does not go through root.FS(), which refuses names that
// are not valid UTF-8, so a run tree holding such a file can still be archived as
// before. Entries come from ReadDir on a handle opened in root, so their FileInfo is
// read relative to that handle, never through a path that could leave the root.
func walkTaskArchiveRoot(root *os.Root, dir string, fn fs.WalkDirFunc) error {
handle, err := root.Open(filepath.FromSlash(dir))
if err != nil {
return fn(dir, nil, err)
}
entries, err := handle.ReadDir(-1)
_ = handle.Close()
if err != nil {
return fn(dir, nil, err)
}
slices.SortFunc(entries, func(a, b fs.DirEntry) int { return strings.Compare(a.Name(), b.Name()) })
for _, entry := range entries {
name := entry.Name()
if dir != "." {
name = dir + "/" + name
}
if err := fn(name, entry, nil); err != nil {
return err
}
if entry.IsDir() {
if err := walkTaskArchiveRoot(root, name, fn); err != nil {
return err
}
}
}
return nil
}
func extractTaskArchivePackage(path, expectedSHA, destination string) error {
file, err := os.Open(path)
if err != nil {
+339
View File
@@ -0,0 +1,339 @@
//go:build unix
package server
import (
"archive/tar"
"bytes"
"errors"
"io"
"os"
"path/filepath"
"strings"
"testing"
pgdb "github.com/Autumn-27/artex/db"
"github.com/klauspost/compress/zstd"
)
const archiveOutsideSecret = "root-only secret outside the payload"
// sameSizeAsSecret returns a filler as long as archiveOutsideSecret, so a tar header
// taken from the listed file still matches the bytes read through a swapped path.
func sameSizeAsSecret(fill string) string {
return strings.Repeat(fill, len(archiveOutsideSecret))
}
// archiveSymlinkFixture builds a payload with main/zzz/{a_big,jwt.key} and, next to
// the payload, an outside directory holding jwt.key with archiveOutsideSecret.
func archiveSymlinkFixture(t *testing.T) (payload, outside string) {
t.Helper()
base := t.TempDir()
payload = filepath.Join(base, "payload")
outside = filepath.Join(base, "keys")
for path, body := range map[string]string{
filepath.Join(payload, "main", "zzz", "a_big"): "earlier sibling",
filepath.Join(payload, "main", "zzz", "jwt.key"): sameSizeAsSecret("d"),
filepath.Join(outside, "jwt.key"): archiveOutsideSecret,
} {
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
t.Fatal(err)
}
}
return payload, outside
}
// swapBeforeOpen runs swap once, right before the packer opens the file named at.
func swapBeforeOpen(t *testing.T, at string, swap func() error) {
t.Helper()
taskArchiveBeforeOpenHook = func(name string) {
if name != at {
return
}
taskArchiveBeforeOpenHook = nil
if err := swap(); err != nil {
t.Errorf("swap: %v", err)
}
}
t.Cleanup(func() { taskArchiveBeforeOpenHook = nil })
}
// readArchiveEntries returns the regular file contents of a task archive by name.
func readArchiveEntries(t *testing.T, path string) map[string]string {
t.Helper()
file, err := os.Open(path)
if err != nil {
t.Fatal(err)
}
defer file.Close()
decoder, err := zstd.NewReader(file)
if err != nil {
t.Fatal(err)
}
defer decoder.Close()
entries := map[string]string{}
tr := tar.NewReader(decoder)
for {
header, err := tr.Next()
if errors.Is(err, io.EOF) {
return entries
}
if err != nil {
t.Fatal(err)
}
body, err := io.ReadAll(tr)
if err != nil {
t.Fatal(err)
}
entries[header.Name] = string(body)
}
}
// packSwapped writes the archive and fails the test if the outside secret, or the
// content of a file other than the one the walk listed, reached it.
func packSwapped(t *testing.T, payload string, unexpected string) {
t.Helper()
archivePath := filepath.Join(filepath.Dir(payload), "archive.tar.zst")
snapshot := &pgdb.TaskArchiveSnapshot{FormatVersion: pgdb.TaskArchiveFormatVersion, TaskID: 42}
_, _, _, err := writeTaskArchivePackage(archivePath, payload, snapshot)
if err != nil {
t.Logf("refused: %v", err)
return
}
for name, body := range readArchiveEntries(t, archivePath) {
if strings.Contains(body, unexpected) {
t.Fatalf("archive entry %s holds %q, read through a swapped path", name, body)
}
}
t.Fatal("the archive was written although a path changed under the packer")
}
// A directory swapped for a symlink to an outside directory after it was listed and
// an earlier child packed: its later children must not be read through the link.
func TestTaskArchivePackageDirSwappedForOutsideSymlink(t *testing.T) {
payload, outside := archiveSymlinkFixture(t)
dir := filepath.Join(payload, "main", "zzz")
swapBeforeOpen(t, "main/zzz/jwt.key", func() error {
if err := os.Rename(dir, dir+".original"); err != nil {
return err
}
return os.Symlink(outside, dir)
})
packSwapped(t, payload, archiveOutsideSecret)
}
// A regular file swapped for a symlink to an outside file after it was listed.
func TestTaskArchivePackageFileSwappedForOutsideSymlink(t *testing.T) {
payload, outside := archiveSymlinkFixture(t)
target := filepath.Join(payload, "main", "zzz", "jwt.key")
swapBeforeOpen(t, "main/zzz/jwt.key", func() error {
if err := os.Remove(target); err != nil {
return err
}
return os.Symlink(filepath.Join(outside, "jwt.key"), target)
})
packSwapped(t, payload, archiveOutsideSecret)
}
// A directory swapped for a relative symlink climbing out with ../ segments.
func TestTaskArchivePackageDirSwappedForDotDotSymlink(t *testing.T) {
payload, _ := archiveSymlinkFixture(t)
dir := filepath.Join(payload, "main", "zzz")
swapBeforeOpen(t, "main/zzz/jwt.key", func() error {
if err := os.Rename(dir, dir+".original"); err != nil {
return err
}
return os.Symlink("../../keys", dir)
})
packSwapped(t, payload, archiveOutsideSecret)
}
// A directory swapped for a symlink after its parent was listed but before the walk
// descends into it (outside and ../ targets): listing its children must not leave the
// payload either. The same-file check cannot catch this case, because the children
// would be listed and opened through the same link.
func TestTaskArchivePackageDirSwappedBeforeDescent(t *testing.T) {
for name, link := range map[string]string{"outside": "", "dotdot": "../../keys"} {
t.Run(name, func(t *testing.T) {
payload, outside := archiveSymlinkFixture(t)
if err := os.WriteFile(filepath.Join(payload, "main", "a_first"), []byte("earlier file"), 0o600); err != nil {
t.Fatal(err)
}
target := link
if target == "" {
target = outside
}
dir := filepath.Join(payload, "main", "zzz")
swapBeforeOpen(t, "main/a_first", func() error {
if err := os.Rename(dir, dir+".original"); err != nil {
return err
}
return os.Symlink(target, dir)
})
packSwapped(t, payload, archiveOutsideSecret)
})
}
}
// A directory swapped for a symlink that stays inside the payload: the file opened
// is not the one the walk listed, so it is refused rather than packed under the
// listed name.
func TestTaskArchivePackageDirSwappedForInsideSymlink(t *testing.T) {
payload, _ := archiveSymlinkFixture(t)
other := filepath.Join(payload, "main", "other")
if err := os.MkdirAll(other, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(other, "jwt.key"), []byte(sameSizeAsSecret("o")), 0o600); err != nil {
t.Fatal(err)
}
dir := filepath.Join(payload, "main", "zzz")
swapBeforeOpen(t, "main/zzz/jwt.key", func() error {
if err := os.Rename(dir, dir+".original"); err != nil {
return err
}
return os.Symlink("other", dir)
})
archivePath := filepath.Join(filepath.Dir(payload), "archive.tar.zst")
snapshot := &pgdb.TaskArchiveSnapshot{FormatVersion: pgdb.TaskArchiveFormatVersion, TaskID: 42}
_, _, _, err := writeTaskArchivePackage(archivePath, payload, snapshot)
if err == nil {
got := readArchiveEntries(t, archivePath)["main/zzz/jwt.key"]
t.Fatalf("archive written with main/zzz/jwt.key = %q after the directory was swapped", got)
}
t.Logf("refused: %v", err)
}
// Symlinks already present to an outside file and an outside directory are skipped:
// neither the file nor the directory's children are packed.
func TestTaskArchivePackageSkipsOutsideSymlinks(t *testing.T) {
payload, outside := archiveSymlinkFixture(t)
if err := os.Symlink(filepath.Join(outside, "jwt.key"), filepath.Join(payload, "main", "key-link")); err != nil {
t.Fatal(err)
}
if err := os.Symlink(outside, filepath.Join(payload, "main", "keys-link")); err != nil {
t.Fatal(err)
}
archivePath := filepath.Join(filepath.Dir(payload), "archive.tar.zst")
snapshot := &pgdb.TaskArchiveSnapshot{FormatVersion: pgdb.TaskArchiveFormatVersion, TaskID: 42}
if _, _, _, err := writeTaskArchivePackage(archivePath, payload, snapshot); err != nil {
t.Fatalf("archive should skip symlinks, not fail: %v", err)
}
entries := readArchiveEntries(t, archivePath)
for name, body := range entries {
if strings.Contains(body, archiveOutsideSecret) || strings.HasPrefix(name, "main/key") {
t.Fatalf("outside symlink packed as %s = %q", name, body)
}
}
if entries["main/zzz/jwt.key"] != sameSizeAsSecret("d") {
t.Fatalf("regular file not packed: %q", entries["main/zzz/jwt.key"])
}
}
// File and directory names that are not valid UTF-8 are packed as before: a run tree
// may hold them (tool output, extracted target data), and refusing them would make
// the task impossible to archive.
func TestTaskArchivePackageKeepsNonUTF8Names(t *testing.T) {
payload, _ := archiveSymlinkFixture(t)
dir := filepath.Join(payload, "main", "\xfe-dir")
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
for _, path := range []string{filepath.Join(payload, "main", "\xff\xfe.txt"), filepath.Join(dir, "inner.txt")} {
if err := os.WriteFile(path, []byte("body"), 0o600); err != nil {
t.Fatal(err)
}
}
archivePath := filepath.Join(filepath.Dir(payload), "archive.tar.zst")
snapshot := &pgdb.TaskArchiveSnapshot{FormatVersion: pgdb.TaskArchiveFormatVersion, TaskID: 42}
if _, _, _, err := writeTaskArchivePackage(archivePath, payload, snapshot); err != nil {
t.Fatalf("archive with non-UTF-8 names failed: %v", err)
}
entries := readArchiveEntries(t, archivePath)
for _, name := range []string{"main/\xff\xfe.txt", "main/\xfe-dir/inner.txt"} {
if entries[name] != "body" {
t.Fatalf("entry %q = %q, want body", name, entries[name])
}
}
}
// Restoring never creates a link or writes outside the destination: a symlink or hard
// link entry followed by a regular entry written through it, and nested ../ names.
func TestTaskArchiveExtractRefusesLinksAndNestedTraversal(t *testing.T) {
type entry struct {
header tar.Header
body string
}
reg := func(name string) entry {
return entry{tar.Header{Name: name, Mode: 0o600, Size: 5, Typeflag: tar.TypeReg}, "pwned"}
}
cases := map[string][]entry{
"symlink then write through it": {
{header: tar.Header{Name: "link", Linkname: "OUTSIDE", Typeflag: tar.TypeSymlink, Mode: 0o777}},
reg("link/pwned"),
},
"hard link then write through it": {
{header: tar.Header{Name: "link", Linkname: "OUTSIDE/pwned", Typeflag: tar.TypeLink, Mode: 0o600}},
reg("link"),
},
"nested dotdot": {reg("a/../../pwned")},
"deep nested dotdot": {reg("a/b/../../../pwned")},
"dotdot after directory": {{header: tar.Header{Name: "a/", Typeflag: tar.TypeDir, Mode: 0o700}}, reg("a/../../pwned")},
}
for name, entries := range cases {
t.Run(name, func(t *testing.T) {
base := t.TempDir()
outside := filepath.Join(base, "outside")
if err := os.MkdirAll(outside, 0o755); err != nil {
t.Fatal(err)
}
var compressed bytes.Buffer
encoder, err := zstd.NewWriter(&compressed)
if err != nil {
t.Fatal(err)
}
tw := tar.NewWriter(encoder)
for _, e := range entries {
header := e.header
header.Linkname = strings.ReplaceAll(header.Linkname, "OUTSIDE", outside)
if err := tw.WriteHeader(&header); err != nil {
t.Fatal(err)
}
if e.body != "" {
if _, err := tw.Write([]byte(e.body)); err != nil {
t.Fatal(err)
}
}
}
if err := tw.Close(); err != nil {
t.Fatal(err)
}
if err := encoder.Close(); err != nil {
t.Fatal(err)
}
path := filepath.Join(base, "malicious.tar.zst")
if err := os.WriteFile(path, compressed.Bytes(), 0o600); err != nil {
t.Fatal(err)
}
destination := filepath.Join(base, "restore", "dest")
if err := extractTaskArchivePackage(path, "", destination); err == nil {
t.Fatal("unsafe archive was accepted")
}
for _, escaped := range []string{
filepath.Join(outside, "pwned"),
filepath.Join(base, "restore", "pwned"),
filepath.Join(base, "pwned"),
} {
if _, err := os.Lstat(escaped); !os.IsNotExist(err) {
t.Fatalf("extraction wrote %s: %v", escaped, err)
}
}
if _, err := os.Lstat(filepath.Join(destination, "link")); !os.IsNotExist(err) {
t.Fatalf("extraction created a link entry: %v", err)
}
})
}
}