From 78b40a9438bc5cc00b53e698685f3ded7f36b145 Mon Sep 17 00:00:00 2001 From: 5P34R Date: Thu, 26 Nov 2026 18:35:03 +0530 Subject: [PATCH 1/5] fix(traffic): refuse non-loopback SOCKS5 clients for every auth method Username/password was offered to any client and accepted any credentials, so a non-loopback client bypassed the loopback-only rule applied to no-auth by offering method 0x02. Credentials are never verified, so both methods are now accepted from loopback clients only; any other client gets 0xFF. --- docs/traffic-socks5-udp.md | 2 +- docs/traffic-socks5.md | 2 +- traffic/socks5.go | 16 +++++-- traffic/socks5_auth_test.go | 96 +++++++++++++++++++++++++++++++++++++ 4 files changed, 110 insertions(+), 6 deletions(-) create mode 100644 traffic/socks5_auth_test.go diff --git a/docs/traffic-socks5-udp.md b/docs/traffic-socks5-udp.md index 57651595..b05294f5 100644 --- a/docs/traffic-socks5-udp.md +++ b/docs/traffic-socks5-udp.md @@ -14,7 +14,7 @@ ARTEX extends the opt-in SOCKS5 inbound listener with **RFC 1928 `UDP ASSOCIATE` - With all SOCKS5 flags unset/off, no SOCKS5 listener and no UDP relay socket are started. - With SOCKS5 TCP enabled and `ARTEX_SOCKS5_UDP_ENABLED` off, `UDP ASSOCIATE` (`0x03`) is refused with RFC 1928 reply `0x07` (*Command not supported*) and no UDP socket is opened. - **Requires traffic recorder**: like P4.1a and P4.1b, the server only starts the SOCKS5 listener when the traffic recorder is enabled (inside the traffic proxy block in `server/manager.go`). -- **Non-loopback warning**: the same authentication caveat from [docs/traffic-socks5.md](traffic-socks5.md) applies—RFC 1929 username/password accepts any credentials, so keep the listener bound to loopback (`127.0.0.1`) or restrict access at the host firewall. +- **Loopback clients only**: as described in [docs/traffic-socks5.md](traffic-socks5.md), the control connection that requests `UDP ASSOCIATE` is accepted from loopback clients only, whichever authentication method it offers. ## Protocol Scope & Lifetime diff --git a/docs/traffic-socks5.md b/docs/traffic-socks5.md index b60fa45a..bf224dcc 100644 --- a/docs/traffic-socks5.md +++ b/docs/traffic-socks5.md @@ -12,7 +12,7 @@ ARTEX ships an opt-in **RFC 1928 SOCKS5 `CONNECT`** inbound listener in `traffic - **Flag off**: no SOCKS5 listener is started and the HTTP MITM recording proxy is byte-identical. - **Requires traffic recorder**: the server only starts the SOCKS5 listener when the traffic recorder is enabled (inside the traffic proxy block in `server/manager.go`). If traffic capture is disabled, setting `ARTEX_SOCKS5_ENABLED` / `ARTEX_SOCKS5_ADDR` does not open a listener. - **Agents unchanged**: workers and tools keep `HTTP_PROXY`, `HTTPS_PROXY`, and `ALL_PROXY` pointing to the existing HTTP proxy; ARTEX does not silently switch agents to SOCKS5. -- **Non-loopback bind warning**: RFC 1929 username/password (`0x02`) accepts **any** username and password without verifying credentials (so the pace marker `artex-pace` can ride in the username). Binding `ARTEX_SOCKS5_ADDR` to a non-loopback address therefore exposes an **unauthenticated proxy** to anyone who can reach that port. The target gate and egress governor still apply to every connection, but keep the listener on loopback (`127.0.0.1`) or restrict access at the host firewall. +- **Loopback clients only**: RFC 1929 username/password (`0x02`) does not verify credentials (the username only carries the pace marker `artex-pace`), so it is offered on the same terms as no-auth (`0x00`): to loopback clients only. A client connecting from any other address is refused with `0xFF` (*no acceptable methods*) whichever method it offers, so binding `ARTEX_SOCKS5_ADDR` to a non-loopback address does not expose an open proxy; it simply accepts no remote clients. The target gate and egress governor still apply to every accepted connection. ## Protocol Scope (P4.1a) diff --git a/traffic/socks5.go b/traffic/socks5.go index ca735d5b..bdfb40b5 100644 --- a/traffic/socks5.go +++ b/traffic/socks5.go @@ -478,16 +478,23 @@ func (s *socks5Server) negotiateAuth(conn net.Conn) (paced bool, ok bool) { } } + // Credentials are never verified (the username only carries the pace marker), + // so username/password grants no more trust than no-auth: both are accepted + // from loopback clients only. A non-loopback client is refused whichever + // method it offers, so a non-loopback bind is not an open proxy. + if !isLoopbackRemote(conn.RemoteAddr()) { + _, _ = conn.Write([]byte{socks5Version, socks5AuthNoAccept}) + return false, false + } // Prefer username/password when offered so clients carrying the pace marker // (egress.PaceUser) can pass it through without requiring real credentials. - // Accept no-auth for loopback clients. if hasUserPass { if _, err := conn.Write([]byte{socks5Version, socks5AuthUserPass}); err != nil { return false, false } return readSOCKS5UserPass(conn) } - if hasNone && isLoopbackRemote(conn.RemoteAddr()) { + if hasNone { if _, err := conn.Write([]byte{socks5Version, socks5AuthNone}); err != nil { return false, false } @@ -498,8 +505,9 @@ func (s *socks5Server) negotiateAuth(conn net.Conn) (paced bool, ok bool) { } // readSOCKS5UserPass parses an RFC 1929 username/password subnegotiation. -// Credentials are never required (any username/password succeeds); a username -// equal to egress.PaceUser marks the connection as paced. +// Credentials are never verified (any username/password succeeds, which is why +// negotiateAuth only offers this method to loopback clients); a username equal +// to egress.PaceUser marks the connection as paced. func readSOCKS5UserPass(conn net.Conn) (paced bool, ok bool) { var head [2]byte if _, err := io.ReadFull(conn, head[:]); err != nil { diff --git a/traffic/socks5_auth_test.go b/traffic/socks5_auth_test.go new file mode 100644 index 00000000..51a803d7 --- /dev/null +++ b/traffic/socks5_auth_test.go @@ -0,0 +1,96 @@ +package traffic + +import ( + "io" + "net" + "testing" + "time" + + "github.com/Autumn-27/artex/egress" +) + +// remoteAddrConn reports a chosen remote address so negotiateAuth can be driven +// as if the client connected from that address. +type remoteAddrConn struct { + net.Conn + remote net.Addr +} + +func (c remoteAddrConn) RemoteAddr() net.Addr { return c.remote } + +// negotiateFrom runs negotiateAuth for a client at remote that offers methods +// and, when the server selects username/password, sends user/pass. It returns +// the server's method selection and negotiateAuth's results. +func negotiateFrom(t *testing.T, remote net.Addr, methods []byte, user, pass string) (selected byte, paced, ok bool) { + t.Helper() + server, client := net.Pipe() + defer server.Close() + defer client.Close() + _ = client.SetDeadline(time.Now().Add(5 * time.Second)) + + type result struct{ paced, ok bool } + done := make(chan result, 1) + go func() { + p, o := (&socks5Server{}).negotiateAuth(remoteAddrConn{Conn: server, remote: remote}) + done <- result{p, o} + }() + + if _, err := client.Write(append([]byte{socks5Version, byte(len(methods))}, methods...)); err != nil { + t.Fatalf("write greeting: %v", err) + } + var sel [2]byte + if _, err := io.ReadFull(client, sel[:]); err != nil { + t.Fatalf("read method selection: %v", err) + } + if sel[1] == socks5AuthUserPass { + msg := []byte{socks5UserPassVer, byte(len(user))} + msg = append(msg, user...) + msg = append(msg, byte(len(pass))) + msg = append(msg, pass...) + if _, err := client.Write(msg); err != nil { + t.Fatalf("write credentials: %v", err) + } + var resp [2]byte + if _, err := io.ReadFull(client, resp[:]); err != nil { + t.Fatalf("read auth response: %v", err) + } + } + r := <-done + return sel[1], r.paced, r.ok +} + +func TestSOCKS5NonLoopbackClientRefusedForEveryMethod(t *testing.T) { + remote := &net.TCPAddr{IP: net.ParseIP("203.0.113.7"), Port: 40000} + cases := []struct { + name string + methods []byte + }{ + {"userpass only", []byte{socks5AuthUserPass}}, + {"none and userpass", []byte{socks5AuthNone, socks5AuthUserPass}}, + {"none only", []byte{socks5AuthNone}}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + sel, _, ok := negotiateFrom(t, remote, tc.methods, "anyone", "anything") + if ok || sel != socks5AuthNoAccept { + t.Fatalf("non-loopback client: selected=%#x ok=%v, want %#x and refused", sel, ok, socks5AuthNoAccept) + } + }) + } +} + +func TestSOCKS5LoopbackClientStillAccepted(t *testing.T) { + for _, ip := range []string{"127.0.0.1", "::1"} { + remote := &net.TCPAddr{IP: net.ParseIP(ip), Port: 40000} + + sel, paced, ok := negotiateFrom(t, remote, []byte{socks5AuthNone, socks5AuthUserPass}, egress.PaceUser, egress.PaceUser) + if !ok || sel != socks5AuthUserPass || !paced { + t.Fatalf("%s userpass with pace marker: selected=%#x paced=%v ok=%v", ip, sel, paced, ok) + } + + sel, paced, ok = negotiateFrom(t, remote, []byte{socks5AuthNone}, "", "") + if !ok || sel != socks5AuthNone || paced { + t.Fatalf("%s no-auth: selected=%#x paced=%v ok=%v", ip, sel, paced, ok) + } + } +} From 86c30e4d9a6888a790e99e606a4612f5f24899a5 Mon Sep 17 00:00:00 2001 From: 5P34R Date: Thu, 26 Nov 2026 18:36:05 +0530 Subject: [PATCH 2/5] fix(server): render custom-tool placeholders in one pass renderTemplate replaced placeholders param by param, so a value containing another placeholder was expanded again inside the first value's shell quotes: a="{b}", b="; id" rendered {a} as ''; id'' and ran id. Whether it happened depended on map iteration order. Scan the template once and never rescan substituted values. --- server/customtool.go | 27 +++++++++++++++++++++++---- server/customtool_test.go | 31 +++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 4 deletions(-) diff --git a/server/customtool.go b/server/customtool.go index 10e1cbb3..39eef4a7 100644 --- a/server/customtool.go +++ b/server/customtool.go @@ -693,12 +693,31 @@ func identity(s string) string { return s } func shellQuote(s string) string { return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'" } // renderTemplate replaces {name} placeholders with each param's rendered value. +// +// It scans the template once, left to right, and never rescans a substituted +// value. Replacing param by param instead would let a value containing +// "{other}" be expanded again by a later param, inside the quotes of the first +// one: with a="{b}" and b="; id", shell-quoted {a} becomes '{b}', and then the +// quoted value of b lands inside those quotes, closing them and running "id" +// (and which param runs first depends on map order). A "{" that does not start a known placeholder is copied as is, +// so "{{a}}" still renders as "{" + value + "}". func renderTemplate(tmpl string, params map[string]any, quote func(string) string) string { - out := tmpl - for k, v := range params { - out = strings.ReplaceAll(out, "{"+k+"}", quote(valToStr(v))) + var b strings.Builder + b.Grow(len(tmpl)) + for i := 0; i < len(tmpl); { + if tmpl[i] == '{' { + if end := strings.IndexByte(tmpl[i+1:], '}'); end >= 0 { + if v, ok := params[tmpl[i+1:i+1+end]]; ok { + b.WriteString(quote(valToStr(v))) + i += end + 2 + continue + } + } + } + b.WriteByte(tmpl[i]) + i++ } - return out + return b.String() } // valToStr renders a param value: scalars as-is, arrays/objects as compact JSON. diff --git a/server/customtool_test.go b/server/customtool_test.go index d0845bf6..46648ae7 100644 --- a/server/customtool_test.go +++ b/server/customtool_test.go @@ -39,6 +39,37 @@ func TestRenderTemplateHTTP(t *testing.T) { } } +func TestRenderTemplateDoesNotExpandSubstitutedValues(t *testing.T) { + // A value that looks like another placeholder must stay literal. Map + // iteration order is random, so render many times: the old param-by-param + // replacement produced cmd ''; id'' whenever "a" was replaced before "b". + params := map[string]any{"a": "{b}", "b": "; id"} + want := `cmd '{b}' '; id'` + for i := 0; i < 200; i++ { + if got := renderTemplate("cmd {a} {b}", params, shellQuote); got != want { + t.Fatalf("render %d: got %q, want %q", i, got, want) + } + } +} + +func TestRenderTemplateLiteralBraces(t *testing.T) { + params := map[string]any{"a": "v"} + cases := map[string]string{ + "{{a}}": "{v}", // doubled braces wrap the value + "{a": "{a", // unclosed + "x{unknown}y": "x{unknown}y", // not a param + "{}{a}": "{}v", + "{a}{a}": "vv", + "}{a}{": "}v{", + "": "", + } + for tmpl, want := range cases { + if got := renderTemplate(tmpl, params, identity); got != want { + t.Fatalf("renderTemplate(%q) = %q, want %q", tmpl, got, want) + } + } +} + func TestScalarStr(t *testing.T) { cases := []struct { v any From f19b67c3c3f6c93da936bba99a837540b80945ed Mon Sep 17 00:00:00 2001 From: 5P34R Date: Thu, 26 Nov 2026 18:37:14 +0530 Subject: [PATCH 3/5] fix(server): cap request bodies that claim a multipart type limitRequestBody skipped every request with a multipart Content-Type, so any handler decoding JSON straight from r.Body (about 30 of them) read an unbounded body when the client simply labelled the request multipart. Multipart bodies now get an upload-sized cap (the largest limit an upload handler sets); upload handlers keep their own tighter limits and messages. --- server/decode_limit_test.go | 37 +++++++++++++++++++++++++++++++++++++ server/server_mgmt.go | 25 ++++++++++++++++++++----- 2 files changed, 57 insertions(+), 5 deletions(-) diff --git a/server/decode_limit_test.go b/server/decode_limit_test.go index 5922673a..3d827809 100644 --- a/server/decode_limit_test.go +++ b/server/decode_limit_test.go @@ -3,6 +3,7 @@ package server import ( "encoding/json" "errors" + "io" "net/http" "net/http/httptest" "strings" @@ -52,6 +53,42 @@ func TestRawJSONBodyOverTheCapIs413(t *testing.T) { } } +func TestMultipartLabelDoesNotUncapTheBody(t *testing.T) { + // A JSON handler reading r.Body directly, reached with a multipart + // Content-Type, must still hit a cap rather than read without limit. + var readErr error + h := limitRequestBody(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, readErr = io.Copy(io.Discard, r.Body) + w.WriteHeader(http.StatusNoContent) + })) + r := httptest.NewRequest(http.MethodPost, "/", io.LimitReader(zeroReader{}, maxMultipartBodyBytes+1)) + r.Header.Set("Content-Type", "multipart/form-data; boundary=abc") + h.ServeHTTP(httptest.NewRecorder(), r) + var tooLarge *http.MaxBytesError + if !errors.As(readErr, &tooLarge) || tooLarge.Limit != maxMultipartBodyBytes { + t.Fatalf("read err=%v, want MaxBytesError at %d", readErr, maxMultipartBodyBytes) + } +} + +func TestMultipartCapCoversEveryUploadHandler(t *testing.T) { + for name, limit := range map[string]int64{ + "chat upload": maxChatUpload + chatUploadMultipartOverhead, + "workspace upload": maxWorkspaceUpload, + "skill zip": maxSkillZipBytes, + } { + if limit > maxMultipartBodyBytes { + t.Fatalf("%s limit %d exceeds maxMultipartBodyBytes %d: real uploads would be refused", name, limit, maxMultipartBodyBytes) + } + } +} + +type zeroReader struct{} + +func (zeroReader) Read(p []byte) (int, error) { + clear(p) + return len(p), nil +} + func TestMultipartBodyIsNotGivenTheJSONCap(t *testing.T) { h := limitRequestBody(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if _, ok := r.Body.(*limitedBody); ok { diff --git a/server/server_mgmt.go b/server/server_mgmt.go index 701c7e80..fdfd4b23 100644 --- a/server/server_mgmt.go +++ b/server/server_mgmt.go @@ -86,11 +86,19 @@ func pathInt(r *http.Request, name string) (int64, bool) { return n, err == nil } -// decodeMaxBytes is the default JSON body cap. Multipart uploads are not capped -// here; those handlers set their own limit. A smaller MaxBytesReader installed -// by a handler still wins, because it sits inside this one. +// decodeMaxBytes is the default JSON body cap. Multipart uploads get the larger +// maxMultipartBodyBytes here instead; the upload handlers set their own, +// tighter limit. A smaller MaxBytesReader installed by a handler still wins, +// because it sits inside this one. const decodeMaxBytes = 32 << 20 +// maxMultipartBodyBytes caps any request that declares a multipart Content-Type. +// It is the largest limit an upload handler sets (chat attachments; workspace +// uploads and skill zips are smaller), so no real upload is refused, while a +// handler that decodes JSON straight from r.Body can no longer be handed an +// unbounded body just by labelling the request multipart. +const maxMultipartBodyBytes = maxChatUpload + chatUploadMultipartOverhead + // limitedBody records a MaxBytesError so a later 400 can be answered as 413. type limitedBody struct { io.ReadCloser @@ -128,10 +136,17 @@ func (b *bodyLimitWriter) Unwrap() http.ResponseWriter { return b.ResponseWriter // limitRequestBody caps a non-multipart body at decodeMaxBytes and passes the // real ResponseWriter into MaxBytesReader. A handler that then answers 400 for -// that read is rewritten to 413. +// that read is rewritten to 413. A multipart body gets the plain upload-sized +// cap instead: it is not a limitedBody, so decode still applies the JSON cap +// if a JSON handler receives it, and upload handlers keep their own messages. func limitRequestBody(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.Body == nil || r.Body == http.NoBody || isMultipart(r) { + if r.Body == nil || r.Body == http.NoBody { + next.ServeHTTP(w, r) + return + } + if isMultipart(r) { + r.Body = http.MaxBytesReader(w, r.Body, maxMultipartBodyBytes) next.ServeHTTP(w, r) return } From 7fbed0fe7c8c791fc3a1d5a836200983c83d4cae Mon Sep 17 00:00:00 2001 From: 5P34R Date: Thu, 26 Nov 2026 18:37:18 +0530 Subject: [PATCH 4/5] fix(traffic): use a documentation address in the traffic_search host example The host filter description showed a real routable IP (107.172.96.177) to the model as its example. Use 192.0.2.10 from TEST-NET-1 (RFC 5737) so the example cannot prime the agent toward a third-party host. --- traffic/traffic.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/traffic/traffic.go b/traffic/traffic.go index b84d493f..c33fedb0 100644 --- a/traffic/traffic.go +++ b/traffic/traffic.go @@ -2510,7 +2510,7 @@ func (t *Traffic) Tools() []actool.CoreTool { Schema: map[string]any{ "type": "object", "properties": map[string]any{ - "host": map[string]any{"type": "string", "description": "Filter by host (required; e.g. '107.172.96.177', '107.172.96.177:8082', or 'http://107.172.96.177:8082/path')"}, + "host": map[string]any{"type": "string", "description": "Filter by host (required; e.g. '192.0.2.10', '192.0.2.10:8082', or 'http://192.0.2.10:8082/path')"}, "contains": map[string]any{"type": "string", "description": "URL substring filter (optional, e.g. 'api' / 'login')"}, "body_contains": map[string]any{"type": "string", "description": "Full-text body search (optional, at least 3 characters); matches request/response headers and bodies, e.g. 'password' / 'root:x:0' / 'internal test'"}, "limit": map[string]any{"type": "integer", "description": "Page size, default 3, max 10"}, From 4d8e752c47c5e5e59381e081143045358cf23538 Mon Sep 17 00:00:00 2001 From: 5P34R Date: Thu, 26 Nov 2026 18:37:28 +0530 Subject: [PATCH 5/5] docs(changelog): record the main-branch security fixes --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5f46c990..e02b86ca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,10 @@ All notable changes to this project are documented in this file. The format is b ### Fixed +- **Custom-tool parameters can no longer inject shell commands through each other**: placeholders were replaced one parameter at a time, so a value containing another placeholder (`a="{b}"`) was expanded again by the later parameter inside the first value's shell quotes, and `b="; id"` then ran `id`. Whether it happened depended on map order. Templates are now rendered in a single pass that never rescans a substituted value. +- **The SOCKS5 listener refuses non-loopback clients for every auth method**: username/password was offered to any client and accepted any credentials, so a remote client got past the loopback-only rule for no-auth by offering method `0x02`. Credentials are still not verified (the username carries only the pace marker), so both methods are now accepted from loopback clients only; binding `ARTEX_SOCKS5_ADDR` to a non-loopback address no longer exposes an open proxy. +- **Request bodies labelled multipart are capped**: the 32 MiB body cap skipped any request with a multipart `Content-Type`, so a JSON handler reading the body directly could be sent an unbounded body. Multipart bodies now get an upload-sized cap (the largest limit an upload handler sets). +- **The `traffic_search` host example no longer names a real IP**: the tool description shown to the model used a routable third-party address; it now uses `192.0.2.10` (RFC 5737). - **Missing Docker buildx is reported before the build**: without the buildx plugin, Compose only warns and falls back to the legacy builder, which fails on the Dockerfile's first `FROM --platform=$BUILDPLATFORM` with `failed to parse platform`. `install.sh` (all-Docker) and `update.sh` (Docker update) now check `docker buildx version` first and stop with an install hint, and the automatic Docker install on apt-based distros not covered by get.docker.com installs the buildx package as well. The README Docker section names buildx as a requirement. - **A goal URL followed by punctuation is still seeded**: a goal such as `Assess http://juiceshop:3000.` no longer logs `could not parse a target host/IP` and skips the site. Trailing punctuation, including full-width `。` and a closing bracket that has no matching opener, is trimmed from the URL before it is parsed, so `http://[::1]` is left alone. The scheme the goal names is kept and a final period does not end up in the host. - **Task timeout triggers fire for every task**: `on_task_timeout` used the task id as a watermark, but tasks time out in deadline order. Once a newer task timed out first, an older task that timed out later was never fired for. Fired timeouts are now kept in a persisted set, like met goals; on first start the set is seeded with the tasks already timed out, so nothing replays.