Compare commits

...
Author SHA1 Message Date
BaaRai 49b9421ed8 Gate the custom HTTP tool's own proxy
With the target gate on, only the tool URL was checked and the proxy in the
tool's proxy field was dialled without a check, so an approved target could
be fetched through any host and port. Read the proxy as a target, as a proxy
named on a Bash command line is: the call waits for its approval, the
request records the proxy without credentials, and the proxy is dialled
through the pinned dialer. The recording and global proxies, required mode
and the gate-off paths are unchanged.
2026-12-04 01:06:32 +01:00
BaaRai 3286e2009c Merge pull request #955 from BaaRai/fix/rm-rule-backslash
fix(intercept): match text deny rules on Bash words as the shell decodes them
2026-12-04 01:06:23 +01:00
BaaRai d92a9e51e2 Match text deny rules on Bash words as the shell decodes them
Regex and string intercept rules were matched on the raw tool input,
but Bash removes quotes and backslashes and decodes $'...' before it
runs a command: r\m -rf, r''m -rf, rm -r''f, rm -R -$'f' and a
backslash-newline inside a word all ran rm -rf while the built-in
recursive-force-delete rule did not match, and so did rm -rf on the
line after another command, because the JSON escape of the newline
glued an "n" to the command name.

A deny or ask rule on a Bash call now also meets the command decoded
with the argv word decoder, the simple commands joined by "; ". Allow
rules are still matched on the text as written. The word decoder now
decodes ANSI-C strings instead of treating them as opaque, which also
lets argv deny and ask rules meet $'nmap' and bash -c $'nmap x'.
2026-12-04 00:43:02 +01:00
BaaRai dcffc35233 Merge pull request #954 from BaaRai/fix/asset-block-ipv6-forms
fix(db): match fuzzy_ip asset rules on canonical IP addresses
2026-12-04 00:42:50 +01:00
BaaRai 44913c1c63 Match fuzzy_ip asset rules on canonical IP addresses
A fuzzy_ip rule compared the raw strings, so a block rule "::1" let
insert_assets register "0:0:0:0:0:0:0:1" or "::0001", and a rule
written expanded missed the compressed address. Match each candidate
as written and in its canonical form, and canonicalize a pattern that
is a whole address; a partial pattern keeps its substring meaning.

cidr rules now also match a zone-qualified address, and a
zone-qualified IPv6 URL host is classified as an IP in insert_assets
and for stored assets, so exact_ip, fuzzy_ip and cidr rules see it.
2026-12-03 23:25:01 +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
31 changed files with 2002 additions and 151 deletions
+8
View File
@@ -6,6 +6,14 @@ All notable changes to this project are documented in this file. The format is b
### Security
- **A custom HTTP tool's own proxy goes through the target gate.** With the gate on, only the tool URL was checked: the proxy in the tool's `proxy` field was dialled without any check, so a tool whose target was approved could send its request to any host and port, loopback and private addresses included, through a proxy nobody approved. With the gate on, the proxy's host and port are now a target like the URL, as a proxy named on a Bash command line is: the call waits for an approval or is refused, the approval request shows the proxy without its credentials, and the connection to the proxy goes through the gate's dialer. That connection is checked and dialled as a direct hop: the approval pins the addresses it resolved rather than the name alone, so a proxy name that later answers another address is refused instead of being dialled unpinned. The recording and global proxies (`use_recording_proxy`) are unchanged. `ARTEX_SANDBOX=required` is unchanged: the sandbox egress policy already checks the proxy connection. With the gate off (no task scope, a task with the gate off, or the custom tool test endpoint) the proxy is not checked, as before, and neither is the tool URL, which can already name a loopback or private address in that mode. Behaviour change: with the gate on, a tool that uses its own proxy now raises an approval request for the proxy host and port (or is refused when none is granted) until the proxy is approved for the task.
- **Text deny and ask rules see a Bash command as the shell decodes it.** Regex and string intercept rules on `tool_input` were matched on the raw text, but Bash removes quotes and backslashes and decodes `$'...'` before it runs a command, so `r\m -rf ./x`, `r''m -rf`, `"r"m -rf`, `/bin/r\m -rf`, `rm -r''f`, `rm -R -$'f'` or a backslash-newline inside a word ran `rm -rf` while the built-in recursive-force-delete rule did not match; so did `rm -rf ./x` on the line after another command, since the input encodes the newline as `\n` and its `n` hid the word boundary. A deny or ask rule on a Bash call now also meets the command decoded with the word decoder argv rules use: the simple commands joined by `; `, every word with its quotes, backslash escapes and line continuations removed, a word with an expansion kept as written. This covers every built-in regex rule and operator deny and ask rules; allow rules are still matched on the text as written only. The word decoder now also decodes ANSI-C strings (`$'r\x6d'`), so argv deny and ask rules meet `$'nmap'` and `bash -c $'nmap x'` too.
- **`fuzzy_ip` asset rules and the URL host check match every spelling of an IP address.** `fuzzy_ip` compared the raw strings, so a block rule `::1` let `insert_assets` register `0:0:0:0:0:0:0:1` or `::0001`, and a rule written expanded missed the compressed form. The rule is now also matched against the canonical form of each address (zeros compressed, lower case, IPv4-mapped addresses unmapped, zone dropped), and a pattern that is a whole address is canonicalized too; a partial pattern such as `10.0.` keeps its substring meaning. `cidr` rules now match a zone-qualified address (`fe80::1%eth0`), and a zone-qualified IPv6 URL host (`http://[fe80::1%25eth0]/`) is classified as an IP instead of a domain, so `exact_ip`, `fuzzy_ip` and `cidr` rules see it, in `insert_assets` and for stored assets.
- **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.
+58
View File
@@ -496,3 +496,61 @@ func TestInsertAssetsRefusesWhenInterceptRulesUnavailable(t *testing.T) {
}
}
}
// TestAssetInterceptCandidatesIPv6URLHost: a URL host that is an IPv6 literal
// in any spelling, zone-qualified or not, is an IP candidate, so exact_ip,
// fuzzy_ip and cidr rules see it.
func TestAssetInterceptCandidatesIPv6URLHost(t *testing.T) {
for _, u := range []string{"http://[fe80::1%25eth0]:8080/x", "http://[FE80:0:0:0:0:0:0:1]/"} {
_, ips, _ := assetInterceptCandidates(assetInputItem{Type: "service", URL: u})
for _, r := range []db.AssetInterceptRule{
{Kind: "exact_ip", Pattern: "fe80::1", Enabled: true},
{Kind: "fuzzy_ip", Pattern: "fe80::1", Enabled: true},
{Kind: "cidr", Pattern: "fe80::/10", Enabled: true},
} {
if d := db.EvaluateAssetGate([]db.AssetInterceptRule{r}, nil, nil, ips, nil); d.Allowed {
t.Fatalf("URL %s: %s rule %s did not block, ips=%v", u, r.Kind, r.Pattern, ips)
}
}
}
}
// TestInsertAssetsFuzzyIPRuleBlocksIPv6Spellings: a fuzzy_ip block rule holds
// for every spelling of the address it names, through the insert_assets
// handler, both for an ip asset and for a URL host.
func TestInsertAssetsFuzzyIPRuleBlocksIPv6Spellings(t *testing.T) {
d := testDB(t)
defer d.Close()
rule, err := d.CreateAssetInterceptRule("fuzzy_ip", "2001:db8:5e::1", "ipv6 spelling test", true)
if err != nil {
t.Fatal(err)
}
defer d.DeleteAssetInterceptRule(rule.ID)
defer d.Exec(`DELETE FROM assets WHERE ip ILIKE '2001:%db8:%5e:%' OR url ILIKE 'http://[2001:%db8:%5e:%'`)
ts := NewToolSet(nil, "")
ts.SetAssetStore(d.Assets(), d.Companies())
items := []any{
map[string]any{"type": "ip", "ip": "2001:db8:5e::1"},
map[string]any{"type": "ip", "ip": "2001:db8:5e:0:0:0:0:1"},
map[string]any{"type": "ip", "ip": "2001:0db8:005e:0000:0000:0000:0000:0001"},
map[string]any{"type": "ip", "ip": "2001:DB8:5E::0001"},
map[string]any{"type": "service", "url": "http://[2001:db8:5e:0::1]:8080/"},
map[string]any{"type": "service", "url": "http://[2001:db8:5e:0:0:0:0:1%25eth0]/"},
}
out := callInsertAssets(t, ts, map[string]any{"assets": items})
if results, _ := out["results"].([]any); len(results) != 0 {
t.Fatalf("results=%v, want every spelling blocked", results)
}
errs, _ := out["errors"].([]any)
if len(errs) != len(items) {
t.Fatalf("errors=%v, want one per item", errs)
}
for _, e := range errs {
entry, _ := e.(map[string]any)
if msg, _ := entry["error"].(string); !strings.Contains(msg, "insertion forbidden") {
t.Fatalf("item %v not refused by the block rule: %q", entry["index"], msg)
}
}
}
+2 -2
View File
@@ -5,7 +5,6 @@ import (
"encoding/json"
"fmt"
"log/slog"
"net"
"net/url"
"strconv"
"strings"
@@ -34,7 +33,8 @@ func assetInterceptCandidates(item assetInputItem) (domains, ips, urls []string)
if item.URL != "" {
if u, err := url.Parse(item.URL); err == nil {
if h := u.Hostname(); h != "" {
if net.ParseIP(h) != nil {
// A zone-qualified IPv6 host is an IP too; net.ParseIP refuses it.
if _, ok := db.CanonicalInterceptIP(h); ok {
add(&ips, h)
} else {
add(&domains, h)
+17 -3
View File
@@ -279,9 +279,22 @@ func matchOne(r AssetInterceptRule, domains, ips, urls []string) (string, bool)
}
}
case "fuzzy_ip":
// A substring of the address as written and of its canonical form, so
// "0:0:0:0:0:0:0:1" and "::0001" meet a "::1" rule. A pattern that is a
// whole address is canonicalized too; a partial one ("10.0.") is not.
lp := strings.ToLower(p)
if c, ok := CanonicalInterceptIP(p); ok {
lp = c
}
for _, ip := range ips {
if ip != "" && strings.Contains(strings.ToLower(strings.TrimSpace(ip)), lp) {
raw := strings.ToLower(strings.TrimSpace(ip))
if raw == "" {
continue
}
if strings.Contains(raw, lp) {
return ip, true
}
if c, ok := CanonicalInterceptIP(raw); ok && strings.Contains(c, lp) {
return ip, true
}
}
@@ -298,7 +311,8 @@ func matchOne(r AssetInterceptRule, domains, ips, urls []string) (string, bool)
return "", false
}
for _, ip := range ips {
if pip := net.ParseIP(strings.TrimSpace(ip)); pip != nil && ipnet.Contains(pip) {
// Canonical first: net.ParseIP refuses a zone-qualified address.
if c, ok := CanonicalInterceptIP(ip); ok && ipnet.Contains(net.ParseIP(c)) {
return ip, true
}
}
@@ -340,7 +354,7 @@ func (a *Asset) interceptCandidates() (domains, ips, urls []string) {
if a.URL != "" {
if u, err := url.Parse(a.URL); err == nil {
if h := u.Hostname(); h != "" {
if net.ParseIP(h) != nil {
if _, ok := CanonicalInterceptIP(h); ok {
add(&ips, h)
} else {
add(&domains, h)
+31
View File
@@ -71,10 +71,30 @@ func TestMatchAssetInterceptRules(t *testing.T) {
nil, []string{"fe80::1"}, nil, true, "fe80::1"},
{"fuzzy IP prefix hit", []AssetInterceptRule{rule("fuzzy_ip", "203.0.113.", true)},
nil, []string{"203.0.113.99"}, nil, true, "203.0.113.99"},
// Another spelling of the same address must not slip past a fuzzy rule,
// whichever side carries it.
{"fuzzy IP fully expanded IPv6 target", []AssetInterceptRule{rule("fuzzy_ip", "::1", true)},
nil, []string{"0:0:0:0:0:0:0:1"}, nil, true, "0:0:0:0:0:0:0:1"},
{"fuzzy IP zero-padded IPv6 target", []AssetInterceptRule{rule("fuzzy_ip", "::1", true)},
nil, []string{"::0001"}, nil, true, "::0001"},
{"fuzzy IP padded uppercase IPv6 target", []AssetInterceptRule{rule("fuzzy_ip", "2001:db8::", true)},
nil, []string{"2001:0DB8:0000:0000:0000:0000:0000:0005"}, nil, true, "2001:0DB8:0000:0000:0000:0000:0000:0005"},
{"fuzzy IP fully expanded IPv6 rule", []AssetInterceptRule{rule("fuzzy_ip", "0:0:0:0:0:0:0:1", true)},
nil, []string{"::1"}, nil, true, "::1"},
{"fuzzy IP mapped IPv4 target", []AssetInterceptRule{rule("fuzzy_ip", "203.0.113.5", true)},
nil, []string{"::ffff:cb00:7105"}, nil, true, "::ffff:cb00:7105"},
{"fuzzy IP zone-qualified target", []AssetInterceptRule{rule("fuzzy_ip", "fe80::1", true)},
nil, []string{"FE80:0:0:0:0:0:0:1%eth0"}, nil, true, "FE80:0:0:0:0:0:0:1%eth0"},
{"fuzzy IP still misses another address", []AssetInterceptRule{rule("fuzzy_ip", "::1", true)},
nil, []string{"0:0:0:0:0:0:0:2"}, nil, false, ""},
{"fuzzy IP matches a range as written", []AssetInterceptRule{rule("fuzzy_ip", "10.0.", true)},
nil, []string{"10.0.0.0/8"}, nil, true, "10.0.0.0/8"},
{"CIDR hit", []AssetInterceptRule{rule("cidr", "192.168.0.0/16", true)},
nil, []string{"192.168.5.20"}, nil, true, "192.168.5.20"},
{"CIDR no hit", []AssetInterceptRule{rule("cidr", "192.168.0.0/16", true)},
nil, []string{"10.0.0.1"}, nil, false, ""},
{"CIDR zone-qualified target", []AssetInterceptRule{rule("cidr", "fe80::/10", true)},
nil, []string{"fe80::1%eth0"}, nil, true, "fe80::1%eth0"},
{"exact URL hit", []AssetInterceptRule{rule("exact_url", "https://a.gov.cn/login", true)},
nil, nil, []string{"https://a.gov.cn/login"}, true, "https://a.gov.cn/login"},
{"fuzzy URL hits path", []AssetInterceptRule{rule("fuzzy_url", "/admin", true)},
@@ -184,4 +204,15 @@ func TestAssetInterceptCandidates(t *testing.T) {
if r, _, ok := MatchAssetInterceptRules([]AssetInterceptRule{rule("cidr", "10.0.0.0/8", true)}, nil, ips, nil); !ok {
t.Fatalf("an IP in a URL should be hit by CIDR, ips=%v rule=%+v", ips, r)
}
// A zone-qualified or expanded IPv6 URL host is an IP too, not a domain.
for _, u := range []string{"http://[fe80::1%25eth0]:8080/x", "http://[FE80:0:0:0:0:0:0:1]/"} {
c := &Asset{Type: "service", URL: u}
_, ips, _ := c.interceptCandidates()
for _, r := range []AssetInterceptRule{rule("exact_ip", "fe80::1", true), rule("fuzzy_ip", "fe80::1", true), rule("cidr", "fe80::/10", true)} {
if _, _, ok := MatchAssetInterceptRules([]AssetInterceptRule{r}, nil, ips, nil); !ok {
t.Fatalf("URL %s: %s rule %s missed, ips=%v", u, r.Kind, r.Pattern, ips)
}
}
}
}
+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 {
+50
View File
@@ -180,6 +180,56 @@ func TestTargetOnlyGuardAppliesBuiltinDenyRules(t *testing.T) {
}
}
// The seeded recursive-force-delete rule holds for every shell spelling of the
// command: Bash removes quotes, backslashes and line continuations and decodes
// $'...' before it runs rm, so the hook decides on the same words. Both the
// worker guard and the target-only guard read the rules from the database.
func TestBuiltinRecursiveDeleteRuleDecodesShellWords(t *testing.T) {
dsn, _, err := db.DSN()
if err != nil {
db.SkipPGUnavailable(t, err)
}
d, err := db.Open(dsn)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { d.Close() })
const ruleMsg = "Recursive force delete is forbidden"
denied := []string{
`rm -rf ./x`,
`r\m -rf ./x`,
`r''m -rf ./x`,
`"r"m -rf ./x`,
`/bin/r\m -rf ./x`,
`$'r\x6d' -rf ./x`,
`rm -r''f ./x`,
`rm $'-rf' ./x`,
`rm -r$'f' ./x`,
`rm -R -$'f' ./x`,
`command r\m --recursive ./x`,
"r\\\nm -rf ./x",
"rm -r \\\n -f ./x",
"cd ./w\nr\\m -rf ./x",
"true\nrm -rf ./x",
}
for name, g := range map[string]*Guard{
"worker guard": NewWithInterceptor(intercept.New(d)),
"target-only guard": NewTargetOnly(intercept.New(d)),
} {
for _, cmd := range denied {
input, _ := json.Marshal(map[string]string{"command": cmd})
if block, msg := pre(g, context.Background(), "Bash", string(input)); !block || !strings.Contains(msg, ruleMsg) {
t.Errorf("%s: %q block=%v msg=%q, want the recursive-force-delete rule", name, cmd, block, msg)
}
}
input, _ := json.Marshal(map[string]string{"command": "rm -r ./x"})
if block, msg := pre(g, context.Background(), "Bash", string(input)); block {
t.Errorf("%s: rm -r without force was blocked: %s", name, msg)
}
}
}
// A deny rule with an oversized message reaches the model capped, with the
// platform framing and the guidance intact.
func TestDenyRuleReasonIsCapped(t *testing.T) {
+1 -1
View File
@@ -78,10 +78,10 @@ func TestHardeningInterceptRules(t *testing.T) {
{"closed: git -c option", `{"command":"git -c protocol.ext.allow=always clone https://github.com/a/b"}`, true, "ask"},
{"closed: bash -c $(curl)", `{"command":"bash -c \"$(curl -s https://e/x.sh)\""}`, true, "ask"},
{"closed: curl | tar", `{"command":"curl -s https://e/x.tgz | tar xzf -"}`, true, "ask"},
{"closed: JSON-escaped whitespace", `{"command":"pip\tinstall requests"}`, true, "ask"},
// Documented OPEN bypasses: no prompt fires (the skill still binds the agent).
{"open: download host not listed", `{"command":"curl -s https://files.example.com/tool.py -o t.py"}`, false, ""},
{"open: JSON-escaped whitespace", `{"command":"pip\tinstall requests"}`, false, ""},
{"open: base64 split from run", `{"command":"base64 -d blob.b64 > s.sh"}`, false, ""},
// Documented false positive: harmless command trips the net.
+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")})
+138 -1
View File
@@ -1,8 +1,10 @@
package intercept
import (
"bytes"
"encoding/json"
"path"
"strconv"
"strings"
"mvdan.cc/sh/v3/syntax"
@@ -51,6 +53,68 @@ func argvCompoundMatches(tokens []string, toolName string, input []byte) bool {
return bashCommandMatchesArgv(tokens, in.Command, 0)
}
// bashDecodedInput returns the input of a Bash call with its command replaced
// by the commands the shell runs, joined by "; ", each word decoded as callWordOf
// decodes it (backslash escapes, line continuations, single and double quotes,
// $'...'), so a text rule written for "rm -rf" also meets r\m -rf. A word
// that holds an expansion is kept as written. ok is false for another tool, or
// when the command is empty or does not parse.
func bashDecodedInput(toolName string, input []byte) (string, bool) {
if toolName != "Bash" {
return "", false
}
var in map[string]json.RawMessage
if json.Unmarshal(input, &in) != nil {
return "", false
}
var command string
if json.Unmarshal(in["command"], &command) != nil || strings.TrimSpace(command) == "" {
return "", false
}
f, err := syntax.NewParser(syntax.Variant(syntax.LangBash)).Parse(strings.NewReader(command), "")
if err != nil {
return "", false
}
printer := syntax.NewPrinter()
var cmds []string
syntax.Walk(f, func(n syntax.Node) bool {
call, ok := n.(*syntax.CallExpr)
if !ok || len(call.Args) == 0 {
return true
}
words := make([]string, len(call.Args))
for i, w := range call.Args {
if cw := callWordOf(w); cw.Literal {
words[i] = cw.Value
continue
}
var sb strings.Builder
_ = printer.Print(&sb, w)
words[i] = sb.String()
}
cmds = append(cmds, strings.Join(words, " "))
return true
})
if len(cmds) == 0 {
return "", false
}
// "; " and not a newline: JSON writes a newline as \n, and its "n" would
// glue to the next word (no word boundary before "rm" in "\nrm"). No HTML
// escaping, so < > & read as they do in the input as written.
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
enc.SetEscapeHTML(false)
if enc.Encode(strings.Join(cmds, "; ")) != nil {
return "", false
}
in["command"] = bytes.Clone(bytes.TrimSpace(buf.Bytes()))
buf.Reset()
if enc.Encode(in) != nil {
return "", false
}
return string(bytes.TrimSpace(buf.Bytes())), true
}
func bashCommandMatchesArgv(rule []string, command string, depth int) bool {
f, err := syntax.NewParser(syntax.Variant(syntax.LangBash)).Parse(strings.NewReader(command), "")
if err != nil {
@@ -190,8 +254,9 @@ func callWordOf(w *syntax.Word) callWord {
}
sb.WriteString(s)
case *syntax.SglQuoted:
// $'...' is fixed text too, once its escapes are decoded.
if p.Dollar {
literal = false
sb.WriteString(unescapeANSIC(p.Value))
continue
}
sb.WriteString(p.Value)
@@ -276,6 +341,78 @@ func unescapeDblQuotedLit(s string) string {
return sb.String()
}
// unescapeANSIC decodes the body of a $'...' string as Bash does: \a \b \e \E
// \f \n \r \t \v \\ \' \" \?, octal \nnn, \xHH, \uHHHH, \UHHHHHHHH and \cX.
// An unknown escape is kept as written, backslash included.
func unescapeANSIC(s string) string {
var sb strings.Builder
sb.Grow(len(s))
for i := 0; i < len(s); i++ {
if s[i] != '\\' || i+1 >= len(s) {
sb.WriteByte(s[i])
continue
}
i++
switch e := s[i]; e {
case 'a':
sb.WriteByte('\a')
case 'b':
sb.WriteByte('\b')
case 'e', 'E':
sb.WriteByte(0x1b)
case 'f':
sb.WriteByte('\f')
case 'n':
sb.WriteByte('\n')
case 'r':
sb.WriteByte('\r')
case 't':
sb.WriteByte('\t')
case 'v':
sb.WriteByte('\v')
case '\\', '\'', '"', '?':
sb.WriteByte(e)
case 'c':
if i+1 < len(s) {
i++
sb.WriteByte(s[i] & 0x1f)
} else {
sb.WriteString(`\c`)
}
case '0', '1', '2', '3', '4', '5', '6', '7':
j := i
for j < len(s) && j < i+3 && s[j] >= '0' && s[j] <= '7' {
j++
}
v, _ := strconv.ParseUint(s[i:j], 8, 16)
sb.WriteByte(byte(v))
i = j - 1
case 'x', 'u', 'U':
digits := map[byte]int{'x': 2, 'u': 4, 'U': 8}[e]
j := i + 1
for j < len(s) && j <= i+digits && strings.IndexByte("0123456789abcdefABCDEF", s[j]) >= 0 {
j++
}
if j == i+1 {
sb.WriteByte('\\')
sb.WriteByte(e)
continue
}
v, _ := strconv.ParseUint(s[i+1:j], 16, 32)
if e == 'x' {
sb.WriteByte(byte(v))
} else {
sb.WriteRune(rune(v))
}
i = j - 1
default:
sb.WriteByte('\\')
sb.WriteByte(e)
}
}
return sb.String()
}
func hasAssignPrefix(s string) bool {
eq := strings.IndexByte(s, '=')
if eq <= 0 {
+117 -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,116 @@ 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)
}
}
// An ANSI-C string is fixed text: $'nmap' and $'\x6emap' run nmap.
func TestArgvDenyDecodesANSICQuoting(t *testing.T) {
for _, cmd := range []string{`$'nmap' -sV x`, `$'\x6emap' -sV x`, `$'\156map' -sV x`, `n$'\u006d'ap x`, `bash -c $'nmap x'`} {
if _, ok := matchSingleArgvRule("deny", `["nmap"]`, "Bash", bashInput(cmd)); !ok {
t.Errorf("deny nmap missed %q", cmd)
}
}
if _, ok := matchSingleArgvRule("deny", `["nmap"]`, "Bash", bashInput(`$'nmapx' x`)); ok {
t.Error(`deny nmap matched $'nmapx'`)
}
}
func TestUnescapeANSIC(t *testing.T) {
for in, want := range map[string]string{
`rm`: "rm",
`r\x6d`: "rm",
`r\155`: "rm",
`r\u006D`: "rm",
`r\U0000006d`: "rm",
`-r\x66`: "-rf",
`a\tb\n`: "a\tb\n",
`\'\"\\\?`: `'"\?`,
`\e\E`: "\x1b\x1b",
`\cA`: "\x01",
`\q\x`: `\q\x`,
} {
if got := unescapeANSIC(in); got != want {
t.Errorf("unescapeANSIC(%q) = %q, want %q", in, got, want)
}
}
}
// A text deny or ask rule on a Bash command also meets the command as the
// shell decodes it: quotes, backslashes, ANSI-C strings and line
// continuations removed, each command on its own line.
func TestTextRulesMatchShellDecodedCommand(t *testing.T) {
const rmrf = `(?i)\brm\b.{0,80}(?:-[a-z]*r[a-z]*f|-[a-z]*r[a-z]*\s+-+[a-z]*f)`
cmds := []string{
`rm -rf ./x`,
`r\m -rf ./x`,
`\r\m -rf ./x`,
`r''m -rf ./x`,
`"r"m -rf ./x`,
`'rm' -rf ./x`,
`/bin/r\m -rf ./x`,
`$'rm' -rf ./x`,
`$'r\x6d' -rf ./x`,
`rm -r''f ./x`,
`rm -r"f" ./x`,
`rm $'-rf' ./x`,
`rm -r$'f' ./x`,
`rm -R -$'f' ./x`,
`command r\m -rf ./x`,
"r\\\nm -rf ./x",
"rm -r\\\nf ./x",
"rm -r \\\n -f ./x",
"cd ./w\nr''m -rf ./x",
"true\nrm -rf ./x",
"echo $(r\\m -rf ./x)",
}
stringCmds := []string{`r\m -rf ./x`, `r''m -rf ./x`, `"r"m -rf ./x`, `rm -r''f ./x`, `rm -r$'f' ./x`}
for _, action := range []string{"deny", "ask"} {
for _, typ := range []string{"regex", "string"} {
pattern, hits := rmrf, cmds
if typ == "string" {
pattern, hits = "rm -rf", stringCmds
}
ic := New(nil)
ic.SetRulesForTest([]db.InterceptRule{{ID: 1, Name: "rm", Enabled: true, Priority: 100,
MatchTarget: "tool_input", MatchType: typ, Pattern: pattern, Action: action}})
for _, cmd := range hits {
if _, ok := ic.Match("Bash", bashInput(cmd)); !ok {
t.Errorf("%s %s rule missed %q", action, typ, cmd)
}
}
for _, cmd := range []string{`rm -r ./x`, `echo r\m`, `ls -rf`} {
if _, ok := ic.Match("Bash", bashInput(cmd)); ok {
t.Errorf("%s %s rule matched %q", action, typ, cmd)
}
}
}
}
// An allow rule is matched on the text as written only.
ic := New(nil)
ic.SetRulesForTest([]db.InterceptRule{{ID: 1, Name: "allow rm", Enabled: true, Priority: 100,
MatchTarget: "tool_input", MatchType: "regex", Pattern: rmrf, Action: "allow"}})
if _, ok := ic.Match("Bash", bashInput(`r\m -rf ./x`)); ok {
t.Error(`allow rule matched the decoded form of r\m -rf`)
}
// Other tools are matched as written.
ic.SetRulesForTest([]db.InterceptRule{{ID: 1, Name: "deny rm", Enabled: true, Priority: 100,
MatchTarget: "tool_input", MatchType: "regex", Pattern: rmrf, Action: "deny"}})
if _, ok := ic.Match("Write", []byte(`{"command":"r\\m -rf ./x"}`)); ok {
t.Error("a non-Bash tool input was shell-decoded")
}
}
+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 {
+21
View File
@@ -0,0 +1,21 @@
package intercept
import "context"
// directHopKey marks a check or a connection the platform opens itself to a
// named hop. A custom HTTP tool's own proxy is such a hop: the tool dials the
// proxy directly, and the proxy, not ARTEX, connects to the target. Pins for it
// bind the addresses the decision compared, never the name alone.
type directHopKey struct{}
// WithDirectHop marks ctx as a direct connection to the hop being checked or
// dialled: the target gate does not treat its pins as name-only.
func WithDirectHop(ctx context.Context) context.Context {
return context.WithValue(ctx, directHopKey{}, true)
}
// DirectHop reports whether ctx was marked by WithDirectHop.
func DirectHop(ctx context.Context) bool {
v, _ := ctx.Value(directHopKey{}).(bool)
return v
}
+16
View File
@@ -834,6 +834,22 @@ func ruleMatches(r compiledRule, toolName string, input []byte) bool {
default:
return false
}
if textRuleMatches(r, subject) {
return true
}
// Bash runs a command only after it removes quotes and backslashes and
// decodes $'...', so r\m -rf runs rm -rf. A deny or ask rule also meets
// the command decoded that way; an allow rule meets the text as written
// only, so decoding never widens what it allows.
if r.MatchTarget != "tool_input" || (r.Action != "deny" && r.Action != "ask") {
return false
}
decoded, ok := bashDecodedInput(toolName, input)
return ok && textRuleMatches(r, decoded)
}
// textRuleMatches matches a regex or string rule against subject.
func textRuleMatches(r compiledRule, subject string) bool {
if r.MatchType == "regex" {
return r.re != nil && r.re.MatchString(subject)
}
+11
View File
@@ -58,6 +58,17 @@ func PinnedDialer(toolName string, scoped bool) func(ctx context.Context, networ
}
}
// PinnedDialerDirect is PinnedDialer for a connection ARTEX opens itself to a
// named hop, such as a custom HTTP tool's own proxy. The hop is not behind the
// proxy: the dial is checked and opened on the addresses the decision compared,
// so a pin for its name cannot be satisfied by a name that later rebinds.
func PinnedDialerDirect(toolName string) func(ctx context.Context, network, addr string) (net.Conn, error) {
dial := PinnedDialer(toolName, true)
return func(ctx context.Context, network, addr string) (net.Conn, error) {
return dial(WithDirectHop(ctx), network, addr)
}
}
// GateOn reports whether ctx carries a target scope whose gate is on.
func GateOn(ctx context.Context) bool {
_, on := renderedScope(ctx)
+15 -10
View File
@@ -233,8 +233,11 @@ func (c *targetCheck) run(targets []Target) ([]TargetRequest, TargetResult) {
// Behind a proxy the proxy chooses the address it connects to, so every pin
// is name-only for this call, whatever the pin row says: the proxy can be
// turned on after a pin was approved. The recording proxy, the global egress
// proxy and a custom tool's own proxy all count.
nameOnly := (proxied != nil && proxied()) || (toolProxy != nil && toolProxy(c.tool))
// proxy and a custom tool's own proxy all count. A direct hop (WithDirectHop)
// is not behind them: the tool dials it itself, so its pins bind the
// addresses the decision compared.
direct := DirectHop(c.ctx)
nameOnly := !direct && ((proxied != nil && proxied()) || (toolProxy != nil && toolProxy(c.tool)))
var unpinned []TargetRequest
var uses []func()
@@ -280,7 +283,7 @@ func (c *targetCheck) run(targets []Target) ([]TargetRequest, TargetResult) {
if err != nil {
return c.block(TargetGateUnavailable, "gate_unavailable", ct, "the pins could not be read: "+err.Error())
}
pin := coveringPin(pins, ct.ips, nameOnly)
pin := coveringPin(pins, ct.ips, nameOnly, direct)
if pin == nil && ct.Kind == TargetDomain && !c.fresh {
// A request is about to be raised: the addresses a human reads and
// pins are resolved now, never taken from the cache. A fresh run
@@ -291,11 +294,11 @@ func (c *targetCheck) run(targets []Target) ([]TargetRequest, TargetResult) {
if rule, hit := blockRule(rules, ct); hit {
return c.block(TargetRuleBlocked, "rule_blocked", ct, fmt.Sprintf("%s is blocked by an asset rule. %s", ct.Target, rule.Reason()))
}
pin = coveringPin(pins, ct.ips, nameOnly)
pin = coveringPin(pins, ct.ips, nameOnly, direct)
}
if pin != nil {
ct.cover = coverPin
if nameOnly || pin.NameOnlyEffective {
if nameOnly || (pin.NameOnlyEffective && !direct) {
ct.cover = coverNameOnly
}
uses = append(uses, func() { c.pinUsed(ct, pin, nameOnly) })
@@ -396,7 +399,7 @@ func (c *targetCheck) pinUsed(ct *checkedTarget, pin *db.TargetPin, nameOnly boo
return
}
t := ct.audit("pin_match")
t.PinID, t.PinVersion, t.PinnedIPs, t.NameOnlyEffective = pin.ID, pin.Version, pin.PinnedIPs, pin.NameOnlyEffective || nameOnly
t.PinID, t.PinVersion, t.PinnedIPs, t.NameOnlyEffective = pin.ID, pin.Version, pin.PinnedIPs, nameOnly || (pin.NameOnlyEffective && !DirectHop(c.ctx))
c.log("allowed", fmt.Sprintf("Target %s is covered by pin v%d of %s.", ct.Target, pin.Version, c.scope.scopeName()), "", t)
}
@@ -529,11 +532,13 @@ func exemptionHolds(ct *checkedTarget) bool {
}
// coveringPin returns the pin that covers the resolved addresses: the first
// candidate that is name-only, or that holds every address. The address sets
// of two pins are never merged.
func coveringPin(pins []*db.TargetPin, resolved []string, nameOnly bool) *db.TargetPin {
// candidate that is name-only, or that holds every address. A direct hop does
// not accept a name-only pin on its name alone: the connection is opened to the
// addresses the decision compared, so such a pin covers only when it holds them
// too. The address sets of two pins are never merged.
func coveringPin(pins []*db.TargetPin, resolved []string, nameOnly, direct bool) *db.TargetPin {
for _, p := range pins {
if nameOnly || p.NameOnlyEffective || subset(resolved, p.PinnedIPs) {
if nameOnly || (!direct && p.NameOnlyEffective) || subset(resolved, p.PinnedIPs) {
return p
}
}
+4 -2
View File
@@ -295,8 +295,10 @@ func (i *Interceptor) openTargetRequest(ctx context.Context, ref db.TargetScopeR
proxied := i.upstreamProxy
i.mu.RUnlock()
// Behind the upstream proxy the proxy chooses the address: the approval is
// for the name, and the pin created from this row says so.
nameOnly := proxied != nil && proxied()
// for the name, and the pin created from this row says so. A direct hop is
// not behind it: the tool dials it itself, so the approval and its pin bind
// the addresses a human reads.
nameOnly := !DirectHop(ctx) && proxied != nil && proxied()
dec := Decision{Action: "ask"}
if ask != nil {
+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.
+194 -3
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
@@ -716,6 +741,20 @@ func (s *Server) runHTTPTool(ctx context.Context, key string, execRaw json.RawMe
if res := intercept.GateRenderedURL(ctx, key, rawURL); res.Code != "" {
return actool.Errorf(guard.TargetBlockMessage(res)), nil
}
// The tool's own proxy is a connection the panel opens too: with the gate
// on it is a target, as a proxy named on a Bash command line is, and the
// dial is checked again (httpToolTransport). Gate off, it is not checked,
// like the tool URL itself, which may name a loopback or private address
// in that mode. In required mode the sandbox policy checks the proxy dial.
if sbPolicy == nil {
if proxy := s.toolOwnProxy(spec); proxy != "" {
// The proxy is a direct hop: ARTEX dials it itself, so its pin binds
// the addresses the approval resolved, not the name alone.
if res := intercept.GateRenderedURL(intercept.WithDirectHop(ctx), key, gateProxyURL(proxy)); res.Code != "" {
return actool.Errorf(guard.TargetBlockMessage(res)), nil
}
}
}
if err := intercept.CheckStatefulTool(ctx, key, nil, rawURL, method); err != nil {
return actool.Errorf(err.Error()), nil
}
@@ -741,6 +780,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 +807,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.
@@ -813,9 +963,16 @@ func sandboxHTTPTransport(tr *http.Transport, policy *sandbox.EgressPolicy) *htt
// httpToolTransport is the transport of one http tool call, or nil
// (http.DefaultTransport). A call through a proxy keeps httpProxyTransport: it
// dials the proxy, which makes the connection to the target. A direct call in
// a gated scope connects through the pinned dialer, to addresses a pin covers.
// a gated scope connects through the pinned dialer, to addresses a pin covers;
// so does the tool's own proxy outside required mode.
func (s *Server) httpToolTransport(ctx context.Context, key string, spec httpExec) *http.Transport {
if tr := s.httpProxyTransport(spec); tr != nil {
if intercept.GateOn(ctx) && !agent.SandboxRequired() && s.toolOwnProxy(spec) != "" {
// The proxy hop is direct: the dial resolves and pins its addresses,
// so a proxy name that later answers another address is refused.
tr.DialContext = intercept.PinnedDialerDirect(key)
tr.DisableKeepAlives = true
}
return tr
}
if !intercept.GateOn(ctx) {
@@ -868,6 +1025,40 @@ func (s *Server) httpProxyTransport(spec httpExec) *http.Transport {
return tr
}
// toolOwnProxy returns the proxy URL of the tool's own exec.proxy when the call
// goes through it, "" when the call is direct or goes through the recording or
// global proxy, endpoints the gate exempts as configured (see
// httpProxyTransport).
func (s *Server) toolOwnProxy(spec httpExec) string {
if spec.UseRecordingProxy {
if tr := s.m.Traffic(); tr != nil && s.m.TrafficEnabled() {
return ""
}
if proxyURLString(s.m.GlobalProxy()) != "" {
return ""
}
}
proxy := proxyURLString(spec.Proxy)
if _, err := url.Parse(proxy); err != nil {
return "" // httpProxyTransport goes direct
}
return proxy
}
// gateProxyURL is a tool proxy as the gate reads it: without credentials,
// since the gate records the URL it checks, and with the port net/http dials
// for a socks5 proxy that names none. "" (no host) fails closed in the gate.
func gateProxyURL(proxy string) string {
u, err := url.Parse(proxyWithoutCredentials(proxy))
if err != nil || u.Host == "" {
return ""
}
if s := strings.ToLower(u.Scheme); (s == "socks5" || s == "socks5h") && u.Port() == "" {
u.Host = strings.TrimSuffix(u.Host, ":") + ":1080" // u.Host keeps IPv6 brackets
}
return u.String()
}
// proxyURLString returns a proxy address as a URL: a bare host:port gets
// "http://", an address that already has a scheme (as ProxyAddr returns it) is
// kept as is.
+42 -22
View File
@@ -118,10 +118,12 @@ func TestCustomHTTPDirectDialPinned(t *testing.T) {
// With the gate off (and without a scope) the call keeps http.DefaultTransport:
// no transport is built. A spec with a proxy keeps its proxy transport, without
// a dialer. Gate on and direct: a transport with the pinned dialer, no
// environment proxy, keep-alive off.
// environment proxy, keep-alive off. Gate on, the tool's own proxy is dialled
// through the pinned dialer too.
func TestCustomHTTPGateOffTransportUnchanged(t *testing.T) {
s := &Server{}
direct := httpExec{URL: "http://api.example.com/"}
proxied := httpExec{URL: direct.URL, Proxy: "http://127.0.0.1:1"}
scope := func(on bool) context.Context {
return intercept.WithTargetScope(context.Background(), intercept.TargetScope{TaskID: "7", Enabled: func() bool { return on }})
}
@@ -129,9 +131,12 @@ func TestCustomHTTPGateOffTransportUnchanged(t *testing.T) {
if tr := s.httpToolTransport(ctx, "probe", direct); tr != nil {
t.Fatalf("%s: transport %+v, want nil (http.DefaultTransport)", name, tr)
}
if tr := s.httpToolTransport(ctx, "probe", proxied); tr == nil || tr.Proxy == nil || tr.DialContext != nil || tr.DisableKeepAlives {
t.Fatalf("%s, operator proxy: transport %+v, want the proxy transport without a dialer", name, tr)
}
}
if tr := s.httpToolTransport(scope(true), "probe", httpExec{URL: direct.URL, Proxy: "http://127.0.0.1:1"}); tr == nil || tr.Proxy == nil || tr.DialContext != nil {
t.Fatalf("operator proxy: transport %+v, want the proxy transport without a dialer", tr)
if tr := s.httpToolTransport(scope(true), "probe", proxied); tr == nil || tr.Proxy == nil || tr.DialContext == nil || !tr.DisableKeepAlives {
t.Fatalf("gated operator proxy: transport %+v, want the proxy transport with the pinned dialer", tr)
}
if tr := s.httpToolTransport(scope(true), "probe", direct); tr == nil || tr.Proxy != nil || tr.DialContext == nil || !tr.DisableKeepAlives {
t.Fatalf("gated direct call: transport %+v", tr)
@@ -239,13 +244,13 @@ func TestCustomToolTestEndpointDialUngated(t *testing.T) {
}
}
// Documents a known limit: a custom http tool that goes through a proxy is not
// bound to pins. The pinned dialer covers direct connections only; through a
// proxy the connection to the target is the proxy's, and the proxy here
// connects to a peer nobody pinned. Step 2.2 binds the recording proxy (and
// flips its half of this test); an operator-written proxy stays unbound
// (OPEN-6).
func TestBypass_CustomHTTPProxyPeerNotPinned(t *testing.T) {
// A custom http tool that goes through a proxy: the target pin is name-only,
// since the proxy makes the connection to the target, and the proxy here
// connects to a peer nobody pinned. The tool's own proxy is a gate target
// (formerly the known limit OPEN-6): the call waits for its approval, then the
// proxy is dialled through the pinned dialer. The recording and global proxies
// are not checked here and are dialled as before.
func TestCustomHTTPOwnProxyGated(t *testing.T) {
g := newGateServer(t)
on := true
task := g.newTask(t, db.TaskCreateOptions{TargetGate: &on})
@@ -270,28 +275,43 @@ func TestBypass_CustomHTTPProxyPeerNotPinned(t *testing.T) {
direct := g.s.buildCustomTool(&db.Tool{Key: "probe_bypass", Kind: "http", Exec: execJSON(t, map[string]any{"url": url})})
approveTarget(t, g, task, direct, func() (string, bool) { return callTool(t, direct, gatedCtx(task, 0), `{}`, nil) }, key)
// The tool's own proxy: refused until its host:port is approved, then
// dialled through the pinned dialer, at the pinned proxy address only.
proxyKey := strings.TrimPrefix(proxy.URL, "http://")
dialer.route(proxyKey, proxy.Listener.Addr().String())
ownProxy := g.s.buildCustomTool(&db.Tool{Key: "probe_bypass", Kind: "http", Exec: execJSON(t, map[string]any{"url": url, "proxy": proxy.URL})})
callOwn := func() (string, bool) { return callTool(t, ownProxy, gatedCtx(task, 0), `{}`, nil) }
approveTarget(t, g, task, ownProxy, callOwn, proxyKey)
if hits.Load() != 0 || len(dialer.calls()) != 0 {
t.Fatalf("the proxy was dialled before its approval: hits=%d dialled %v", hits.Load(), dialer.calls())
}
if out, isErr := callOwn(); isErr || !strings.Contains(out, "probe-reached") || hits.Load() != 1 {
t.Fatalf("operator proxy after the approval: error=%v out=%q hits=%d", isErr, out, hits.Load())
}
if got := dialer.calls(); !slices.Equal(got, []string{proxyKey}) {
t.Fatalf("dialled %v, want the pinned proxy only; the pinned address 203.0.113.7 is never dialled through a proxy", got)
}
// use_recording_proxy through the global proxy: not checked here, as before.
// The global proxy carries a scheme, as in production (ProxyAddr returns it
// as is with capture off); httpProxyTransport must not write a second one.
global := httptest.NewServer(proxy.Config.Handler)
t.Cleanup(global.Close)
g.m.mu.Lock()
g.m.globalProxy = proxy.URL
g.m.globalProxy = global.URL
g.m.mu.Unlock()
t.Cleanup(func() {
g.m.mu.Lock()
g.m.globalProxy = ""
g.m.mu.Unlock()
})
for name, exec := range map[string]map[string]any{
"operator proxy": {"url": url, "proxy": proxy.URL},
"use_recording_proxy": {"url": url, "use_recording_proxy": true},
} {
before := hits.Load()
tool := g.s.buildCustomTool(&db.Tool{Key: "probe_bypass", Kind: "http", Exec: execJSON(t, exec)})
if out, isErr := callTool(t, tool, gatedCtx(task, 0), `{}`, nil); isErr || !strings.Contains(out, "probe-reached") || hits.Load() != before+1 {
t.Fatalf("%s: error=%v out=%q", name, isErr, out)
}
before, dialled := hits.Load(), len(dialer.calls())
tool := g.s.buildCustomTool(&db.Tool{Key: "probe_bypass", Kind: "http", Exec: execJSON(t, map[string]any{"url": url, "use_recording_proxy": true})})
if out, isErr := callTool(t, tool, gatedCtx(task, 0), `{}`, nil); isErr || !strings.Contains(out, "probe-reached") || hits.Load() != before+1 {
t.Fatalf("use_recording_proxy: error=%v out=%q", isErr, out)
}
if got := dialer.calls(); len(got) != 0 {
t.Fatalf("dialled %v; the pinned address 203.0.113.7 is never dialled through a proxy", got)
if got := dialer.calls(); len(got) != dialled {
t.Fatalf("dialled %v; the global proxy is not dialled through the gate", got[dialled:])
}
}
+141
View File
@@ -0,0 +1,141 @@
package server
import (
"strings"
"testing"
"github.com/Autumn-27/artex/agent"
"github.com/Autumn-27/artex/db"
)
// Gate on: the tool's own proxy is a target. An approved target URL does not
// let the call reach an unapproved proxy: the proxy is not dialled and a
// request opens on its host:port, recorded without the proxy credentials.
func TestCustomHTTPGatedOwnProxyNotDialed(t *testing.T) {
g := newGateServer(t)
on := true
task := g.newTask(t, db.TaskCreateOptions{TargetGate: &on})
_, targetHits, host, port := countingServer(t)
_, proxyHits, _, proxyPort := countingServer(t)
targetURL := "http://" + host + ":" + port + "/"
direct := g.s.buildCustomTool(&db.Tool{Key: "probe_own_proxy", Kind: "http", Exec: execJSON(t, map[string]any{"url": targetURL})})
approveTarget(t, g, task, direct, func() (string, bool) { return callTool(t, direct, gatedCtx(task, 0), `{}`, nil) }, host+":"+port)
if out, isErr := callTool(t, direct, gatedCtx(task, 0), `{}`, nil); isErr || targetHits.Load() != 1 {
t.Fatalf("approved direct call: error=%v out=%q", isErr, out)
}
proxyKey := "127.0.0.1:" + proxyPort
tool := g.s.buildCustomTool(&db.Tool{Key: "probe_own_proxy", Kind: "http",
Exec: execJSON(t, map[string]any{"url": targetURL, "proxy": "http://user:pw-secret@" + proxyKey})})
out, isErr := callTool(t, tool, gatedCtx(task, 0), `{}`, nil)
if !isErr || !strings.Contains(out, "TARGET_APPROVAL_PENDING") || !strings.Contains(out, proxyKey) {
t.Fatalf("unapproved proxy: error=%v out=%q", isErr, out)
}
if n := proxyHits.Load(); n != 0 {
t.Fatalf("unapproved proxy received %d request(s)", n)
}
if n := targetHits.Load(); n != 1 {
t.Fatalf("target received %d request(s), want only the direct one", n)
}
_, toolName, input, ok := openTargetRequest(t, g.m.pg, task.ID, proxyKey)
if !ok || toolName != "probe_own_proxy" || strings.Contains(input, "pw-secret") || strings.Contains(input, "user") {
t.Fatalf("request on the proxy: ok=%v tool=%q input=%s", ok, toolName, input)
}
}
// A saved tool's own proxy is a direct hop: the approval pins the addresses it
// resolved, and a proxy name that later answers another address is refused
// instead of being dialled unpinned (DNS rebinding). The tool is saved so the
// manager knows it uses a proxy, as in production.
func TestCustomHTTPOwnProxyHostnameRebindingRefused(t *testing.T) {
g := newGateServer(t)
on := true
task := g.newTask(t, db.TaskCreateOptions{TargetGate: &on})
_, targetHits, host, port := countingServer(t)
proxy, proxyHits, _, _ := countingServer(t)
targetKey := host + ":" + port
proxyKey := "proxy.example.com:3128"
res := &countingResolver{answers: map[string][]string{"proxy.example.com": {"203.0.113.7"}}}
g.m.interceptor.SetResolver(res)
dialer := newRouteDialer(g)
dialer.route("203.0.113.7:3128", proxy.Listener.Addr().String())
tool := &db.Tool{Key: "probe_rebind_proxy", Kind: "http", Description: "probe",
Exec: execJSON(t, map[string]any{"url": "http://" + targetKey + "/", "proxy": "http://" + proxyKey})}
if err := g.m.pg.CreateCustomTool(tool); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = g.m.pg.DeleteCustomTool(tool.Key) })
built := g.s.buildCustomTool(tool)
call := func() (string, bool) { return callTool(t, built, gatedCtx(task, 0), `{}`, nil) }
approveTarget(t, g, task, built, call, targetKey)
approveTarget(t, g, task, built, call, proxyKey)
if out, isErr := call(); isErr || !strings.Contains(out, "probe-reached") || proxyHits.Load() != 1 {
t.Fatalf("approved proxy: error=%v out=%q hits=%d", isErr, out, proxyHits.Load())
}
pins, err := g.m.pg.ActiveTargetPins(taskRef(t, task), "proxy.example.com", 3128)
if err != nil || len(pins) != 1 || pins[0].NameOnlyEffective ||
len(pins[0].PinnedIPs) != 1 || pins[0].PinnedIPs[0] != "203.0.113.7" {
t.Fatalf("proxy pin: %+v, %v", pins, err)
}
res.set("proxy.example.com", "203.0.113.9")
beforeTarget, beforeProxy, beforeCalls := targetHits.Load(), proxyHits.Load(), len(dialer.calls())
out, isErr := call()
if !isErr || !strings.Contains(out, "TARGET_APPROVAL_PENDING") || !strings.Contains(out, proxyKey) {
t.Fatalf("rebound proxy: error=%v out=%q", isErr, out)
}
if proxyHits.Load() != beforeProxy || targetHits.Load() != beforeTarget {
t.Fatalf("rebound proxy was reached: proxy=%d target=%d",
proxyHits.Load()-beforeProxy, targetHits.Load()-beforeTarget)
}
if got := len(dialer.calls()); got != beforeCalls {
t.Fatalf("dialled %v after the rebind", dialer.calls()[beforeCalls:])
}
}
// Gate off (sandbox off): the proxy is not checked, as on c03939c1. The tool
// URL itself is not checked in that mode either.
func TestCustomHTTPOwnProxyGateOffUnchanged(t *testing.T) {
g := newGateServer(t)
off := false
task := g.newTask(t, db.TaskCreateOptions{TargetGate: &off})
_, hits, host, port := countingServer(t)
tool := g.s.buildCustomTool(&db.Tool{Key: "probe_gate_off", Kind: "http",
Exec: execJSON(t, map[string]any{"url": "http://api.example.com/", "proxy": "http://" + host + ":" + port})})
if out, isErr := callTool(t, tool, gatedCtx(task, 0), `{}`, nil); isErr || !strings.Contains(out, "probe-reached") || hits.Load() != 1 {
t.Fatalf("gate off, loopback proxy: error=%v out=%q hits=%d", isErr, out, hits.Load())
}
}
// ARTEX_SANDBOX=required with the gate on: the proxy is checked by the sandbox
// egress policy only, as on c03939c1. A proxy inside the sandbox scope and
// never approved in the gate is dialled, and no gate request opens on it.
func TestSandboxHTTPToolGatedProxyUnchanged(t *testing.T) {
g := newGateServer(t)
on := true
task := g.newTask(t, db.TaskCreateOptions{TargetGate: &on})
target, targetHits := canaryServer(t, "127.0.0.1", nil)
proxy, proxyHits := canaryServer(t, "127.0.0.2", nil)
targetKey := strings.TrimPrefix(target.URL, "http://")
proxyKey := strings.TrimPrefix(proxy.URL, "http://")
sandboxRequired(t)
call := func(exec map[string]any) (string, bool) {
tool := g.s.buildCustomTool(&db.Tool{Key: "probe_sb_proxy", Kind: "http", Exec: execJSON(t, exec)})
ctx := agent.WithSandboxRunInfo(gatedCtx(task, 0), agent.SandboxRunInfo{
TaskID: task.ID, ScopeCIDRs: []string{"127.0.0.1/32", "127.0.0.2/32"},
})
return callTool(t, tool, ctx, `{}`, nil)
}
direct := map[string]any{"method": "GET", "url": target.URL + "/"}
directTool := g.s.buildCustomTool(&db.Tool{Key: "probe_sb_proxy", Kind: "http", Exec: execJSON(t, direct)})
approveTarget(t, g, task, directTool, func() (string, bool) { return call(direct) }, targetKey)
before := targetHits.Load()
out, isErr := call(map[string]any{"method": "GET", "url": target.URL + "/", "proxy": proxy.URL})
if isErr || !strings.Contains(out, "CANARY_BODY") || proxyHits.Load() != 1 || targetHits.Load() != before {
t.Fatalf("required mode, in-scope proxy: error=%v out=%q proxy hits=%d", isErr, out, proxyHits.Load())
}
if _, _, _, ok := openTargetRequest(t, g.m.pg, task.ID, proxyKey); ok {
t.Fatal("required mode opened a gate request on the proxy")
}
}
+20
View File
@@ -0,0 +1,20 @@
package server
import "testing"
// The gate reads a tool proxy without its credentials, with the port a socks5
// proxy without one is dialled on.
func TestGateProxyURL(t *testing.T) {
for in, want := range map[string]string{
"http://user:pw@10.0.0.5:8080": "http://10.0.0.5:8080",
"socks5://user:pw@10.0.0.5": "socks5://10.0.0.5:1080",
"socks5h://[::1]": "socks5h://[::1]:1080",
"socks5://10.0.0.5:9050": "socks5://10.0.0.5:9050",
"https://proxy.example": "https://proxy.example",
"http://": "",
} {
if got := gateProxyURL(in); got != want {
t.Fatalf("gateProxyURL(%q) = %q, want %q", in, got, want)
}
}
}
+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)
}
}
+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)
+10
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"
@@ -582,6 +583,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()
+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)
}
})
}
}