fix(sandbox): pass scope entries on in canonical form and refuse IPv6 zones

Review of the scope filter:
- netip.ParseAddr accepts any text after % as an IPv6 zone, commas
  included, so "fe80::1%eth0,10.0.0.0/8" was kept and the comma join
  added 10.0.0.0/8. Zoned addresses are now dropped, and every kept
  entry is passed on in canonical form (p.Masked().String(),
  a.String()), which never holds a comma or space. IPv4-mapped entries
  become the IPv4 range they map.
- The cap was 1,024 entries; a company scope can be larger. It is now
  8,192 entries and 120 KiB per list (the proxy gets each list as one
  environment string, limited to 128 KiB).
- The runner logs dropped entries with the task ID and their values (up
  to 20), so an operator can see why an approved target is refused.
- More names that make a shell or interpreter run extra code are
  refused: SHELLOPTS, BASHOPTS, PS4, IFS, PROMPT_COMMAND, GLIBC_TUNABLES,
  PYTHONSTARTUP, PYTHONHOME, NODE_OPTIONS, PERL5OPT, PERL5LIB, RUBYOPT,
  JAVA_TOOL_OPTIONS, GIT_SSH_COMMAND, GIT_CONFIG_PARAMETERS.
This commit is contained in:
Marco Azarmaneche 2026-12-03 03:42:03 +02:00
parent 3666be70e8
commit 3eedbdc326
5 changed files with 83 additions and 31 deletions

View file

@ -37,7 +37,7 @@ All notable changes to this project are documented in this file. The format is b
### Fixed
- **The goal decomposer caches its system prompt**: `DecomposeGoalsWithProvider` built its session without a `DynamicBoundary`, and Norma reads 0 as "no cache breakpoint", so each turn of goal decomposition resent its tools and system prompt uncached on Anthropic profiles. It now sets 1, the same breakpoint #836 gave the other agents without global MCP tools.
- **Exec requests can no longer override the worker proxy, `PATH` or the loader, or smuggle scope entries.** The runner accepted any non-secret env name in an exec request, so a caller could set `HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY` or `NO_PROXY` (any case), `PATH`, `LD_PRELOAD` or another `LD_*` variable, `BASH_ENV`, `ENV`, `GCONV_PATH` or `PYTHONPATH`, and route the command around the egress proxy or run code before it. These names are now refused with 400 (the panel drops them from the env it forwards). Scope entries are checked one by one: a scope domain or CIDR holding a comma, a space or an invalid value is dropped whole (never split) and the valid ones are kept, since both backends join the entries with commas into the egress proxy environment; the narrower scope fails closed at the proxy and the runner logs how many entries it dropped. A request with more than 1,024 entries in either list is refused.
- **Exec requests can no longer set the worker's proxy, `PATH` or interpreter start-up variables, or smuggle scope entries.** The runner accepted any non-secret env name in an exec request. It now refuses with 400 the proxy variables (any case), `PATH`, `LD_*`, and variables that make a shell or interpreter run extra code (`BASH_ENV`, `ENV`, `SHELLOPTS`, `PS4`, `NODE_OPTIONS`, `PERL5OPT`, `PYTHONSTARTUP` and similar); the panel drops them from the env it forwards. Scope entries are checked one by one and passed on in canonical form: an entry that is not a valid domain, prefix or address, or an IPv6 address with a zone, is dropped and logged with the task, never split at a comma, so `1.2.3.4/32,10.0.0.0/8` or `fe80::1%x,0.0.0.0/0` can no longer add scope nobody approved. Scope lists are capped at 8,192 entries and 120 KiB each.
- **Docker updates reuse the runtime image layers again**: the runtime stage declared `ARTEX_VERSION` and `ARTEX_REVISION` before its first `RUN`, and a declared build argument is part of the cache key of every later `RUN`. `update.sh` writes the new commit into `.env`, so each update reinstalled apt packages, bbot, Playwright and the rest of the stage (6 to 11 minutes per update) and left another copy of about 8 GB of layers in the build cache. The arguments and the `LABEL` that uses them now come at the end of the stage. The Go, Next.js and npm caches are also kept between builds as BuildKit cache mounts, so a code change recompiles only what changed: an update rebuild drops to well under a minute.
- **A command that exits 124 no longer removes the Docker worker.** The runner treated every exit code 124 as its own timeout and removed the task's worker container, which also stopped the task's background jobs. Commands such as `timeout 5 curl ...` exit 124 by themselves. An exit 124 now counts as a runner timeout only when the command ran for at least `timeout_ms`.
- **An `exact_ip` task allow rule grants sandbox egress**: the egress allowlist read task allow rules of kind `ip`, which the rule tables never store, so an `exact_ip` allow rule granted nothing. A task scoped to one private address (`10.0.0.5`) could not reach it from the sandbox, directly or through a name resolving only to it. `exact_ip` allow rules now join the allowed CIDRs as a host prefix, like `cidr` allow rules.

View file

@ -107,6 +107,12 @@ func (rs *RunnerServer) handleExec(w http.ResponseWriter, r *http.Request) {
writeRunnerErr(w, http.StatusBadRequest, err.Error())
return
}
if d := req.droppedScope; len(d) > 0 {
if len(d) > 20 {
d = append(d[:20:20], fmt.Sprintf("... %d more", len(req.droppedScope)-20))
}
log.Printf("[runner] task %s: dropped %d invalid scope entries: %q", taskID, len(req.droppedScope), d)
}
res, err := rs.backend.Exec(r.Context(), taskID, req)
if err != nil {
rs.writeBackendErr(w, err)

View file

@ -73,6 +73,10 @@ type ExecRequest struct {
Env map[string]string `json:"env,omitempty"`
ScopeDomains []string `json:"scope_domains,omitempty"`
ScopeCIDRs []string `json:"scope_cidrs,omitempty"`
// droppedScope holds the scope entries ValidateExecRequest dropped as
// invalid, for the runner's log.
droppedScope []string
}
// ExecResponse is the response body for POST /v1/tasks/{id}/exec.

View file

@ -2,7 +2,6 @@ package sandbox
import (
"fmt"
"log"
"net/netip"
"path"
"regexp"
@ -16,8 +15,13 @@ var (
scopeDomainRE = regexp.MustCompile(`^(\*\.)?[\p{L}\p{N}_-]+(\.[\p{L}\p{N}_-]+)*\.?$`)
)
// MaxScopeEntries caps scope_domains and scope_cidrs (each) in one request.
const MaxScopeEntries = 1024
// MaxScopeEntries caps scope_domains and scope_cidrs (each) in one request, and
// MaxScopeBytes their comma-joined length: the egress proxy gets each list as one
// environment string, which Linux limits to 128 KiB.
const (
MaxScopeEntries = 8192
MaxScopeBytes = 120 << 10
)
// ValidateTaskID verifies a task ID is safe for Docker names, labels, and workspace paths.
func ValidateTaskID(id string) error {
@ -55,7 +59,11 @@ func IsForbiddenEnvName(name string) bool {
func isReservedEnvName(name string) bool {
u := strings.ToUpper(name)
switch u {
case "PATH", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY", "BASH_ENV", "ENV", "GCONV_PATH", "PYTHONPATH":
case "PATH", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY",
"BASH_ENV", "ENV", "SHELLOPTS", "BASHOPTS", "PS4", "IFS", "PROMPT_COMMAND",
"GCONV_PATH", "GLIBC_TUNABLES", "PYTHONPATH", "PYTHONSTARTUP", "PYTHONHOME",
"NODE_OPTIONS", "PERL5OPT", "PERL5LIB", "RUBYOPT", "JAVA_TOOL_OPTIONS",
"GIT_SSH_COMMAND", "GIT_CONFIG_PARAMETERS":
return true
}
return strings.HasPrefix(u, "LD_")
@ -131,37 +139,60 @@ func ValidateExecRequest(req *ExecRequest) error {
if len(req.ScopeDomains) > MaxScopeEntries || len(req.ScopeCIDRs) > MaxScopeEntries {
return fmt.Errorf("%w: more than %d scope entries", ErrBadRequest, MaxScopeEntries)
}
var dropped int
req.ScopeDomains, dropped = filterScope(req.ScopeDomains, validScopeDomain)
n := dropped
req.ScopeCIDRs, dropped = filterScope(req.ScopeCIDRs, validScopeCIDR)
if n += dropped; n > 0 {
log.Printf("[runner] exec request: dropped %d invalid scope entries", n)
var d1, d2 []string
req.ScopeDomains, d1 = filterScope(req.ScopeDomains, canonScopeDomain)
req.ScopeCIDRs, d2 = filterScope(req.ScopeCIDRs, canonScopeCIDR)
req.droppedScope = append(d1, d2...)
if joinedLen(req.ScopeDomains) > MaxScopeBytes || joinedLen(req.ScopeCIDRs) > MaxScopeBytes {
return fmt.Errorf("%w: scope lists longer than %d bytes", ErrBadRequest, MaxScopeBytes)
}
return ValidateEnv(req.Env)
}
// filterScope keeps the entries ok accepts. Both backends join scope entries
// with commas into the egress proxy's environment, so an entry holding a comma
// would add entries nobody approved; it is dropped whole, never split. The
// panel builds scope from free-text fields, so one odd entry must not fail
// every command: a narrower scope fails closed at the deny-by-default proxy.
func filterScope(entries []string, ok func(string) bool) ([]string, int) {
out := entries[:0:0]
// filterScope keeps the canonical form of each entry canon accepts and returns
// the dropped ones. Backends join scope entries with commas into the egress
// proxy's environment, so only the canonical form (which never holds a comma,
// space or IPv6 zone) is passed on, and an invalid entry is dropped whole,
// never split. The panel builds scope from free-text fields, so one odd entry
// must not fail every command: a narrower scope fails closed at the
// deny-by-default proxy.
func filterScope(entries []string, canon func(string) (string, bool)) (kept, dropped []string) {
kept = entries[:0:0]
for _, e := range entries {
if ok(e) {
out = append(out, e)
if c, ok := canon(e); ok {
kept = append(kept, c)
} else {
dropped = append(dropped, e)
}
}
return out, len(entries) - len(out)
return kept, dropped
}
func validScopeDomain(d string) bool { return len(d) <= 253 && scopeDomainRE.MatchString(d) }
func validScopeCIDR(c string) bool {
if _, err := netip.ParsePrefix(c); err == nil {
return true
func joinedLen(entries []string) int {
n := 0
for _, e := range entries {
n += len(e) + 1
}
_, err := netip.ParseAddr(c)
return err == nil
return n
}
func canonScopeDomain(d string) (string, bool) {
return d, len(d) <= 253 && scopeDomainRE.MatchString(d)
}
// canonScopeCIDR returns a prefix or address in canonical form. An address with
// a zone is refused (the zone may hold any text, commas included), and an
// IPv4-mapped IPv6 entry becomes the IPv4 range it maps.
func canonScopeCIDR(c string) (string, bool) {
if p, err := netip.ParsePrefix(c); err == nil {
if p.Addr().Is4In6() && p.Bits() >= 96 {
p = netip.PrefixFrom(p.Addr().Unmap(), p.Bits()-96)
}
return p.Masked().String(), true
}
a, err := netip.ParseAddr(c)
if err != nil || a.Zone() != "" {
return "", false
}
return a.Unmap().String(), true
}

View file

@ -8,7 +8,8 @@ import (
func TestValidateEnvRefusesReservedNames(t *testing.T) {
for _, k := range []string{"PATH", "path", "HTTP_PROXY", "https_proxy", "All_Proxy", "no_proxy",
"LD_PRELOAD", "LD_LIBRARY_PATH", "ld_audit", "BASH_ENV", "env", "GCONV_PATH", "PythonPath"} {
"LD_PRELOAD", "LD_LIBRARY_PATH", "ld_audit", "BASH_ENV", "env", "GCONV_PATH", "PythonPath",
"SHELLOPTS", "PS4", "NODE_OPTIONS", "PERL5OPT", "GIT_SSH_COMMAND", "GLIBC_TUNABLES"} {
if err := ValidateEnv(map[string]string{k: "x"}); !errors.Is(err, ErrBadRequest) {
t.Errorf("ValidateEnv(%s) = %v", k, err)
}
@ -26,7 +27,8 @@ func TestValidateExecRequestFiltersScopeEntries(t *testing.T) {
req := ExecRequest{Argv: []string{"true"},
ScopeDomains: []string{"example.com", "a.example,evil.example", "*.example.org", "a.example evil", "",
"example.com:8443", "https://x", "api-*.example.com", "xn--bcher-kva.example", "bücher.example", "host_1.lab.", strings.Repeat("a", 254)},
ScopeCIDRs: []string{"203.0.113.0/24", "1.2.3.4/32,10.0.0.0/8", "10.0.0.0/33", " 10.0.0.1", "198.51.100.7", "2001:db8::/32"}}
ScopeCIDRs: []string{"203.0.113.0/24", "1.2.3.4/32,10.0.0.0/8", "10.0.0.0/33", " 10.0.0.1", "198.51.100.7", "2001:db8::/32",
"fe80::1%eth0,10.0.0.0/8", "::1%a,0.0.0.0/0", "fe80::1%eth0", "203.0.113.9/24", "::ffff:10.1.0.0/112", "::ffff:198.51.100.8"}}
if err := ValidateExecRequest(&req); err != nil {
t.Fatalf("invalid entries failed the request: %v", err)
}
@ -34,9 +36,18 @@ func TestValidateExecRequestFiltersScopeEntries(t *testing.T) {
if got := strings.Join(req.ScopeDomains, " "); got != "example.com *.example.org xn--bcher-kva.example bücher.example host_1.lab." {
t.Errorf("domains = %q", got)
}
if got := strings.Join(req.ScopeCIDRs, " "); got != "203.0.113.0/24 198.51.100.7 2001:db8::/32" {
// An IPv6 zone may hold any text, commas included, so zoned addresses are
// dropped; entries are passed on in canonical form, mapped ones as IPv4.
if got := strings.Join(req.ScopeCIDRs, " "); got != "203.0.113.0/24 198.51.100.7 2001:db8::/32 203.0.113.0/24 10.1.0.0/16 198.51.100.8" {
t.Errorf("CIDRs = %q", got)
}
long := make([]string, MaxScopeBytes/200)
for i := range long {
long[i] = strings.Repeat("a", 240) + ".example"
}
if err := ValidateExecRequest(&ExecRequest{Argv: []string{"true"}, ScopeDomains: long}); !errors.Is(err, ErrBadRequest) {
t.Errorf("%d bytes of scope accepted: %v", joinedLen(long), err)
}
many := make([]string, MaxScopeEntries+1)
for i := range many {
many[i] = "a.example"