mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-12-06 22:53:55 +08:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c711af59b2 | ||
|
|
b39a8e2f5d |
@@ -40,6 +40,7 @@ All notable changes to this project are documented in this file. The format is b
|
||||
### Added
|
||||
|
||||
- **The task page links to the task's files.** A folder button in the task header opens Workspace at `tasks/<id>`, where the task's agents write their output, instead of browsing there by hand. In the Sessions tab, a worker whose folder exists (`tasks/<id>/i<intent id>`) gets a folder button next to it that opens that folder.
|
||||
- **The task page links to the task's files.** A folder button in the task header opens Workspace at `tasks/<id>`, where the task's agents write their output, instead of browsing there by hand.
|
||||
- **The Workspace file sheet previews files.** Opening a file in Workspace now shows a Preview tab next to the editor: Markdown is rendered, JSON and HTML/XML are shown with line numbers and highlighting, other text with line numbers, and PNG, JPEG, GIF, WebP, BMP, ICO and AVIF images are shown inline (up to 10 MiB, fetched through `/api/workspace/download`). SVG is shown as source, never rendered. Text over 200,000 characters or 5,000 lines is shown as plain text so the page stays responsive; text over the server's 2 MiB read limit shows its last 256 KB, fetched with a `Range` request and scrolled to the end; binary files still offer a download. The sheet also gets the 672 px width it asked for: a Tailwind specificity clash held it at 384 px.
|
||||
|
||||
- **Kubernetes sandbox backend for `artex-runner`.** With `ARTEX_RUNNER_BACKEND=kubernetes` each task runs in a worker pod behind its own egress-proxy pod, created through the Kubernetes API with no container runtime socket. The worker runs as uid/gid 10001 with `runAsNonRoot`, a read-only root filesystem, all capabilities dropped, `seccomp: RuntimeDefault`, no service-account token and no service links, and mounts only its task directory. Per-task NetworkPolicies are created before the pods and deleted after them: the worker can reach only its own proxy, and the proxy only cluster DNS, public addresses and the task's scope CIDRs. No scope opens the cluster's own ranges, the API server or cloud metadata: set `ARTEX_KUBE_CLUSTER_CIDRS` to the pod, service and node CIDRs, plus the API server endpoint addresses when they lie outside them as on managed clusters (without it, private scope CIDRs are dropped). The runner waits until the policies are in effect before the first command, runs commands through `pods/exec`, and re-adopts task pods after a restart.
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
package config
|
||||
|
||||
import "testing"
|
||||
|
||||
func BenchmarkRedactCleanURL(b *testing.B) {
|
||||
dsn := "postgres://artex:secretpass@127.0.0.1:5432/artex?sslmode=disable"
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for b.Loop() {
|
||||
if got := Redact(dsn); got == "" {
|
||||
b.Fatal("empty")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkRedactTokenQuery(b *testing.B) {
|
||||
dsn := "postgres://artex:secretpass@127.0.0.1:5432/artex?sslmode=disable&token=abc123&api_key=xyz"
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for b.Loop() {
|
||||
if got := Redact(dsn); got == "" {
|
||||
b.Fatal("empty")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkRedactLibpq(b *testing.B) {
|
||||
dsn := "host=127.0.0.1 port=5432 user=artex password=secretpass dbname=artex sslmode=disable"
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for b.Loop() {
|
||||
if got := Redact(dsn); got == "" {
|
||||
b.Fatal("empty")
|
||||
}
|
||||
}
|
||||
}
|
||||
+130
-35
@@ -254,18 +254,97 @@ func (d Database) buildDSN() string {
|
||||
return u.String()
|
||||
}
|
||||
|
||||
// libpqPassword matches the libpq secret keywords: password, and sslpassword
|
||||
// (the passphrase of an encrypted client key), in any letter case.
|
||||
// isASCIIWord reports whether c matches regex \w ([A-Za-z0-9_]).
|
||||
func isASCIIWord(c byte) bool {
|
||||
return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '_'
|
||||
}
|
||||
|
||||
// hasNonASCII reports whether s holds a byte outside ASCII.
|
||||
func hasNonASCII(s string) bool {
|
||||
for i := 0; i < len(s); i++ {
|
||||
if s[i] >= 0x80 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// libpqPassword is the regexp keyword matcher. Unicode case folding can change a
|
||||
// keyword's byte length (ſ folds to s, the Kelvin sign K to k), which the byte
|
||||
// scanner below cannot model, so any input holding a non-ASCII byte uses it.
|
||||
var libpqPassword = regexp.MustCompile(`(?i)\b((?:ssl)?password)\s*=\s*`)
|
||||
|
||||
// findLibpqPassword locates the next occurrence of (?i)\b((?:ssl)?password)\s*=\s*
|
||||
// in s, returning (start, keyEnd, valStart, ok). ASCII input takes the byte
|
||||
// scanner; a non-ASCII byte falls back to the regexp for the reason above.
|
||||
func findLibpqPassword(s string) (start, keyEnd, valStart int, ok bool) {
|
||||
if hasNonASCII(s) {
|
||||
loc := libpqPassword.FindStringSubmatchIndex(s)
|
||||
if loc == nil {
|
||||
return 0, 0, 0, false
|
||||
}
|
||||
return loc[0], loc[3], loc[1], true
|
||||
}
|
||||
const pwLen = len("password")
|
||||
for i := 0; i+pwLen < len(s); i++ {
|
||||
if i > 0 && isASCIIWord(s[i-1]) {
|
||||
continue
|
||||
}
|
||||
kStart := i
|
||||
kEnd := i
|
||||
switch s[i] {
|
||||
case 's', 'S':
|
||||
if i+3+pwLen < len(s) && strings.EqualFold(s[i:i+3+pwLen], "sslpassword") {
|
||||
kEnd = i + 3 + pwLen
|
||||
}
|
||||
case 'p', 'P':
|
||||
if strings.EqualFold(s[i:i+pwLen], "password") {
|
||||
kEnd = i + pwLen
|
||||
}
|
||||
}
|
||||
if kEnd == kStart {
|
||||
continue
|
||||
}
|
||||
j := kEnd
|
||||
for j < len(s) && (s[j] == ' ' || s[j] == '\t' || s[j] == '\r' || s[j] == '\n' || s[j] == '\f') {
|
||||
j++
|
||||
}
|
||||
if j >= len(s) || s[j] != '=' {
|
||||
continue
|
||||
}
|
||||
j++
|
||||
for j < len(s) && (s[j] == ' ' || s[j] == '\t' || s[j] == '\r' || s[j] == '\n' || s[j] == '\f') {
|
||||
j++
|
||||
}
|
||||
return kStart, kEnd, j, true
|
||||
}
|
||||
return 0, 0, 0, false
|
||||
}
|
||||
|
||||
// isDSNSecretParam reports whether a URL query parameter carries a secret.
|
||||
func isDSNSecretParam(key string) bool {
|
||||
switch strings.ToLower(key) {
|
||||
case "password", "sslpassword",
|
||||
"token", "access_token", "access-token", "auth_token", "auth-token", "refresh_token", "id_token",
|
||||
"api_key", "api-key", "apikey",
|
||||
"secret", "client_secret", "client-secret":
|
||||
return true
|
||||
if hasNonASCII(key) {
|
||||
// Unicode case folding can change the byte length of a word (the Kelvin
|
||||
// sign K folds to k), so the length switch below cannot decide.
|
||||
key = strings.ToLower(key)
|
||||
}
|
||||
switch len(key) {
|
||||
case 5:
|
||||
return strings.EqualFold(key, "token")
|
||||
case 6:
|
||||
return strings.EqualFold(key, "apikey") || strings.EqualFold(key, "secret")
|
||||
case 7:
|
||||
return strings.EqualFold(key, "api_key") || strings.EqualFold(key, "api-key")
|
||||
case 8:
|
||||
return strings.EqualFold(key, "password") || strings.EqualFold(key, "id_token")
|
||||
case 10:
|
||||
return strings.EqualFold(key, "auth_token") || strings.EqualFold(key, "auth-token")
|
||||
case 11:
|
||||
return strings.EqualFold(key, "sslpassword")
|
||||
case 12:
|
||||
return strings.EqualFold(key, "access_token") || strings.EqualFold(key, "access-token")
|
||||
case 13:
|
||||
return strings.EqualFold(key, "refresh_token") || strings.EqualFold(key, "client_secret") || strings.EqualFold(key, "client-secret")
|
||||
default:
|
||||
return false
|
||||
}
|
||||
@@ -275,16 +354,24 @@ func isDSNSecretParam(key string) bool {
|
||||
// including escaped whitespace and quotes. An unterminated quoted value consumes
|
||||
// the rest of the input: malformed configuration must not reveal its secret.
|
||||
func redactKeywordPasswords(dsn string) string {
|
||||
start, keyEnd, i, ok := findLibpqPassword(dsn)
|
||||
if !ok {
|
||||
return dsn
|
||||
}
|
||||
var out strings.Builder
|
||||
out.Grow(len(dsn))
|
||||
for {
|
||||
loc := libpqPassword.FindStringSubmatchIndex(dsn)
|
||||
if loc == nil {
|
||||
out.WriteString(dsn)
|
||||
return out.String()
|
||||
out.WriteString(dsn[:start])
|
||||
key := dsn[start:keyEnd]
|
||||
if hasNonASCII(key) {
|
||||
// Keep the spelling: a Unicode keyword's byte length does not say
|
||||
// which keyword it is.
|
||||
out.WriteString(strings.ToLower(key) + "=****")
|
||||
} else if keyEnd-start == len("sslpassword") {
|
||||
out.WriteString("sslpassword=****")
|
||||
} else {
|
||||
out.WriteString("password=****")
|
||||
}
|
||||
out.WriteString(dsn[:loc[0]])
|
||||
out.WriteString(strings.ToLower(dsn[loc[2]:loc[3]]) + "=****")
|
||||
i := loc[1]
|
||||
var quote byte
|
||||
if i < len(dsn) && (dsn[i] == '\'' || dsn[i] == '"') {
|
||||
quote = dsn[i]
|
||||
@@ -305,13 +392,18 @@ func redactKeywordPasswords(dsn string) string {
|
||||
break
|
||||
}
|
||||
} else {
|
||||
if strings.ContainsRune(" \t\r\n\v\f", rune(c)) {
|
||||
if c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '\v' || c == '\f' {
|
||||
break
|
||||
}
|
||||
i++
|
||||
}
|
||||
}
|
||||
dsn = dsn[i:]
|
||||
start, keyEnd, i, ok = findLibpqPassword(dsn)
|
||||
if !ok {
|
||||
out.WriteString(dsn)
|
||||
return out.String()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -320,9 +412,9 @@ func redactKeywordPasswords(dsn string) string {
|
||||
// password contains an unencoded '#', '/' or '?'. Any such '@' fails closed: a
|
||||
// split password cannot be told apart from a harmless '@' in a query value.
|
||||
func hasSplitUserinfoPassword(u *url.URL) bool {
|
||||
return strings.Contains(u.Fragment, "@") ||
|
||||
strings.Contains(u.Path, "@") ||
|
||||
strings.Contains(u.RawQuery, "@")
|
||||
return strings.IndexByte(u.Fragment, '@') >= 0 ||
|
||||
strings.IndexByte(u.Path, '@') >= 0 ||
|
||||
strings.IndexByte(u.RawQuery, '@') >= 0
|
||||
}
|
||||
|
||||
// Redact is a log-safe view of a PostgreSQL DSN. It masks URL userinfo
|
||||
@@ -346,33 +438,36 @@ func Redact(dsn string) string {
|
||||
u.User = url.UserPassword(u.User.Username(), "****")
|
||||
}
|
||||
}
|
||||
q, qerr := url.ParseQuery(u.RawQuery)
|
||||
if qerr != nil {
|
||||
return u.Scheme + "://[redacted]"
|
||||
}
|
||||
masked := false
|
||||
for k := range q {
|
||||
if isDSNSecretParam(k) {
|
||||
q[k] = []string{"****"}
|
||||
masked = true
|
||||
if u.RawQuery != "" {
|
||||
q, qerr := url.ParseQuery(u.RawQuery)
|
||||
if qerr != nil {
|
||||
return u.Scheme + "://[redacted]"
|
||||
}
|
||||
masked := false
|
||||
for k := range q {
|
||||
if isDSNSecretParam(k) {
|
||||
q[k] = []string{"****"}
|
||||
masked = true
|
||||
}
|
||||
}
|
||||
if masked {
|
||||
u.RawQuery = q.Encode()
|
||||
}
|
||||
}
|
||||
if masked {
|
||||
u.RawQuery = q.Encode()
|
||||
}
|
||||
return u.String()
|
||||
}
|
||||
// A URL whose password has an unencoded # / ? or % does not parse; its
|
||||
// password still runs from the first : after the scheme to the last @.
|
||||
if i := strings.Index(dsn, "://"); i >= 0 {
|
||||
if at := strings.LastIndex(dsn, "@"); at > i {
|
||||
if c := strings.Index(dsn[i+3:at], ":"); c >= 0 {
|
||||
if at := strings.LastIndexByte(dsn, '@'); at > i {
|
||||
if c := strings.IndexByte(dsn[i+3:at], ':'); c >= 0 {
|
||||
dsn = dsn[:i+3+c+1] + "****" + dsn[at:]
|
||||
}
|
||||
}
|
||||
}
|
||||
lower := strings.ToLower(strings.TrimSpace(dsn))
|
||||
if strings.HasPrefix(lower, "postgres://") || strings.HasPrefix(lower, "postgresql://") {
|
||||
trimmed := strings.TrimSpace(dsn)
|
||||
if len(trimmed) >= len("postgres://") && (strings.EqualFold(trimmed[:len("postgres://")], "postgres://") ||
|
||||
(len(trimmed) >= len("postgresql://") && strings.EqualFold(trimmed[:len("postgresql://")], "postgresql://"))) {
|
||||
// Fail closed: a malformed URL (e.g. raw '%' in password or bad port) may
|
||||
// carry user:pass@ that keyword=value redaction will not match.
|
||||
return "postgres://[redacted]"
|
||||
|
||||
@@ -161,6 +161,27 @@ func TestRedactMasksEveryDSNPasswordForm(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A non-ASCII letter can case-fold to an ASCII one and change a keyword's byte
|
||||
// length: ſ folds to s and the Kelvin sign K to k. The byte scanner cannot read
|
||||
// those spellings, so they must keep the regex and lowercase behaviour that
|
||||
// masked them before.
|
||||
func TestRedactUnicodeCaseFoldedSecrets(t *testing.T) {
|
||||
cases := []struct{ in, secret string }{
|
||||
{"host=db.example paſſword=SECRET_ONE dbname=app", "SECRET_ONE"},
|
||||
{"host=db.example sslpaſſword=SECRET_TWO dbname=app", "SECRET_TWO"},
|
||||
{"postgres://u@db.example/app?to\u212Aen=SECRET_THREE", "SECRET_THREE"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := Redact(c.in); strings.Contains(got, c.secret) {
|
||||
t.Errorf("Redact(%q)=%q still contains %q", c.in, got, c.secret)
|
||||
}
|
||||
}
|
||||
// The non-ASCII keyword keeps its spelling in the mask, as before.
|
||||
if got := Redact("host=db.example paſſword=SECRET_ONE"); got != "host=db.example paſſword=****" {
|
||||
t.Errorf("Redact kept spelling: got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMalformedConfigIsAnError(t *testing.T) {
|
||||
cfgPath := filepath.Join(t.TempDir(), "config.json")
|
||||
// What install.sh used to write for a password containing a double quote.
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand/v2"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Property 1: Fast findLibpqPassword scanner exact equivalence with the original
|
||||
// (?i)\b((?:ssl)?password)\s*=\s* regex across 5,000 generated inputs.
|
||||
func TestPropertyLibpqScannerEquivalence(t *testing.T) {
|
||||
re := regexp.MustCompile(`(?i)\b((?:ssl)?password)\s*=\s*`)
|
||||
rng := rand.New(rand.NewPCG(656, 1014))
|
||||
tokens := []string{
|
||||
"host=db", "user=u", "password=", "PASSWORD = ", "SslPassword\t=\n",
|
||||
"xpassword=1", "my_sslpassword=2", "password", "sslpassword", " ", "\t", "=", "'sec'", `"sec"`, "secret",
|
||||
// A Unicode letter that folds to an ASCII one changes the keyword's byte
|
||||
// length; the scanner must fall back to the regex on such input.
|
||||
"paſſword=", "sslpaſſword = ", "paſſword='sec'",
|
||||
}
|
||||
for range 5000 {
|
||||
var sb strings.Builder
|
||||
for range 1 + rng.IntN(6) {
|
||||
sb.WriteString(tokens[rng.IntN(len(tokens))])
|
||||
}
|
||||
s := sb.String()
|
||||
loc := re.FindStringSubmatchIndex(s)
|
||||
start, keyEnd, valStart, ok := findLibpqPassword(s)
|
||||
if loc == nil {
|
||||
if ok {
|
||||
t.Fatalf("scanner matched %q at (%d,%d,%d) but regex did not", s, start, keyEnd, valStart)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if !ok || start != loc[0] || keyEnd != loc[3] || valStart != loc[1] {
|
||||
t.Fatalf("mismatch on %q: scanner=(%d,%d,%d,%v) regex=(%d,%d,%d)",
|
||||
s, start, keyEnd, valStart, ok, loc[0], loc[3], loc[1])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Property 2: Historical bugs #656, #1014, #1019:
|
||||
// High-entropy secrets with arbitrary delimiter chars (#, /, ?, @, %, ;, ', ", \, space)
|
||||
// MUST NEVER appear in Redact(dsn), and Redact MUST be idempotent.
|
||||
func TestPropertyRedactNonLeakageAndIdempotence(t *testing.T) {
|
||||
rng := rand.New(rand.NewPCG(1014, 1019))
|
||||
delims := []string{"#", "/", "?", "@", "%", "%ZZ", ";", "'", `"`, `\`, " ", "=", ":"}
|
||||
secretParams := []string{
|
||||
"password", "sslpassword", "token", "access_token", "access-token",
|
||||
"auth_token", "auth-token", "refresh_token", "id_token",
|
||||
"api_key", "api-key", "apikey", "secret", "client_secret", "client-secret",
|
||||
}
|
||||
randCase := func(s string) string {
|
||||
b := []byte(s)
|
||||
for i := range b {
|
||||
if b[i] >= 'a' && b[i] <= 'z' && rng.IntN(2) == 1 {
|
||||
b[i] -= 'a' - 'A'
|
||||
}
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
for i := range 1000 {
|
||||
// Secret marker split around a hostile delimiter.
|
||||
tag := fmt.Sprintf("SEC%06d", i)
|
||||
d := delims[rng.IntN(len(delims))]
|
||||
pw := "p" + d + tag
|
||||
scheme := "postgres"
|
||||
if rng.IntN(2) == 1 {
|
||||
scheme = "postgresql"
|
||||
}
|
||||
if rng.IntN(4) == 0 {
|
||||
scheme = strings.ToUpper(scheme)
|
||||
}
|
||||
|
||||
// 1) Userinfo password (including split passwords with #, /, ?, @, %ZZ).
|
||||
u1 := fmt.Sprintf("%s://artex:%s@db.example:5432/app?sslmode=require", scheme, pw)
|
||||
out1 := Redact(u1)
|
||||
if strings.Contains(out1, tag) {
|
||||
t.Fatalf("userinfo secret leaked: in=%q out=%q", u1, out1)
|
||||
}
|
||||
if out1b := Redact(out1); out1b != out1 {
|
||||
t.Fatalf("Redact not idempotent on %q: once=%q twice=%q", u1, out1, out1b)
|
||||
}
|
||||
|
||||
// 2) Secret query parameter (any case, optional malformed sibling).
|
||||
pk := randCase(secretParams[rng.IntN(len(secretParams))])
|
||||
u2 := fmt.Sprintf("%s://artex@db.example:5432/app?sslmode=disable&%s=%s", scheme, pk, tag)
|
||||
out2 := Redact(u2)
|
||||
if strings.Contains(out2, tag) {
|
||||
t.Fatalf("query secret leaked: in=%q out=%q", u2, out2)
|
||||
}
|
||||
if out2b := Redact(out2); out2b != out2 {
|
||||
t.Fatalf("Redact not idempotent on %q: once=%q twice=%q", u2, out2, out2b)
|
||||
}
|
||||
|
||||
// 3) libpq keyword=value password / sslpassword (bare, single-quoted, double-quoted).
|
||||
kw := randCase("password")
|
||||
if rng.IntN(2) == 1 {
|
||||
kw = randCase("sslpassword")
|
||||
}
|
||||
var u3 string
|
||||
switch rng.IntN(3) {
|
||||
case 0:
|
||||
u3 = fmt.Sprintf("host=db.example %s=%s dbname=app", kw, tag)
|
||||
case 1:
|
||||
u3 = fmt.Sprintf("host=db.example %s='a\\' %s' dbname=app", kw, tag)
|
||||
default:
|
||||
u3 = fmt.Sprintf(`host=db.example %s="unterminated %s`, kw, tag)
|
||||
}
|
||||
out3 := Redact(u3)
|
||||
if strings.Contains(out3, tag) {
|
||||
t.Fatalf("libpq secret leaked: in=%q out=%q", u3, out3)
|
||||
}
|
||||
if out3b := Redact(out3); out3b != out3 {
|
||||
t.Fatalf("Redact not idempotent on %q: once=%q twice=%q", u3, out3, out3b)
|
||||
}
|
||||
}
|
||||
}
|
||||
+45
-30
@@ -87,11 +87,21 @@ func (w *argvWalk) step() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// argvCompoundMatches reports whether any command executed within a Bash tool
|
||||
// call matches or may match the deny/ask prefix rule tokens. See
|
||||
// argvCompoundMatch.
|
||||
func argvCompoundMatches(tokens []string, toolName string, input []byte) bool {
|
||||
return argvCompoundMatch(tokens, toolName, input) != argvNoMatch
|
||||
// parseBashCommand extracts the "command" field from a Bash tool input and
|
||||
// parses it once with the Bash parser. Callers reuse the resulting *syntax.File
|
||||
// across both decoded text rules and compound argv rules.
|
||||
func parseBashCommand(input []byte) (*syntax.File, string, bool) {
|
||||
var in struct {
|
||||
Command string `json:"command"`
|
||||
}
|
||||
if json.Unmarshal(input, &in) != nil || strings.TrimSpace(in.Command) == "" {
|
||||
return nil, "", false
|
||||
}
|
||||
f, err := syntax.NewParser(syntax.Variant(syntax.LangBash)).Parse(strings.NewReader(in.Command), "")
|
||||
if err != nil {
|
||||
return nil, "", false
|
||||
}
|
||||
return f, in.Command, true
|
||||
}
|
||||
|
||||
// argvCompoundMatch matches the deny/ask prefix rule tokens against every
|
||||
@@ -107,17 +117,19 @@ func argvCompoundMatch(tokens []string, toolName string, input []byte) argvMatch
|
||||
if toolName != "Bash" || len(tokens) == 0 {
|
||||
return argvNoMatch
|
||||
}
|
||||
var in struct {
|
||||
Command string `json:"command"`
|
||||
}
|
||||
if json.Unmarshal(input, &in) != nil {
|
||||
f, _, ok := parseBashCommand(input)
|
||||
if !ok {
|
||||
return argvNoMatch
|
||||
}
|
||||
if strings.TrimSpace(in.Command) == "" {
|
||||
return argvCompoundMatchFile(tokens, f)
|
||||
}
|
||||
|
||||
func argvCompoundMatchFile(tokens []string, f *syntax.File) argvMatch {
|
||||
if f == nil || len(tokens) == 0 {
|
||||
return argvNoMatch
|
||||
}
|
||||
w := &argvWalk{rule: tokens}
|
||||
if bashCommandMatchesArgv(w, in.Command, 0) {
|
||||
if bashFileMatchesArgv(w, f, 0) {
|
||||
return argvMatched
|
||||
}
|
||||
if w.possible {
|
||||
@@ -126,30 +138,19 @@ func argvCompoundMatch(tokens []string, toolName string, input []byte) argvMatch
|
||||
return argvNoMatch
|
||||
}
|
||||
|
||||
// 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 cmdIn struct {
|
||||
Command string `json:"command"`
|
||||
}
|
||||
if json.Unmarshal(input, &cmdIn) != nil || strings.TrimSpace(cmdIn.Command) == "" {
|
||||
// bashDecodedInputFromAST 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.
|
||||
func bashDecodedInputFromAST(input []byte, f *syntax.File) (string, bool) {
|
||||
if f == nil {
|
||||
return "", false
|
||||
}
|
||||
var in map[string]json.RawMessage
|
||||
if json.Unmarshal(input, &in) != nil {
|
||||
return "", false
|
||||
}
|
||||
f, err := syntax.NewParser(syntax.Variant(syntax.LangBash)).Parse(strings.NewReader(cmdIn.Command), "")
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
printer := syntax.NewPrinter()
|
||||
var cmds []string
|
||||
syntax.Walk(f, func(n syntax.Node) bool {
|
||||
@@ -187,7 +188,17 @@ func bashDecodedInput(toolName string, input []byte) (string, bool) {
|
||||
delete(in, k)
|
||||
}
|
||||
}
|
||||
in["command"] = bytes.Clone(bytes.TrimSpace(buf.Bytes()))
|
||||
cmdJSON := bytes.TrimSpace(buf.Bytes())
|
||||
if len(in) == 0 {
|
||||
// Common case: {"command":"..."} with no sibling fields.
|
||||
var out strings.Builder
|
||||
out.Grow(len(cmdJSON) + 13)
|
||||
out.WriteString(`{"command":`)
|
||||
out.Write(cmdJSON)
|
||||
out.WriteByte('}')
|
||||
return out.String(), true
|
||||
}
|
||||
in["command"] = bytes.Clone(cmdJSON)
|
||||
buf.Reset()
|
||||
if enc.Encode(in) != nil {
|
||||
return "", false
|
||||
@@ -204,6 +215,10 @@ func bashCommandMatchesArgv(w *argvWalk, command string, depth int) bool {
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return bashFileMatchesArgv(w, f, depth)
|
||||
}
|
||||
|
||||
func bashFileMatchesArgv(w *argvWalk, f *syntax.File, depth int) bool {
|
||||
outer := w.stdin
|
||||
defer func() { w.stdin = outer }()
|
||||
piped := map[*syntax.Stmt]*argvFeed{}
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
package intercept
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
)
|
||||
|
||||
func benchRuleSet() []db.InterceptRule {
|
||||
return []db.InterceptRule{
|
||||
{ID: 1, Name: "[built-in] Recursive force delete rm -rf", Enabled: true, Priority: 100, MatchTarget: "tool_input", MatchType: "regex", Action: "deny",
|
||||
Pattern: `(?i)\brm\b.{0,80}(?:-[a-z]*(?:r[a-z]*f|f[a-z]*r)[a-z]*|-[a-z]*r[a-z]*(?:\s+-+[a-z][a-z-]*)*?\s+-+[a-z]*f[a-z]*|-[a-z]*f[a-z]*(?:\s+-+[a-z][a-z-]*)*?\s+-+[a-z]*r[a-z]*|--recursive|--no-preserve-root)`},
|
||||
{ID: 2, Name: "[built-in] Delete critical system directories", Enabled: true, Priority: 100, MatchTarget: "tool_input", MatchType: "regex", Action: "deny",
|
||||
Pattern: `\brm\b[^"'\n]{0,60}["'\s](/|/etc|/bin|/usr|/boot|/var|/lib|/sys|/proc|/dev|/sbin|/root)`},
|
||||
{ID: 3, Name: "[built-in] Disk formatting mkfs", Enabled: true, Priority: 100, MatchTarget: "tool_input", MatchType: "regex", Action: "deny", Pattern: `\bmkfs\b`},
|
||||
{ID: 4, Name: "[built-in] Overwrite disk device dd", Enabled: true, Priority: 100, MatchTarget: "tool_input", MatchType: "regex", Action: "deny", Pattern: `\bdd\b[^|\n]{0,100}\bof=\s*/dev/[a-zA-Z]`},
|
||||
{ID: 5, Name: "[built-in] Fork bomb", Enabled: true, Priority: 100, MatchTarget: "tool_input", MatchType: "regex", Action: "deny", Pattern: `:\(\)\s*\{[^}]*:\|:`},
|
||||
{ID: 6, Name: "[built-in] Shutdown / reboot", Enabled: true, Priority: 100, MatchTarget: "tool_input", MatchType: "regex", Action: "deny", Pattern: `\b(?:shutdown|reboot|halt|poweroff|init\s+[06])\b`},
|
||||
{ID: 7, Name: "[built-in] Kill all processes", Enabled: true, Priority: 100, MatchTarget: "tool_input", MatchType: "regex", Action: "deny", Pattern: `\bkill\s+-9\s+-1\b|\bkillall\s+-9\b`},
|
||||
{ID: 8, Name: "[built-in] Disk wipe shred / wipe", Enabled: true, Priority: 100, MatchTarget: "tool_input", MatchType: "regex", Action: "deny", Pattern: `\b(?:shred|wipe)\b[^|\n]{0,80}/dev/[a-zA-Z]`},
|
||||
{ID: 9, Name: "[built-in] Flush firewall rules", Enabled: true, Priority: 100, MatchTarget: "tool_input", MatchType: "regex", Action: "deny", Pattern: `\biptables\s+(?:-F|--flush)\b|\bnft\s+flush\s+ruleset\b`},
|
||||
{ID: 10, Name: "[built-in] SQL DROP", Enabled: true, Priority: 90, MatchTarget: "tool_input", MatchType: "regex", Action: "deny", Pattern: `(?i)\bDROP\s+(?:DATABASE|TABLE|SCHEMA|INDEX|VIEW|TABLESPACE|USER|ROLE)\b`},
|
||||
{ID: 11, Name: "[built-in] SQL TRUNCATE", Enabled: true, Priority: 90, MatchTarget: "tool_input", MatchType: "regex", Action: "deny", Pattern: `(?i)\bTRUNCATE\s+(?:TABLE\s+)?\w`},
|
||||
{ID: 12, Name: "[built-in] MongoDB drop", Enabled: true, Priority: 90, MatchTarget: "tool_input", MatchType: "regex", Action: "deny", Pattern: `(?i)\.(?:dropDatabase|dropCollection|drop)\s*\(`},
|
||||
{ID: 13, Name: "[built-in] Redis FLUSH", Enabled: true, Priority: 90, MatchTarget: "tool_input", MatchType: "regex", Action: "deny", Pattern: `(?i)\b(?:FLUSHALL|FLUSHDB)\b`},
|
||||
{ID: 14, Name: "[built-in] curl/wget DELETE", Enabled: true, Priority: 80, MatchTarget: "tool_input", MatchType: "regex", Action: "deny",
|
||||
Pattern: `(?i)\bcurl\b[^|\n&;"]{0,300}(?:-X\s*DELETE|--request\s+DELETE|-XDELETE)|\bwget\b[^|\n&;"]{0,300}--method[=\s]+DELETE`},
|
||||
{ID: 15, Name: "[built-in] Python HTTP DELETE", Enabled: true, Priority: 80, MatchTarget: "tool_input", MatchType: "regex", Action: "deny",
|
||||
Pattern: `(?i)\b(?:requests|httpx|aiohttp|urllib\.request)\.delete\s*\(|session\.delete\s*\(|client\.delete\s*\(`},
|
||||
{ID: 16, Name: "[built-in] JS HTTP DELETE", Enabled: true, Priority: 80, MatchTarget: "tool_input", MatchType: "regex", Action: "deny",
|
||||
Pattern: `(?i)axios\.delete\s*\(|method\s*[:=]\s*['"]DELETE['"]`},
|
||||
{ID: 17, Name: "[built-in] Bulk clear/wipe paths", Enabled: true, Priority: 80, MatchTarget: "tool_input", MatchType: "regex", Action: "deny",
|
||||
Pattern: `(?i)/(?:clear|wipe|flush|purge|truncate|drop|destroy|factory[-_]reset|reset[-_]all)(?:[/?#"'\s]|$)`},
|
||||
{ID: 18, Name: "[built-in] Delete-style paths", Enabled: true, Priority: 80, MatchTarget: "tool_input", MatchType: "regex", Action: "deny",
|
||||
Pattern: `(?i)/(?:(?:delete|remove|unlink|erase|destroy)[-\w]*|del)(?:[/?#"'\s]|$)`},
|
||||
{ID: 19, Name: "deny git push", Enabled: true, Priority: 70, MatchTarget: "tool_input", MatchType: "argv", Action: "deny", Pattern: `["git","push"]`},
|
||||
{ID: 20, Name: "deny kubectl delete", Enabled: true, Priority: 70, MatchTarget: "tool_input", MatchType: "argv", Action: "deny", Pattern: `["kubectl","delete"]`},
|
||||
{ID: 21, Name: "deny terraform destroy", Enabled: true, Priority: 70, MatchTarget: "tool_input", MatchType: "argv", Action: "deny", Pattern: `["terraform","destroy"]`},
|
||||
{ID: 22, Name: "deny docker rm", Enabled: true, Priority: 70, MatchTarget: "tool_input", MatchType: "argv", Action: "deny", Pattern: `["docker","rm"]`},
|
||||
{ID: 23, Name: "deny aws s3 rm", Enabled: true, Priority: 70, MatchTarget: "tool_input", MatchType: "argv", Action: "deny", Pattern: `["aws","s3","rm"]`},
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkMatchBash23RulesBenign(b *testing.B) {
|
||||
ic := New(nil)
|
||||
ic.SetRulesForTest(benchRuleSet())
|
||||
in := []byte(`{"command":"curl -s -H 'Accept: application/json' https://app.example.com/api/v1/health | jq .status"}`)
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for b.Loop() {
|
||||
if _, ok := ic.Match("Bash", in); ok {
|
||||
b.Fatal("unexpected match")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkMatchBash23RulesMatch(b *testing.B) {
|
||||
ic := New(nil)
|
||||
ic.SetRulesForTest(benchRuleSet())
|
||||
in := []byte(`{"command":"r\\m -r -f /tmp/work"}`)
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for b.Loop() {
|
||||
if dec, ok := ic.Match("Bash", in); !ok || dec.Action != "deny" {
|
||||
b.Fatalf("expected deny, got ok=%v dec=%+v", ok, dec)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkMatchBashArgvCompound(b *testing.B) {
|
||||
ic := New(nil)
|
||||
ic.SetRulesForTest([]db.InterceptRule{
|
||||
{ID: 1, Name: "deny git push", Enabled: true, Priority: 70, MatchTarget: "tool_input", MatchType: "argv", Action: "deny", Pattern: `["git","push"]`},
|
||||
{ID: 2, Name: "deny kubectl delete", Enabled: true, Priority: 70, MatchTarget: "tool_input", MatchType: "argv", Action: "deny", Pattern: `["kubectl","delete"]`},
|
||||
{ID: 3, Name: "deny terraform destroy", Enabled: true, Priority: 70, MatchTarget: "tool_input", MatchType: "argv", Action: "deny", Pattern: `["terraform","destroy"]`},
|
||||
{ID: 4, Name: "deny docker rm", Enabled: true, Priority: 70, MatchTarget: "tool_input", MatchType: "argv", Action: "deny", Pattern: `["docker","rm"]`},
|
||||
{ID: 5, Name: "deny aws s3 rm", Enabled: true, Priority: 70, MatchTarget: "tool_input", MatchType: "argv", Action: "deny", Pattern: `["aws","s3","rm"]`},
|
||||
{ID: 6, Name: "deny helm uninstall", Enabled: true, Priority: 70, MatchTarget: "tool_input", MatchType: "argv", Action: "deny", Pattern: `["helm","uninstall"]`},
|
||||
{ID: 7, Name: "deny psql drop", Enabled: true, Priority: 70, MatchTarget: "tool_input", MatchType: "argv", Action: "deny", Pattern: `["psql"]`},
|
||||
{ID: 8, Name: "deny rsync", Enabled: true, Priority: 70, MatchTarget: "tool_input", MatchType: "argv", Action: "deny", Pattern: `["rsync"]`},
|
||||
})
|
||||
in := []byte(`{"command":"sudo -u app env FOO=1 timeout 30 curl -s https://app.example.com/api | jq .items"}`)
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for b.Loop() {
|
||||
if _, ok := ic.Match("Bash", in); ok {
|
||||
b.Fatal("unexpected match")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkExtractTargetsPlain(b *testing.B) {
|
||||
in := []byte(`{"command":"ls -la /workspace && grep -rn TODO src/ && wc -l README"}`)
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for b.Loop() {
|
||||
if ts := ExtractTargets("Bash", in); len(ts) != 0 {
|
||||
b.Fatalf("unexpected targets: %+v", ts)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkExtractTargetsURLAndIP(b *testing.B) {
|
||||
in := []byte(`{"command":"curl -A Chrome/156.0.0.0 -H 'Accept: application/json' https://api.example.com:8443/v1/users 192.0.2.10:8080"}`)
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for b.Loop() {
|
||||
if ts := ExtractTargets("Bash", in); len(ts) != 2 {
|
||||
b.Fatalf("want 2 targets, got %d: %+v", len(ts), ts)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkNormalizeTargetDomain(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for b.Loop() {
|
||||
if t, ok := NormalizeTarget("https://api.example.com:8443/v1/users"); !ok || t.Host != "api.example.com" {
|
||||
b.Fatalf("unexpected target: %+v ok=%v", t, ok)
|
||||
}
|
||||
}
|
||||
}
|
||||
+286
-52
@@ -19,6 +19,7 @@ import (
|
||||
"log/slog"
|
||||
"net"
|
||||
"regexp"
|
||||
"regexp/syntax"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -27,6 +28,7 @@ import (
|
||||
|
||||
"github.com/Autumn-27/artex/config"
|
||||
"github.com/Autumn-27/artex/db"
|
||||
shsyntax "mvdan.cc/sh/v3/syntax"
|
||||
)
|
||||
|
||||
// ctxKey is the unexported context key type to avoid collisions.
|
||||
@@ -120,15 +122,166 @@ func TargetScopeFromContext(ctx context.Context) (s TargetScope, ok bool) {
|
||||
// ask rule whose pattern does not compile: it matches every call, as a deny.
|
||||
type compiledRule struct {
|
||||
db.InterceptRule
|
||||
re *regexp.Regexp
|
||||
argv []string
|
||||
bad bool
|
||||
re *regexp.Regexp
|
||||
reNeedles []string // sound necessary lowercase-ASCII disjunction: if non-empty, a match must contain at least one needle
|
||||
argv []string
|
||||
bad bool
|
||||
allowOK bool
|
||||
configDigest string
|
||||
}
|
||||
|
||||
// extractRegexNeedles derives a sound necessary condition from a Perl regex:
|
||||
// if it returns a non-empty slice of lowercase ASCII strings, then any string
|
||||
// matched by the regex is guaranteed to contain at least one of those needles
|
||||
// when ASCII-lowercased. Returning nil means "unconstrained" (always run re).
|
||||
//
|
||||
// Soundness proof by structural induction on syntax.Regexp:
|
||||
// - OpLiteral (pure ASCII, no non-ASCII fold targets like 'k'/'s' under FoldCase):
|
||||
// every match must contain strings.ToLower(lit) (for FoldCase, only literals
|
||||
// whose runes cannot fold from non-ASCII are used, or we check ASCII-only
|
||||
// needles after full strings.ToLower). Since Go's strings.ToLower maps
|
||||
// Kelvin 'K'→'k' and long-s 'ſ'→'ſ' (wait: 'ſ' does NOT map to 's' under
|
||||
// strings.ToLower!), under FoldCase we skip literals containing 's' or 'k'
|
||||
// only if non-ASCII exists; even simpler, matchState only applies the
|
||||
// prefilter when the subject is pure ASCII (<0x80), where Unicode folding
|
||||
// cannot match any non-ASCII rune!
|
||||
// - OpCapture / OpPlus / OpRepeat(Min>=1): necessary condition of child holds.
|
||||
// - OpConcat: every child must match, so the most selective child's necessary
|
||||
// condition (fewest needles, breaking ties by longest min-needle) holds.
|
||||
// - OpAlternate: one branch must match, so the union of all branches' needle
|
||||
// sets holds (if every branch is constrained and total <= maxNeedles).
|
||||
// - All other ops return nil (unconstrained).
|
||||
func extractRegexNeedles(pattern string) []string {
|
||||
ast, err := syntax.Parse(pattern, syntax.Perl)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return regexASTNeedles(ast.Simplify())
|
||||
}
|
||||
|
||||
const maxPrefilterNeedles = 12
|
||||
|
||||
func regexASTNeedles(re *syntax.Regexp) []string {
|
||||
if re == nil {
|
||||
return nil
|
||||
}
|
||||
switch re.Op {
|
||||
case syntax.OpLiteral:
|
||||
if len(re.Rune) == 0 {
|
||||
return nil
|
||||
}
|
||||
buf := make([]byte, 0, len(re.Rune))
|
||||
for _, r := range re.Rune {
|
||||
if r >= 0x80 {
|
||||
return nil
|
||||
}
|
||||
c := byte(r)
|
||||
if c >= 'A' && c <= 'Z' {
|
||||
c += 'a' - 'A'
|
||||
}
|
||||
buf = append(buf, c)
|
||||
}
|
||||
return []string{string(buf)}
|
||||
case syntax.OpCapture, syntax.OpPlus:
|
||||
if len(re.Sub) == 1 {
|
||||
return regexASTNeedles(re.Sub[0])
|
||||
}
|
||||
case syntax.OpRepeat:
|
||||
if re.Min >= 1 && len(re.Sub) == 1 {
|
||||
return regexASTNeedles(re.Sub[0])
|
||||
}
|
||||
case syntax.OpConcat:
|
||||
var best []string
|
||||
bestScore := -1
|
||||
for _, sub := range re.Sub {
|
||||
ns := regexASTNeedles(sub)
|
||||
if len(ns) == 0 {
|
||||
continue
|
||||
}
|
||||
minLen := len(ns[0])
|
||||
for _, n := range ns[1:] {
|
||||
if len(n) < minLen {
|
||||
minLen = len(n)
|
||||
}
|
||||
}
|
||||
// Prefer single-needle filters first, then longer minimum needle length.
|
||||
score := minLen*100 - len(ns)*20
|
||||
if best == nil || score > bestScore {
|
||||
best = ns
|
||||
bestScore = score
|
||||
}
|
||||
}
|
||||
return best
|
||||
case syntax.OpAlternate:
|
||||
if len(re.Sub) == 0 {
|
||||
return nil
|
||||
}
|
||||
var union []string
|
||||
for _, sub := range re.Sub {
|
||||
ns := regexASTNeedles(sub)
|
||||
if len(ns) == 0 {
|
||||
return nil
|
||||
}
|
||||
for _, n := range ns {
|
||||
if !slices.Contains(union, n) {
|
||||
union = append(union, n)
|
||||
if len(union) > maxPrefilterNeedles {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return union
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func asciiLower(s string) (lower string, isASCII bool) {
|
||||
hasUpper := false
|
||||
for i := 0; i < len(s); i++ {
|
||||
c := s[i]
|
||||
if c >= 0x80 {
|
||||
return "", false
|
||||
}
|
||||
if c >= 'A' && c <= 'Z' {
|
||||
hasUpper = true
|
||||
}
|
||||
}
|
||||
if !hasUpper {
|
||||
return s, true
|
||||
}
|
||||
b := make([]byte, len(s))
|
||||
for i := 0; i < len(s); i++ {
|
||||
c := s[i]
|
||||
if c >= 'A' && c <= 'Z' {
|
||||
c += 'a' - 'A'
|
||||
}
|
||||
b[i] = c
|
||||
}
|
||||
return string(b), true
|
||||
}
|
||||
|
||||
func needlesMayMatch(lower string, needles []string) bool {
|
||||
for _, n := range needles {
|
||||
if strings.Contains(lower, n) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func ruleConfigDigest(r db.InterceptRule) string {
|
||||
configJSON, _ := json.Marshal(r)
|
||||
return digestInput(configJSON)
|
||||
}
|
||||
|
||||
// compileRule prepares a rule for matching. ok is false for a rule whose
|
||||
// pattern does not compile; see loadLocked for what happens to it.
|
||||
func compileRule(r db.InterceptRule) (compiledRule, bool) {
|
||||
cr := compiledRule{InterceptRule: r}
|
||||
cr := compiledRule{
|
||||
InterceptRule: r,
|
||||
configDigest: ruleConfigDigest(r),
|
||||
}
|
||||
switch r.MatchType {
|
||||
case "regex":
|
||||
re, err := regexp.Compile(r.Pattern)
|
||||
@@ -136,12 +289,14 @@ func compileRule(r db.InterceptRule) (compiledRule, bool) {
|
||||
return cr, false
|
||||
}
|
||||
cr.re = re
|
||||
cr.reNeedles = extractRegexNeedles(r.Pattern)
|
||||
case "argv":
|
||||
tokens, err := ParseArgvPattern(r.Pattern)
|
||||
if err != nil {
|
||||
return cr, false
|
||||
}
|
||||
cr.argv = tokens
|
||||
cr.allowOK = r.Action == "allow" && CheckArgvAllow(tokens) == nil
|
||||
}
|
||||
return cr, true
|
||||
}
|
||||
@@ -330,6 +485,7 @@ func (i *Interceptor) loadLocked() error {
|
||||
// A deny or ask rule that cannot be evaluated must not fail open.
|
||||
cr.bad, cr.Action = true, "deny"
|
||||
cr.Message = "intercept rule [" + r.Name + "] has a pattern that does not compile; calls are blocked until the rule is fixed or disabled"
|
||||
cr.configDigest = ruleConfigDigest(cr.InterceptRule)
|
||||
}
|
||||
out = append(out, cr)
|
||||
}
|
||||
@@ -708,6 +864,85 @@ func judgeActionLabel(action string) string {
|
||||
}
|
||||
}
|
||||
|
||||
// matchState caches per-call derived views of a tool invocation (raw string
|
||||
// subject, parsed Bash AST, decoded Bash JSON input, and argv allow prefix) so
|
||||
// evaluating N rules parses and decodes the call at most once.
|
||||
type matchState struct {
|
||||
toolName string
|
||||
input []byte
|
||||
rawReady bool
|
||||
rawInput string
|
||||
rawLowerOK bool
|
||||
rawLower string
|
||||
toolLowerOK bool
|
||||
toolLower string
|
||||
toolReady bool
|
||||
bashReady bool
|
||||
bashFile *shsyntax.File
|
||||
bashCmd string
|
||||
bashOK bool
|
||||
decReady bool
|
||||
decInput string
|
||||
decLowerOK bool
|
||||
decLower string
|
||||
decOK bool
|
||||
prefixReady bool
|
||||
prefix []string
|
||||
prefixOK bool
|
||||
}
|
||||
|
||||
func (m *matchState) rawSubject() (string, string, bool) {
|
||||
if !m.rawReady {
|
||||
m.rawInput = string(m.input)
|
||||
m.rawLower, m.rawLowerOK = asciiLower(m.rawInput)
|
||||
m.rawReady = true
|
||||
}
|
||||
return m.rawInput, m.rawLower, m.rawLowerOK
|
||||
}
|
||||
|
||||
func (m *matchState) toolSubject() (string, string, bool) {
|
||||
if !m.toolReady {
|
||||
m.toolLower, m.toolLowerOK = asciiLower(m.toolName)
|
||||
m.toolReady = true
|
||||
}
|
||||
return m.toolName, m.toolLower, m.toolLowerOK
|
||||
}
|
||||
|
||||
func (m *matchState) bashAST() (*shsyntax.File, bool) {
|
||||
if !m.bashReady {
|
||||
m.bashReady = true
|
||||
if m.toolName == "Bash" {
|
||||
m.bashFile, m.bashCmd, m.bashOK = parseBashCommand(m.input)
|
||||
}
|
||||
}
|
||||
return m.bashFile, m.bashOK
|
||||
}
|
||||
|
||||
func (m *matchState) decodedInput() (string, string, bool, bool) {
|
||||
if !m.decReady {
|
||||
m.decReady = true
|
||||
if f, ok := m.bashAST(); ok {
|
||||
m.decInput, m.decOK = bashDecodedInputFromAST(m.input, f)
|
||||
if m.decOK {
|
||||
m.decLower, m.decLowerOK = asciiLower(m.decInput)
|
||||
}
|
||||
}
|
||||
}
|
||||
return m.decInput, m.decLower, m.decLowerOK, m.decOK
|
||||
}
|
||||
|
||||
func (m *matchState) argvAllowPrefix() ([]string, bool) {
|
||||
if !m.prefixReady {
|
||||
m.prefixReady = true
|
||||
if _, ok := m.bashAST(); ok {
|
||||
if p, err := ArgvPrefix(m.bashCmd); err == nil {
|
||||
m.prefix, m.prefixOK = p, true
|
||||
}
|
||||
}
|
||||
}
|
||||
return m.prefix, m.prefixOK
|
||||
}
|
||||
|
||||
// Match evaluates the rule list (priority DESC) against a tool call.
|
||||
// Returns (Decision, true) for the first matching enabled rule, or
|
||||
// (Decision{}, false) if no rule matches. When the rules cannot be loaded it
|
||||
@@ -721,28 +956,17 @@ func (i *Interceptor) Match(toolName string, input []byte) (Decision, bool) {
|
||||
if err != nil {
|
||||
return storeUnreadableDecision(), true
|
||||
}
|
||||
ms := matchState{toolName: toolName, input: input}
|
||||
var possible *Decision
|
||||
for _, r := range rules {
|
||||
m := ruleMatch(r, toolName, input)
|
||||
for idx := range rules {
|
||||
r := rules[idx]
|
||||
m := ruleMatchState(r, &ms)
|
||||
if m == argvPossible && possible == nil {
|
||||
d := possibleArgvDecision(r)
|
||||
possible = &d
|
||||
}
|
||||
if m == argvMatched && (possible == nil || r.Action == "deny") {
|
||||
msg := r.Message
|
||||
if msg == "" {
|
||||
msg = defaultMessage(r.Action, r.Name)
|
||||
}
|
||||
configJSON, _ := json.Marshal(r.InterceptRule)
|
||||
return Decision{
|
||||
RuleName: r.Name, ConfigDigest: digestInput(configJSON),
|
||||
Action: r.Action,
|
||||
Message: msg,
|
||||
RuleID: r.ID,
|
||||
TimeoutEnabled: r.TimeoutEnabled,
|
||||
TimeoutSeconds: r.TimeoutSeconds,
|
||||
TimeoutAction: r.TimeoutAction,
|
||||
}, true
|
||||
return persistenceDecision(r), true
|
||||
}
|
||||
}
|
||||
if possible != nil {
|
||||
@@ -768,16 +992,20 @@ func possibleArgvDecision(r compiledRule) Decision {
|
||||
return d
|
||||
}
|
||||
|
||||
// ruleMatch is ruleMatches, keeping apart a deny or ask argv rule that may
|
||||
// match from one that matches.
|
||||
func ruleMatch(r compiledRule, toolName string, input []byte) argvMatch {
|
||||
// ruleMatchState is ruleMatchesState, keeping apart a deny or ask argv rule
|
||||
// that may match from one that matches.
|
||||
func ruleMatchState(r compiledRule, ms *matchState) argvMatch {
|
||||
if !r.bad && r.MatchType == "argv" && (r.Action == "deny" || r.Action == "ask") {
|
||||
if r.MatchTarget != "tool_input" {
|
||||
return argvNoMatch
|
||||
}
|
||||
return argvCompoundMatch(r.argv, toolName, input)
|
||||
f, ok := ms.bashAST()
|
||||
if !ok {
|
||||
return argvNoMatch
|
||||
}
|
||||
return argvCompoundMatchFile(r.argv, f)
|
||||
}
|
||||
if ruleMatches(r, toolName, input) {
|
||||
if ruleMatchesState(r, ms) {
|
||||
return argvMatched
|
||||
}
|
||||
return argvNoMatch
|
||||
@@ -807,21 +1035,15 @@ func (i *Interceptor) MatchBuiltin(toolName string, input []byte) (Decision, boo
|
||||
if err != nil {
|
||||
return storeUnreadableDecision(), true
|
||||
}
|
||||
for _, r := range rules {
|
||||
if r.Action != "deny" || !strings.HasPrefix(r.Name, builtinRulePrefix) || !ruleMatches(r, toolName, input) {
|
||||
ms := matchState{toolName: toolName, input: input}
|
||||
for idx := range rules {
|
||||
r := rules[idx]
|
||||
if r.Action != "deny" || !strings.HasPrefix(r.Name, builtinRulePrefix) || !ruleMatchesState(r, &ms) {
|
||||
continue
|
||||
}
|
||||
msg := r.Message
|
||||
if msg == "" {
|
||||
msg = defaultMessage(r.Action, r.Name)
|
||||
}
|
||||
configJSON, _ := json.Marshal(r.InterceptRule)
|
||||
return Decision{
|
||||
RuleName: r.Name, ConfigDigest: digestInput(configJSON),
|
||||
Action: r.Action,
|
||||
Message: msg,
|
||||
RuleID: r.ID,
|
||||
}, true
|
||||
d := persistenceDecision(r)
|
||||
d.TimeoutEnabled, d.TimeoutSeconds, d.TimeoutAction = false, 0, ""
|
||||
return d, true
|
||||
}
|
||||
return Decision{}, false
|
||||
}
|
||||
@@ -851,7 +1073,7 @@ func (i *Interceptor) SetRulesForTest(rules []db.InterceptRule) {
|
||||
i.mu.Unlock()
|
||||
}
|
||||
|
||||
func ruleMatches(r compiledRule, toolName string, input []byte) bool {
|
||||
func ruleMatchesState(r compiledRule, ms *matchState) bool {
|
||||
if r.bad {
|
||||
return true
|
||||
}
|
||||
@@ -861,28 +1083,34 @@ func ruleMatches(r compiledRule, toolName string, input []byte) bool {
|
||||
// exact derived prefix and denylist enforcement. Deny and ask rules
|
||||
// walk every call in a compound Bash command, stripping known wrappers
|
||||
// and recursing into eval / shell -c payloads. One that may match
|
||||
// counts as a match here; Match asks for it instead (ruleMatch).
|
||||
// counts as a match here; Match asks for it instead (ruleMatchState).
|
||||
if r.Action == "allow" {
|
||||
if CheckArgvAllow(r.argv) != nil {
|
||||
if !r.allowOK || r.MatchTarget != "tool_input" {
|
||||
return false
|
||||
}
|
||||
return r.MatchTarget == "tool_input" && argvRuleMatches(r.argv, toolName, input)
|
||||
prefix, ok := ms.argvAllowPrefix()
|
||||
return ok && slices.Equal(prefix, r.argv)
|
||||
}
|
||||
if r.Action == "deny" || r.Action == "ask" {
|
||||
return r.MatchTarget == "tool_input" && argvCompoundMatches(r.argv, toolName, input)
|
||||
if r.MatchTarget != "tool_input" {
|
||||
return false
|
||||
}
|
||||
f, ok := ms.bashAST()
|
||||
return ok && argvCompoundMatchFile(r.argv, f) != argvNoMatch
|
||||
}
|
||||
return false
|
||||
}
|
||||
var subject string
|
||||
var subject, lower string
|
||||
var lowerOK bool
|
||||
switch r.MatchTarget {
|
||||
case "tool_name":
|
||||
subject = toolName
|
||||
subject, lower, lowerOK = ms.toolSubject()
|
||||
case "tool_input":
|
||||
subject = string(input)
|
||||
subject, lower, lowerOK = ms.rawSubject()
|
||||
default:
|
||||
return false
|
||||
}
|
||||
if textRuleMatches(r, subject) {
|
||||
if textRuleMatchesFast(r, subject, lower, lowerOK) {
|
||||
return true
|
||||
}
|
||||
// Bash runs a command only after it removes quotes and backslashes and
|
||||
@@ -892,14 +1120,20 @@ func ruleMatches(r compiledRule, toolName string, input []byte) bool {
|
||||
if r.MatchTarget != "tool_input" || (r.Action != "deny" && r.Action != "ask") {
|
||||
return false
|
||||
}
|
||||
decoded, ok := bashDecodedInput(toolName, input)
|
||||
return ok && textRuleMatches(r, decoded)
|
||||
decoded, decLower, decLowerOK, ok := ms.decodedInput()
|
||||
return ok && textRuleMatchesFast(r, decoded, decLower, decLowerOK)
|
||||
}
|
||||
|
||||
// textRuleMatches matches a regex or string rule against subject.
|
||||
func textRuleMatches(r compiledRule, subject string) bool {
|
||||
// textRuleMatchesFast checks the sound ASCII needle prefilter before running RE2.
|
||||
func textRuleMatchesFast(r compiledRule, subject, lower string, lowerOK bool) bool {
|
||||
if r.MatchType == "regex" {
|
||||
return r.re != nil && r.re.MatchString(subject)
|
||||
if r.re == nil {
|
||||
return false
|
||||
}
|
||||
if lowerOK && len(r.reNeedles) > 0 && !needlesMayMatch(lower, r.reNeedles) {
|
||||
return false
|
||||
}
|
||||
return r.re.MatchString(subject)
|
||||
}
|
||||
return strings.Contains(subject, r.Pattern)
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package intercept
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"slices"
|
||||
"strings"
|
||||
)
|
||||
@@ -36,10 +35,11 @@ func (i *Interceptor) MatchPersistence(toolName string, input []byte) (Decision,
|
||||
if err != nil {
|
||||
return storeUnreadableDecision(), true
|
||||
}
|
||||
ms := matchState{toolName: toolName, input: input}
|
||||
var ask *compiledRule
|
||||
for idx := range rules {
|
||||
r := rules[idx]
|
||||
if !ruleMatches(r, toolName, input) {
|
||||
if !ruleMatchesState(r, &ms) {
|
||||
continue
|
||||
}
|
||||
if r.Action == "deny" {
|
||||
@@ -60,9 +60,12 @@ func persistenceDecision(r compiledRule) Decision {
|
||||
if msg == "" {
|
||||
msg = defaultMessage(r.Action, r.Name)
|
||||
}
|
||||
configJSON, _ := json.Marshal(r.InterceptRule)
|
||||
digest := r.configDigest
|
||||
if digest == "" {
|
||||
digest = ruleConfigDigest(r.InterceptRule)
|
||||
}
|
||||
return Decision{
|
||||
RuleName: r.Name, ConfigDigest: digestInput(configJSON),
|
||||
RuleName: r.Name, ConfigDigest: digest,
|
||||
Action: r.Action,
|
||||
Message: msg,
|
||||
RuleID: r.ID,
|
||||
|
||||
@@ -0,0 +1,321 @@
|
||||
package intercept
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math/rand/v2"
|
||||
"net/netip"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
"golang.org/x/net/idna"
|
||||
)
|
||||
|
||||
// Property 1: Soundness of extractRegexNeedles prefilter.
|
||||
// Invariant: for any regex pattern and ASCII subject s, if the prefilter says
|
||||
// no needle matches asciiLower(s), then re.MatchString(s) MUST be false.
|
||||
func TestPropertyRegexPrefilterSoundness(t *testing.T) {
|
||||
patterns := []string{
|
||||
`(?i)\brm\b.{0,80}(?:-[a-z]*(?:r[a-z]*f|f[a-z]*r)[a-z]*|--recursive|--no-preserve-root)`,
|
||||
`\brm\b[^"'\n]{0,60}["'\s](/|/etc|/bin|/usr|/boot|/var|/lib|/sys|/proc|/dev|/sbin|/root)`,
|
||||
`\bmkfs\b`,
|
||||
`\bdd\b[^|\n]{0,100}\bof=\s*/dev/[a-zA-Z]`,
|
||||
`:\(\)\s*\{[^}]*:\|:`,
|
||||
`\b(?:shutdown|reboot|halt|poweroff|init\s+[06])\b`,
|
||||
`\bkill\s+-9\s+-1\b|\bkillall\s+-9\b`,
|
||||
`\b(?:shred|wipe)\b[^|\n]{0,80}/dev/[a-zA-Z]`,
|
||||
`\biptables\s+(?:-F|--flush)\b|\bnft\s+flush\s+ruleset\b`,
|
||||
`(?i)\bDROP\s+(?:DATABASE|TABLE|SCHEMA|INDEX|VIEW|TABLESPACE|USER|ROLE)\b`,
|
||||
`(?i)\bTRUNCATE\s+(?:TABLE\s+)?\w`,
|
||||
`(?i)\.(?:dropDatabase|dropCollection|drop)\s*\(`,
|
||||
`(?i)\b(?:FLUSHALL|FLUSHDB)\b`,
|
||||
`(?i)\bcurl\b[^|\n&;"]{0,300}(?:-X\s*DELETE|--request\s+DELETE|-XDELETE)|\bwget\b[^|\n&;"]{0,300}--method[=\s]+DELETE`,
|
||||
`(?i)\b(?:requests|httpx|aiohttp|urllib\.request)\.delete\s*\(|session\.delete\s*\(|client\.delete\s*\(`,
|
||||
`(?i)axios\.delete\s*\(|method\s*[:=]\s*['"]DELETE['"]`,
|
||||
`(?i)/(?:clear|wipe|flush|purge|truncate|drop|destroy|factory[-_]reset|reset[-_]all)(?:[/?#"'\s]|$)`,
|
||||
`(?i)/(?:(?:delete|remove|unlink|erase|destroy)[-\w]*|del)(?:[/?#"'\s]|$)`,
|
||||
`foo+bar`,
|
||||
`(alpha|beta|gamma){2,4}`,
|
||||
`(?:a|b)?c`,
|
||||
`.*`,
|
||||
`^$`,
|
||||
}
|
||||
rng := rand.New(rand.NewPCG(42, 99))
|
||||
vocab := []string{
|
||||
"rm", "RM", "-rf", "/etc", "mkfs", "dd", "of=", "/dev/sda", ":(){:|:&};:",
|
||||
"shutdown", "reboot", "kill -9 -1", "iptables -F", "DROP TABLE", "truncate x",
|
||||
".drop(", "FLUSHALL", "curl", "-X", "DELETE", "wget", "--method=DELETE",
|
||||
"requests.delete(", "axios.delete(", "/clear", "/delete", "foobar", "alpha", "beta",
|
||||
"echo", "hello", " ", "/", "-", "'", `"`, ";", "|", "\n", "k", "K", "s", "S",
|
||||
}
|
||||
for _, pat := range patterns {
|
||||
re := regexp.MustCompile(pat)
|
||||
needles := extractRegexNeedles(pat)
|
||||
for range 500 {
|
||||
var sb strings.Builder
|
||||
n := rng.IntN(8) + 1
|
||||
for range n {
|
||||
sb.WriteString(vocab[rng.IntN(len(vocab))])
|
||||
}
|
||||
s := sb.String()
|
||||
lower, ok := asciiLower(s)
|
||||
if ok && len(needles) > 0 && !needlesMayMatch(lower, needles) {
|
||||
if re.MatchString(s) {
|
||||
t.Fatalf("SOUNDNESS VIOLATION: pattern=%q needles=%v rejected %q but regexp matched", pat, needles, s)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Property 2: Fast ASCII hostname path equivalence with idna.Lookup.ToASCII +
|
||||
// NormalizeTarget idempotence + IPv4 form equivalence (fixes a5000882, f67f7ef4).
|
||||
func TestPropertyNormalizeTargetInvariants(t *testing.T) {
|
||||
rng := rand.New(rand.NewPCG(101, 202))
|
||||
chars := "abcdefghijklmnopqrstuvwxyz0123456789.-_ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
||||
|
||||
// 2a: isPlainLowerASCIIHost(h) => idna.Lookup.ToASCII(h) == h
|
||||
for range 5000 {
|
||||
n := rng.IntN(40) + 1
|
||||
b := make([]byte, n)
|
||||
for i := range b {
|
||||
b[i] = chars[rng.IntN(len(chars))]
|
||||
}
|
||||
h := string(b)
|
||||
if isPlainLowerASCIIHost(h) {
|
||||
got, err := idna.Lookup.ToASCII(h)
|
||||
if err != nil || got != h {
|
||||
t.Fatalf("isPlainLowerASCIIHost(%q)=true, but idna.Lookup.ToASCII=%q err=%v", h, got, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2b: IPv4 dotted / decimal / hex / octal / mapped-IPv6 all canonicalize identically.
|
||||
for range 500 {
|
||||
o0, o1, o2, o3 := rng.IntN(256), rng.IntN(256), rng.IntN(256), rng.IntN(256)
|
||||
want := fmt.Sprintf("%d.%d.%d.%d", o0, o1, o2, o3)
|
||||
u32 := uint32(o0)<<24 | uint32(o1)<<16 | uint32(o2)<<8 | uint32(o3)
|
||||
port := rng.IntN(65535) + 1
|
||||
forms := []string{
|
||||
fmt.Sprintf("http://%s:%d/path", want, port),
|
||||
fmt.Sprintf("http://%d:%d/path", u32, port),
|
||||
fmt.Sprintf("http://0x%08x:%d/path", u32, port),
|
||||
fmt.Sprintf("http://0%o.0%o.0%o.0%o:%d/path", o0, o1, o2, o3, port),
|
||||
fmt.Sprintf("http://[::ffff:%s]:%d/path", want, port),
|
||||
}
|
||||
for _, f := range forms {
|
||||
got, ok := NormalizeTarget(f)
|
||||
if !ok || got.Kind != TargetIP || got.Host != want || got.Port != port {
|
||||
t.Fatalf("NormalizeTarget(%q) = (%+v, %v), want {ip %s %d}", f, got, ok, want, port)
|
||||
}
|
||||
// Idempotence: normalizing canonical string reproduces the exact same Target.
|
||||
got2, ok2 := NormalizeTarget(got.String())
|
||||
if !ok2 || got2 != got {
|
||||
t.Fatalf("NormalizeTarget not idempotent on %q: first=%+v second=(%+v,%v)", f, got, got2, ok2)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Property 3: Historical bug #984 (fc94b108, 52d1b3af, 3559d0c8):
|
||||
// shell-expansion, /dev/tcp, IP:port, and CIDR shapes ALWAYS extract as targets,
|
||||
// while plain User-Agent/version shapes NEVER extract as bare IPv4 targets.
|
||||
func TestPropertyVersionSkipVsRealTargets(t *testing.T) {
|
||||
rng := rand.New(rand.NewPCG(984, 984))
|
||||
uaNames := []string{"Chrome", "Edg", "Firefox", "Go-http-client", "app", "Safari"}
|
||||
for range 300 {
|
||||
ip := fmt.Sprintf("%d.%d.%d.%d", 1+rng.IntN(220), rng.IntN(256), rng.IntN(256), 1+rng.IntN(254))
|
||||
port := 1 + rng.IntN(65535)
|
||||
prefixLen := 8 + rng.IntN(25)
|
||||
mustExtract := []string{
|
||||
fmt.Sprintf("curl ${x-%s}", ip),
|
||||
fmt.Sprintf("curl ${x:-%s}", ip),
|
||||
fmt.Sprintf("curl ${!x-%s}", ip),
|
||||
fmt.Sprintf("exec 3<>'/dev/'tcp/%s/%d", ip, port),
|
||||
fmt.Sprintf("exec 3<>/dev/''udp/%s/%d", ip, port),
|
||||
fmt.Sprintf("curl tcp/%s:%d", ip, port),
|
||||
fmt.Sprintf("nmap net/%s/%d", ip, prefixLen),
|
||||
fmt.Sprintf("curl //%s:%d/test", ip, port),
|
||||
}
|
||||
for _, cmd := range mustExtract {
|
||||
raw, _ := json.Marshal(map[string]string{"command": cmd})
|
||||
ts := ExtractTargets("Bash", raw)
|
||||
found := false
|
||||
for _, tgt := range ts {
|
||||
if tgt.Kind == TargetIP && tgt.Host == ip {
|
||||
found = true
|
||||
}
|
||||
if tgt.Kind == TargetCIDR {
|
||||
if p, err := netip.ParsePrefix(tgt.Host); err == nil {
|
||||
if a, err := netip.ParseAddr(ip); err == nil && p.Contains(a) {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("#984 property violated: %q failed to extract %s (got %+v)", cmd, ip, ts)
|
||||
}
|
||||
}
|
||||
|
||||
ua := uaNames[rng.IntN(len(uaNames))]
|
||||
mustSkip := []string{
|
||||
fmt.Sprintf("curl -A %s/%s echo", ua, ip),
|
||||
fmt.Sprintf("curl -H 'User-Agent: %s/%s' echo", ua, ip),
|
||||
fmt.Sprintf("echo %s-%s", ua, ip),
|
||||
}
|
||||
for _, cmd := range mustSkip {
|
||||
raw, _ := json.Marshal(map[string]string{"command": cmd})
|
||||
if ts := ExtractTargets("Bash", raw); len(ts) != 0 {
|
||||
t.Fatalf("#984 property violated: version token %q extracted targets %+v", cmd, ts)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Property 4: Historical bug #849 / #863 (5dc46272, dc3e75c3, 3d15d568):
|
||||
// Python/JS subscripts never extract as IPv6, while real bracketed IPv6 always does.
|
||||
func TestPropertyBracketSubscriptVsIPv6(t *testing.T) {
|
||||
rng := rand.New(rand.NewPCG(849, 863))
|
||||
idents := []string{"d", "arr", "items_1", "data", "res"}
|
||||
for range 200 {
|
||||
id := idents[rng.IntN(len(idents))]
|
||||
k := rng.IntN(9) + 1
|
||||
subscripts := []string{
|
||||
fmt.Sprintf("python3 -c 'print(%s[::%d])'", id, k),
|
||||
fmt.Sprintf("python3 -c 'print(%s[%d][::%d])'", id, k, k),
|
||||
fmt.Sprintf("python3 -c 'print(%s()[::%d])'", id, k),
|
||||
}
|
||||
for _, cmd := range subscripts {
|
||||
raw, _ := json.Marshal(map[string]string{"command": cmd})
|
||||
if ts := ExtractTargets("Bash", raw); len(ts) != 0 {
|
||||
t.Fatalf("#849 property violated: subscript %q extracted %+v", cmd, ts)
|
||||
}
|
||||
}
|
||||
|
||||
port := 1 + rng.IntN(65535)
|
||||
realV6 := fmt.Sprintf("curl -g http://[2001:db8::%x]:%d/", k, port)
|
||||
raw, _ := json.Marshal(map[string]string{"command": realV6})
|
||||
ts := ExtractTargets("Bash", raw)
|
||||
want := Target{Kind: TargetIP, Host: fmt.Sprintf("2001:db8::%x", k), Port: port}
|
||||
if len(ts) != 1 || ts[0] != want {
|
||||
t.Fatalf("#849 property violated: %q extracted %+v, want [%+v]", realV6, ts, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Property 5: Historical bug #1013 (c9a0bbac):
|
||||
// Case-insensitive and duplicate JSON "command" keys ALWAYS produce the exact
|
||||
// same Match verdict as canonical {"command": <effectiveCommand>}.
|
||||
func TestPropertyCaseInsensitiveJSONCommandParity(t *testing.T) {
|
||||
ic := New(nil)
|
||||
ic.SetRulesForTest(benchRuleSet())
|
||||
rng := rand.New(rand.NewPCG(1013, 1013))
|
||||
cmds := []string{
|
||||
`r\m -r -f /tmp/x`,
|
||||
`r''m -rf /etc/passwd`,
|
||||
`curl -X DELETE https://example.com/a`,
|
||||
`echo hello world`,
|
||||
`git push origin main`,
|
||||
`sudo env FOO=1 kubectl delete pod x`,
|
||||
}
|
||||
randCase := func(s string) string {
|
||||
b := []byte(s)
|
||||
for i := range b {
|
||||
if rng.IntN(2) == 1 {
|
||||
b[i] -= 'a' - 'A'
|
||||
}
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
for range 300 {
|
||||
cmd := cmds[rng.IntN(len(cmds))]
|
||||
canon, _ := json.Marshal(map[string]string{"command": cmd})
|
||||
wantDec, wantOK := ic.Match("Bash", canon)
|
||||
|
||||
cmdJSON, _ := json.Marshal(cmd)
|
||||
key := randCase("command")
|
||||
variant := []byte(fmt.Sprintf(`{"command":"echo harmless",%q:%s}`, key, string(cmdJSON)))
|
||||
gotDec, gotOK := ic.Match("Bash", variant)
|
||||
if gotOK != wantOK || gotDec.Action != wantDec.Action || gotDec.RuleName != wantDec.RuleName {
|
||||
t.Fatalf("#1013 parity violated for key=%q cmd=%q: got=(%v,%q,%q) want=(%v,%q,%q)",
|
||||
key, cmd, gotOK, gotDec.Action, gotDec.RuleName, wantOK, wantDec.Action, wantDec.RuleName)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Property 6: Historical bug #990 (d785c7d9, bbdb064a, da00bf7c, 8f0b73f5):
|
||||
// Argv deny rule MUST deny any wrapped/quoted invocation and MUST NOT return
|
||||
// ok=false on opaque dynamic shell execution.
|
||||
func TestPropertyArgvFailClosedWrappersAndDynamic(t *testing.T) {
|
||||
ic := New(nil)
|
||||
ic.SetRulesForTest([]db.InterceptRule{
|
||||
{ID: 1, Name: "deny targetcmd", Enabled: true, Priority: 100, MatchTarget: "tool_input", MatchType: "argv", Pattern: `["rm"]`, Action: "deny"},
|
||||
})
|
||||
rng := rand.New(rand.NewPCG(990, 990))
|
||||
wrappers := []string{
|
||||
"sudo", "sudo -u root", "env FOO=1", "timeout 10", "nice -n 5",
|
||||
"nohup", "setsid", "command", "exec", "stdbuf -oL",
|
||||
}
|
||||
obfuscated := []string{`rm`, `r''m`, `r""m`, `r\m`, `/bin/rm`, `/usr/bin/r\m`}
|
||||
|
||||
for range 200 {
|
||||
depth := 1 + rng.IntN(3)
|
||||
var parts []string
|
||||
for range depth {
|
||||
parts = append(parts, wrappers[rng.IntN(len(wrappers))])
|
||||
}
|
||||
parts = append(parts, obfuscated[rng.IntN(len(obfuscated))], "-rf", "/tmp/x")
|
||||
cmd := strings.Join(parts, " ")
|
||||
raw, _ := json.Marshal(map[string]string{"command": cmd})
|
||||
dec, ok := ic.Match("Bash", raw)
|
||||
if !ok || dec.Action != "deny" {
|
||||
t.Fatalf("#990 wrapper bypass: %q -> ok=%v action=%q", cmd, ok, dec.Action)
|
||||
}
|
||||
}
|
||||
|
||||
dynamic := []string{
|
||||
`CMD=rm; $CMD -rf /tmp/x`,
|
||||
`echo cm0gLXJmIC90bXAvWA== | base64 -d | sh`,
|
||||
`sh -c "$(echo cm0gLXJmIC90bXAvWA== | base64 -d)"`,
|
||||
`eval "$(echo cm0gLXJmIC90bXAvWA== | base64 -d)"`,
|
||||
`bash <(echo cm0gLXJmIC90bXAvWA== | base64 -d)`,
|
||||
`bash <<< "$(echo cm0gLXJmIC90bXAvWA== | base64 -d)"`,
|
||||
`source <(echo cm0gLXJmIC90bXAvWA== | base64 -d)`,
|
||||
`echo cm0gLXJmIC90bXAvWA== | base64 -d | xargs sh -c`,
|
||||
}
|
||||
for _, cmd := range dynamic {
|
||||
raw, _ := json.Marshal(map[string]string{"command": cmd})
|
||||
dec, ok := ic.Match("Bash", raw)
|
||||
if !ok || (dec.Action != "ask" && dec.Action != "deny") {
|
||||
t.Fatalf("#990 dynamic fail-closed violated: %q -> ok=%v action=%q", cmd, ok, dec.Action)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Property 7: Historical bug #687 (44ea93a2, b8ca0054, df30888f):
|
||||
// Curl attached and spaced body/method flags are always classified as mutating.
|
||||
func TestPropertyStatefulGuardCurlMutating(t *testing.T) {
|
||||
rng := rand.New(rand.NewPCG(687, 687))
|
||||
methods := []string{"POST", "PUT", "PATCH", "DELETE", "post", "delete"}
|
||||
flags := []string{
|
||||
"-dfoo=bar", "-d foo=bar", "--data=foo=bar", "--data-raw=x",
|
||||
"-Ffile=@a", "-T/tmp/a", "--json={}", "--upload-file=/tmp/a",
|
||||
}
|
||||
for range 100 {
|
||||
m := methods[rng.IntN(len(methods))]
|
||||
for _, cmd := range []string{
|
||||
fmt.Sprintf("curl -X %s https://app.example.com/items", m),
|
||||
fmt.Sprintf("curl -X%s https://app.example.com/items", m),
|
||||
fmt.Sprintf("curl --request=%s https://app.example.com/items", m),
|
||||
fmt.Sprintf("curl %s https://app.example.com/items", flags[rng.IntN(len(flags))]),
|
||||
} {
|
||||
raw, _ := json.Marshal(map[string]string{"command": cmd})
|
||||
if _, mutating := ClassifyHTTPAction("Bash", raw, "", ""); !mutating {
|
||||
t.Fatalf("#687 property violated: %q classified as non-mutating", cmd)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -106,7 +106,6 @@ type StatefulTargetGuard struct {
|
||||
leases map[string]mutationLease // taskID+"\x00"+host -> lease entry
|
||||
baselines map[string]bool // taskID+"\x00"+host -> true once read-only GET completed
|
||||
now func() time.Time
|
||||
ttl time.Duration
|
||||
}
|
||||
|
||||
func NewStatefulTargetGuard() *StatefulTargetGuard {
|
||||
@@ -127,16 +126,6 @@ func (g *StatefulTargetGuard) SetClock(fn func() time.Time) {
|
||||
g.mu.Unlock()
|
||||
}
|
||||
|
||||
// SetTTL overrides the lease heartbeat TTL on this guard instance (0 = read env).
|
||||
func (g *StatefulTargetGuard) SetTTL(d time.Duration) {
|
||||
if g == nil {
|
||||
return
|
||||
}
|
||||
g.mu.Lock()
|
||||
g.ttl = d
|
||||
g.mu.Unlock()
|
||||
}
|
||||
|
||||
func (g *StatefulTargetGuard) clockNow() time.Time {
|
||||
if g.now != nil {
|
||||
return g.now().UTC()
|
||||
@@ -145,9 +134,6 @@ func (g *StatefulTargetGuard) clockNow() time.Time {
|
||||
}
|
||||
|
||||
func (g *StatefulTargetGuard) effectiveTTL() time.Duration {
|
||||
if g != nil && g.ttl > 0 {
|
||||
return g.ttl
|
||||
}
|
||||
return StatefulLeaseTTL()
|
||||
}
|
||||
|
||||
|
||||
+71
-9
@@ -47,7 +47,7 @@ func NormalizeTarget(raw string) (Target, bool) {
|
||||
def, isURL := 0, false
|
||||
if i := strings.Index(raw, "://"); i > 0 {
|
||||
isURL = true
|
||||
def = schemePorts[strings.ToLower(raw[:i])]
|
||||
def = schemePorts[toLowerFast(raw[:i])]
|
||||
raw = raw[i+3:]
|
||||
if end := strings.IndexAny(raw, "/?#"); end >= 0 {
|
||||
raw = raw[:end]
|
||||
@@ -71,7 +71,7 @@ func NormalizeTarget(raw string) (Target, bool) {
|
||||
case strings.Count(raw, ":") == 1:
|
||||
host, port, _ = strings.Cut(raw, ":")
|
||||
}
|
||||
if isURL && !strings.HasPrefix(raw, "[") {
|
||||
if isURL && !strings.HasPrefix(raw, "[") && strings.IndexByte(host, '%') >= 0 {
|
||||
// A client decodes a percent-encoded host before it resolves it.
|
||||
if decoded, err := url.PathUnescape(host); err == nil {
|
||||
host = decoded
|
||||
@@ -90,16 +90,58 @@ func NormalizeTarget(raw string) (Target, bool) {
|
||||
return t, ok
|
||||
}
|
||||
|
||||
// toLowerFast avoids allocating when s is already lowercase ASCII.
|
||||
func toLowerFast(s string) string {
|
||||
for i := 0; i < len(s); i++ {
|
||||
c := s[i]
|
||||
if c >= 'A' && c <= 'Z' || c >= 0x80 {
|
||||
return strings.ToLower(s)
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// isPlainLowerASCIIHost reports whether h is a non-empty lowercase ASCII DNS
|
||||
// name containing no punycode labels ("xn--"), for which idna.Lookup.ToASCII is
|
||||
// guaranteed to be the identity function.
|
||||
func isPlainLowerASCIIHost(h string) bool {
|
||||
if len(h) == 0 || len(h) > 253 {
|
||||
return false
|
||||
}
|
||||
labelStart := 0
|
||||
for i := 0; i <= len(h); i++ {
|
||||
if i == len(h) || h[i] == '.' {
|
||||
labelLen := i - labelStart
|
||||
if labelLen == 0 || labelLen > 63 {
|
||||
return false
|
||||
}
|
||||
if h[labelStart] == '-' || h[i-1] == '-' {
|
||||
return false
|
||||
}
|
||||
if labelLen >= 4 && h[labelStart] == 'x' && h[labelStart+1] == 'n' && h[labelStart+2] == '-' && h[labelStart+3] == '-' {
|
||||
return false
|
||||
}
|
||||
labelStart = i + 1
|
||||
continue
|
||||
}
|
||||
c := h[i]
|
||||
if !(c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-') {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// normalizeHost returns the kind and the canonical form of a host. numeric
|
||||
// accepts the forms of an IPv4 address that are not dotted decimal
|
||||
// (2130706433, 0x7f000001, 0177.0.0.1, 127.1), which a URL host may use; in
|
||||
// free text they would turn every number into an address.
|
||||
func normalizeHost(raw string, numeric bool) (kind, host string, ok bool) {
|
||||
h := strings.TrimSuffix(strings.ToLower(strings.TrimSpace(raw)), ".")
|
||||
h := strings.TrimSuffix(toLowerFast(strings.TrimSpace(raw)), ".")
|
||||
if h == "" {
|
||||
return "", "", false
|
||||
}
|
||||
if strings.Contains(h, "/") {
|
||||
if strings.IndexByte(h, '/') >= 0 {
|
||||
p, err := netip.ParsePrefix(h)
|
||||
if err != nil {
|
||||
return "", "", false
|
||||
@@ -109,11 +151,14 @@ func normalizeHost(raw string, numeric bool) (kind, host string, ok bool) {
|
||||
if a, err := netip.ParseAddr(h); err == nil {
|
||||
return TargetIP, a.Unmap().WithZone("").String(), true
|
||||
}
|
||||
if numeric {
|
||||
if numeric && h[0] >= '0' && h[0] <= '9' {
|
||||
if a, ok := parseIPv4Forms(h); ok {
|
||||
return TargetIP, a.String(), true
|
||||
}
|
||||
}
|
||||
if isPlainLowerASCIIHost(h) {
|
||||
return TargetDomain, h, true
|
||||
}
|
||||
// A name the profile refuses is kept as written: it then fails to resolve and
|
||||
// the call is blocked, instead of passing as a call without a target.
|
||||
if name, err := hostProfile.ToASCII(h); err == nil && name != "" {
|
||||
@@ -126,12 +171,29 @@ func normalizeHost(raw string, numeric bool) (kind, host string, ok bool) {
|
||||
// parts, each decimal, hex (0x) or octal (leading 0), the last one filling the
|
||||
// remaining bytes.
|
||||
func parseIPv4Forms(s string) (netip.Addr, bool) {
|
||||
parts := strings.Split(s, ".")
|
||||
if len(parts) > 4 {
|
||||
if s == "" || s[0] < '0' || s[0] > '9' {
|
||||
return netip.Addr{}, false
|
||||
}
|
||||
var parts [4]string
|
||||
nParts := 0
|
||||
rem := s
|
||||
for {
|
||||
if nParts == 4 {
|
||||
return netip.Addr{}, false
|
||||
}
|
||||
dot := strings.IndexByte(rem, '.')
|
||||
if dot < 0 {
|
||||
parts[nParts] = rem
|
||||
nParts++
|
||||
break
|
||||
}
|
||||
parts[nParts] = rem[:dot]
|
||||
nParts++
|
||||
rem = rem[dot+1:]
|
||||
}
|
||||
var v uint64
|
||||
for n, p := range parts {
|
||||
for n := 0; n < nParts; n++ {
|
||||
p := parts[n]
|
||||
base := 10
|
||||
switch {
|
||||
case strings.HasPrefix(p, "0x"):
|
||||
@@ -143,7 +205,7 @@ func parseIPv4Forms(s string) (netip.Addr, bool) {
|
||||
if err != nil {
|
||||
return netip.Addr{}, false
|
||||
}
|
||||
if n < len(parts)-1 {
|
||||
if n < nParts-1 {
|
||||
if x > 255 {
|
||||
return netip.Addr{}, false
|
||||
}
|
||||
|
||||
+191
-122
@@ -17,7 +17,7 @@ const executeExtraTool = "ExecuteExtraTool"
|
||||
// tool (its input is a query), the file and session tools, and the platform's
|
||||
// domain tools, which read and write the platform's own records. Every name
|
||||
// that is not listed here is scanned, so a tool added later is gated by default.
|
||||
var noTargetTools = toolSet(
|
||||
var noTargetTools = strSet(
|
||||
"web_search",
|
||||
"Read", "Write", "Edit", "MultiEdit", "LS", "Glob", "Grep",
|
||||
"TodoWrite", "sleep", "TaskOutput", "TaskStop", "TaskList",
|
||||
@@ -48,14 +48,6 @@ var noTargetTools = toolSet(
|
||||
"traffic_search", "traffic_get", "traffic_blob", "traffic_messages",
|
||||
)
|
||||
|
||||
func toolSet(names ...string) map[string]bool {
|
||||
m := make(map[string]bool, len(names))
|
||||
for _, n := range names {
|
||||
m[n] = true
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// ExtractTargets returns the network targets a tool call declares in its
|
||||
// input, normalised and without duplicates, in order of appearance.
|
||||
//
|
||||
@@ -214,13 +206,46 @@ func (l *targetList) scan(s string) {
|
||||
if s == "" {
|
||||
return
|
||||
}
|
||||
var dotCount, colonCount int
|
||||
var hasLBracket, hasRBracket, hasSlash, hasNonASCII bool
|
||||
for i := 0; i < len(s); i++ {
|
||||
if s[i] >= 0x80 {
|
||||
hasNonASCII = true
|
||||
}
|
||||
switch s[i] {
|
||||
case '.':
|
||||
dotCount++
|
||||
case ':':
|
||||
colonCount++
|
||||
case '[':
|
||||
hasLBracket = true
|
||||
case ']':
|
||||
hasRBracket = true
|
||||
case '/':
|
||||
hasSlash = true
|
||||
}
|
||||
}
|
||||
canURL := colonCount > 0 && hasSlash && strings.Contains(s, "://")
|
||||
canBracket := hasLBracket && hasRBracket
|
||||
canIPv6 := colonCount >= 2
|
||||
canIPv4 := dotCount >= 3
|
||||
// The host:port pattern is case-insensitive over Unicode, so a non-ASCII
|
||||
// letter that folds to an ASCII one (ſ for s) matches it. Any non-ASCII byte
|
||||
// keeps that pass enabled instead of deciding from an ASCII-only substring.
|
||||
canHostPort := colonCount > 0 && (dotCount > 0 || hasNonASCII || containsASCIIFold(s, "localhost:"))
|
||||
if !canURL && !canBracket && !canIPv6 && !canIPv4 && !canHostPort {
|
||||
return
|
||||
}
|
||||
b := []byte(s)
|
||||
// Left context for the subscript guard below must come from the
|
||||
// original bytes: a matched bracket is blanked as it is read, so by
|
||||
// the time a chained subscript like `a[1][::2]` is examined, the `]`
|
||||
// before it has been blanked and no longer proves the glue.
|
||||
orig := make([]byte, len(b))
|
||||
copy(orig, b)
|
||||
var orig []byte
|
||||
if canBracket {
|
||||
// Left context for the subscript guard below must come from the
|
||||
// original bytes: a matched bracket is blanked as it is read, so by
|
||||
// the time a chained subscript like `a[1][::2]` is examined, the `]`
|
||||
// before it has been blanked and no longer proves the glue.
|
||||
orig = make([]byte, len(b))
|
||||
copy(orig, b)
|
||||
}
|
||||
blank := func(from, to int) {
|
||||
for i := from; i < to; i++ {
|
||||
b[i] = ' '
|
||||
@@ -233,122 +258,166 @@ func (l *targetList) scan(s string) {
|
||||
}
|
||||
}
|
||||
}
|
||||
each(reURL, func(m []int) bool {
|
||||
scheme, found := string(b[m[2]:m[3]]), false
|
||||
for _, host := range urlHosts(string(b[m[4]:m[5]])) {
|
||||
// A host that is not a name ($HOST, a glob) is what the shell or the
|
||||
// client will make of it, which the gate cannot read.
|
||||
if t, ok := NormalizeTarget(scheme + host); ok && (t.Kind != TargetDomain || validHostname(t.Host)) {
|
||||
l.add(t)
|
||||
found = true
|
||||
if canURL {
|
||||
each(reURL, func(m []int) bool {
|
||||
scheme, found := string(b[m[2]:m[3]]), false
|
||||
for _, host := range urlHosts(string(b[m[4]:m[5]])) {
|
||||
// A host that is not a name ($HOST, a glob) is what the shell or the
|
||||
// client will make of it, which the gate cannot read.
|
||||
if t, ok := NormalizeTarget(scheme + host); ok && (t.Kind != TargetDomain || validHostname(t.Host)) {
|
||||
l.add(t)
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if found {
|
||||
// The whole token, path and query included, from the original string.
|
||||
l.urls = append(l.urls, s[m[0]:m[1]])
|
||||
}
|
||||
// The scheme and what follows the authority are never read again. An
|
||||
// authority that named no host is: an address written in it still counts.
|
||||
blank(m[0], m[4])
|
||||
blank(m[5], m[1])
|
||||
return found
|
||||
})
|
||||
}
|
||||
if canBracket {
|
||||
each(reBracketed, func(m []int) bool {
|
||||
if m[0] > 0 && (isWord(orig[m[0]-1]) || orig[m[0]-1] == ']' || orig[m[0]-1] == ')') {
|
||||
// Not a bracketed address: a subscript glued to an expression.
|
||||
// A bracketed IPv6 stands at the edge of a token or follows `:`,
|
||||
// `/` or `@` in a URL; it is never glued to a word character, and
|
||||
// never glued to the `]` or `)` that close a subscript or a call.
|
||||
// `d[::2][::-1]` is a Python step slice, `a[1][::2]` a chained
|
||||
// subscript and `f()[::2]` a subscript on a call result: the
|
||||
// brackets hold slice bounds that happen to read as a valid
|
||||
// address. Consume the subscript, so the IPv6 rule below does not
|
||||
// read the same bounds again.
|
||||
blank(m[0], m[1])
|
||||
return false
|
||||
}
|
||||
a, err := netip.ParseAddr(string(b[m[2]:m[3]]))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
t := Target{Kind: TargetIP, Host: a.Unmap().WithZone("").String()}
|
||||
if m[4] >= 0 {
|
||||
t.Port = validPort(string(b[m[4]:m[5]]))
|
||||
}
|
||||
l.add(t)
|
||||
return true
|
||||
})
|
||||
}
|
||||
if canIPv6 {
|
||||
each(reIPv6, func(m []int) bool {
|
||||
start, end := m[0], m[1]
|
||||
if start > 0 && isWord(b[start-1]) || end < len(b) && (isWord(b[end]) || b[end] == ':') {
|
||||
return false
|
||||
}
|
||||
kind, host, ok := normalizeHost(string(b[start:end]), false)
|
||||
// "::" alone is punctuation (a slice, a scope operator), not an address.
|
||||
if !ok || kind == TargetDomain || host == "::" {
|
||||
return false
|
||||
}
|
||||
l.add(Target{Kind: kind, Host: host})
|
||||
return true
|
||||
})
|
||||
}
|
||||
if canIPv4 {
|
||||
each(reIPv4, func(m []int) bool {
|
||||
start, end := m[0], m[1]
|
||||
if start > 0 && (isWord(b[start-1]) || b[start-1] == '.') {
|
||||
return false
|
||||
}
|
||||
// A port or a prefix length makes the quad a target, not a version
|
||||
// token: a name/version component has neither.
|
||||
if bytes.IndexAny(b[start:end], "/:") < 0 && hasVersionPrefix(b, start) {
|
||||
return false
|
||||
}
|
||||
// The address alone, when what follows it is not a port or a prefix length.
|
||||
addrEnd := start + bytes.IndexAny(b[start:end], "/:")
|
||||
if addrEnd < start {
|
||||
addrEnd = end
|
||||
}
|
||||
if !endsToken(b, end) {
|
||||
end = addrEnd
|
||||
if !endsToken(b, end) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
a, err := netip.ParseAddr(string(b[start:addrEnd]))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
t := Target{Kind: TargetIP, Host: a.String()}
|
||||
if end > addrEnd {
|
||||
switch suffix := string(b[addrEnd+1 : end]); b[addrEnd] {
|
||||
case '/':
|
||||
if p, err := netip.ParsePrefix(string(b[start:end])); err == nil {
|
||||
t = Target{Kind: TargetCIDR, Host: p.Masked().String()}
|
||||
}
|
||||
case ':':
|
||||
t.Port = validPort(suffix)
|
||||
}
|
||||
}
|
||||
l.add(t)
|
||||
return true
|
||||
})
|
||||
}
|
||||
if canHostPort {
|
||||
each(reHostPort, func(m []int) bool {
|
||||
start, end := m[0], m[1]
|
||||
// Not the tail of a longer word, a path or an address, and not the head of
|
||||
// a version number (name:1.25).
|
||||
if start > 0 && (isWord(b[start-1]) || strings.IndexByte(`.-/\`, b[start-1]) >= 0) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
if found {
|
||||
// The whole token, path and query included, from the original string.
|
||||
l.urls = append(l.urls, s[m[0]:m[1]])
|
||||
}
|
||||
// The scheme and what follows the authority are never read again. An
|
||||
// authority that named no host is: an address written in it still counts.
|
||||
blank(m[0], m[4])
|
||||
blank(m[5], m[1])
|
||||
return found
|
||||
})
|
||||
each(reBracketed, func(m []int) bool {
|
||||
if m[0] > 0 && (isWord(orig[m[0]-1]) || orig[m[0]-1] == ']' || orig[m[0]-1] == ')') {
|
||||
// Not a bracketed address: a subscript glued to an expression.
|
||||
// A bracketed IPv6 stands at the edge of a token or follows `:`,
|
||||
// `/` or `@` in a URL; it is never glued to a word character, and
|
||||
// never glued to the `]` or `)` that close a subscript or a call.
|
||||
// `d[::2][::-1]` is a Python step slice, `a[1][::2]` a chained
|
||||
// subscript and `f()[::2]` a subscript on a call result: the
|
||||
// brackets hold slice bounds that happen to read as a valid
|
||||
// address. Consume the subscript, so the IPv6 rule below does not
|
||||
// read the same bounds again.
|
||||
blank(m[0], m[1])
|
||||
return false
|
||||
}
|
||||
a, err := netip.ParseAddr(string(b[m[2]:m[3]]))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
t := Target{Kind: TargetIP, Host: a.Unmap().WithZone("").String()}
|
||||
if m[4] >= 0 {
|
||||
t.Port = validPort(string(b[m[4]:m[5]]))
|
||||
}
|
||||
l.add(t)
|
||||
return true
|
||||
})
|
||||
each(reIPv6, func(m []int) bool {
|
||||
start, end := m[0], m[1]
|
||||
if start > 0 && isWord(b[start-1]) || end < len(b) && (isWord(b[end]) || b[end] == ':') {
|
||||
return false
|
||||
}
|
||||
kind, host, ok := normalizeHost(string(b[start:end]), false)
|
||||
// "::" alone is punctuation (a slice, a scope operator), not an address.
|
||||
if !ok || kind == TargetDomain || host == "::" {
|
||||
return false
|
||||
}
|
||||
l.add(Target{Kind: kind, Host: host})
|
||||
return true
|
||||
})
|
||||
each(reIPv4, func(m []int) bool {
|
||||
start, end := m[0], m[1]
|
||||
if start > 0 && (isWord(b[start-1]) || b[start-1] == '.') {
|
||||
return false
|
||||
}
|
||||
// A port or a prefix length makes the quad a target, not a version
|
||||
// token: a name/version component has neither.
|
||||
if bytes.IndexAny(b[start:end], "/:") < 0 && hasVersionPrefix(b, start) {
|
||||
return false
|
||||
}
|
||||
// The address alone, when what follows it is not a port or a prefix length.
|
||||
addrEnd := start + bytes.IndexAny(b[start:end], "/:")
|
||||
if addrEnd < start {
|
||||
addrEnd = end
|
||||
}
|
||||
if !endsToken(b, end) {
|
||||
end = addrEnd
|
||||
if !endsToken(b, end) {
|
||||
return false
|
||||
}
|
||||
host, port, _ := strings.Cut(string(b[start:end]), ":")
|
||||
n := validPort(port)
|
||||
_, host, ok := normalizeHost(host, false)
|
||||
if n == 0 || !ok {
|
||||
return false
|
||||
}
|
||||
l.add(Target{Kind: TargetDomain, Host: host, Port: n})
|
||||
return true
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// containsASCIIFold reports whether s contains needle (which must be lowercase ASCII)
|
||||
// ignoring ASCII letter case, with zero allocations.
|
||||
func containsASCIIFold(s, needle string) bool {
|
||||
if len(needle) == 0 || len(s) < len(needle) {
|
||||
return false
|
||||
}
|
||||
first := needle[0]
|
||||
limit := len(s) - len(needle)
|
||||
for i := 0; i <= limit; i++ {
|
||||
c := s[i]
|
||||
if c >= 'A' && c <= 'Z' {
|
||||
c += 'a' - 'A'
|
||||
}
|
||||
a, err := netip.ParseAddr(string(b[start:addrEnd]))
|
||||
if err != nil {
|
||||
return false
|
||||
if c != first {
|
||||
continue
|
||||
}
|
||||
t := Target{Kind: TargetIP, Host: a.String()}
|
||||
if end > addrEnd {
|
||||
switch suffix := string(b[addrEnd+1 : end]); b[addrEnd] {
|
||||
case '/':
|
||||
if p, err := netip.ParsePrefix(string(b[start:end])); err == nil {
|
||||
t = Target{Kind: TargetCIDR, Host: p.Masked().String()}
|
||||
}
|
||||
case ':':
|
||||
t.Port = validPort(suffix)
|
||||
match := true
|
||||
for j := 1; j < len(needle); j++ {
|
||||
cj := s[i+j]
|
||||
if cj >= 'A' && cj <= 'Z' {
|
||||
cj += 'a' - 'A'
|
||||
}
|
||||
if cj != needle[j] {
|
||||
match = false
|
||||
break
|
||||
}
|
||||
}
|
||||
l.add(t)
|
||||
return true
|
||||
})
|
||||
each(reHostPort, func(m []int) bool {
|
||||
start, end := m[0], m[1]
|
||||
// Not the tail of a longer word, a path or an address, and not the head of
|
||||
// a version number (name:1.25).
|
||||
if start > 0 && (isWord(b[start-1]) || strings.IndexByte(`.-/\`, b[start-1]) >= 0) {
|
||||
return false
|
||||
if match {
|
||||
return true
|
||||
}
|
||||
if !endsToken(b, end) {
|
||||
return false
|
||||
}
|
||||
host, port, _ := strings.Cut(string(b[start:end]), ":")
|
||||
n := validPort(port)
|
||||
_, host, ok := normalizeHost(host, false)
|
||||
if n == 0 || !ok {
|
||||
return false
|
||||
}
|
||||
l.add(Target{Kind: TargetDomain, Host: host, Port: n})
|
||||
return true
|
||||
})
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// endsToken reports whether the token that ends before b[i] really ends there:
|
||||
|
||||
@@ -97,6 +97,9 @@ func TestExtractTargets(t *testing.T) {
|
||||
{"mysql --host=203.0.113.7 -uroot", []Target{{TargetIP, "203.0.113.7", 0}}},
|
||||
{"openssl s_client -connect app.example.com:443 -servername x", []Target{app}},
|
||||
{"nc localhost:8080", []Target{{TargetDomain, "localhost", 8080}}},
|
||||
// The host:port pattern is case-insensitive over Unicode: ſ folds to s,
|
||||
// so localhoſt:8080 names localhost and is still a target.
|
||||
{"curl localhoſt:8080", []Target{{TargetDomain, "localhost", 8080}}},
|
||||
{"ping6 2001:db8::1", []Target{{TargetIP, "2001:db8::1", 0}}},
|
||||
{"curl 'http://[2001:db8::1]:8080/'; nc [2001:db8::2]:22", []Target{{TargetIP, "2001:db8::1", 8080}, {TargetIP, "2001:db8::2", 22}}},
|
||||
{"nmap fd00::/8 ::ffff:203.0.113.7", []Target{{TargetCIDR, "fd00::/8", 0}, {TargetIP, "203.0.113.7", 0}}},
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
package sandbox
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/netip"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func BenchmarkEgressPolicyResolveLargeScope(b *testing.B) {
|
||||
domains := make([]string, 2000)
|
||||
for i := range domains {
|
||||
domains[i] = fmt.Sprintf("svc-%04d.corp.example.com", i)
|
||||
}
|
||||
pol, err := NewEgressPolicy("1", domains, []string{"203.0.113.0/24"}, nil)
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
pol.Resolver = func(_ context.Context, _ string) ([]netip.Addr, error) {
|
||||
return []netip.Addr{netip.MustParseAddr("203.0.113.10")}, nil
|
||||
}
|
||||
ctx := context.Background()
|
||||
|
||||
b.Run("allowed_tail", func(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for b.Loop() {
|
||||
if _, err := pol.ResolveAndCheck(ctx, "api.svc-1999.corp.example.com"); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
b.Run("denied_miss", func(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for b.Loop() {
|
||||
if _, err := pol.ResolveAndCheck(ctx, "evil.unapproved.example.org"); err == nil {
|
||||
b.Fatal("expected deny")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func BenchmarkEgressPolicyCheckURL(b *testing.B) {
|
||||
domains := make([]string, 200)
|
||||
for i := range domains {
|
||||
domains[i] = fmt.Sprintf("app-%03d.example.com", i)
|
||||
}
|
||||
pol, err := NewEgressPolicy("1", domains, []string{"203.0.113.0/24"}, nil)
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
pol.Resolver = func(_ context.Context, _ string) ([]netip.Addr, error) {
|
||||
return []netip.Addr{netip.MustParseAddr("198.51.100.42")}, nil
|
||||
}
|
||||
ctx := context.Background()
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for b.Loop() {
|
||||
if err := pol.CheckURL(ctx, "https://v1.app-199.example.com/health"); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkValidateExecRequest(b *testing.B) {
|
||||
domains := make([]string, 100)
|
||||
for i := range domains {
|
||||
domains[i] = fmt.Sprintf("*.svc-%03d.example.com", i)
|
||||
}
|
||||
cidrs := make([]string, 50)
|
||||
for i := range cidrs {
|
||||
cidrs[i] = fmt.Sprintf("198.51.100.%d/32", i+1)
|
||||
}
|
||||
env := map[string]string{
|
||||
"TERM": "xterm", "LANG": "C.UTF-8", "CI": "true", "TZ": "UTC",
|
||||
"APP_ENV": "test", "LOG_LEVEL": "info", "NO_COLOR": "1", "PAGER": "cat",
|
||||
}
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for b.Loop() {
|
||||
req := ExecRequest{
|
||||
Argv: []string{"curl", "-s", "https://svc-001.example.com/"},
|
||||
Workdir: "/workspace/i1",
|
||||
TimeoutMS: 30000,
|
||||
ScopeDomains: domains,
|
||||
ScopeCIDRs: cidrs,
|
||||
Env: env,
|
||||
}
|
||||
if err := ValidateExecRequest(&req); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
+56
-8
@@ -136,6 +136,9 @@ type EgressPolicy struct {
|
||||
// Never lists prefixes denied even when a scope CIDR covers them (the
|
||||
// Kubernetes backend passes cluster and metadata ranges here).
|
||||
Never []netip.Prefix
|
||||
|
||||
domainSet map[string]struct{}
|
||||
domainSetLen int
|
||||
}
|
||||
|
||||
// NewEgressPolicy parses comma-separated domain suffixes and IP/CIDR entries.
|
||||
@@ -144,6 +147,10 @@ func NewEgressPolicy(taskID string, domains, cidrs []string, logger *EgressLogge
|
||||
TaskID: taskID,
|
||||
Logger: logger,
|
||||
}
|
||||
if len(domains) > 0 {
|
||||
p.Domains = make([]string, 0, len(domains))
|
||||
p.domainSet = make(map[string]struct{}, len(domains))
|
||||
}
|
||||
for _, d := range domains {
|
||||
d = strings.ToLower(strings.TrimSpace(d))
|
||||
d = strings.TrimPrefix(d, "*.")
|
||||
@@ -151,14 +158,19 @@ func NewEgressPolicy(taskID string, domains, cidrs []string, logger *EgressLogge
|
||||
d = strings.TrimSuffix(d, ".")
|
||||
if d != "" {
|
||||
p.Domains = append(p.Domains, d)
|
||||
p.domainSet[d] = struct{}{}
|
||||
}
|
||||
}
|
||||
p.domainSetLen = len(p.Domains)
|
||||
if len(cidrs) > 0 {
|
||||
p.CIDRs = make([]netip.Prefix, 0, len(cidrs))
|
||||
}
|
||||
for _, raw := range cidrs {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
continue
|
||||
}
|
||||
if strings.Contains(raw, "/") {
|
||||
if strings.IndexByte(raw, '/') >= 0 {
|
||||
pfx, err := netip.ParsePrefix(raw)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid scope CIDR %q: %w", raw, err)
|
||||
@@ -188,13 +200,35 @@ func ParseCSV(raw string) []string {
|
||||
return out
|
||||
}
|
||||
|
||||
func toLowerFast(s string) string {
|
||||
for i := 0; i < len(s); i++ {
|
||||
c := s[i]
|
||||
if c >= 'A' && c <= 'Z' || c >= 0x80 {
|
||||
return strings.ToLower(s)
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func (p *EgressPolicy) domainAllowed(host string) bool {
|
||||
h := strings.ToLower(strings.TrimSuffix(strings.TrimSpace(host), "."))
|
||||
h := toLowerFast(strings.TrimSuffix(strings.TrimSpace(host), "."))
|
||||
if h == "" {
|
||||
return false
|
||||
}
|
||||
if p.domainSet != nil && len(p.Domains) == p.domainSetLen {
|
||||
for rem := h; ; {
|
||||
if _, ok := p.domainSet[rem]; ok {
|
||||
return true
|
||||
}
|
||||
dot := strings.IndexByte(rem, '.')
|
||||
if dot < 0 || dot+1 >= len(rem) {
|
||||
return false
|
||||
}
|
||||
rem = rem[dot+1:]
|
||||
}
|
||||
}
|
||||
for _, suffix := range p.Domains {
|
||||
if h == suffix || strings.HasSuffix(h, "."+suffix) {
|
||||
if h == suffix || (len(h) > len(suffix) && h[len(h)-len(suffix)-1] == '.' && strings.HasSuffix(h, suffix)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -230,12 +264,26 @@ func isDefaultDeniedAddr(addr netip.Addr) bool {
|
||||
if addr.Is6() {
|
||||
return true
|
||||
}
|
||||
for _, pfx := range defaultDeniedPrefixes {
|
||||
if pfx.Contains(addr) {
|
||||
return true
|
||||
}
|
||||
if !addr.Is4() {
|
||||
return true
|
||||
}
|
||||
b := addr.As4()
|
||||
switch b[0] {
|
||||
case 0, 10, 127:
|
||||
return true // 0.0.0.0/8, 10.0.0.0/8, 127.0.0.0/8
|
||||
case 100:
|
||||
return (b[1] >= 64 && b[1] <= 127) || (b[1] == 100 && b[2] == 100 && b[3] == 200) // 100.64.0.0/10, 100.100.100.200/32
|
||||
case 168:
|
||||
return b[1] == 63 && b[2] == 129 && b[3] == 16 // 168.63.129.16/32
|
||||
case 169:
|
||||
return b[1] == 254 // 169.254.0.0/16
|
||||
case 172:
|
||||
return b[1] >= 16 && b[1] <= 31 // 172.16.0.0/12
|
||||
case 192:
|
||||
return b[1] == 168 // 192.168.0.0/16
|
||||
default:
|
||||
return b[0] >= 224 // 224.0.0.0/4, 240.0.0.0/4
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type resolverCtxKey struct{}
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
package sandbox
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math/rand/v2"
|
||||
"net/netip"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Property 1: Exhaustive equivalence between O(1) isDefaultDeniedAddr and
|
||||
// defaultDeniedPrefixes across all 256 /8 IPv4 blocks, edge addresses, and
|
||||
// IPv4-mapped IPv6 forms (fixes #925, d92a02fa).
|
||||
func TestPropertyDefaultDeniedAddrEquivalence(t *testing.T) {
|
||||
ref := func(a netip.Addr) bool {
|
||||
a = a.Unmap()
|
||||
if a.Is6() {
|
||||
return true
|
||||
}
|
||||
for _, pfx := range defaultDeniedPrefixes {
|
||||
if pfx.Contains(a) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
check := func(a netip.Addr) {
|
||||
t.Helper()
|
||||
if got, want := isDefaultDeniedAddr(a), ref(a); got != want {
|
||||
t.Fatalf("isDefaultDeniedAddr(%s) = %v, want %v", a, got, want)
|
||||
}
|
||||
if a.Is4() {
|
||||
mapped := netip.AddrFrom16([16]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, a.As4()[0], a.As4()[1], a.As4()[2], a.As4()[3]})
|
||||
if got, want := isDefaultDeniedAddr(mapped), ref(mapped); got != want {
|
||||
t.Fatalf("isDefaultDeniedAddr(%s) = %v, want %v", mapped, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// All 256 first octets with key boundary values.
|
||||
for b0 := 0; b0 < 256; b0++ {
|
||||
for _, b1 := range []int{0, 15, 16, 31, 32, 63, 64, 100, 127, 128, 168, 254, 255} {
|
||||
check(netip.AddrFrom4([4]byte{byte(b0), byte(b1), 0, 0}))
|
||||
check(netip.AddrFrom4([4]byte{byte(b0), byte(b1), 255, 255}))
|
||||
}
|
||||
}
|
||||
// Exact /32 cloud metadata boundaries and neighbors.
|
||||
for _, raw := range []string{
|
||||
"100.100.100.199", "100.100.100.200", "100.100.100.201",
|
||||
"168.63.129.15", "168.63.129.16", "168.63.129.17",
|
||||
"169.254.169.254", "172.15.255.255", "172.16.0.0", "172.31.255.255", "172.32.0.0",
|
||||
"::1", "::", "fe80::1", "fc00::1", "fd00:ec2::254", "2001:db8::1", "64:ff9b::7f00:1",
|
||||
} {
|
||||
check(netip.MustParseAddr(raw))
|
||||
}
|
||||
}
|
||||
|
||||
// Property 2: Never-list dominance invariant (fixes #925 d2f902db, c09be6c4).
|
||||
// Even with widest-possible scope CIDRs (0.0.0.0/0, ::/0), every IP in Never
|
||||
// (including NAT64 forms of loopback/private/IMDS) MUST be denied by both
|
||||
// ResolveAndCheck and CheckURL.
|
||||
func TestPropertyNeverListDominatesWideScope(t *testing.T) {
|
||||
pol, err := NewEgressPolicy("1", []string{"example.com"}, []string{"0.0.0.0/0", "::/0"}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pol.Never = mustParsePrefixes([]string{
|
||||
"127.0.0.0/8", "10.0.0.0/8", "169.254.0.0/16",
|
||||
"64:ff9b::7f00:0/104", "64:ff9b::a00:0/104", "64:ff9b::a9fe:0/112",
|
||||
"64:ff9b:1::/48",
|
||||
})
|
||||
forbidden := []string{
|
||||
"127.0.0.1", "::ffff:127.0.0.1", "10.0.0.1", "169.254.169.254",
|
||||
"64:ff9b::7f00:1", "64:ff9b::a00:1", "64:ff9b::a9fe:a9fe", "64:ff9b:1::1",
|
||||
}
|
||||
ctx := context.Background()
|
||||
for _, rawIP := range forbidden {
|
||||
if _, err := pol.ResolveAndCheck(ctx, rawIP); err == nil {
|
||||
t.Fatalf("Never dominance violated in ResolveAndCheck(%s): got allow", rawIP)
|
||||
}
|
||||
u := "http://" + rawIP + "/"
|
||||
if strings.Contains(rawIP, ":") {
|
||||
u = "http://[" + rawIP + "]/"
|
||||
}
|
||||
if err := pol.CheckURL(ctx, u); err == nil {
|
||||
t.Fatalf("Never dominance violated in CheckURL(%s): got allow", u)
|
||||
}
|
||||
// Domain resolving to a Never IP must also fail CheckURL and ResolveAndCheck.
|
||||
pol.Resolver = func(_ context.Context, _ string) ([]netip.Addr, error) {
|
||||
return []netip.Addr{netip.MustParseAddr(rawIP)}, nil
|
||||
}
|
||||
if _, err := pol.ResolveAndCheck(ctx, "app.example.com"); err == nil {
|
||||
t.Fatalf("Never dominance violated for domain -> %s in ResolveAndCheck", rawIP)
|
||||
}
|
||||
if err := pol.CheckURL(ctx, "https://app.example.com/"); err == nil {
|
||||
t.Fatalf("Never dominance violated for domain -> %s in CheckURL", rawIP)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Property 3: EgressPolicy.domainAllowed hash-index vs linear reference equivalence
|
||||
// and no suffix-confusion invariant.
|
||||
func TestPropertyDomainAllowedEquivalenceAndBoundary(t *testing.T) {
|
||||
rng := rand.New(rand.NewPCG(985, 985))
|
||||
labels := []string{"a", "api", "dev", "prod", "example", "corp", "test", "io", "com", "evil-example"}
|
||||
randDomain := func(n int) string {
|
||||
parts := make([]string, n)
|
||||
for i := range parts {
|
||||
parts[i] = labels[rng.IntN(len(labels))]
|
||||
}
|
||||
return strings.Join(parts, ".")
|
||||
}
|
||||
|
||||
scope := make([]string, 50)
|
||||
for i := range scope {
|
||||
scope[i] = randDomain(2 + rng.IntN(2))
|
||||
}
|
||||
pol, err := NewEgressPolicy("1", scope, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
linearRef := func(host string) bool {
|
||||
h := strings.ToLower(strings.TrimSuffix(strings.TrimSpace(host), "."))
|
||||
if h == "" {
|
||||
return false
|
||||
}
|
||||
for _, s := range pol.Domains {
|
||||
if h == s || strings.HasSuffix(h, "."+s) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
for range 2000 {
|
||||
cand := randDomain(1 + rng.IntN(4))
|
||||
if rng.IntN(3) == 0 {
|
||||
cand = strings.ToUpper(cand) + "."
|
||||
}
|
||||
if got, want := pol.domainAllowed(cand), linearRef(cand); got != want {
|
||||
t.Fatalf("domainAllowed(%q) = %v, want %v", cand, got, want)
|
||||
}
|
||||
}
|
||||
// Explicit suffix-confusion check: "evil-example.com" must NOT match "example.com".
|
||||
p2, _ := NewEgressPolicy("1", []string{"example.com"}, nil, nil)
|
||||
if p2.domainAllowed("evil-example.com") || p2.domainAllowed("notexample.com") {
|
||||
t.Fatal("suffix confusion allowed non-subdomain")
|
||||
}
|
||||
}
|
||||
|
||||
// Property 4: canonScopeDomain fast ASCII path == scopeDomainRE + canonical scope
|
||||
// entries never hold comma/space/NUL/zone + ValidateExecRequest workdir confinement
|
||||
// + ValidateEnv forbidden/reserved invariants (fixes 3eedbdc3, 3666be70).
|
||||
func TestPropertyValidateInvariants(t *testing.T) {
|
||||
rng := rand.New(rand.NewPCG(3666, 3666))
|
||||
ascii := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-* /,@%:"
|
||||
for range 5000 {
|
||||
n := rng.IntN(30)
|
||||
b := make([]byte, n)
|
||||
for i := range b {
|
||||
b[i] = ascii[rng.IntN(len(ascii))]
|
||||
}
|
||||
s := string(b)
|
||||
_, got := canonScopeDomain(s)
|
||||
want := len(s) <= 253 && scopeDomainRE.MatchString(s)
|
||||
if got != want {
|
||||
t.Fatalf("canonScopeDomain(%q) = %v, want regex=%v", s, got, want)
|
||||
}
|
||||
if got && (strings.ContainsAny(s, ", \t\r\n\x00%")) {
|
||||
t.Fatalf("accepted unsafe scope domain %q", s)
|
||||
}
|
||||
}
|
||||
|
||||
// Forbidden / reserved env names must always be rejected regardless of case.
|
||||
badEnvNames := []string{
|
||||
"ARTEX_TOKEN", "artex_pg_dsn", "PGPASSWORD", "pguser", "AWS_SECRET_ACCESS_KEY",
|
||||
"GCP_PROJECT", "AZURE_TENANT_ID", "MY_API_KEY", "AUTH_TOKEN", "DB_PASSWORD",
|
||||
"CLIENT_SECRET", "LD_PRELOAD", "ld_library_path", "PATH", "http_proxy",
|
||||
"HTTPS_PROXY", "BASH_ENV", "PYTHONPATH", "NODE_OPTIONS", "GIT_SSH_COMMAND",
|
||||
}
|
||||
for _, k := range badEnvNames {
|
||||
if err := ValidateEnv(map[string]string{k: "x"}); err == nil {
|
||||
t.Fatalf("ValidateEnv accepted forbidden/reserved var %q", k)
|
||||
}
|
||||
}
|
||||
|
||||
// Workdir confinement: no traversal escapes /workspace.
|
||||
escapes := []string{
|
||||
"/workspace/../etc", "/workspace/../../root", "/workspace2", "/tmp",
|
||||
"/workspace/a/../../etc/passwd", "workspace/a", "../workspace",
|
||||
}
|
||||
for _, wd := range escapes {
|
||||
req := ExecRequest{Argv: []string{"true"}, Workdir: wd}
|
||||
if err := ValidateExecRequest(&req); err == nil {
|
||||
t.Fatalf("ValidateExecRequest accepted escaping workdir %q -> %q", wd, req.Workdir)
|
||||
}
|
||||
}
|
||||
|
||||
// IPv6 zone refusal in canonScopeCIDR.
|
||||
for _, zoned := range []string{"fe80::1%eth0", "fe80::1%eth0,evil.com", "2001:db8::1%lo/64"} {
|
||||
if c, ok := canonScopeCIDR(zoned); ok {
|
||||
t.Fatalf("canonScopeCIDR(%q) accepted zoned IPv6 -> %q", zoned, c)
|
||||
}
|
||||
}
|
||||
_ = fmt.Sprintf
|
||||
}
|
||||
+101
-22
@@ -9,12 +9,58 @@ import (
|
||||
)
|
||||
|
||||
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.
|
||||
// Used as fallback for non-ASCII Unicode domains; ASCII domains use a zero-alloc fast path.
|
||||
scopeDomainRE = regexp.MustCompile(`^(\*\.)?[\p{L}\p{N}_-]+(\.[\p{L}\p{N}_-]+)*\.?$`)
|
||||
)
|
||||
|
||||
func isValidTaskID(id string) bool {
|
||||
if len(id) == 0 || len(id) > 64 {
|
||||
return false
|
||||
}
|
||||
c0 := id[0]
|
||||
if !(c0 >= 'a' && c0 <= 'z' || c0 >= 'A' && c0 <= 'Z' || c0 >= '0' && c0 <= '9') {
|
||||
return false
|
||||
}
|
||||
for i := 1; i < len(id); i++ {
|
||||
c := id[i]
|
||||
if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '_' || c == '.' || c == '-') {
|
||||
return false
|
||||
}
|
||||
if c == '.' && id[i-1] == '.' {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func isValidEnvName(k string) bool {
|
||||
if len(k) == 0 || len(k) > 128 {
|
||||
return false
|
||||
}
|
||||
c0 := k[0]
|
||||
if !(c0 >= 'A' && c0 <= 'Z' || c0 >= 'a' && c0 <= 'z' || c0 == '_') {
|
||||
return false
|
||||
}
|
||||
for i := 1; i < len(k); i++ {
|
||||
c := k[i]
|
||||
if !(c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '_') {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func toUpperFast(s string) string {
|
||||
for i := 0; i < len(s); i++ {
|
||||
c := s[i]
|
||||
if c >= 'a' && c <= 'z' || c >= 0x80 {
|
||||
return strings.ToUpper(s)
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// 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.
|
||||
@@ -26,7 +72,7 @@ const (
|
||||
// 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, "..") {
|
||||
if !isValidTaskID(id) {
|
||||
return fmt.Errorf("%w: invalid task id %q", ErrBadRequest, id)
|
||||
}
|
||||
return nil
|
||||
@@ -35,21 +81,16 @@ func ValidateTaskID(id string) error {
|
||||
// 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))
|
||||
u := toUpperFast(strings.TrimSpace(name))
|
||||
if u == "" {
|
||||
return true
|
||||
}
|
||||
for _, prefix := range []string{"ARTEX_", "PG", "AWS_", "GCP_", "AZURE_"} {
|
||||
if strings.HasPrefix(u, prefix) {
|
||||
return true
|
||||
}
|
||||
if strings.HasPrefix(u, "ARTEX_") || strings.HasPrefix(u, "PG") ||
|
||||
strings.HasPrefix(u, "AWS_") || strings.HasPrefix(u, "GCP_") || strings.HasPrefix(u, "AZURE_") {
|
||||
return true
|
||||
}
|
||||
for _, suffix := range []string{"_KEY", "_TOKEN", "_PASSWORD", "_SECRET"} {
|
||||
if strings.HasSuffix(u, suffix) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
return strings.HasSuffix(u, "_KEY") || strings.HasSuffix(u, "_TOKEN") ||
|
||||
strings.HasSuffix(u, "_PASSWORD") || strings.HasSuffix(u, "_SECRET")
|
||||
}
|
||||
|
||||
// isReservedEnvName reports whether name is set by the worker itself (proxy
|
||||
@@ -57,7 +98,7 @@ func IsForbiddenEnvName(name string) bool {
|
||||
// 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)
|
||||
u := toUpperFast(name)
|
||||
switch u {
|
||||
case "PATH", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY",
|
||||
"BASH_ENV", "ENV", "SHELLOPTS", "BASHOPTS", "PS4", "IFS", "PROMPT_COMMAND",
|
||||
@@ -73,7 +114,7 @@ func isReservedEnvName(name string) bool {
|
||||
// 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) {
|
||||
if !isValidEnvName(k) {
|
||||
return fmt.Errorf("%w: invalid env variable name %q", ErrBadRequest, k)
|
||||
}
|
||||
if IsForbiddenEnvName(k) || isReservedEnvName(k) {
|
||||
@@ -82,7 +123,7 @@ func ValidateEnv(env map[string]string) error {
|
||||
if len(v) > MaxEnvValueBytes {
|
||||
return fmt.Errorf("%w: env variable %q exceeds %d bytes", ErrBadRequest, k, MaxEnvValueBytes)
|
||||
}
|
||||
if strings.ContainsRune(v, 0) {
|
||||
if strings.IndexByte(v, 0) >= 0 {
|
||||
return fmt.Errorf("%w: env variable %q contains NUL byte", ErrBadRequest, k)
|
||||
}
|
||||
}
|
||||
@@ -95,11 +136,11 @@ 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) {
|
||||
if !ok || !isValidEnvName(k) || IsForbiddenEnvName(k) || isReservedEnvName(k) || len(v) > MaxEnvValueBytes || strings.IndexByte(v, 0) >= 0 {
|
||||
continue
|
||||
}
|
||||
// Never override worker home variables from panel process env.
|
||||
switch strings.ToUpper(k) {
|
||||
switch toUpperFast(k) {
|
||||
case "HOME", "XDG_CACHE_HOME":
|
||||
continue
|
||||
}
|
||||
@@ -157,7 +198,7 @@ func ValidateExecRequest(req *ExecRequest) error {
|
||||
// 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]
|
||||
kept = make([]string, 0, len(entries))
|
||||
for _, e := range entries {
|
||||
if c, ok := canon(e); ok {
|
||||
kept = append(kept, c)
|
||||
@@ -177,14 +218,52 @@ func joinedLen(entries []string) int {
|
||||
}
|
||||
|
||||
func canonScopeDomain(d string) (string, bool) {
|
||||
return d, len(d) <= 253 && scopeDomainRE.MatchString(d)
|
||||
if len(d) == 0 || len(d) > 253 {
|
||||
return d, false
|
||||
}
|
||||
s := d
|
||||
if strings.HasPrefix(s, "*.") {
|
||||
s = s[2:]
|
||||
}
|
||||
if len(s) == 0 {
|
||||
return d, false
|
||||
}
|
||||
if s[len(s)-1] == '.' {
|
||||
s = s[:len(s)-1]
|
||||
}
|
||||
if len(s) == 0 {
|
||||
return d, false
|
||||
}
|
||||
labelLen := 0
|
||||
for i := 0; i < len(s); i++ {
|
||||
c := s[i]
|
||||
if c >= 0x80 {
|
||||
return d, scopeDomainRE.MatchString(d)
|
||||
}
|
||||
if c == '.' {
|
||||
if labelLen == 0 {
|
||||
return d, false
|
||||
}
|
||||
labelLen = 0
|
||||
continue
|
||||
}
|
||||
if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '_' || c == '-') {
|
||||
return d, false
|
||||
}
|
||||
labelLen++
|
||||
}
|
||||
return d, labelLen > 0
|
||||
}
|
||||
|
||||
// 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 strings.IndexByte(c, '/') >= 0 {
|
||||
p, err := netip.ParsePrefix(c)
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
if p.Addr().Is4In6() && p.Bits() >= 96 {
|
||||
p = netip.PrefixFrom(p.Addr().Unmap(), p.Bits()-96)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user