Files
ARTEX/sandbox/validate.go
Marco Azarmaneche 3eedbdc326 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.
2026-12-03 14:38:15 +02:00

199 lines
6.8 KiB
Go

package sandbox
import (
"fmt"
"net/netip"
"path"
"regexp"
"strings"
)
var (
taskIDRE = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,63}$`)
envNameRE = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]{0,127}$`)
// A scope domain: labels of letters, digits, '-' or '_', optionally "*." first.
scopeDomainRE = regexp.MustCompile(`^(\*\.)?[\p{L}\p{N}_-]+(\.[\p{L}\p{N}_-]+)*\.?$`)
)
// 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 {
id = strings.TrimSpace(id)
if id == "" || !taskIDRE.MatchString(id) || strings.Contains(id, "..") {
return fmt.Errorf("%w: invalid task id %q", ErrBadRequest, id)
}
return nil
}
// IsForbiddenEnvName reports whether name matches any forbidden secret/cloud/DB pattern
// pinned in CONTRACT.md §3: ARTEX_*, *_KEY, *_TOKEN, *_PASSWORD, *_SECRET, PG*, AWS_*, GCP_*, AZURE_*.
func IsForbiddenEnvName(name string) bool {
u := strings.ToUpper(strings.TrimSpace(name))
if u == "" {
return true
}
for _, prefix := range []string{"ARTEX_", "PG", "AWS_", "GCP_", "AZURE_"} {
if strings.HasPrefix(u, prefix) {
return true
}
}
for _, suffix := range []string{"_KEY", "_TOKEN", "_PASSWORD", "_SECRET"} {
if strings.HasSuffix(u, suffix) {
return true
}
}
return false
}
// isReservedEnvName reports whether name is set by the worker itself (proxy
// routing, PATH) or makes a shell, the loader or Python run code the command did
// not ask for (LD_*, BASH_ENV, ENV, GCONV_PATH, PYTHONPATH). A request may not
// set these in either backend.
func isReservedEnvName(name string) bool {
u := strings.ToUpper(name)
switch u {
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_")
}
// ValidateEnv rejects forbidden or reserved variable names, invalid names, NUL bytes, or values > 8192 bytes.
// Per CONTRACT.md §3 this is always a 400 validation error, never a silent drop.
func ValidateEnv(env map[string]string) error {
for k, v := range env {
if !envNameRE.MatchString(k) {
return fmt.Errorf("%w: invalid env variable name %q", ErrBadRequest, k)
}
if IsForbiddenEnvName(k) || isReservedEnvName(k) {
return fmt.Errorf("%w: forbidden env variable %q", ErrBadRequest, k)
}
if len(v) > MaxEnvValueBytes {
return fmt.Errorf("%w: env variable %q exceeds %d bytes", ErrBadRequest, k, MaxEnvValueBytes)
}
if strings.ContainsRune(v, 0) {
return fmt.Errorf("%w: env variable %q contains NUL byte", ErrBadRequest, k)
}
}
return nil
}
// FilterPanelEnv strips forbidden variables from an ambient/session env slice before
// sending additive env vars from the panel to the runner (the runner still validates strictly).
func FilterPanelEnv(kvs []string) map[string]string {
out := make(map[string]string)
for _, kv := range kvs {
k, v, ok := strings.Cut(kv, "=")
if !ok || !envNameRE.MatchString(k) || IsForbiddenEnvName(k) || isReservedEnvName(k) || len(v) > MaxEnvValueBytes || strings.ContainsRune(v, 0) {
continue
}
// Never override worker home variables from panel process env.
switch strings.ToUpper(k) {
case "HOME", "XDG_CACHE_HOME":
continue
}
out[k] = v
}
return out
}
// ValidateExecRequest validates and normalizes an ExecRequest in place.
func ValidateExecRequest(req *ExecRequest) error {
if req == nil {
return fmt.Errorf("%w: missing request body", ErrBadRequest)
}
if len(req.Argv) == 0 || strings.TrimSpace(req.Argv[0]) == "" {
return fmt.Errorf("%w: argv must be non-empty", ErrBadRequest)
}
for i, arg := range req.Argv {
if strings.ContainsRune(arg, 0) {
return fmt.Errorf("%w: argv[%d] contains NUL byte", ErrBadRequest, i)
}
}
if req.TimeoutMS < 0 || req.TimeoutMS > MaxTimeoutMS {
return fmt.Errorf("%w: timeout_ms must be between 0 and %d", ErrBadRequest, MaxTimeoutMS)
}
if req.TimeoutMS == 0 {
req.TimeoutMS = DefaultTimeoutMS
}
if strings.TrimSpace(req.Workdir) == "" {
req.Workdir = "/workspace"
} else {
clean := path.Clean(req.Workdir)
if clean != "/workspace" && !strings.HasPrefix(clean, "/workspace/") {
return fmt.Errorf("%w: workdir must stay inside /workspace (got %q)", ErrBadRequest, req.Workdir)
}
req.Workdir = clean
}
if len(req.ScopeDomains) > MaxScopeEntries || len(req.ScopeCIDRs) > MaxScopeEntries {
return fmt.Errorf("%w: more than %d scope entries", ErrBadRequest, MaxScopeEntries)
}
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 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 c, ok := canon(e); ok {
kept = append(kept, c)
} else {
dropped = append(dropped, e)
}
}
return kept, dropped
}
func joinedLen(entries []string) int {
n := 0
for _, e := range entries {
n += len(e) + 1
}
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
}