Files
ARTEX-chixuweihu/traffic/attribution.go
T
ji ruo d786de90af feat(traffic,sandbox): add TUN/netstack transparent gateway, egress controls, CAP_NET_RAW hardening, and i18n fixes
- Implement full-traffic transparent gateway (cmd/artex-gateway, traffic/netstack.go, traffic/transparent.go) using Linux TUN + gVisor netstack deferred TCP handshakes (eliminating nmap/nc false-positive open ports), real ICMPv4 Echo proxying, UDP/DNS interception, and per-container upstream proxy overrides.
- Add egress blacklist + asset-intercept sync, non-HTTP flow/DNS SQLite persistence and APIs, and /system/proxy & /function/traffic TCP/UDP/DNS UI panels.
- Fix sandbox Playwright MCP browser loopback --proxy-server rewrite and NODE_EXTRA_CA_CERTS override in server/mcpstdio.go.
- Strip all SUID/SGID binaries in Dockerfile.sandbox, grant minimal cap_net_raw+ep to nmap/nping/ping with ARTEX_SANDBOX_ALLOW_NET_RAW toggle, and enforce IPv4/IPv6 anti-spoofing in iptables and netstack.
- Remove hardcoded Chinese "(全局)" from GET /api/proxy/routes, localize ContainerRoutesTab / NonHTTPTrafficPanel labels, and expose reactive locale/isEn from useLiveTranslation for React Compiler compatibility.
2026-12-02 02:51:36 +08:00

293 lines
8.6 KiB
Go

package traffic
import (
"crypto/subtle"
"encoding/base64"
"net"
"net/http"
"net/url"
"strconv"
"strings"
mproxy "github.com/lqqyt2423/go-mitmproxy/proxy"
)
// SourceIdentity identifies which sandbox container / task / chat / intent
// originated a proxied request (#218 Phase 2).
type SourceIdentity struct {
Scope string `json:"sandbox_scope,omitempty"`
OwnerID string `json:"sandbox_owner_id,omitempty"`
ContainerID string `json:"container_id,omitempty"`
SessionID string `json:"session_id,omitempty"`
IntentID int64 `json:"intent_id,omitempty"`
SrcIP string `json:"src_ip,omitempty"`
}
// SourceResolver maps an unforgeable client source IP to its sandbox identity.
type SourceResolver func(srcIP string) (SourceIdentity, bool)
// TaskBlacklistChecker evaluates task-scoped egress rules for a attributed task.
// Returning a non-empty reason blocks the request.
type TaskBlacklistChecker func(taskID, rawHost, scheme string) (reason, pattern string)
const proxyContextUserPrefix = "artexctx_"
// FormatProxyContextURL embeds a fine-grained observability tag (session_id /
// intent_id / host-side scope+owner) as HTTP Basic Proxy-Authorization userinfo.
// The recording proxy parses and strips this header before forwarding upstream
// so it never reaches target servers.
func FormatProxyContextURL(baseProxyURL string, id SourceIdentity) string {
baseProxyURL = strings.TrimSpace(baseProxyURL)
if baseProxyURL == "" {
return ""
}
u, err := url.Parse(baseProxyURL)
if err != nil {
return baseProxyURL
}
// Preserve any pre-existing proxy auth; only tag untagged local/sandbox URLs.
if u.User != nil {
return baseProxyURL
}
q := url.Values{}
if id.Scope != "" {
q.Set("sc", id.Scope)
}
if id.OwnerID != "" {
q.Set("ow", id.OwnerID)
}
if id.SessionID != "" {
q.Set("sid", id.SessionID)
}
if id.IntentID > 0 {
q.Set("iid", strconv.FormatInt(id.IntentID, 10))
}
if len(q) == 0 {
return baseProxyURL
}
u.User = url.UserPassword(proxyContextUserPrefix+q.Encode(), "x")
return u.String()
}
// parseAndStripProxyContext extracts our internal Proxy-Authorization context
// tag (if present) and deletes the header so it is never forwarded to targets.
func parseAndStripProxyContext(h http.Header) (SourceIdentity, string, bool) {
if h == nil {
return SourceIdentity{}, "", false
}
raw := strings.TrimSpace(h.Get("Proxy-Authorization"))
if raw == "" {
return SourceIdentity{}, "", false
}
if !strings.HasPrefix(strings.ToLower(raw), "basic ") {
return SourceIdentity{}, "", false
}
dec, err := base64.StdEncoding.DecodeString(strings.TrimSpace(raw[6:]))
if err != nil {
return SourceIdentity{}, "", false
}
user, pwd, ok := strings.Cut(string(dec), ":")
if !ok || !strings.HasPrefix(user, proxyContextUserPrefix) {
return SourceIdentity{}, "", false
}
// Strip our internal observability header before forwarding upstream.
h.Del("Proxy-Authorization")
vals, err := url.ParseQuery(strings.TrimPrefix(user, proxyContextUserPrefix))
if err != nil {
return SourceIdentity{}, "", false
}
var id SourceIdentity
id.Scope = strings.TrimSpace(vals.Get("sc"))
id.OwnerID = strings.TrimSpace(vals.Get("ow"))
id.ContainerID = strings.TrimSpace(vals.Get("cid"))
id.SrcIP = normalizeIPString(vals.Get("sip"))
id.SessionID = strings.TrimSpace(vals.Get("sid"))
if rawIID := strings.TrimSpace(vals.Get("iid")); rawIID != "" {
if n, err := strconv.ParseInt(rawIID, 10, 64); err == nil && n > 0 {
id.IntentID = n
}
}
return id, pwd, true
}
// SetSourceResolver installs a real-time container source IP -> SourceIdentity
// lookup function on the recording proxy.
func (t *Traffic) SetSourceResolver(fn SourceResolver) {
if t == nil {
return
}
t.attrMu.Lock()
t.sourceResolver = fn
t.attrMu.Unlock()
}
// SetTaskBlacklistChecker installs an optional per-task egress rule evaluator
// consulted when a request is hard-attributed to a task container.
func (t *Traffic) SetTaskBlacklistChecker(fn TaskBlacklistChecker) {
if t == nil {
return
}
t.attrMu.Lock()
t.taskBlacklistFn = fn
t.attrMu.Unlock()
}
// resolveSource combines Layer 1 (unforgeable container source IP) with Layer 2
// (stripped Proxy-Authorization observability tags). Security boundary: when
// srcIP maps to a sandbox container, Scope/OwnerID/ContainerID come strictly
// from the source IP; Proxy-Authorization can only enrich SessionID/IntentID.
// For loopback host-process callers (WebFetch/enrich), Scope/OwnerID from the
// tag are accepted as well.
func (t *Traffic) resolveSource(srcIP string, h http.Header) SourceIdentity {
return t.resolveSourceWithTag(srcIP, h, SourceIdentity{}, "", false)
}
type connAttrEntry struct {
tag SourceIdentity
pwd string
}
func (t *Traffic) resolveSourceForConn(remoteAddr string, h http.Header) SourceIdentity {
tag, pwd, hasTag := parseAndStripProxyContext(h)
if hasTag && remoteAddr != "" && t != nil {
t.connAttr.Store(remoteAddr, connAttrEntry{tag: tag, pwd: pwd})
} else if !hasTag && remoteAddr != "" && t != nil {
if v, ok := t.connAttr.Load(remoteAddr); ok {
switch saved := v.(type) {
case connAttrEntry:
tag = saved.tag
pwd = saved.pwd
hasTag = true
case SourceIdentity:
tag = saved
hasTag = true
}
}
}
return t.resolveSourceWithTag(remoteAddr, nil, tag, pwd, hasTag)
}
func (t *Traffic) resolveSourceWithTag(rawRemote string, h http.Header, tag SourceIdentity, pwd string, hasTag bool) SourceIdentity {
srcIP := normalizeIPString(rawRemote)
if h != nil {
if parsed, parsedPwd, ok := parseAndStripProxyContext(h); ok {
tag = parsed
pwd = parsedPwd
hasTag = true
}
}
var out SourceIdentity
out.SrcIP = srcIP
if t != nil && srcIP != "" {
t.attrMu.RLock()
resolver := t.sourceResolver
gwTok := t.gatewayToken
t.attrMu.RUnlock()
if resolver != nil {
if hard, ok := resolver(srcIP); ok {
out.Scope = hard.Scope
out.OwnerID = hard.OwnerID
out.ContainerID = hard.ContainerID
if hasTag {
out.SessionID = tag.SessionID
out.IntentID = tag.IntentID
}
return out
}
}
// Transparent gateway forwarding (loopback OR via docker-proxy bridge IP
// when authenticated by ARTEX_GATEWAY_TOKEN): trust forwarded SrcIP/ContainerID
// so transparent HTTP/TLS keeps exact sandbox container attribution.
gwAuthed := gwTok != "" && len(pwd) == len(gwTok) && subtle.ConstantTimeCompare([]byte(pwd), []byte(gwTok)) == 1
if hasTag && tag.SrcIP != "" && (gwAuthed || (gwTok == "" && isLoopbackIPString(srcIP))) {
out.SrcIP = tag.SrcIP
if resolver != nil {
if hard, ok := resolver(tag.SrcIP); ok {
out.Scope = hard.Scope
out.OwnerID = hard.OwnerID
out.ContainerID = hard.ContainerID
out.SessionID = tag.SessionID
out.IntentID = tag.IntentID
return out
}
}
out.Scope = tag.Scope
out.OwnerID = tag.OwnerID
out.ContainerID = tag.ContainerID
out.SessionID = tag.SessionID
out.IntentID = tag.IntentID
return out
}
}
// Host-process loopback callers (e.g. WebFetch) may supply full tags.
if hasTag && isLoopbackIPString(srcIP) {
out.Scope = tag.Scope
out.OwnerID = tag.OwnerID
out.ContainerID = tag.ContainerID
if tag.SrcIP != "" {
out.SrcIP = tag.SrcIP
}
out.SessionID = tag.SessionID
out.IntentID = tag.IntentID
}
return out
}
func flowClientAddr(f *mproxy.Flow) string {
if f == nil {
return ""
}
return connClientAddr(f.ConnContext)
}
func connClientAddr(connCtx *mproxy.ConnContext) string {
if connCtx == nil || connCtx.ClientConn == nil || connCtx.ClientConn.Conn == nil || connCtx.ClientConn.Conn.RemoteAddr() == nil {
return ""
}
return connCtx.ClientConn.Conn.RemoteAddr().String()
}
func normalizeIPString(raw string) string {
h, _ := splitHostAndPort(raw)
h = strings.Trim(strings.TrimSpace(h), "[]")
if ip := net.ParseIP(h); ip != nil {
return normalizeIP(ip).String()
}
return h
}
func isLoopbackIPString(raw string) bool {
if raw == "" {
return true
}
ip := net.ParseIP(raw)
return ip != nil && ip.IsLoopback()
}
// checkOutboundForSource runs built-in SSRF guard, global/synced egress
// blacklist, and (when attributed to a task) task-scoped egress rules.
func (t *Traffic) checkOutboundForSource(rawHost, scheme string, src SourceIdentity) *blockMatch {
if m := t.checkOutboundDestination(rawHost, scheme); m != nil {
return m
}
if t == nil || src.Scope != "task" || src.OwnerID == "" {
return nil
}
t.attrMu.RLock()
fn := t.taskBlacklistFn
t.attrMu.RUnlock()
if fn == nil {
return nil
}
if reason, pat := fn(src.OwnerID, rawHost, scheme); reason != "" {
return &blockMatch{
Reason: reason,
RuleKind: "task_intercept",
Pattern: pat,
Source: "asset_intercept",
}
}
return nil
}