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.
This commit is contained in:
ji ruo committed 2026-12-02 02:51:36 +08:00
1 parent 9c43e694a3
commit d786de90af
69 files changed
+13082 -1433

No files matched your search

+292
View File
@@ -0,0 +1,292 @@
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
}
+296
View File
@@ -0,0 +1,296 @@
package traffic
import (
"database/sql"
"fmt"
"io"
"net"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
func TestFormatAndStripProxyContext(t *testing.T) {
tagged := FormatProxyContextURL("http://127.0.0.1:8788", SourceIdentity{
Scope: "task",
OwnerID: "42",
SessionID: "conv-9",
IntentID: 123,
})
u, err := url.Parse(tagged)
if err != nil {
t.Fatalf("parse tagged url: %v", err)
}
if u.User == nil || !strings.HasPrefix(u.User.Username(), proxyContextUserPrefix) {
t.Fatalf("expected artexctx userinfo, got %v", u.User)
}
// Pre-existing proxy auth must be preserved untouched.
preAuth := "http://alice:[email protected]:8788"
if got := FormatProxyContextURL(preAuth, SourceIdentity{Scope: "task", OwnerID: "1"}); got != preAuth {
t.Fatalf("expected pre-auth URL unchanged, got %q", got)
}
req, _ := http.NewRequest("GET", "http://example.com/", nil)
req.SetBasicAuth(u.User.Username(), "x")
req.Header.Set("Proxy-Authorization", req.Header.Get("Authorization"))
req.Header.Del("Authorization")
id, _, ok := parseAndStripProxyContext(req.Header)
if !ok {
t.Fatalf("expected parseAndStripProxyContext ok=true")
}
if req.Header.Get("Proxy-Authorization") != "" {
t.Fatalf("Proxy-Authorization should be stripped, got %q", req.Header.Get("Proxy-Authorization"))
}
if id.Scope != "task" || id.OwnerID != "42" || id.SessionID != "conv-9" || id.IntentID != 123 {
t.Fatalf("unexpected parsed identity: %+v", id)
}
// Unrelated Proxy-Authorization must NOT be stripped.
h2 := http.Header{"Proxy-Authorization": []string{"Basic dXNlcjpwYXNz"}}
if _, _, ok := parseAndStripProxyContext(h2); ok {
t.Fatalf("non-artexctx header should not parse as context")
}
if h2.Get("Proxy-Authorization") == "" {
t.Fatalf("non-artexctx Proxy-Authorization must not be stripped")
}
}
func TestResolveSourceSecurityBoundary(t *testing.T) {
tr := &Traffic{}
tr.SetSourceResolver(func(srcIP string) (SourceIdentity, bool) {
if srcIP == "172.28.0.5" {
return SourceIdentity{
Scope: "task",
OwnerID: "42",
ContainerID: "abcdef123456",
SrcIP: srcIP,
}, true
}
return SourceIdentity{}, false
})
// Sandbox container attempting to forge OwnerID=99 via Proxy-Authorization.
tagged := FormatProxyContextURL("http://172.28.0.1:8788", SourceIdentity{
Scope: "session",
OwnerID: "99",
SessionID: "sess-1",
IntentID: 77,
})
u, _ := url.Parse(tagged)
r, _ := http.NewRequest("GET", "http://example.com/", nil)
r.SetBasicAuth(u.User.Username(), "x")
r.Header.Set("Proxy-Authorization", r.Header.Get("Authorization"))
got := tr.resolveSource("172.28.0.5:54321", r.Header)
if got.Scope != "task" || got.OwnerID != "42" || got.ContainerID != "abcdef123456" {
t.Fatalf("sandbox container IP must enforce hard identity, got %+v", got)
}
if got.IntentID != 77 || got.SessionID != "sess-1" {
t.Fatalf("observability fields should still be enriched, got %+v", got)
}
if got.SrcIP != "172.28.0.5" {
t.Fatalf("expected normalized src_ip 172.28.0.5, got %q", got.SrcIP)
}
// Host loopback caller may supply full scope+owner tags.
r2, _ := http.NewRequest("GET", "http://example.com/", nil)
r2.SetBasicAuth(u.User.Username(), "x")
r2.Header.Set("Proxy-Authorization", r2.Header.Get("Authorization"))
gotHost := tr.resolveSource("127.0.0.1:41234", r2.Header)
if gotHost.Scope != "session" || gotHost.OwnerID != "99" || gotHost.IntentID != 77 {
t.Fatalf("loopback host caller should accept full tag, got %+v", gotHost)
}
}
func TestProxyAttributionAndTaskIsolationLive(t *testing.T) {
var seenProxyAuth string
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
seenProxyAuth = r.Header.Get("Proxy-Authorization")
w.Header().Set("Content-Type", "text/plain")
_, _ = w.Write([]byte("hello-target"))
}))
defer upstream.Close()
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen: %v", err)
}
proxyAddr := ln.Addr().String()
_ = ln.Close()
tr, err := Open(t.TempDir(), proxyAddr)
if err != nil {
t.Fatalf("Open: %v", err)
}
defer tr.Close()
tr.SetTaskBlacklistChecker(func(taskID, rawHost, scheme string) (string, string) {
if taskID == "10" && strings.Contains(rawHost, "blocked-task10.example") {
return "task #10 intercept rule: blocked", "blocked-task10.example"
}
return "", ""
})
go func() { _ = tr.Start() }()
// Wait until proxy accepts connections.
deadline := time.Now().Add(3 * time.Second)
for time.Now().Before(deadline) {
c, err := net.DialTimeout("tcp", proxyAddr, 100*time.Millisecond)
if err == nil {
_ = c.Close()
break
}
time.Sleep(25 * time.Millisecond)
}
sendThrough := func(id SourceIdentity, targetURL string) *http.Response {
pURLStr := FormatProxyContextURL("http://"+proxyAddr, id)
pURL, _ := url.Parse(pURLStr)
client := &http.Client{
Transport: &http.Transport{Proxy: http.ProxyURL(pURL)},
Timeout: 5 * time.Second,
}
resp, err := client.Get(targetURL)
if err != nil {
t.Fatalf("GET %s via proxy: %v", targetURL, err)
}
return resp
}
// 1. Task 10 request -> recorded with attribution, Proxy-Authorization stripped before reaching target.
resp1 := sendThrough(SourceIdentity{Scope: "task", OwnerID: "10", IntentID: 55}, upstream.URL+"/t10")
_, _ = io.ReadAll(resp1.Body)
_ = resp1.Body.Close()
if resp1.StatusCode != 200 {
t.Fatalf("expected 200 for task 10, got %d", resp1.StatusCode)
}
if seenProxyAuth != "" {
t.Fatalf("target server must never receive internal Proxy-Authorization, got %q", seenProxyAuth)
}
// 2. Task 20 request to the SAME target host -> must NOT leak into Task 10's query!
resp2 := sendThrough(SourceIdentity{Scope: "task", OwnerID: "20", IntentID: 88}, upstream.URL+"/t20")
_, _ = io.ReadAll(resp2.Body)
_ = resp2.Body.Close()
// 3. Task 10 blocked by per-task intercept rule -> 403 + block event attributed to task 10.
resp3 := sendThrough(SourceIdentity{Scope: "task", OwnerID: "10", IntentID: 56}, "http://blocked-task10.example/secret")
body3, _ := io.ReadAll(resp3.Body)
_ = resp3.Body.Close()
if resp3.StatusCode != http.StatusForbidden {
t.Fatalf("expected 403 for task 10 blocked host, got %d (%s)", resp3.StatusCode, string(body3))
}
events := tr.BlockEvents(10)
if len(events) == 0 || events[0].Scope != "task" || events[0].OwnerID != "10" || events[0].RuleKind != "task_intercept" {
t.Fatalf("expected task 10 block event, got %+v", events)
}
// 4. Insert a legacy unattributed row for the same host to verify backward compatibility.
uParsed, _ := url.Parse(upstream.URL)
targetHost := uParsed.Hostname()
_, err = tr.DB().Exec(`INSERT INTO exchanges(id,ts,host,method,url_template,url,status,content_type,req_len,resp_len,path) VALUES('legacy-1', 100, ?, 'GET', '/old', ?, 200, 'text/plain', 0, 5, '')`, targetHost, upstream.URL+"/old")
if err != nil {
t.Fatalf("insert legacy row: %v", err)
}
// Query Task 10 with shared targetHost in scope: must see Task 10 + legacy, NOT Task 20!
rows10, total10, err := tr.Page(PageQuery{
OwnerTaskID: "10",
Hosts: []string{targetHost},
RespMin: -1,
RespMax: -1,
}, 0, 50)
if err != nil {
t.Fatalf("Page task 10: %v", err)
}
if total10 != 2 {
t.Fatalf("expected 2 rows for task 10 (task10 + legacy, excluding task20), got %d: %+v", total10, rows10)
}
for _, r := range rows10 {
if r.SandboxOwnerID == "20" {
t.Fatalf("task 20 traffic leaked into task 10 query: %+v", r)
}
if strings.HasSuffix(r.URL, "/t10") {
if r.SandboxScope != "task" || r.SandboxOwnerID != "10" || r.IntentID != 55 || r.SrcIP != "127.0.0.1" {
t.Fatalf("unexpected attribution on /t10: %+v", r)
}
}
}
// Query Task 10 with EMPTY host scope (e.g. before assets are discovered): still returns Task 10's attributed traffic!
rows10NoScope, totalNoScope, err := tr.Page(PageQuery{
OwnerTaskID: "10",
RespMin: -1,
RespMax: -1,
}, 0, 50)
if err != nil || totalNoScope != 1 || len(rows10NoScope) != 1 || rows10NoScope[0].SandboxOwnerID != "10" {
t.Fatalf("expected 1 attributed row with empty host scope, got total=%d rows=%+v err=%v", totalNoScope, rows10NoScope, err)
}
// HostsForTask returns attributed host even with empty scope.
hosts10, err := tr.HostsForTask("10", nil)
if err != nil || len(hosts10) != 1 || hosts10[0].Host != targetHost {
t.Fatalf("HostsForTask expected [%s], got %+v err=%v", targetHost, hosts10, err)
}
}
func TestAttributionMigrationOnLegacyDB(t *testing.T) {
dir := t.TempDir()
idxDir := filepath.Join(dir, "_index")
if err := os.MkdirAll(idxDir, 0o755); err != nil {
t.Fatal(err)
}
dbPath := filepath.Join(idxDir, "index.sqlite")
rawDB, err := sql.Open("sqlite", dbPath)
if err != nil {
t.Fatal(err)
}
_, err = rawDB.Exec(`CREATE TABLE exchanges (
id TEXT PRIMARY KEY,
ts INTEGER,
host TEXT,
method TEXT,
url_template TEXT,
url TEXT,
status INTEGER,
content_type TEXT,
req_len INTEGER,
resp_len INTEGER,
path TEXT
);
INSERT INTO exchanges VALUES ('old-1', 123, 'example.com', 'GET', '/', 'http://example.com/', 200, 'text/html', 0, 10, '');`)
if err != nil {
t.Fatal(err)
}
_ = rawDB.Close()
tr, err := Open(dir, "127.0.0.1:0")
if err != nil {
t.Fatalf("Open legacy DB failed: %v", err)
}
defer tr.Close()
rows, total, err := tr.Page(PageQuery{RespMin: -1, RespMax: -1}, 0, 10)
if err != nil {
t.Fatalf("Page after migration failed: %v", err)
}
if total != 1 || len(rows) != 1 || rows[0].ID != "old-1" {
t.Fatalf("unexpected rows after migration: total=%d rows=%+v", total, rows)
}
// Verify new attribution insert works on migrated DB.
if _, err := tr.DB().Exec(`INSERT INTO exchanges(id,ts,host,method,url_template,url,status,content_type,req_len,resp_len,path,sandbox_scope,sandbox_owner_id,container_id,session_id,intent_id,src_ip) VALUES('new-1', 456, 'example.com', 'GET', '/new', 'http://example.com/new', 200, 'text/plain', 0, 4, '', 'task', '7', 'cid123456789', '', 3, '172.28.0.9')`); err != nil {
t.Fatalf("insert attributed row after migration failed: %v", err)
}
filtered, tot, err := tr.Page(PageQuery{ContainerID: "cid123", RespMin: -1, RespMax: -1}, 0, 10)
if err != nil || tot != 1 || len(filtered) != 1 || filtered[0].SrcIP != "172.28.0.9" {
t.Fatalf("container filter failed: tot=%d rows=%+v err=%v", tot, filtered, err)
}
_ = fmt.Sprintf("migrated ok")
}
+68
View File
@@ -0,0 +1,68 @@
package traffic
import (
"bytes"
"os"
"path/filepath"
)
var systemCABundleCandidates = []string{
"/etc/ssl/certs/ca-certificates.crt",
"/etc/pki/tls/certs/ca-bundle.crt",
"/etc/ssl/cert.pem",
}
// SystemCABundlePath returns the path to the merged CA bundle (system roots +
// ARTEX MITM CA) maintained under <trafficDir>/_ca/ca-certificates.crt.
func (t *Traffic) SystemCABundlePath() string {
if t == nil {
return ""
}
return filepath.Join(t.dir, "_ca", "ca-certificates.crt")
}
// EnsureSystemCABundle builds a merged CA bundle combining the host/container
// system root store with ARTEX's MITM CA cert so sandbox containers can mount
// it read-only at /etc/ssl/certs/ca-certificates.crt without requiring root or
// runtime update-ca-certificates (#218 Phase 3). Returns the bundle path if
// built, or empty string if no base system bundle or MITM CA is present.
func (t *Traffic) EnsureSystemCABundle() string {
if t == nil {
return ""
}
mitmPEM, err := os.ReadFile(t.CACertPath())
if err != nil || len(bytes.TrimSpace(mitmPEM)) == 0 {
return ""
}
var sysPEM []byte
for _, p := range systemCABundleCandidates {
if b, err := os.ReadFile(p); err == nil && len(bytes.TrimSpace(b)) > 0 {
sysPEM = b
break
}
}
if len(sysPEM) == 0 {
return ""
}
var merged bytes.Buffer
merged.Write(sysPEM)
if !bytes.HasSuffix(sysPEM, []byte("\n")) {
merged.WriteByte('\n')
}
merged.WriteString("# ARTEX Recording Proxy MITM CA\n")
merged.Write(mitmPEM)
if !bytes.HasSuffix(mitmPEM, []byte("\n")) {
merged.WriteByte('\n')
}
dest := t.SystemCABundlePath()
tmp := dest + ".tmp"
if err := os.WriteFile(tmp, merged.Bytes(), 0o644); err != nil {
return ""
}
if err := os.Rename(tmp, dest); err != nil {
_ = os.Remove(tmp)
return ""
}
return dest
}
+393
View File
@@ -0,0 +1,393 @@
package traffic
import (
"fmt"
"net"
"net/url"
"strconv"
"strings"
"sync"
"time"
)
// EgressBlacklistRule defines one network-layer outbound block rule enforced at
// the recording proxy dial/request boundary (both local and Docker sandbox modes).
type EgressBlacklistRule struct {
ID string `json:"id"`
Enabled bool `json:"enabled"`
Kind string `json:"kind"` // domain | suffix | ip | cidr
Pattern string `json:"pattern"` // exact domain, suffix (*.example.com / .example.com), IP, or CIDR
Port int `json:"port,omitempty"` // optional; 0 matches all ports
Note string `json:"note,omitempty"`
Source string `json:"source,omitempty"` // custom | asset_intercept
CreatedAt string `json:"created_at,omitempty"`
UpdatedAt string `json:"updated_at,omitempty"`
}
// EgressBlockEvent captures one outbound connection/request rejected by either
// the built-in SSRF guard or an egress blacklist rule.
type EgressBlockEvent struct {
At time.Time `json:"at"`
Host string `json:"host"`
Port string `json:"port,omitempty"`
Method string `json:"method,omitempty"`
URL string `json:"url,omitempty"`
SrcIP string `json:"src_ip,omitempty"`
Scope string `json:"scope,omitempty"`
OwnerID string `json:"owner_id,omitempty"`
Reason string `json:"reason"`
RuleKind string `json:"rule_kind,omitempty"` // ssrf | domain | suffix | ip | cidr
RuleID string `json:"rule_id,omitempty"`
Pattern string `json:"pattern,omitempty"`
Source string `json:"source,omitempty"` // ssrf_guard | custom | asset_intercept
}
type blockMatch struct {
Reason string
RuleKind string
RuleID string
Pattern string
Source string
}
type compiledRule struct {
rule EgressBlacklistRule
domain string // normalized lowercase domain / suffix (no leading dot or wildcard)
ip net.IP // normalized IP for kind=ip
cidr *net.IPNet // parsed CIDR for kind=cidr
port string // "" = any port
}
type egressBlacklist struct {
domainRules []compiledRule
suffixRules []compiledRule
ipRules []compiledRule
cidrRules []compiledRule
}
// NormalizeEgressRule validates and normalizes a rule's kind and pattern.
func NormalizeEgressRule(r *EgressBlacklistRule) error {
r.Kind = strings.ToLower(strings.TrimSpace(r.Kind))
r.Pattern = strings.TrimSpace(r.Pattern)
r.Note = strings.TrimSpace(r.Note)
if r.Port < 0 || r.Port > 65535 {
return fmt.Errorf("端口必须在 0 到 65535 之间")
}
if r.Pattern == "" {
return fmt.Errorf("规则匹配内容不能为空")
}
switch r.Kind {
case "domain":
h := normalizeDomainPattern(r.Pattern)
if h == "" || strings.ContainsAny(h, " /\\*?@") {
return fmt.Errorf("无效的精确域名:%q", r.Pattern)
}
if net.ParseIP(h) != nil {
return fmt.Errorf("IP 地址请使用 ip 类型规则:%q", r.Pattern)
}
r.Pattern = h
case "suffix":
raw := strings.ToLower(strings.TrimSpace(r.Pattern))
raw = strings.TrimPrefix(raw, "*.")
raw = strings.TrimPrefix(raw, ".")
raw = strings.TrimSuffix(raw, ".")
if raw == "" || strings.ContainsAny(raw, " /\\*?@") {
return fmt.Errorf("无效的域名后缀/泛域名:%q", r.Pattern)
}
r.Pattern = "*." + raw
case "ip":
ip := net.ParseIP(strings.Trim(r.Pattern, "[]"))
if ip == nil {
return fmt.Errorf("无效的 IP 地址:%q", r.Pattern)
}
r.Pattern = normalizeIP(ip).String()
case "cidr":
_, ipnet, err := net.ParseCIDR(r.Pattern)
if err != nil {
return fmt.Errorf("无效的 CIDR 网段:%q", r.Pattern)
}
r.Pattern = ipnet.String()
default:
return fmt.Errorf("不支持的规则类型 %q(支持 domain / suffix / ip / cidr)", r.Kind)
}
return nil
}
func normalizeDomainPattern(raw string) string {
s := strings.ToLower(strings.TrimSpace(raw))
if strings.Contains(s, "://") {
if u, err := url.Parse(s); err == nil && u.Hostname() != "" {
s = strings.ToLower(u.Hostname())
}
}
if h, _, err := net.SplitHostPort(s); err == nil {
s = h
}
s = strings.Trim(s, "[]")
s = strings.TrimSuffix(s, ".")
return s
}
func newEgressBlacklist(rules []EgressBlacklistRule) *egressBlacklist {
b := &egressBlacklist{}
for _, r := range rules {
if !r.Enabled {
continue
}
cp := r
if err := NormalizeEgressRule(&cp); err != nil {
continue
}
cr := compiledRule{rule: cp}
if cp.Port > 0 {
cr.port = strconv.Itoa(cp.Port)
}
switch cp.Kind {
case "domain":
cr.domain = cp.Pattern
b.domainRules = append(b.domainRules, cr)
case "suffix":
cr.domain = strings.TrimPrefix(cp.Pattern, "*.")
b.suffixRules = append(b.suffixRules, cr)
case "ip":
cr.ip = normalizeIP(net.ParseIP(cp.Pattern))
if cr.ip != nil {
b.ipRules = append(b.ipRules, cr)
}
case "cidr":
if _, ipnet, err := net.ParseCIDR(cp.Pattern); err == nil {
cr.cidr = ipnet
b.cidrRules = append(b.cidrRules, cr)
}
}
}
if len(b.domainRules) == 0 && len(b.suffixRules) == 0 && len(b.ipRules) == 0 && len(b.cidrRules) == 0 {
return nil
}
return b
}
func (b *egressBlacklist) Check(rawHost, scheme string) *blockMatch {
if b == nil {
return nil
}
host, port := splitHostAndPort(rawHost)
host = strings.ToLower(strings.TrimSpace(host))
host = strings.TrimPrefix(host, "[")
host = strings.TrimSuffix(host, "]")
host = strings.TrimSuffix(host, ".")
if host == "" {
return nil
}
if port == "" {
switch strings.ToLower(scheme) {
case "https":
port = "443"
case "http":
port = "80"
}
}
// 1. Exact domain rules
for _, cr := range b.domainRules {
if cr.port != "" && cr.port != port {
continue
}
if host == cr.domain {
return ruleMatch(cr.rule, fmt.Sprintf("domain %q matches egress blacklist %q", host, cr.rule.Pattern))
}
}
// 2. Suffix / wildcard domain rules
for _, cr := range b.suffixRules {
if cr.port != "" && cr.port != port {
continue
}
if host == cr.domain || strings.HasSuffix(host, "."+cr.domain) {
return ruleMatch(cr.rule, fmt.Sprintf("domain %q matches egress blacklist %q", host, cr.rule.Pattern))
}
}
// 3. Literal IP rules & CIDR rules
if len(b.ipRules) == 0 && len(b.cidrRules) == 0 {
return nil
}
if ip := net.ParseIP(host); ip != nil {
return b.checkIP(ip, port, "")
}
// 4. DNS-resolved IPs (prevents domain -> blacklisted IP bypass / rebinding)
ips, err := net.LookupIP(host)
if err != nil {
return nil
}
for _, ip := range ips {
if m := b.checkIP(ip, port, host); m != nil {
return m
}
}
return nil
}
func (b *egressBlacklist) checkIP(ip net.IP, port, resolvedFrom string) *blockMatch {
ip = normalizeIP(ip)
if ip == nil {
return nil
}
suffix := ""
if resolvedFrom != "" {
suffix = fmt.Sprintf(" (resolved from %s)", resolvedFrom)
}
for _, cr := range b.ipRules {
if cr.port != "" && cr.port != port {
continue
}
if cr.ip.Equal(ip) {
return ruleMatch(cr.rule, fmt.Sprintf("IP %s%s matches egress blacklist %s", ip.String(), suffix, cr.rule.Pattern))
}
}
for _, cr := range b.cidrRules {
if cr.port != "" && cr.port != port {
continue
}
if cr.cidr.Contains(ip) {
return ruleMatch(cr.rule, fmt.Sprintf("IP %s%s matches egress blacklist %s", ip.String(), suffix, cr.rule.Pattern))
}
}
return nil
}
func ruleMatch(r EgressBlacklistRule, reason string) *blockMatch {
src := r.Source
if src == "" {
src = "custom"
}
return &blockMatch{
Reason: reason,
RuleKind: r.Kind,
RuleID: r.ID,
Pattern: r.Pattern,
Source: src,
}
}
const maxBlockEvents = 200
type blockEventLog struct {
mu sync.Mutex
events []EgressBlockEvent
}
func (l *blockEventLog) Record(ev EgressBlockEvent) {
if l == nil {
return
}
if ev.At.IsZero() {
ev.At = time.Now().UTC()
}
l.mu.Lock()
defer l.mu.Unlock()
// Deduplicate back-to-back identical events triggered at both CONNECT and
// Requestheaders within a short window so one blocked request logs once.
if n := len(l.events); n > 0 {
last := l.events[n-1]
if last.Host == ev.Host && last.Port == ev.Port && last.SrcIP == ev.SrcIP &&
last.Reason == ev.Reason && ev.At.Sub(last.At) < 150*time.Millisecond {
return
}
}
l.events = append(l.events, ev)
if len(l.events) > maxBlockEvents {
l.events = append([]EgressBlockEvent(nil), l.events[len(l.events)-maxBlockEvents:]...)
}
}
func (l *blockEventLog) List(limit int) []EgressBlockEvent {
if l == nil {
return []EgressBlockEvent{}
}
l.mu.Lock()
defer l.mu.Unlock()
n := len(l.events)
if n == 0 {
return []EgressBlockEvent{}
}
if limit <= 0 || limit > n {
limit = n
}
out := make([]EgressBlockEvent, 0, limit)
for i := n - 1; i >= n-limit; i-- {
out = append(out, l.events[i])
}
return out
}
func (l *blockEventLog) Clear() {
if l == nil {
return
}
l.mu.Lock()
l.events = nil
l.mu.Unlock()
}
// SetEgressBlacklist hot-reloads the network-layer outbound blacklist on the
// recording proxy. Passing an empty slice clears all custom/synced rules.
func (t *Traffic) SetEgressBlacklist(rules []EgressBlacklistRule) {
if t == nil {
return
}
t.blacklist.Store(newEgressBlacklist(rules))
}
// BlockEvents returns recent outbound block events (newest first).
func (t *Traffic) BlockEvents(limit int) []EgressBlockEvent {
if t == nil || t.blockLog == nil {
return []EgressBlockEvent{}
}
return t.blockLog.List(limit)
}
// ClearBlockEvents clears the in-memory recent block event ring buffer.
func (t *Traffic) ClearBlockEvents() {
if t == nil || t.blockLog == nil {
return
}
t.blockLog.Clear()
}
// checkOutboundDestination evaluates both the built-in SSRF guard and the
// dynamic egress blacklist.
func (t *Traffic) checkOutboundDestination(rawHost, scheme string) *blockMatch {
if t == nil || strings.TrimSpace(rawHost) == "" {
return nil
}
if g := t.ssrf.Load(); g != nil {
if reason := g.Check(rawHost); reason != "" {
return &blockMatch{
Reason: reason,
RuleKind: "ssrf",
Source: "ssrf_guard",
}
}
}
if bl := t.blacklist.Load(); bl != nil {
if m := bl.Check(rawHost, scheme); m != nil {
return m
}
}
return nil
}
// MatchEgressRules compiles a slice of EgressBlacklistRule and checks a single
// outbound destination against it. Used for on-demand task-level intercept checks.
func MatchEgressRules(rules []EgressBlacklistRule, rawHost, scheme string) (reason, pattern string) {
if len(rules) == 0 || strings.TrimSpace(rawHost) == "" {
return "", ""
}
bl := newEgressBlacklist(rules)
if bl == nil {
return "", ""
}
if m := bl.Check(rawHost, scheme); m != nil {
return m.Reason, m.Pattern
}
return "", ""
}
+122
View File
@@ -0,0 +1,122 @@
package traffic
import (
"io"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
)
func TestEgressBlacklistRuleMatching(t *testing.T) {
bl := newEgressBlacklist([]EgressBlacklistRule{
{ID: "r1", Enabled: true, Kind: "domain", Pattern: "Exact.Example.COM"},
{ID: "r2", Enabled: true, Kind: "suffix", Pattern: "*.gov.cn"},
{ID: "r3", Enabled: true, Kind: "ip", Pattern: "203.0.113.5"},
{ID: "r4", Enabled: true, Kind: "cidr", Pattern: "198.51.100.0/24"},
{ID: "r5", Enabled: true, Kind: "domain", Pattern: "port-only.example", Port: 8443},
{ID: "r6", Enabled: false, Kind: "domain", Pattern: "disabled.example"},
})
if bl == nil {
t.Fatal("expected compiled blacklist")
}
blocked := []struct {
host string
scheme string
wantID string
}{
{"exact.example.com:443", "https", "r1"},
{"gov.cn", "https", "r2"},
{"sub.dept.gov.cn:80", "http", "r2"},
{"203.0.113.5:8080", "http", "r3"},
{"198.51.100.42:443", "https", "r4"},
{"port-only.example:8443", "https", "r5"},
}
for _, tc := range blocked {
m := bl.Check(tc.host, tc.scheme)
if m == nil || m.RuleID != tc.wantID {
t.Fatalf("Check(%q, %q) = %+v, want rule %s", tc.host, tc.scheme, m, tc.wantID)
}
}
allowed := []struct {
host string
scheme string
}{
{"other.exact.example.com:443", "https"},
{"notgov.cn:443", "https"},
{"203.0.113.6:80", "http"},
{"198.51.101.1:80", "http"},
{"port-only.example:443", "https"},
{"disabled.example:443", "https"},
}
for _, tc := range allowed {
if m := bl.Check(tc.host, tc.scheme); m != nil {
t.Fatalf("Check(%q, %q) unexpectedly blocked: %+v", tc.host, tc.scheme, m)
}
}
}
func TestProxyEnforcesEgressBlacklistInLocalModeAndLogsEvents(t *testing.T) {
// Target HTTP server on loopback (SSRF guard intentionally OFF to verify
// egress blacklist works independently in local mode).
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte("REACHED"))
}))
defer target.Close()
tr, addr := startProxy(t, false)
proxyURL, err := url.Parse("http://" + addr)
if err != nil {
t.Fatal(err)
}
client := &http.Client{
Transport: &http.Transport{Proxy: http.ProxyURL(proxyURL)},
Timeout: 5 * time.Second,
}
// 1. Allowed before adding rule
resp, err := client.Get(target.URL)
if err != nil {
t.Fatalf("initial GET: %v", err)
}
body, _ := io.ReadAll(resp.Body)
resp.Body.Close()
if resp.StatusCode != 200 || string(body) != "REACHED" {
t.Fatalf("initial GET = %d %q", resp.StatusCode, string(body))
}
// 2. Hot-reload blacklist blocking 127.0.0.1 -> must return 403 + log block event
tr.SetEgressBlacklist([]EgressBlacklistRule{
{ID: "blk-1", Enabled: true, Kind: "ip", Pattern: "127.0.0.1", Source: "custom"},
})
resp2, err := client.Get(target.URL)
if err != nil {
t.Fatalf("blocked GET error: %v", err)
}
body2, _ := io.ReadAll(resp2.Body)
resp2.Body.Close()
if resp2.StatusCode != http.StatusForbidden || !strings.Contains(string(body2), "blocked by ARTEX egress blacklist") {
t.Fatalf("blocked GET = %d %q", resp2.StatusCode, string(body2))
}
events := tr.BlockEvents(10)
if len(events) == 0 || events[0].RuleID != "blk-1" || events[0].Source != "custom" {
t.Fatalf("expected recorded block event, got %+v", events)
}
// 3. Clearing blacklist immediately restores connectivity
tr.SetEgressBlacklist(nil)
resp3, err := client.Get(target.URL)
if err != nil {
t.Fatalf("post-clear GET: %v", err)
}
resp3.Body.Close()
if resp3.StatusCode != 200 {
t.Fatalf("post-clear GET = %d, want 200", resp3.StatusCode)
}
}
+287
View File
@@ -0,0 +1,287 @@
package traffic
import (
"net"
"net/url"
"strings"
"sync"
)
// GatewaySSRFPolicy is the JSON-serializable form of SSRFGuardConfig synced to artex-gateway.
type GatewaySSRFPolicy struct {
Enabled bool `json:"enabled"`
BlockPrivate bool `json:"block_private"`
BlockedHosts []string `json:"blocked_hosts,omitempty"`
BlockedCIDRs []string `json:"blocked_cidrs,omitempty"`
InfraIPs []string `json:"infra_ips,omitempty"`
}
// GatewayContainerRoute describes one per-owner upstream proxy override.
type GatewayContainerRoute struct {
Scope string `json:"scope"`
OwnerID string `json:"owner_id"`
Mode string `json:"mode"` // inherit, direct, proxy
ProxyPoolID string `json:"proxy_pool_id,omitempty"`
ProxyURL string `json:"proxy_url,omitempty"`
EffectiveURL string `json:"effective_url,omitempty"` // resolved raw URL (only in internal gateway sync)
Note string `json:"note,omitempty"`
UpdatedAt string `json:"updated_at,omitempty"`
}
// GatewayPolicySnapshot is returned by GET /api/internal/gateway/policy so the
// standalone artex-gateway enforces the exact same real-time SSRF guard, egress
// blacklist, task rules, container IP attribution, and per-container proxy routing
// as the main ARTEX control plane.
type GatewayPolicySnapshot struct {
SSRF *GatewaySSRFPolicy `json:"ssrf,omitempty"`
BlacklistRules []EgressBlacklistRule `json:"blacklist_rules,omitempty"`
TaskRules map[string][]EgressBlacklistRule `json:"task_rules,omitempty"`
ContainerIPs map[string]SourceIdentity `json:"container_ips,omitempty"`
GlobalUpstreamURL string `json:"global_upstream_url,omitempty"`
ContainerRoutes map[string]GatewayContainerRoute `json:"container_routes,omitempty"` // key: "scope:owner_id"
PassthroughHosts []string `json:"passthrough_hosts,omitempty"`
UDPPolicy string `json:"udp_policy"`
DNSUpstream string `json:"dns_upstream,omitempty"`
}
// GatewayEventBatch is posted by artex-gateway to POST /api/internal/gateway/events.
type GatewayEventBatch struct {
GatewayID string `json:"gateway_id,omitempty"`
NetFlows []NetFlowRecord `json:"net_flows,omitempty"`
DNSQueries []DNSQueryRecord `json:"dns_queries,omitempty"`
BlockEvents []EgressBlockEvent `json:"block_events,omitempty"`
}
// RemotePolicyState holds an in-memory compiled snapshot of GatewayPolicySnapshot
// and implements the read side of TransparentBackend for cmd/artex-gateway.
type RemotePolicyState struct {
mu sync.RWMutex
ssrf *ssrfGuard
blacklist *egressBlacklist
taskRules map[string]*egressBlacklist
containerIPs map[string]SourceIdentity
globalUpstream *url.URL
containerRoutes map[string]*url.URL // key -> nil (direct) or *url.URL (proxy)
passthroughHosts map[string]struct{}
udpPolicy string
dnsUpstream string
dnsCache *dnsReverseCache
gatewayToken string
onNetFlow func(NetFlowRecord)
onDNSQuery func(DNSQueryRecord)
onBlockEvent func(EgressBlockEvent)
}
// NewRemotePolicyState creates a RemotePolicyState wired to event callbacks.
func NewRemotePolicyState(token string, onFlow func(NetFlowRecord), onDNS func(DNSQueryRecord), onBlock func(EgressBlockEvent)) *RemotePolicyState {
return &RemotePolicyState{
taskRules: map[string]*egressBlacklist{},
containerIPs: map[string]SourceIdentity{},
containerRoutes: map[string]*url.URL{},
passthroughHosts: map[string]struct{}{},
udpPolicy: UDPPolicyBlockOnProxy,
dnsCache: newDNSReverseCache(),
gatewayToken: strings.TrimSpace(token),
onNetFlow: onFlow,
onDNSQuery: onDNS,
onBlockEvent: onBlock,
}
}
// Apply atomically replaces the compiled policy from snap.
func (s *RemotePolicyState) Apply(snap GatewayPolicySnapshot) {
var ssrf *ssrfGuard
if snap.SSRF != nil && snap.SSRF.Enabled {
var cidrs []*net.IPNet
for _, c := range snap.SSRF.BlockedCIDRs {
if _, n, err := net.ParseCIDR(strings.TrimSpace(c)); err == nil {
cidrs = append(cidrs, n)
}
}
var infraIPs []net.IP
for _, raw := range snap.SSRF.InfraIPs {
if ip := net.ParseIP(strings.TrimSpace(raw)); ip != nil {
infraIPs = append(infraIPs, ip)
}
}
ssrf = newSSRFGuard(SSRFGuardConfig{
Enabled: true,
BlockPrivate: snap.SSRF.BlockPrivate,
BlockedHosts: snap.SSRF.BlockedHosts,
BlockedCIDRs: cidrs,
InfraIPs: infraIPs,
HostNetworkMode: true,
})
}
bl := newEgressBlacklist(snap.BlacklistRules)
taskBL := make(map[string]*egressBlacklist, len(snap.TaskRules))
for tid, rules := range snap.TaskRules {
if len(rules) > 0 {
taskBL[tid] = newEgressBlacklist(rules)
}
}
ipMap := make(map[string]SourceIdentity, len(snap.ContainerIPs))
for ip, id := range snap.ContainerIPs {
norm := normalizeIPString(ip)
if norm != "" {
id.SrcIP = norm
ipMap[norm] = id
}
}
var globalUp *url.URL
if strings.TrimSpace(snap.GlobalUpstreamURL) != "" {
if u, err := ValidateProxyURL(snap.GlobalUpstreamURL); err == nil {
globalUp = u
}
}
routes := make(map[string]*url.URL, len(snap.ContainerRoutes))
for key, r := range snap.ContainerRoutes {
switch strings.ToLower(strings.TrimSpace(r.Mode)) {
case "direct":
routes[key] = nil
case "proxy":
raw := strings.TrimSpace(r.EffectiveURL)
if raw == "" {
raw = strings.TrimSpace(r.ProxyURL)
}
if u, err := ValidateProxyURL(raw); err == nil {
routes[key] = u
}
}
}
pass := make(map[string]struct{}, len(snap.PassthroughHosts))
for _, h := range snap.PassthroughHosts {
if h = hostOnly(h); h != "" {
pass[h] = struct{}{}
}
}
s.mu.Lock()
s.ssrf = ssrf
s.blacklist = bl
s.taskRules = taskBL
s.containerIPs = ipMap
s.globalUpstream = globalUp
s.containerRoutes = routes
s.passthroughHosts = pass
s.udpPolicy = NormalizeUDPPolicy(snap.UDPPolicy)
s.dnsUpstream = strings.TrimSpace(snap.DNSUpstream)
s.mu.Unlock()
}
func (s *RemotePolicyState) ResolveSource(srcIP string) SourceIdentity {
norm := normalizeIPString(srcIP)
s.mu.RLock()
id, ok := s.containerIPs[norm]
s.mu.RUnlock()
if ok {
id.SrcIP = norm
return id
}
return SourceIdentity{SrcIP: norm}
}
func (s *RemotePolicyState) CheckOutbound(rawHost, scheme string, src SourceIdentity) *BlockDecision {
s.mu.RLock()
ssrf := s.ssrf
bl := s.blacklist
var taskBL *egressBlacklist
if src.Scope == "task" && src.OwnerID != "" {
taskBL = s.taskRules[src.OwnerID]
}
s.mu.RUnlock()
if ssrf != nil {
if reason := ssrf.Check(rawHost); reason != "" {
return &BlockDecision{Reason: reason, RuleKind: "ssrf_guard", Source: "ssrf_guard"}
}
}
if bl != nil {
if m := bl.Check(rawHost, scheme); m != nil {
return &BlockDecision{
Reason: m.Reason,
RuleKind: m.RuleKind,
RuleID: m.RuleID,
Pattern: m.Pattern,
Source: m.Source,
}
}
}
if taskBL != nil {
if m := taskBL.Check(rawHost, scheme); m != nil {
return &BlockDecision{
Reason: m.Reason,
RuleKind: "task_intercept",
RuleID: m.RuleID,
Pattern: m.Pattern,
Source: "asset_intercept",
}
}
}
return nil
}
func (s *RemotePolicyState) ResolveUpstream(src SourceIdentity) *url.URL {
s.mu.RLock()
defer s.mu.RUnlock()
if src.Scope != "" && src.OwnerID != "" {
if u, ok := s.containerRoutes[src.Scope+":"+src.OwnerID]; ok {
return u // nil means explicit direct
}
}
return s.globalUpstream
}
func (s *RemotePolicyState) IsPassthrough(host string) bool {
s.mu.RLock()
_, ok := s.passthroughHosts[hostOnly(host)]
s.mu.RUnlock()
return ok
}
func (s *RemotePolicyState) LookupDNSReverse(ip string) string {
return s.dnsCache.Lookup(ip)
}
func (s *RemotePolicyState) RememberDNS(ip, domain string) {
s.dnsCache.Set(ip, domain)
}
func (s *RemotePolicyState) RecordNetFlow(rec NetFlowRecord) {
if s.onNetFlow != nil {
s.onNetFlow(rec)
}
}
func (s *RemotePolicyState) RecordDNSQuery(rec DNSQueryRecord) {
if s.onDNSQuery != nil {
s.onDNSQuery(rec)
}
}
func (s *RemotePolicyState) RecordBlockEvent(ev EgressBlockEvent) {
if s.onBlockEvent != nil {
s.onBlockEvent(ev)
}
}
func (s *RemotePolicyState) UDPPolicy() string {
s.mu.RLock()
defer s.mu.RUnlock()
return s.udpPolicy
}
func (s *RemotePolicyState) DNSUpstream() string {
s.mu.RLock()
defer s.mu.RUnlock()
return s.dnsUpstream
}
func (s *RemotePolicyState) GatewayToken() string {
return s.gatewayToken
}
+709
View File
@@ -0,0 +1,709 @@
package traffic
import (
"context"
"database/sql"
"encoding/hex"
"encoding/json"
"fmt"
"log"
"strings"
"sync"
"sync/atomic"
"time"
"unicode/utf8"
)
const netFlowSchema = `
CREATE TABLE IF NOT EXISTS net_flows (
id TEXT PRIMARY KEY,
ts INTEGER NOT NULL,
ended_at INTEGER NOT NULL DEFAULT 0,
duration_ms INTEGER NOT NULL DEFAULT 0,
protocol TEXT NOT NULL,
dst_ip TEXT NOT NULL DEFAULT '',
dst_port INTEGER NOT NULL DEFAULT 0,
dst_host TEXT NOT NULL DEFAULT '',
sni TEXT NOT NULL DEFAULT '',
action TEXT NOT NULL DEFAULT 'allow',
block_reason TEXT NOT NULL DEFAULT '',
upstream_proxy TEXT NOT NULL DEFAULT '',
bytes_tx INTEGER NOT NULL DEFAULT 0,
bytes_rx INTEGER NOT NULL DEFAULT 0,
tx_preview BLOB,
rx_preview BLOB,
sandbox_scope TEXT NOT NULL DEFAULT '',
sandbox_owner_id TEXT NOT NULL DEFAULT '',
container_id TEXT NOT NULL DEFAULT '',
session_id TEXT NOT NULL DEFAULT '',
intent_id INTEGER NOT NULL DEFAULT 0,
src_ip TEXT NOT NULL DEFAULT '',
src_port INTEGER NOT NULL DEFAULT 0,
error TEXT NOT NULL DEFAULT ''
);
CREATE INDEX IF NOT EXISTS idx_nf_ts ON net_flows(ts);
CREATE INDEX IF NOT EXISTS idx_nf_proto ON net_flows(protocol, ts);
CREATE INDEX IF NOT EXISTS idx_nf_owner ON net_flows(sandbox_scope, sandbox_owner_id, ts);
CREATE INDEX IF NOT EXISTS idx_nf_dst ON net_flows(dst_host, dst_ip, dst_port);
CREATE INDEX IF NOT EXISTS idx_nf_action ON net_flows(action, ts);
CREATE TABLE IF NOT EXISTS dns_queries (
id TEXT PRIMARY KEY,
ts INTEGER NOT NULL,
duration_ms INTEGER NOT NULL DEFAULT 0,
qname TEXT NOT NULL,
qtype TEXT NOT NULL DEFAULT 'A',
rcode TEXT NOT NULL DEFAULT 'NOERROR',
answers_json TEXT NOT NULL DEFAULT '[]',
action TEXT NOT NULL DEFAULT 'allow',
block_reason TEXT NOT NULL DEFAULT '',
upstream TEXT NOT NULL DEFAULT '',
sandbox_scope TEXT NOT NULL DEFAULT '',
sandbox_owner_id TEXT NOT NULL DEFAULT '',
container_id TEXT NOT NULL DEFAULT '',
session_id TEXT NOT NULL DEFAULT '',
intent_id INTEGER NOT NULL DEFAULT 0,
src_ip TEXT NOT NULL DEFAULT '',
error TEXT NOT NULL DEFAULT ''
);
CREATE INDEX IF NOT EXISTS idx_dns_ts ON dns_queries(ts);
CREATE INDEX IF NOT EXISTS idx_dns_qname ON dns_queries(qname, ts);
CREATE INDEX IF NOT EXISTS idx_dns_owner ON dns_queries(sandbox_scope, sandbox_owner_id, ts);
CREATE INDEX IF NOT EXISTS idx_dns_action ON dns_queries(action, ts);
`
const (
// maxFlowPreviewBytes caps per-direction payload previews persisted in SQLite
// so port scans and large binary transfers cannot bloat index.sqlite.
maxFlowPreviewBytes = 4096
// maxNetFlowRows / maxDNSQueryRows bound rolling retention for non-HTTP logs.
maxNetFlowRows = 50000
maxDNSQueryRows = 50000
trimCheckEvery = 500
dnsCacheMax = 4096
dnsCacheTTL = 10 * time.Minute
)
// NetFlowRecord captures one non-HTTP L4 flow (raw TCP, TLS passthrough, UDP)
// or blocked outbound connection observed by the transparent gateway (#218 Phase 3/4).
type NetFlowRecord struct {
ID string `json:"id"`
TS int64 `json:"ts"`
EndedAt int64 `json:"ended_at,omitempty"`
DurationMS int64 `json:"duration_ms"`
Protocol string `json:"protocol"` // tcp, tls, udp
DstIP string `json:"dst_ip"`
DstPort int `json:"dst_port"`
DstHost string `json:"dst_host,omitempty"`
SNI string `json:"sni,omitempty"`
Action string `json:"action"` // allow, block, error, passthrough
BlockReason string `json:"block_reason,omitempty"`
UpstreamProxy string `json:"upstream_proxy,omitempty"`
BytesTX int64 `json:"bytes_tx"`
BytesRX int64 `json:"bytes_rx"`
TXPreview []byte `json:"tx_preview,omitempty"`
RXPreview []byte `json:"rx_preview,omitempty"`
TXPreviewText string `json:"tx_preview_text,omitempty"`
TXPreviewHex string `json:"tx_preview_hex,omitempty"`
TXBinary bool `json:"tx_binary,omitempty"`
RXPreviewText string `json:"rx_preview_text,omitempty"`
RXPreviewHex string `json:"rx_preview_hex,omitempty"`
RXBinary bool `json:"rx_binary,omitempty"`
SandboxScope string `json:"sandbox_scope,omitempty"`
SandboxOwnerID 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"`
SrcPort int `json:"src_port,omitempty"`
Error string `json:"error,omitempty"`
}
// NetFlowQuery filters paged net_flows queries.
type NetFlowQuery struct {
Protocol string
Action string
SandboxScope string
SandboxOwnerID string
ContainerID string
OwnerTaskID string
Query string // matches dst_host, dst_ip, sni, src_ip, block_reason
}
// DNSQueryRecord captures one intercepted DNS query and its answer/block decision.
type DNSQueryRecord struct {
ID string `json:"id"`
TS int64 `json:"ts"`
DurationMS int64 `json:"duration_ms"`
QName string `json:"qname"`
QType string `json:"qtype"`
RCode string `json:"rcode"`
Answers []string `json:"answers"`
Action string `json:"action"` // allow, block, error
BlockReason string `json:"block_reason,omitempty"`
Upstream string `json:"upstream,omitempty"`
SandboxScope string `json:"sandbox_scope,omitempty"`
SandboxOwnerID 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"`
Error string `json:"error,omitempty"`
}
// DNSQueryFilter filters paged dns_queries queries.
type DNSQueryFilter struct {
QType string
RCode string
Action string
SandboxScope string
SandboxOwnerID string
ContainerID string
OwnerTaskID string
Query string // matches qname, answers_json, src_ip, block_reason
}
type dnsCacheEntry struct {
domain string
expiresAt time.Time
}
// dnsReverseCache maps recently resolved IPs back to their queried domain name
// so subsequent raw TCP/UDP connections to that IP carry dst_host attribution
// and domain-based egress blacklist enforcement.
type dnsReverseCache struct {
mu sync.RWMutex
entries map[string]dnsCacheEntry
}
func newDNSReverseCache() *dnsReverseCache {
return &dnsReverseCache{entries: make(map[string]dnsCacheEntry, 128)}
}
func (c *dnsReverseCache) Set(ip, domain string) {
if c == nil {
return
}
ip = normalizeIPString(ip)
domain = strings.TrimSuffix(strings.ToLower(strings.TrimSpace(domain)), ".")
if ip == "" || domain == "" {
return
}
now := time.Now()
c.mu.Lock()
if len(c.entries) >= dnsCacheMax {
for k, v := range c.entries {
if now.After(v.expiresAt) {
delete(c.entries, k)
}
}
if len(c.entries) >= dnsCacheMax {
// Evict a small slice so writes stay O(1) amortized.
dropped := 0
for k := range c.entries {
delete(c.entries, k)
dropped++
if dropped >= 256 {
break
}
}
}
}
c.entries[ip] = dnsCacheEntry{domain: domain, expiresAt: now.Add(dnsCacheTTL)}
c.mu.Unlock()
}
func (c *dnsReverseCache) Lookup(ip string) string {
if c == nil {
return ""
}
ip = normalizeIPString(ip)
if ip == "" {
return ""
}
c.mu.RLock()
e, ok := c.entries[ip]
c.mu.RUnlock()
if !ok || time.Now().After(e.expiresAt) {
return ""
}
return e.domain
}
// RememberDNS records an ip -> domain mapping in the reverse DNS cache.
func (t *Traffic) RememberDNS(ip, domain string) {
if t == nil || t.dnsCache == nil {
return
}
t.dnsCache.Set(ip, domain)
}
// LookupDNSReverse returns the most recently resolved domain for ip, if cached.
func (t *Traffic) LookupDNSReverse(ip string) string {
if t == nil || t.dnsCache == nil {
return ""
}
return t.dnsCache.Lookup(ip)
}
func ensureNetFlowSchema(ctx context.Context, conn *sql.Conn) error {
_, err := conn.ExecContext(ctx, netFlowSchema)
return err
}
// FormatPayloadPreview converts raw preview bytes into a display-safe UTF-8 text
// preview and hex dump when binary bytes are present.
func FormatPayloadPreview(b []byte) (text string, hexStr string, binary bool) {
if len(b) == 0 {
return "", "", false
}
if len(b) > maxFlowPreviewBytes {
b = b[:maxFlowPreviewBytes]
}
binary = isBinaryPayload(b)
if binary {
capHex := b
if len(capHex) > 1024 {
capHex = capHex[:1024]
}
return sanitizeASCIIPreview(b), hex.EncodeToString(capHex), true
}
return string(b), "", false
}
func isBinaryPayload(b []byte) bool {
if len(b) == 0 {
return false
}
if !utf8.Valid(b) {
return true
}
ctrl := 0
for _, c := range b {
if c == 0 {
return true
}
if c < 0x20 && c != '\n' && c != '\r' && c != '\t' {
ctrl++
}
}
return ctrl*10 > len(b)
}
func sanitizeASCIIPreview(b []byte) string {
var sb strings.Builder
sb.Grow(len(b))
for _, c := range b {
if (c >= 0x20 && c < 0x7f) || c == '\n' || c == '\r' || c == '\t' {
sb.WriteByte(c)
} else {
sb.WriteByte('.')
}
}
return sb.String()
}
// RecordNetFlow persists a non-HTTP flow record into SQLite with bounded
// payload previews and rolling row-count retention.
func (t *Traffic) RecordNetFlow(rec NetFlowRecord) error {
if t == nil || t.db == nil {
return nil
}
now := time.Now()
if rec.TS <= 0 {
rec.TS = now.Unix()
}
if rec.ID == "" {
n := t.seq.Add(1)
rec.ID = fmt.Sprintf("nf-%d-%04d", rec.TS, n%10000)
}
rec.Protocol = strings.ToLower(strings.TrimSpace(rec.Protocol))
if rec.Protocol == "" {
rec.Protocol = "tcp"
}
rec.Action = strings.ToLower(strings.TrimSpace(rec.Action))
if rec.Action == "" {
rec.Action = "allow"
}
if len(rec.TXPreview) > maxFlowPreviewBytes {
rec.TXPreview = rec.TXPreview[:maxFlowPreviewBytes]
}
if len(rec.RXPreview) > maxFlowPreviewBytes {
rec.RXPreview = rec.RXPreview[:maxFlowPreviewBytes]
}
t.wmu.Lock()
defer t.wmu.Unlock()
_, err := t.db.Exec(`INSERT OR REPLACE INTO net_flows(
id, ts, ended_at, duration_ms, protocol, dst_ip, dst_port, dst_host, sni,
action, block_reason, upstream_proxy, bytes_tx, bytes_rx, tx_preview, rx_preview,
sandbox_scope, sandbox_owner_id, container_id, session_id, intent_id, src_ip, src_port, error
) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
rec.ID, rec.TS, rec.EndedAt, rec.DurationMS, rec.Protocol, rec.DstIP, rec.DstPort, rec.DstHost, rec.SNI,
rec.Action, rec.BlockReason, rec.UpstreamProxy, rec.BytesTX, rec.BytesRX, rec.TXPreview, rec.RXPreview,
rec.SandboxScope, rec.SandboxOwnerID, rec.ContainerID, rec.SessionID, rec.IntentID, rec.SrcIP, rec.SrcPort, rec.Error,
)
if err != nil {
log.Printf("[traffic] 记录 net_flow %s 失败:%v", rec.ID, err)
return err
}
if t.nfWrites.Add(1)%trimCheckEvery == 0 {
t.trimTableLocked("net_flows", maxNetFlowRows)
}
return nil
}
// RecordDNSQuery persists an intercepted DNS query record into SQLite.
func (t *Traffic) RecordDNSQuery(rec DNSQueryRecord) error {
if t == nil || t.db == nil {
return nil
}
now := time.Now()
if rec.TS <= 0 {
rec.TS = now.Unix()
}
if rec.ID == "" {
n := t.seq.Add(1)
rec.ID = fmt.Sprintf("dns-%d-%04d", rec.TS, n%10000)
}
rec.QName = strings.TrimSuffix(strings.ToLower(strings.TrimSpace(rec.QName)), ".")
if rec.QType == "" {
rec.QType = "A"
}
if rec.Action == "" {
rec.Action = "allow"
}
answers := rec.Answers
if answers == nil {
answers = []string{}
}
answersJSON, _ := json.Marshal(answers)
t.wmu.Lock()
defer t.wmu.Unlock()
_, err := t.db.Exec(`INSERT OR REPLACE INTO dns_queries(
id, ts, duration_ms, qname, qtype, rcode, answers_json, action, block_reason, upstream,
sandbox_scope, sandbox_owner_id, container_id, session_id, intent_id, src_ip, error
) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
rec.ID, rec.TS, rec.DurationMS, rec.QName, rec.QType, rec.RCode, string(answersJSON), rec.Action, rec.BlockReason, rec.Upstream,
rec.SandboxScope, rec.SandboxOwnerID, rec.ContainerID, rec.SessionID, rec.IntentID, rec.SrcIP, rec.Error,
)
if err != nil {
log.Printf("[traffic] 记录 dns_query %s 失败:%v", rec.ID, err)
return err
}
if t.dnsWrites.Add(1)%trimCheckEvery == 0 {
t.trimTableLocked("dns_queries", maxDNSQueryRows)
}
return nil
}
func (t *Traffic) trimTableLocked(table string, maxRows int) {
var count int
if err := t.db.QueryRow(`SELECT count(*) FROM ` + table).Scan(&count); err != nil || count <= maxRows {
return
}
excess := count - maxRows
if _, err := t.db.Exec(
`DELETE FROM `+table+` WHERE id IN (SELECT id FROM `+table+` ORDER BY ts ASC, rowid ASC LIMIT ?)`,
excess,
); err != nil {
log.Printf("[traffic] 滚动清理 %s 失败:%v", table, err)
return
}
t.reclaim()
}
// PageNetFlows returns a filtered, newest-first page of non-HTTP flow records.
func (t *Traffic) PageNetFlows(q NetFlowQuery, page, size int) ([]NetFlowRecord, int, error) {
if t == nil || t.db == nil {
return []NetFlowRecord{}, 0, nil
}
if page < 0 {
page = 0
}
if size <= 0 || size > 500 {
size = 100
}
var conds []string
var args []any
if p := strings.ToLower(strings.TrimSpace(q.Protocol)); p != "" && p != "all" {
conds = append(conds, `protocol=?`)
args = append(args, p)
}
if a := strings.ToLower(strings.TrimSpace(q.Action)); a != "" && a != "all" {
conds = append(conds, `action=?`)
args = append(args, a)
}
if taskID := strings.TrimSpace(q.OwnerTaskID); taskID != "" {
conds = append(conds, `(sandbox_scope='task' AND sandbox_owner_id=?)`)
args = append(args, taskID)
}
if sc := strings.TrimSpace(q.SandboxScope); sc != "" {
conds = append(conds, `sandbox_scope=?`)
args = append(args, sc)
}
if ow := strings.TrimSpace(q.SandboxOwnerID); ow != "" {
conds = append(conds, `sandbox_owner_id=?`)
args = append(args, ow)
}
if cid := strings.TrimSpace(q.ContainerID); cid != "" {
conds = append(conds, `(container_id=? OR container_id LIKE ?)`)
args = append(args, cid, cid+"%")
}
if kw := strings.TrimSpace(q.Query); kw != "" {
like := "%" + kw + "%"
conds = append(conds, `(dst_host LIKE ? OR dst_ip LIKE ? OR sni LIKE ? OR src_ip LIKE ? OR block_reason LIKE ? OR CAST(dst_port AS TEXT)=?)`)
args = append(args, like, like, like, like, like, kw)
}
where := ""
if len(conds) > 0 {
where = " WHERE " + strings.Join(conds, " AND ")
}
var total int
if err := t.db.QueryRow(`SELECT count(*) FROM net_flows`+where, args...).Scan(&total); err != nil {
return nil, 0, err
}
if total == 0 {
return []NetFlowRecord{}, 0, nil
}
queryArgs := append(append([]any{}, args...), size, page*size)
rows, err := t.db.Query(`SELECT id, ts, ended_at, duration_ms, protocol, dst_ip, dst_port, dst_host, sni,
action, block_reason, upstream_proxy, bytes_tx, bytes_rx,
sandbox_scope, sandbox_owner_id, container_id, session_id, intent_id, src_ip, src_port, error
FROM net_flows`+where+` ORDER BY ts DESC, rowid DESC LIMIT ? OFFSET ?`, queryArgs...)
if err != nil {
return nil, 0, err
}
defer rows.Close()
out := make([]NetFlowRecord, 0, size)
for rows.Next() {
var r NetFlowRecord
if err := rows.Scan(
&r.ID, &r.TS, &r.EndedAt, &r.DurationMS, &r.Protocol, &r.DstIP, &r.DstPort, &r.DstHost, &r.SNI,
&r.Action, &r.BlockReason, &r.UpstreamProxy, &r.BytesTX, &r.BytesRX,
&r.SandboxScope, &r.SandboxOwnerID, &r.ContainerID, &r.SessionID, &r.IntentID, &r.SrcIP, &r.SrcPort, &r.Error,
); err != nil {
return nil, 0, err
}
out = append(out, r)
}
return out, total, rows.Err()
}
// GetNetFlow fetches one flow record including its TX/RX payload previews.
func (t *Traffic) GetNetFlow(id string) (*NetFlowRecord, error) {
if t == nil || t.db == nil {
return nil, sql.ErrNoRows
}
var r NetFlowRecord
err := t.db.QueryRow(`SELECT id, ts, ended_at, duration_ms, protocol, dst_ip, dst_port, dst_host, sni,
action, block_reason, upstream_proxy, bytes_tx, bytes_rx, tx_preview, rx_preview,
sandbox_scope, sandbox_owner_id, container_id, session_id, intent_id, src_ip, src_port, error
FROM net_flows WHERE id=?`, strings.TrimSpace(id)).Scan(
&r.ID, &r.TS, &r.EndedAt, &r.DurationMS, &r.Protocol, &r.DstIP, &r.DstPort, &r.DstHost, &r.SNI,
&r.Action, &r.BlockReason, &r.UpstreamProxy, &r.BytesTX, &r.BytesRX, &r.TXPreview, &r.RXPreview,
&r.SandboxScope, &r.SandboxOwnerID, &r.ContainerID, &r.SessionID, &r.IntentID, &r.SrcIP, &r.SrcPort, &r.Error,
)
if err != nil {
return nil, err
}
r.TXPreviewText, r.TXPreviewHex, r.TXBinary = FormatPayloadPreview(r.TXPreview)
r.RXPreviewText, r.RXPreviewHex, r.RXBinary = FormatPayloadPreview(r.RXPreview)
r.TXPreview = nil
r.RXPreview = nil
return &r, nil
}
// PageDNSQueries returns a filtered, newest-first page of DNS query records.
func (t *Traffic) PageDNSQueries(q DNSQueryFilter, page, size int) ([]DNSQueryRecord, int, error) {
if t == nil || t.db == nil {
return []DNSQueryRecord{}, 0, nil
}
if page < 0 {
page = 0
}
if size <= 0 || size > 500 {
size = 100
}
var conds []string
var args []any
if qt := strings.ToUpper(strings.TrimSpace(q.QType)); qt != "" && qt != "ALL" {
conds = append(conds, `qtype=?`)
args = append(args, qt)
}
if rc := strings.ToUpper(strings.TrimSpace(q.RCode)); rc != "" && rc != "ALL" {
conds = append(conds, `rcode=?`)
args = append(args, rc)
}
if a := strings.ToLower(strings.TrimSpace(q.Action)); a != "" && a != "all" {
conds = append(conds, `action=?`)
args = append(args, a)
}
if taskID := strings.TrimSpace(q.OwnerTaskID); taskID != "" {
conds = append(conds, `(sandbox_scope='task' AND sandbox_owner_id=?)`)
args = append(args, taskID)
}
if sc := strings.TrimSpace(q.SandboxScope); sc != "" {
conds = append(conds, `sandbox_scope=?`)
args = append(args, sc)
}
if ow := strings.TrimSpace(q.SandboxOwnerID); ow != "" {
conds = append(conds, `sandbox_owner_id=?`)
args = append(args, ow)
}
if cid := strings.TrimSpace(q.ContainerID); cid != "" {
conds = append(conds, `(container_id=? OR container_id LIKE ?)`)
args = append(args, cid, cid+"%")
}
if kw := strings.TrimSpace(q.Query); kw != "" {
like := "%" + kw + "%"
conds = append(conds, `(qname LIKE ? OR answers_json LIKE ? OR src_ip LIKE ? OR block_reason LIKE ?)`)
args = append(args, like, like, like, like)
}
where := ""
if len(conds) > 0 {
where = " WHERE " + strings.Join(conds, " AND ")
}
var total int
if err := t.db.QueryRow(`SELECT count(*) FROM dns_queries`+where, args...).Scan(&total); err != nil {
return nil, 0, err
}
if total == 0 {
return []DNSQueryRecord{}, 0, nil
}
queryArgs := append(append([]any{}, args...), size, page*size)
rows, err := t.db.Query(`SELECT id, ts, duration_ms, qname, qtype, rcode, answers_json, action, block_reason, upstream,
sandbox_scope, sandbox_owner_id, container_id, session_id, intent_id, src_ip, error
FROM dns_queries`+where+` ORDER BY ts DESC, rowid DESC LIMIT ? OFFSET ?`, queryArgs...)
if err != nil {
return nil, 0, err
}
defer rows.Close()
out := make([]DNSQueryRecord, 0, size)
for rows.Next() {
var r DNSQueryRecord
var answersRaw string
if err := rows.Scan(
&r.ID, &r.TS, &r.DurationMS, &r.QName, &r.QType, &r.RCode, &answersRaw, &r.Action, &r.BlockReason, &r.Upstream,
&r.SandboxScope, &r.SandboxOwnerID, &r.ContainerID, &r.SessionID, &r.IntentID, &r.SrcIP, &r.Error,
); err != nil {
return nil, 0, err
}
if answersRaw != "" {
_ = json.Unmarshal([]byte(answersRaw), &r.Answers)
}
if r.Answers == nil {
r.Answers = []string{}
}
out = append(out, r)
}
return out, total, rows.Err()
}
// CountNetFlows returns total stored rows in net_flows.
func (t *Traffic) CountNetFlows() (int, error) {
if t == nil || t.db == nil {
return 0, nil
}
var n int
err := t.db.QueryRow(`SELECT count(*) FROM net_flows`).Scan(&n)
return n, err
}
// CountDNSQueries returns total stored rows in dns_queries.
func (t *Traffic) CountDNSQueries() (int, error) {
if t == nil || t.db == nil {
return 0, nil
}
var n int
err := t.db.QueryRow(`SELECT count(*) FROM dns_queries`).Scan(&n)
return n, err
}
// DeleteNetFlows deletes net_flows rows, optionally restricted to one sandbox owner.
func (t *Traffic) DeleteNetFlows(scope, ownerID string) (int64, error) {
if t == nil || t.db == nil {
return 0, nil
}
t.wmu.Lock()
defer t.wmu.Unlock()
var (
res sql.Result
err error
)
if strings.TrimSpace(scope) != "" && strings.TrimSpace(ownerID) != "" {
res, err = t.db.Exec(`DELETE FROM net_flows WHERE sandbox_scope=? AND sandbox_owner_id=?`, strings.TrimSpace(scope), strings.TrimSpace(ownerID))
} else {
res, err = t.db.Exec(`DELETE FROM net_flows`)
}
if err != nil {
return 0, err
}
n, _ := res.RowsAffected()
if n > 0 {
t.reclaim()
}
return n, nil
}
// DeleteDNSQueries deletes dns_queries rows, optionally restricted to one sandbox owner.
func (t *Traffic) DeleteDNSQueries(scope, ownerID string) (int64, error) {
if t == nil || t.db == nil {
return 0, nil
}
t.wmu.Lock()
defer t.wmu.Unlock()
var (
res sql.Result
err error
)
if strings.TrimSpace(scope) != "" && strings.TrimSpace(ownerID) != "" {
res, err = t.db.Exec(`DELETE FROM dns_queries WHERE sandbox_scope=? AND sandbox_owner_id=?`, strings.TrimSpace(scope), strings.TrimSpace(ownerID))
} else {
res, err = t.db.Exec(`DELETE FROM dns_queries`)
}
if err != nil {
return 0, err
}
n, _ := res.RowsAffected()
if n > 0 {
t.reclaim()
}
return n, nil
}
// DeleteNonHTTPByOwner deletes both net_flows and dns_queries attributed to one
// sandbox owner (used when deleting a task with DeleteTraffic enabled).
func (t *Traffic) DeleteNonHTTPByOwner(scope, ownerID string) (int64, error) {
if t == nil || t.db == nil || strings.TrimSpace(scope) == "" || strings.TrimSpace(ownerID) == "" {
return 0, nil
}
t.wmu.Lock()
defer t.wmu.Unlock()
var total int64
if res, err := t.db.Exec(`DELETE FROM net_flows WHERE sandbox_scope=? AND sandbox_owner_id=?`, scope, ownerID); err == nil {
n, _ := res.RowsAffected()
total += n
} else {
return 0, err
}
if res, err := t.db.Exec(`DELETE FROM dns_queries WHERE sandbox_scope=? AND sandbox_owner_id=?`, scope, ownerID); err == nil {
n, _ := res.RowsAffected()
total += n
} else {
return total, err
}
if total > 0 {
t.reclaim()
}
return total, nil
}
var _ = atomic.Int64{}
+1087
View File
File diff suppressed because it is too large. Load diff
+394
View File
@@ -0,0 +1,394 @@
package traffic
import (
"context"
"encoding/binary"
"fmt"
"io"
"net"
"net/http"
"net/url"
"testing"
"time"
"gvisor.dev/gvisor/pkg/tcpip"
"gvisor.dev/gvisor/pkg/tcpip/checksum"
"gvisor.dev/gvisor/pkg/tcpip/header"
)
// memTunPipe simulates a Linux TUN L3 packet device in memory so NetstackGateway's
// deferred TCP handshake (SYN-ACK on open vs RST on closed/blocked) can be tested
// deterministically on any OS without CAP_NET_ADMIN.
type memTunPipe struct {
in chan []byte
out chan []byte
end chan struct{}
}
func newMemTunPipe() *memTunPipe {
return &memTunPipe{
in: make(chan []byte, 64),
out: make(chan []byte, 64),
end: make(chan struct{}),
}
}
func (p *memTunPipe) Read(b []byte) (int, error) {
select {
case pkt := <-p.in:
return copy(b, pkt), nil
case <-p.end:
return 0, io.EOF
}
}
func (p *memTunPipe) Write(b []byte) (int, error) {
cp := append([]byte(nil), b...)
select {
case p.out <- cp:
return len(b), nil
case <-p.end:
return 0, io.ErrClosedPipe
}
}
func (p *memTunPipe) Close() error {
select {
case <-p.end:
default:
close(p.end)
}
return nil
}
func buildIPv4TCPSYN(srcIP, dstIP net.IP, srcPort, dstPort uint16, seq uint32) []byte {
const ipLen = header.IPv4MinimumSize
const tcpLen = header.TCPMinimumSize
pkt := make([]byte, ipLen+tcpLen)
ip := header.IPv4(pkt[:ipLen])
ip.Encode(&header.IPv4Fields{
TotalLength: uint16(len(pkt)),
ID: 1,
TTL: 64,
Protocol: uint8(header.TCPProtocolNumber),
SrcAddr: header.IPv4(pkt).SourceAddress(), // overwritten below
})
copy(pkt[12:16], srcIP.To4())
copy(pkt[16:20], dstIP.To4())
ip.SetChecksum(0)
ip.SetChecksum(^ip.CalculateChecksum())
tcpHdr := header.TCP(pkt[ipLen:])
binary.BigEndian.PutUint16(tcpHdr[0:2], srcPort)
binary.BigEndian.PutUint16(tcpHdr[2:4], dstPort)
binary.BigEndian.PutUint32(tcpHdr[4:8], seq)
tcpHdr[12] = (tcpLen / 4) << 4
tcpHdr[13] = uint8(header.TCPFlagSyn)
binary.BigEndian.PutUint16(tcpHdr[14:16], 65535)
xsum := header.PseudoHeaderChecksum(header.TCPProtocolNumber, ip.SourceAddress(), ip.DestinationAddress(), uint16(tcpLen))
xsum = checksum.Checksum(tcpHdr, xsum)
tcpHdr.SetChecksum(^xsum)
return pkt
}
func parseTCPFlags(pkt []byte) (header.TCPFlags, bool) {
if len(pkt) < header.IPv4MinimumSize+header.TCPMinimumSize || header.IPVersion(pkt) != header.IPv4Version {
return 0, false
}
ip := header.IPv4(pkt)
if ip.TransportProtocol() != header.TCPProtocolNumber {
return 0, false
}
tcpHdr := header.TCP(pkt[ip.HeaderLength():])
return tcpHdr.Flags(), true
}
func TestNetstackDeferredTCPHandshakeOpenClosedBlocked(t *testing.T) {
tr, err := Open(t.TempDir(), "127.0.0.1:0")
if err != nil {
t.Fatalf("open traffic: %v", err)
}
defer tr.Close()
tr.SetSourceResolver(func(srcIP string) (SourceIdentity, bool) {
if srcIP == "172.30.0.3" {
return SourceIdentity{Scope: "task", OwnerID: "218", ContainerID: "sbx218", SrcIP: srcIP}, true
}
return SourceIdentity{}, false
})
tr.SetEgressBlacklist([]EgressBlacklistRule{
{ID: "blk-1", Enabled: true, Kind: "ip", Pattern: "198.51.100.99"},
})
// 1. Start a real open TCP listener on loopback.
openLn, err := net.Listen("tcp4", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen open: %v", err)
}
defer openLn.Close()
go func() {
for {
c, err := openLn.Accept()
if err != nil {
return
}
_ = c.Close()
}
}()
openPort := uint16(openLn.Addr().(*net.TCPAddr).Port)
// 2. Reserve and immediately close a port to guarantee ECONNREFUSED ("closed").
closedLn, err := net.Listen("tcp4", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen closed probe: %v", err)
}
closedPort := uint16(closedLn.Addr().(*net.TCPAddr).Port)
_ = closedLn.Close()
pipe := newMemTunPipe()
ns, err := NewNetstackGateway(pipe, NetstackConfig{
DialTimeout: 200 * time.Millisecond,
PeekTimeout: 50 * time.Millisecond,
DialFunc: func(ctx context.Context, upstream *url.URL, target string, timeout time.Duration) (net.Conn, error) {
switch target {
case fmt.Sprintf("203.0.113.10:%d", openPort):
return dialTCPThroughUpstream(ctx, upstream, fmt.Sprintf("127.0.0.1:%d", openPort), timeout)
case fmt.Sprintf("203.0.113.10:%d", closedPort):
return dialTCPThroughUpstream(ctx, upstream, fmt.Sprintf("127.0.0.1:%d", closedPort), timeout)
case "203.0.113.20:80":
return nil, context.DeadlineExceeded
default:
return dialTCPThroughUpstream(ctx, upstream, target, timeout)
}
},
}, LocalTransparentBackend{T: tr})
if err != nil {
t.Fatalf("NewNetstackGateway: %v", err)
}
ns.Start()
defer ns.Close()
readReplyFlags := func(t *testing.T, label string) header.TCPFlags {
t.Helper()
select {
case pkt := <-pipe.out:
flags, ok := parseTCPFlags(pkt)
if !ok {
t.Fatalf("%s: non-TCP reply packet (%d bytes)", label, len(pkt))
}
return flags
case <-time.After(3 * time.Second):
t.Fatalf("%s: timed out waiting for reply packet", label)
return 0
}
}
// Case A: OPEN port => MUST reply SYN+ACK.
pipe.in <- buildIPv4TCPSYN(net.ParseIP("172.30.0.3"), net.ParseIP("203.0.113.10"), 41001, openPort, 100)
flagsOpen := readReplyFlags(t, "open port")
if !flagsOpen.Contains(header.TCPFlagSyn | header.TCPFlagAck) {
t.Fatalf("open port: expected SYN+ACK, got flags=%v", flagsOpen)
}
// Case B: CLOSED port (ECONNREFUSED) => MUST reply RST (NEVER SYN+ACK -> zero nmap false positives!).
pipe.in <- buildIPv4TCPSYN(net.ParseIP("172.30.0.3"), net.ParseIP("203.0.113.10"), 41002, closedPort, 200)
flagsClosed := readReplyFlags(t, "closed port")
if !flagsClosed.Contains(header.TCPFlagRst) || flagsClosed.Contains(header.TCPFlagSyn) {
t.Fatalf("closed port: expected RST without SYN, got flags=%v", flagsClosed)
}
// Case C: FILTERED port (timeout) => MUST drop silently (neither SYN+ACK nor RST!).
pipe.in <- buildIPv4TCPSYN(net.ParseIP("172.30.0.3"), net.ParseIP("203.0.113.20"), 41004, 80, 250)
select {
case pkt := <-pipe.out:
flags, _ := parseTCPFlags(pkt)
t.Fatalf("filtered port: expected silent drop, got reply packet with flags=%v", flags)
case <-time.After(150 * time.Millisecond):
}
// Case D: BLACKLISTED IP => MUST reply immediate RST and record net_flows(action=block).
pipe.in <- buildIPv4TCPSYN(net.ParseIP("172.30.0.3"), net.ParseIP("198.51.100.99"), 41003, 80, 300)
flagsBlocked := readReplyFlags(t, "blacklisted IP")
if !flagsBlocked.Contains(header.TCPFlagRst) || flagsBlocked.Contains(header.TCPFlagSyn) {
t.Fatalf("blacklisted IP: expected RST without SYN, got flags=%v", flagsBlocked)
}
deadline := time.Now().Add(2 * time.Second)
var blocked []NetFlowRecord
for time.Now().Before(deadline) {
rows, _, _ := tr.PageNetFlows(NetFlowQuery{OwnerTaskID: "218", Action: "block"}, 0, 10)
if len(rows) > 0 {
blocked = rows
break
}
time.Sleep(20 * time.Millisecond)
}
if len(blocked) != 1 || blocked[0].DstIP != "198.51.100.99" {
t.Fatalf("expected 1 blocked net_flow for 198.51.100.99, got %+v", blocked)
}
}
func TestGatewayTokenAttributionAcrossDockerBridge(t *testing.T) {
tr, err := Open(t.TempDir(), "127.0.0.1:0")
if err != nil {
t.Fatalf("open traffic: %v", err)
}
defer tr.Close()
tr.SetGatewayToken("gw-secret-218")
tr.SetSourceResolver(func(srcIP string) (SourceIdentity, bool) {
if srcIP == "172.30.0.3" {
return SourceIdentity{Scope: "session", OwnerID: "conv-6", ContainerID: "abcdef123456", SrcIP: srcIP}, true
}
return SourceIdentity{}, false
})
// Simulated docker-proxy source IP (172.19.0.1) carrying valid gateway token must resolve to 172.30.0.3 / session:conv-6.
authVal := FormatProxyContextAuthValue(SourceIdentity{SrcIP: "172.30.0.3"}, "gw-secret-218")
h := http.Header{"Proxy-Authorization": []string{"Basic " + authVal}}
src := tr.resolveSourceForConn("172.19.0.1:51234", h)
if src.SrcIP != "172.30.0.3" || src.Scope != "session" || src.OwnerID != "conv-6" {
t.Fatalf("valid gateway token from docker-proxy should preserve attribution, got %+v", src)
}
// Wrong token from non-loopback must NOT trust forwarded SrcIP.
badVal := FormatProxyContextAuthValue(SourceIdentity{SrcIP: "172.30.0.3"}, "wrong-token")
hBad := http.Header{"Proxy-Authorization": []string{"Basic " + badVal}}
srcBad := tr.resolveSourceForConn("172.19.0.1:51235", hBad)
if srcBad.SrcIP != "172.19.0.1" || srcBad.Scope != "" {
t.Fatalf("invalid gateway token must not spoof attribution, got %+v", srcBad)
}
}
func TestSSRFGuardHostNetworkModeInfraPorts(t *testing.T) {
g := newSSRFGuard(SSRFGuardConfig{
Enabled: true,
InfraIPs: []net.IP{net.ParseIP("192.168.110.238")},
HostNetworkMode: true,
})
if r := g.Check("192.168.110.238:8787"); r == "" {
t.Fatalf("expected :8787 on host LAN IP to be blocked")
}
if r := g.Check("192.168.110.238:8788"); r == "" {
t.Fatalf("expected :8788 on host LAN IP to be blocked")
}
if r := g.Check("192.168.110.238:22"); r != "" {
t.Fatalf("expected :22 on host LAN IP to remain reachable, got %q", r)
}
if r := g.Check("127.0.0.1:80"); r == "" {
t.Fatalf("expected loopback 127.0.0.1:80 to remain blocked")
}
}
func buildIPv4ICMPEcho(srcIP, dstIP net.IP, id, seq uint16, payload []byte) []byte {
totalLen := header.IPv4MinimumSize + header.ICMPv4MinimumSize + len(payload)
pkt := make([]byte, totalLen)
ip := header.IPv4(pkt[:header.IPv4MinimumSize])
ip.Encode(&header.IPv4Fields{
TotalLength: uint16(totalLen),
TTL: 64,
Protocol: uint8(header.ICMPv4ProtocolNumber),
SrcAddr: tcpip.AddrFrom4Slice(srcIP.To4()),
DstAddr: tcpip.AddrFrom4Slice(dstIP.To4()),
})
ip.SetChecksum(^ip.CalculateChecksum())
icmp := header.ICMPv4(pkt[header.IPv4MinimumSize:])
icmp.SetType(header.ICMPv4Echo)
icmp.SetCode(0)
icmp.SetIdent(id)
icmp.SetSequence(seq)
copy(pkt[header.IPv4MinimumSize+header.ICMPv4MinimumSize:], payload)
icmp.SetChecksum(0)
icmp.SetChecksum(header.ICMPv4Checksum(icmp, 0))
return pkt
}
func TestNetstackAntiSpoofingAndICMPProxy(t *testing.T) {
tr, err := Open(t.TempDir(), "127.0.0.1:0")
if err != nil {
t.Fatalf("open traffic: %v", err)
}
defer tr.Close()
tr.SetEgressBlacklist([]EgressBlacklistRule{{
ID: "blk-icmp",
Kind: "ip",
Pattern: "203.0.113.99",
Enabled: true,
}})
pipe := newMemTunPipe()
ng, err := NewNetstackGateway(pipe, NetstackConfig{
DialTimeout: 300 * time.Millisecond,
AllowedSrcCIDR: "172.30.0.0/16",
DeniedSrcIPs: []string{"172.30.0.1"},
ICMPPingFunc: func(_ context.Context, dstIP net.IP, _ uint16, payload []byte) ([]byte, error) {
if dstIP.String() == "203.0.113.10" {
return payload, nil
}
return nil, context.DeadlineExceeded
},
}, LocalTransparentBackend{T: tr})
if err != nil {
t.Fatalf("NewNetstackGateway: %v", err)
}
ng.Start()
defer ng.Close()
// 1. Live host ICMP Echo -> genuine Echo Reply with matching ID/Seq/Payload.
pipe.in <- buildIPv4ICMPEcho(net.ParseIP("172.30.0.3"), net.ParseIP("203.0.113.10"), 0x1234, 7, []byte("ping-ok"))
select {
case resp := <-pipe.out:
ip4 := header.IPv4(resp)
if ip4.Protocol() != uint8(header.ICMPv4ProtocolNumber) {
t.Fatalf("expected ICMPv4 reply, got proto=%d", ip4.Protocol())
}
icmp := header.ICMPv4(resp[ip4.HeaderLength():])
if icmp.Type() != header.ICMPv4EchoReply || icmp.Ident() != 0x1234 || icmp.Sequence() != 7 || string(icmp.Payload()) != "ping-ok" {
t.Fatalf("unexpected ICMP echo reply: type=%d id=%#x seq=%d payload=%q", icmp.Type(), icmp.Ident(), icmp.Sequence(), string(icmp.Payload()))
}
case <-time.After(2 * time.Second):
t.Fatal("timed out waiting for ICMP echo reply from live target")
}
// 2. Dead host ICMP Echo -> MUST NOT receive a fake local Echo Reply from gVisor.
pipe.in <- buildIPv4ICMPEcho(net.ParseIP("172.30.0.3"), net.ParseIP("203.0.113.55"), 0x1234, 8, []byte("ping-dead"))
select {
case resp := <-pipe.out:
t.Fatalf("dead host must not receive synthetic reply, got %d bytes", len(resp))
case <-time.After(250 * time.Millisecond):
}
// 3. Blacklisted host ICMP Echo -> no reply + recorded as blocked flow.
pipe.in <- buildIPv4ICMPEcho(net.ParseIP("172.30.0.3"), net.ParseIP("203.0.113.99"), 0x1234, 9, []byte("ping-blk"))
select {
case resp := <-pipe.out:
t.Fatalf("blacklisted host must not receive reply, got %d bytes", len(resp))
case <-time.After(200 * time.Millisecond):
}
// 4. Spoofed source IP outside AllowedSrcCIDR or equal to gateway IP -> silently dropped.
pipe.in <- buildIPv4ICMPEcho(net.ParseIP("10.99.0.5"), net.ParseIP("203.0.113.10"), 0x5678, 1, []byte("spoof-ext"))
pipe.in <- buildIPv4ICMPEcho(net.ParseIP("172.30.0.1"), net.ParseIP("203.0.113.10"), 0x5678, 2, []byte("spoof-gw"))
select {
case resp := <-pipe.out:
t.Fatalf("spoofed source packet must be dropped, got %d bytes", len(resp))
case <-time.After(200 * time.Millisecond):
}
deadline := time.Now().Add(2 * time.Second)
var flows []NetFlowRecord
var total int
for time.Now().Before(deadline) {
flows, total, err = tr.PageNetFlows(NetFlowQuery{Protocol: "icmp"}, 0, 20)
if err == nil && total >= 3 {
break
}
time.Sleep(20 * time.Millisecond)
}
if err != nil || total < 3 {
t.Fatalf("expected >=3 recorded icmp flows (allow/error/block), got total=%d err=%v flows=%+v", total, err, flows)
}
}
+170
View File
@@ -0,0 +1,170 @@
//go:build linux
package traffic
import (
"context"
"encoding/binary"
"errors"
"fmt"
"net"
"syscall"
"unsafe"
"golang.org/x/sys/unix"
)
const (
soOriginalDst = 80 // linux/netfilter_ipv4.h SO_ORIGINAL_DST
ip6tOriginalDst = 80 // linux/netfilter_ipv6/ip6_tables.h IP6T_SO_ORIGINAL_DST
)
// originalDstTCP retrieves the pre-REDIRECT destination address of a netfilter-
// redirected TCP connection via SO_ORIGINAL_DST / IP6T_SO_ORIGINAL_DST.
func originalDstTCP(conn net.Conn) (net.IP, int, error) {
sc, ok := conn.(syscall.Conn)
if !ok {
return nil, 0, errors.New("connection does not implement syscall.Conn")
}
rc, err := sc.SyscallConn()
if err != nil {
return nil, 0, err
}
var (
ip net.IP
port int
sockErr error
)
if err := rc.Control(func(fd uintptr) {
var addr4 unix.RawSockaddrInet4
vallen := uint32(unsafe.Sizeof(addr4))
_, _, errno := unix.Syscall6(
unix.SYS_GETSOCKOPT,
fd,
unix.SOL_IP,
soOriginalDst,
uintptr(unsafe.Pointer(&addr4)),
uintptr(unsafe.Pointer(&vallen)),
0,
)
if errno == 0 {
ip = net.IPv4(addr4.Addr[0], addr4.Addr[1], addr4.Addr[2], addr4.Addr[3])
port = int(binary.BigEndian.Uint16((*(*[2]byte)(unsafe.Pointer(&addr4.Port)))[:]))
return
}
var addr6 unix.RawSockaddrInet6
vallen6 := uint32(unsafe.Sizeof(addr6))
_, _, errno6 := unix.Syscall6(
unix.SYS_GETSOCKOPT,
fd,
unix.SOL_IPV6,
ip6tOriginalDst,
uintptr(unsafe.Pointer(&addr6)),
uintptr(unsafe.Pointer(&vallen6)),
0,
)
if errno6 == 0 {
b := make([]byte, net.IPv6len)
copy(b, addr6.Addr[:])
ip = net.IP(b)
port = int(binary.BigEndian.Uint16((*(*[2]byte)(unsafe.Pointer(&addr6.Port)))[:]))
return
}
sockErr = fmt.Errorf("getsockopt SO_ORIGINAL_DST failed: ipv4=%v ipv6=%v", errno, errno6)
}); err != nil {
return nil, 0, err
}
if sockErr != nil {
return nil, 0, sockErr
}
return normalizeIP(ip), port, nil
}
// listenTransparentUDP creates a UDP listener configured with IP_TRANSPARENT
// and IP_RECVORIGDSTADDR for Linux iptables TPROXY interception.
func listenTransparentUDP(addr string) (*net.UDPConn, error) {
lc := net.ListenConfig{
Control: func(network, address string, c syscall.RawConn) error {
var ctrlErr error
err := c.Control(func(fd uintptr) {
_ = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEADDR, 1)
if err := unix.SetsockoptInt(int(fd), unix.SOL_IP, unix.IP_TRANSPARENT, 1); err != nil {
ctrlErr = fmt.Errorf("setsockopt IP_TRANSPARENT: %w", err)
return
}
if err := unix.SetsockoptInt(int(fd), unix.SOL_IP, unix.IP_RECVORIGDSTADDR, 1); err != nil {
ctrlErr = fmt.Errorf("setsockopt IP_RECVORIGDSTADDR: %w", err)
return
}
})
if err != nil {
return err
}
return ctrlErr
},
}
pc, err := lc.ListenPacket(context.Background(), "udp4", addr)
if err != nil {
return nil, err
}
uc, ok := pc.(*net.UDPConn)
if !ok {
_ = pc.Close()
return nil, errors.New("expected *net.UDPConn")
}
return uc, nil
}
// readTransparentUDP reads one TPROXY UDP datagram along with its source and
// original destination addresses from the IP_ORIGDSTADDR control message.
func readTransparentUDP(conn *net.UDPConn, buf []byte) (n int, src, origDst *net.UDPAddr, err error) {
oob := make([]byte, 1024)
n, oobn, _, src, err := conn.ReadMsgUDP(buf, oob)
if err != nil {
return 0, nil, nil, err
}
msgs, parseErr := unix.ParseSocketControlMessage(oob[:oobn])
if parseErr != nil {
return n, src, nil, parseErr
}
for _, msg := range msgs {
if msg.Header.Level == unix.SOL_IP && msg.Header.Type == unix.IP_ORIGDSTADDR && len(msg.Data) >= 8 {
port := int(binary.BigEndian.Uint16(msg.Data[2:4]))
ip := net.IPv4(msg.Data[4], msg.Data[5], msg.Data[6], msg.Data[7])
origDst = &net.UDPAddr{IP: ip, Port: port}
break
}
}
if origDst == nil {
return n, src, nil, errors.New("missing IP_ORIGDSTADDR control message")
}
return n, src, origDst, nil
}
// dialTransparentUDPReply sends a UDP reply packet back to clientAddr spoofed
// as coming from origDst (requires CAP_NET_ADMIN / IP_TRANSPARENT).
func sendTransparentUDPReply(origDst, clientAddr *net.UDPAddr, payload []byte) error {
d := net.Dialer{
LocalAddr: origDst,
Control: func(network, address string, c syscall.RawConn) error {
var ctrlErr error
err := c.Control(func(fd uintptr) {
_ = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEADDR, 1)
if err := unix.SetsockoptInt(int(fd), unix.SOL_IP, unix.IP_TRANSPARENT, 1); err != nil {
ctrlErr = err
}
})
if err != nil {
return err
}
return ctrlErr
},
}
conn, err := d.Dial("udp4", clientAddr.String())
if err != nil {
return err
}
defer conn.Close()
_, err = conn.Write(payload)
return err
}
+32
View File
@@ -0,0 +1,32 @@
//go:build !linux
package traffic
import (
"errors"
"net"
)
func originalDstTCP(_ net.Conn) (net.IP, int, error) {
return nil, 0, errors.New("SO_ORIGINAL_DST is only supported on Linux")
}
func listenTransparentUDP(addr string) (*net.UDPConn, error) {
udpAddr, err := net.ResolveUDPAddr("udp", addr)
if err != nil {
return nil, err
}
return net.ListenUDP("udp", udpAddr)
}
func readTransparentUDP(conn *net.UDPConn, buf []byte) (int, *net.UDPAddr, *net.UDPAddr, error) {
n, src, err := conn.ReadFromUDP(buf)
if err != nil {
return 0, nil, nil, err
}
return n, src, nil, errors.New("TPROXY IP_ORIGDSTADDR is only supported on Linux")
}
func sendTransparentUDPReply(_, _ *net.UDPAddr, _ []byte) error {
return errors.New("transparent UDP reply is only supported on Linux")
}
+163
View File
@@ -0,0 +1,163 @@
package traffic
import (
"bufio"
"context"
"crypto/tls"
"encoding/base64"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
xproxy "golang.org/x/net/proxy"
)
// UpstreamResolver overrides the global upstream proxy for a specific traffic
// source (sandbox container / task / session). Returning (nil, true) forces a
// direct connection; returning (u, true) routes through u; returning (_, false)
// inherits the global upstream proxy.
type UpstreamResolver func(src SourceIdentity) (*url.URL, bool)
// SetUpstreamResolver installs an optional per-source upstream proxy resolver
// (#218 Phase 4). Both explicit HTTP/HTTPS proxy traffic and transparent L4
// TCP/DNS traffic honor it.
func (t *Traffic) SetUpstreamResolver(fn UpstreamResolver) {
if t == nil {
return
}
t.attrMu.Lock()
t.upstreamResolver = fn
t.attrMu.Unlock()
}
// resolveUpstreamForSource returns the effective upstream proxy URL for src
// (nil means direct connection).
func (t *Traffic) resolveUpstreamForSource(src SourceIdentity) *url.URL {
if t == nil {
return nil
}
t.attrMu.RLock()
fn := t.upstreamResolver
t.attrMu.RUnlock()
if fn != nil {
if u, override := fn(src); override {
return u
}
}
return t.upstream.Load()
}
// MaskProxyURL removes credentials from a proxy URL for logs/storage/UI.
func MaskProxyURL(u *url.URL) string {
if u == nil {
return "direct"
}
cp := *u
if cp.User != nil {
cp.User = url.User("***")
}
return cp.String()
}
// dialTCPThroughUpstream establishes a TCP connection to target (host:port),
// either directly or via an HTTP/HTTPS CONNECT or SOCKS5/SOCKS5H upstream proxy.
func dialTCPThroughUpstream(ctx context.Context, upstream *url.URL, target string, timeout time.Duration) (net.Conn, error) {
if timeout <= 0 {
timeout = 15 * time.Second
}
baseDialer := &net.Dialer{Timeout: timeout, KeepAlive: 30 * time.Second}
if upstream == nil {
return baseDialer.DialContext(ctx, "tcp", target)
}
scheme := strings.ToLower(strings.TrimSpace(upstream.Scheme))
switch scheme {
case "socks5", "socks5h":
var auth *xproxy.Auth
if upstream.User != nil {
pwd, _ := upstream.User.Password()
auth = &xproxy.Auth{User: upstream.User.Username(), Password: pwd}
}
socksDialer, err := xproxy.SOCKS5("tcp", upstream.Host, auth, baseDialer)
if err != nil {
return nil, fmt.Errorf("socks5 dialer init: %w", err)
}
if cd, ok := socksDialer.(xproxy.ContextDialer); ok {
return cd.DialContext(ctx, "tcp", target)
}
return socksDialer.Dial("tcp", target)
case "http", "https":
proxyAddr := upstream.Host
if _, _, err := net.SplitHostPort(proxyAddr); err != nil {
if scheme == "https" {
proxyAddr = net.JoinHostPort(proxyAddr, "443")
} else {
proxyAddr = net.JoinHostPort(proxyAddr, "80")
}
}
conn, err := baseDialer.DialContext(ctx, "tcp", proxyAddr)
if err != nil {
return nil, fmt.Errorf("dial http proxy %s: %w", MaskProxyURL(upstream), err)
}
if scheme == "https" {
tlsConn := tls.Client(conn, &tls.Config{
ServerName: upstream.Hostname(),
InsecureSkipVerify: true,
})
if err := tlsConn.HandshakeContext(ctx); err != nil {
_ = conn.Close()
return nil, fmt.Errorf("tls handshake http proxy %s: %w", MaskProxyURL(upstream), err)
}
conn = tlsConn
}
if err := httpConnectHandshake(ctx, conn, target, upstream.User); err != nil {
_ = conn.Close()
return nil, err
}
return conn, nil
default:
return nil, fmt.Errorf("unsupported upstream proxy scheme %q", scheme)
}
}
func httpConnectHandshake(ctx context.Context, conn net.Conn, target string, user *url.Userinfo) error {
if dl, ok := ctx.Deadline(); ok {
_ = conn.SetDeadline(dl)
defer func() { _ = conn.SetDeadline(time.Time{}) }()
} else {
_ = conn.SetDeadline(time.Now().Add(15 * time.Second))
defer func() { _ = conn.SetDeadline(time.Time{}) }()
}
var sb strings.Builder
sb.WriteString("CONNECT ")
sb.WriteString(target)
sb.WriteString(" HTTP/1.1\r\nHost: ")
sb.WriteString(target)
sb.WriteString("\r\n")
if user != nil {
pwd, _ := user.Password()
cred := base64.StdEncoding.EncodeToString([]byte(user.Username() + ":" + pwd))
sb.WriteString("Proxy-Authorization: Basic ")
sb.WriteString(cred)
sb.WriteString("\r\n")
}
sb.WriteString("\r\n")
if _, err := conn.Write([]byte(sb.String())); err != nil {
return fmt.Errorf("send CONNECT %s: %w", target, err)
}
br := bufio.NewReader(conn)
resp, err := http.ReadResponse(br, &http.Request{Method: http.MethodConnect})
if err != nil {
return fmt.Errorf("read CONNECT response for %s: %w", target, err)
}
_ = resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return fmt.Errorf("upstream proxy rejected CONNECT %s: %s", target, resp.Status)
}
return nil
}
+234
View File
@@ -0,0 +1,234 @@
package traffic
import (
"bufio"
"bytes"
"encoding/binary"
"io"
"net"
"os"
"strings"
"time"
)
// SniffedProto identifies the detected L7 protocol from a TCP stream's first bytes.
type SniffedProto string
const (
ProtoTCP SniffedProto = "tcp"
ProtoHTTP SniffedProto = "http"
ProtoTLS SniffedProto = "tls"
)
// SniffResult carries the sniffed protocol plus any extracted Host / SNI.
type SniffResult struct {
Proto SniffedProto
Host string
SNI string
}
// PeekConn wraps a net.Conn so already-peeked bytes are transparently replayed
// on subsequent Read calls.
type PeekConn struct {
net.Conn
br *bufio.Reader
}
func (c *PeekConn) Read(p []byte) (int, error) {
return c.br.Read(p)
}
// CloseWrite propagates TCP half-close to the underlying net.Conn so L4 relays
// deliver EOF to the peer instead of deadlocking when one side finishes first.
func (c *PeekConn) CloseWrite() error {
if cw, ok := c.Conn.(interface{ CloseWrite() error }); ok {
return cw.CloseWrite()
}
return nil
}
// SniffProtocol inspects the first bytes of a newly accepted TCP connection
// without consuming them from the returned net.Conn.
//
// If the client does not send bytes within peekTimeout (e.g. server-speaks-first
// protocols like SSH, MySQL, SMTP), it classifies the stream as raw ProtoTCP
// immediately without blocking the connection.
func SniffProtocol(conn net.Conn, peekTimeout time.Duration) (SniffResult, net.Conn) {
if peekTimeout <= 0 {
peekTimeout = 250 * time.Millisecond
}
br := bufio.NewReaderSize(conn, 4096)
wrapped := &PeekConn{Conn: conn, br: br}
_ = conn.SetReadDeadline(time.Now().Add(peekTimeout))
buf, err := peekAvailable(br, 2048)
_ = conn.SetReadDeadline(time.Time{})
if len(buf) == 0 {
if err != nil && !os.IsTimeout(err) && err != io.EOF {
return SniffResult{Proto: ProtoTCP}, wrapped
}
return SniffResult{Proto: ProtoTCP}, wrapped
}
if sni, ok := parseTLSClientHelloSNI(buf); ok {
return SniffResult{Proto: ProtoTLS, SNI: sni, Host: sni}, wrapped
}
if host, ok := parseHTTPFirstLineHost(buf); ok {
return SniffResult{Proto: ProtoHTTP, Host: host}, wrapped
}
return SniffResult{Proto: ProtoTCP}, wrapped
}
func peekAvailable(br *bufio.Reader, maxBytes int) ([]byte, error) {
if _, err := br.Peek(1); err != nil {
return nil, err
}
n := br.Buffered()
if n > maxBytes {
n = maxBytes
}
if n <= 0 {
return nil, nil
}
return br.Peek(n)
}
// parseTLSClientHelloSNI checks whether buf starts with a TLS Handshake
// ClientHello record and extracts the RFC 6066 server_name (SNI) if present.
func parseTLSClientHelloSNI(buf []byte) (sni string, isTLS bool) {
if len(buf) < 6 {
return "", false
}
if buf[0] != 0x16 || buf[1] != 0x03 || buf[2] > 0x04 {
return "", false
}
if buf[5] != 0x01 {
return "", false
}
isTLS = true
recLen := int(binary.BigEndian.Uint16(buf[3:5]))
end := 5 + recLen
if end > len(buf) {
end = len(buf)
}
p := buf[5:end]
if len(p) < 4 {
return "", true
}
p = p[4:] // handshake header
if len(p) < 34 {
return "", true
}
p = p[34:] // version + random
if len(p) < 1 {
return "", true
}
sidLen := int(p[0])
if len(p) < 1+sidLen {
return "", true
}
p = p[1+sidLen:]
if len(p) < 2 {
return "", true
}
csLen := int(binary.BigEndian.Uint16(p[:2]))
if len(p) < 2+csLen {
return "", true
}
p = p[2+csLen:]
if len(p) < 1 {
return "", true
}
cmLen := int(p[0])
if len(p) < 1+cmLen {
return "", true
}
p = p[1+cmLen:]
if len(p) < 2 {
return "", true
}
extTotal := int(binary.BigEndian.Uint16(p[:2]))
p = p[2:]
if extTotal < len(p) {
p = p[:extTotal]
}
for len(p) >= 4 {
extType := binary.BigEndian.Uint16(p[0:2])
extLen := int(binary.BigEndian.Uint16(p[2:4]))
p = p[4:]
if extLen > len(p) {
break
}
if extType == 0x0000 { // server_name
ext := p[:extLen]
if len(ext) < 2 {
return "", true
}
listLen := int(binary.BigEndian.Uint16(ext[0:2]))
ext = ext[2:]
if listLen < len(ext) {
ext = ext[:listLen]
}
for len(ext) >= 3 {
nameType := ext[0]
nameLen := int(binary.BigEndian.Uint16(ext[1:3]))
ext = ext[3:]
if nameLen > len(ext) {
break
}
if nameType == 0x00 {
return strings.ToLower(strings.TrimSpace(string(ext[:nameLen]))), true
}
ext = ext[nameLen:]
}
return "", true
}
p = p[extLen:]
}
return "", true
}
var httpMethodPrefixes = [][]byte{
[]byte("GET "),
[]byte("POST "),
[]byte("PUT "),
[]byte("DELETE "),
[]byte("HEAD "),
[]byte("OPTIONS "),
[]byte("PATCH "),
[]byte("CONNECT "),
[]byte("TRACE "),
}
func parseHTTPFirstLineHost(buf []byte) (host string, isHTTP bool) {
matched := false
for _, m := range httpMethodPrefixes {
if bytes.HasPrefix(buf, m) {
matched = true
break
}
}
if !matched {
return "", false
}
lineEnd := bytes.IndexByte(buf, '\n')
firstLine := buf
if lineEnd > 0 {
firstLine = buf[:lineEnd]
}
if !bytes.Contains(firstLine, []byte("HTTP/1.")) && !bytes.Contains(firstLine, []byte("HTTP/2")) {
return "", false
}
lines := bytes.Split(buf, []byte("\n"))
for i := 1; i < len(lines); i++ {
line := strings.TrimSpace(string(lines[i]))
if line == "" {
break
}
if len(line) > 5 && strings.EqualFold(line[:5], "host:") {
return strings.TrimSpace(line[5:]), true
}
}
return "", true
}
+40 -9
View File
@@ -24,8 +24,12 @@ type SSRFGuardConfig struct {
// addresses stays reachable except AdminPorts, which would reach this process.
InfraIPs []net.IP
AdminPorts []int
// HostNetworkMode should be set when the guard runs in the Docker host's
// network namespace (artex-gateway): local host interface IPs are protected
// on AdminPorts (via InfraIPs) rather than blocked on every port, and the
// host's LAN router is not treated as a Docker bridge hairpin address.
HostNetworkMode bool
}
type ssrfGuard struct {
mu sync.RWMutex
enabled bool
@@ -108,19 +112,46 @@ func newSSRFGuard(cfg SSRFGuardConfig) *ssrfGuard {
}
}
}
// Always block local interface IPs so a sandboxed container cannot use the
// recording proxy to reach ARTEX's own management port (:8787) via its container IP.
infraSet := make(map[string]struct{}, len(g.infraIPs))
for _, ip := range g.infraIPs {
infraSet[ip.String()] = struct{}{}
}
// Protect local interface IPs. Inside the ARTEX container, block all ports on
// container IPs (unless explicitly listed in InfraIPs). In host network mode
// (artex-gateway), protect all host interface IPs on AdminPorts via infraIPs
// so ARTEX :8787/:8788 stay unreachable while other host LAN ports remain scannable.
if addrs, err := net.InterfaceAddrs(); err == nil {
for _, a := range addrs {
if ipnet, ok := a.(*net.IPNet); ok && ipnet.IP != nil {
g.blockedIPs[normalizeIP(ipnet.IP).String()] = struct{}{}
ipnet, ok := a.(*net.IPNet)
if !ok || ipnet.IP == nil {
continue
}
ip := normalizeIP(ipnet.IP)
if ip == nil {
continue
}
if cfg.HostNetworkMode {
if _, seen := infraSet[ip.String()]; !seen {
g.infraIPs = append(g.infraIPs, ip)
infraSet[ip.String()] = struct{}{}
}
continue
}
if _, isInfra := infraSet[ip.String()]; isInfra {
continue
}
g.blockedIPs[ip.String()] = struct{}{}
}
}
// The container default gateway is the Docker host bridge. Blocking it stops
// the proxy from hairpinning back onto published host ports.
if gw := linuxDefaultGatewayIPv4(); gw != nil {
g.blockedIPs[gw.String()] = struct{}{}
// In container mode, the default gateway is the Docker host bridge; blocking it
// stops hairpinning onto published host ports. In host network mode, the default
// gateway is the LAN router and must not be blocked on all ports.
if !cfg.HostNetworkMode {
if gw := linuxDefaultGatewayIPv4(); gw != nil {
if _, isInfra := infraSet[gw.String()]; !isInfra {
g.blockedIPs[gw.String()] = struct{}{}
}
}
}
return g
}
+400 -103
View File
@@ -39,17 +39,23 @@ import (
const indexSchema = `
CREATE TABLE IF NOT EXISTS exchanges (
id TEXT PRIMARY KEY,
ts INTEGER,
host TEXT,
method TEXT,
url_template TEXT,
url TEXT,
status INTEGER,
content_type TEXT,
req_len INTEGER,
resp_len INTEGER,
path TEXT
id TEXT PRIMARY KEY,
ts INTEGER,
host TEXT,
method TEXT,
url_template TEXT,
url TEXT,
status INTEGER,
content_type TEXT,
req_len INTEGER,
resp_len INTEGER,
path TEXT,
sandbox_scope TEXT NOT NULL DEFAULT '',
sandbox_owner_id TEXT NOT NULL DEFAULT '',
container_id TEXT NOT NULL DEFAULT '',
session_id TEXT NOT NULL DEFAULT '',
intent_id INTEGER NOT NULL DEFAULT 0,
src_ip TEXT NOT NULL DEFAULT ''
);
CREATE INDEX IF NOT EXISTS idx_ex_host ON exchanges(host);
CREATE INDEX IF NOT EXISTS idx_ex_tmpl ON exchanges(host, url_template);
@@ -131,7 +137,7 @@ const (
// TrafficSearchDescription is persisted into the tool catalog for new and
// upgraded installations. Keep it in the traffic package so the runtime tool
// and the catalog migration cannot drift apart.
const TrafficSearchDescription = "查询记录代理已抓取的目标流量(必须指定 host;支持裸主机、主机:端口或完整 URL,可再按 URL 子串或正文关键词过滤)。指定端口时只返回该服务的流量,避免同一 IP 的不同端口串包。body_contains 会在已抓取的请求/响应头与正文中做全文搜索,支持任意子串和中文(至少 3 个字符)。仅返回极轻量索引(id/method/url/status/resp_len),不含响应内容;结果非空后必须用 traffic_get 逐条核实请求/响应,再把确实支持当前漏洞的 ID 交给 bind_finding_traffic。默认只返回 3 条、每页最多 10 条;结果多时用 page 翻页。"
const TrafficSearchDescription = "查询记录代理与透明网关已抓取的目标流量(HTTP/HTTPS 默认按 host 过滤,支持裸主机、主机:端口或完整 URL,可再按 URL 子串或正文关键词过滤;也可通过 protocol='tcp'|'tls'|'udp'|'dns' 查询非 HTTP 原始 TCP/UDP 连接和 DNS 解析记录,支持按 action='block' 查出口拦截记录)。HTTP 流量仅返回轻量索引(id/method/url/status/resp_len),需用 traffic_get 核实正文后再交给 bind_finding_traffic。"
// Traffic runs the recording proxy and owns the file tree + index.
type Traffic struct {
@@ -173,8 +179,22 @@ type Traffic struct {
upstreamMu sync.RWMutex
upstreamFailure func(error)
ssrf atomic.Pointer[ssrfGuard]
blacklist atomic.Pointer[egressBlacklist]
blockLog *blockEventLog
attrMu sync.RWMutex
sourceResolver SourceResolver
taskBlacklistFn TaskBlacklistChecker
upstreamResolver UpstreamResolver
gatewayToken string
udpPolicy string
dnsUpstream string
ssrfCfg *SSRFGuardConfig
dnsCache *dnsReverseCache
nfWrites atomic.Int64
dnsWrites atomic.Int64
flowAttr sync.Map // uuid.UUID -> SourceIdentity
connAttr sync.Map // remoteAddr(string) -> connAttrEntry
}
// EnableSSRFGuard installs an outbound destination filter on the recording
// proxy so sandboxed workloads cannot pivot to localhost, cloud metadata, or
// ARTEX's own management/database endpoints.
@@ -182,10 +202,16 @@ func (t *Traffic) EnableSSRFGuard(cfg SSRFGuardConfig) {
if t == nil {
return
}
t.attrMu.Lock()
if !cfg.Enabled {
t.ssrfCfg = nil
t.attrMu.Unlock()
t.ssrf.Store(nil)
return
}
cp := cfg
t.ssrfCfg = &cp
t.attrMu.Unlock()
t.ssrf.Store(newSSRFGuard(cfg))
}
@@ -212,7 +238,7 @@ func Open(dir, addr string) (*Traffic, error) {
if err != nil {
return nil, err
}
t := &Traffic{dir: dir, addr: addr, db: db, closed: make(chan struct{})}
t := &Traffic{dir: dir, addr: addr, db: db, closed: make(chan struct{}), blockLog: &blockEventLog{}, dnsCache: newDNSReverseCache()}
if err := t.initIndex(); err != nil {
db.Close()
return nil, err
@@ -242,6 +268,10 @@ func Open(dir, addr string) (*Traffic, error) {
if err := t.rejectBlockedDestination(req); err != nil {
return nil, err
}
if req != nil {
src := t.resolveSourceForConn(req.RemoteAddr, req.Header)
return t.resolveUpstreamForSource(src), nil
}
return t.upstream.Load(), nil
})
// Fail-open: MITM every host by default, EXCEPT ones a prior request proved we
@@ -249,8 +279,15 @@ func Open(dir, addr string) (*Traffic, error) {
// transparently so the request still reaches the target instead of being killed.
// Blocked destinations stay intercepted so the addon can return 403 before dial.
p.SetShouldInterceptRule(func(req *http.Request) bool {
if g := t.ssrf.Load(); g != nil && req != nil && g.Check(req.Host) != "" {
return true
if req != nil {
scheme := ""
if req.URL != nil {
scheme = req.URL.Scheme
}
src := t.resolveSourceForConn(req.RemoteAddr, req.Header)
if t.checkOutboundForSource(req.Host, scheme, src) != nil {
return true
}
}
host := ""
if req != nil {
@@ -272,19 +309,40 @@ func (t *Traffic) rejectBlockedDestination(req *http.Request) error {
if t == nil || req == nil {
return nil
}
g := t.ssrf.Load()
if g == nil {
return nil
}
host := req.Host
if host == "" && req.URL != nil {
host = req.URL.Host
scheme := ""
rawURL := ""
if req.URL != nil {
if host == "" {
host = req.URL.Host
}
scheme = req.URL.Scheme
rawURL = req.URL.String()
}
if strings.TrimSpace(host) == "" {
return nil
}
if reason := g.Check(host); reason != "" {
return fmt.Errorf("blocked by ARTEX proxy SSRF guard: %s", reason)
src := t.resolveSourceForConn(req.RemoteAddr, req.Header)
if m := t.checkOutboundForSource(host, scheme, src); m != nil {
h, port := splitHostAndPort(host)
t.blockLog.Record(EgressBlockEvent{
Host: h,
Port: port,
Method: req.Method,
URL: rawURL,
SrcIP: src.SrcIP,
Scope: src.Scope,
OwnerID: src.OwnerID,
Reason: m.Reason,
RuleKind: m.RuleKind,
RuleID: m.RuleID,
Pattern: m.Pattern,
Source: m.Source,
})
if m.Source == "ssrf_guard" {
return fmt.Errorf("blocked by ARTEX proxy SSRF guard: %s", m.Reason)
}
return fmt.Errorf("blocked by ARTEX egress blacklist: %s", m.Reason)
}
return nil
}
@@ -341,6 +399,12 @@ func (t *Traffic) initIndex() error {
if _, err := conn.ExecContext(ctx, indexSchema); err != nil {
return err
}
if err := ensureAttributionColumns(ctx, conn); err != nil {
return err
}
if err := ensureNetFlowSchema(ctx, conn); err != nil {
return err
}
if _, err := conn.ExecContext(ctx, ftsSchema); err != nil {
log.Printf("[traffic] 全文索引不可用,正文搜索将被禁用(元数据搜索不受影响):%v", err)
return nil
@@ -349,6 +413,59 @@ func (t *Traffic) initIndex() error {
return nil
}
func ensureAttributionColumns(ctx context.Context, conn *sql.Conn) error {
rows, err := conn.QueryContext(ctx, `PRAGMA table_info(exchanges)`)
if err != nil {
return err
}
have := make(map[string]bool)
for rows.Next() {
var cid int
var name, typ string
var notNull int
var dflt sql.NullString
var pk int
if err := rows.Scan(&cid, &name, &typ, &notNull, &dflt, &pk); err != nil {
rows.Close()
return err
}
have[strings.ToLower(name)] = true
}
if err := rows.Err(); err != nil {
rows.Close()
return err
}
rows.Close()
cols := []struct {
name string
ddl string
}{
{"sandbox_scope", `ALTER TABLE exchanges ADD COLUMN sandbox_scope TEXT NOT NULL DEFAULT ''`},
{"sandbox_owner_id", `ALTER TABLE exchanges ADD COLUMN sandbox_owner_id TEXT NOT NULL DEFAULT ''`},
{"container_id", `ALTER TABLE exchanges ADD COLUMN container_id TEXT NOT NULL DEFAULT ''`},
{"session_id", `ALTER TABLE exchanges ADD COLUMN session_id TEXT NOT NULL DEFAULT ''`},
{"intent_id", `ALTER TABLE exchanges ADD COLUMN intent_id INTEGER NOT NULL DEFAULT 0`},
{"src_ip", `ALTER TABLE exchanges ADD COLUMN src_ip TEXT NOT NULL DEFAULT ''`},
}
for _, c := range cols {
if !have[c.name] {
if _, err := conn.ExecContext(ctx, c.ddl); err != nil {
return err
}
}
}
for _, idx := range []string{
`CREATE INDEX IF NOT EXISTS idx_ex_owner ON exchanges(sandbox_scope, sandbox_owner_id)`,
`CREATE INDEX IF NOT EXISTS idx_ex_container ON exchanges(container_id)`,
} {
if _, err := conn.ExecContext(ctx, idx); err != nil {
return err
}
}
return nil
}
// hostOnly strips an optional :port, so passthrough keys match whether the host
// arrives as "example.com:443" (CONNECT) or "example.com" (request URL).
func hostOnly(hostport string) string {
@@ -483,23 +600,46 @@ func (s *sink) Requestheaders(f *mproxy.Flow) {
return
}
if s.t != nil {
if g := s.t.ssrf.Load(); g != nil {
host := ""
if f.Request.URL != nil {
host = f.Request.URL.Host
}
if host == "" && f.Request.Header != nil {
host = f.Request.Header.Get("Host")
}
if reason := g.Check(host); reason != "" {
f.Response = &mproxy.Response{
StatusCode: http.StatusForbidden,
Header: http.Header{"Content-Type": []string{"text/plain; charset=utf-8"}},
Body: []byte("blocked by ARTEX proxy SSRF guard: " + reason),
}
return
}
host := ""
scheme := ""
rawURL := ""
if f.Request.URL != nil {
host = f.Request.URL.Host
scheme = f.Request.URL.Scheme
rawURL = f.Request.URL.String()
}
if host == "" && f.Request.Header != nil {
host = f.Request.Header.Get("Host")
}
src := s.t.resolveSourceForConn(flowClientAddr(f), f.Request.Header)
if m := s.t.checkOutboundForSource(host, scheme, src); m != nil {
h, port := splitHostAndPort(host)
s.t.blockLog.Record(EgressBlockEvent{
Host: h,
Port: port,
Method: f.Request.Method,
URL: rawURL,
SrcIP: src.SrcIP,
Scope: src.Scope,
OwnerID: src.OwnerID,
Reason: m.Reason,
RuleKind: m.RuleKind,
RuleID: m.RuleID,
Pattern: m.Pattern,
Source: m.Source,
})
prefix := "blocked by ARTEX egress blacklist: "
if m.Source == "ssrf_guard" {
prefix = "blocked by ARTEX proxy SSRF guard: "
}
f.Response = &mproxy.Response{
StatusCode: http.StatusForbidden,
Header: http.Header{"Content-Type": []string{"text/plain; charset=utf-8"}},
Body: []byte(prefix + m.Reason),
}
return
}
s.t.flowAttr.Store(f.Id, src)
}
if f.Request.Header == nil {
f.Request.Header = make(http.Header)
@@ -509,14 +649,33 @@ func (s *sink) Requestheaders(f *mproxy.Flow) {
}
}
func (s *sink) ClientDisconnected(c *mproxy.ClientConn) {
if s.t == nil || c == nil || c.Conn == nil || c.Conn.RemoteAddr() == nil {
return
}
s.t.connAttr.Delete(c.Conn.RemoteAddr().String())
}
func (s *sink) ServerConnected(connCtx *mproxy.ConnContext) {
if connCtx == nil || connCtx.ServerConn == nil || s.t == nil {
return
}
if g := s.t.ssrf.Load(); g != nil {
if reason := g.Check(connCtx.ServerConn.Address); reason != "" && connCtx.ServerConn.Conn != nil {
_ = connCtx.ServerConn.Conn.Close()
}
src := s.t.resolveSourceForConn(connClientAddr(connCtx), nil)
if m := s.t.checkOutboundForSource(connCtx.ServerConn.Address, "", src); m != nil && connCtx.ServerConn.Conn != nil {
h, port := splitHostAndPort(connCtx.ServerConn.Address)
s.t.blockLog.Record(EgressBlockEvent{
Host: h,
Port: port,
SrcIP: src.SrcIP,
Scope: src.Scope,
OwnerID: src.OwnerID,
Reason: m.Reason,
RuleKind: m.RuleKind,
RuleID: m.RuleID,
Pattern: m.Pattern,
Source: m.Source,
})
_ = connCtx.ServerConn.Conn.Close()
}
}
func (s *sink) Response(f *mproxy.Flow) {
@@ -531,10 +690,12 @@ func (s *sink) Response(f *mproxy.Flow) {
// errors) — not a plain target-unreachable error — we flag the host for
// transparent passthrough so future requests to it succeed instead of dying.
func (s *sink) RequestError(f *mproxy.Flow, err error) {
if f != nil && s.t != nil {
s.t.flowAttr.Delete(f.Id)
}
s.t.reportUpstreamFailure(err)
s.t.maybePassthrough(f, err)
}
func (s *sink) HTTPConnectError(_ *mproxy.Flow, err error) {
s.t.reportUpstreamFailure(err)
}
@@ -598,14 +759,23 @@ func (t *Traffic) record(f *mproxy.Flow) {
}
defer tx.Rollback() //nolint:errcheck // no-op once committed
var src SourceIdentity
if v, ok := t.flowAttr.LoadAndDelete(f.Id); ok {
if s, ok2 := v.(SourceIdentity); ok2 {
src = s
}
} else {
src = t.resolveSourceForConn(flowClientAddr(f), nil)
}
// path stays empty for db-resident exchanges; a non-empty path marks a legacy
// row whose bodies still live in the old on-disk tree (see Get).
res, err := tx.Exec(`INSERT OR REPLACE INTO exchanges(id,ts,host,method,url_template,url,status,content_type,req_len,resp_len,path)
VALUES(?,?,?,?,?,?,?,?,?,?,'')`,
res, err := tx.Exec(`INSERT OR REPLACE INTO exchanges(id,ts,host,method,url_template,url,status,content_type,req_len,resp_len,path,sandbox_scope,sandbox_owner_id,container_id,session_id,intent_id,src_ip)
VALUES(?,?,?,?,?,?,?,?,?,?,'',?,?,?,?,?,?)`,
id, now.Unix(), host, method, tmpl, url, f.Response.StatusCode, ct,
len(f.Request.Body), len(f.Response.Body))
len(f.Request.Body), len(f.Response.Body),
src.Scope, src.OwnerID, src.ContainerID, src.SessionID, src.IntentID, src.SrcIP)
if err != nil {
log.Printf("[traffic] 记录 %s 失败(写索引):%v", url, err)
return
}
rowid, err := res.LastInsertId()
@@ -890,16 +1060,22 @@ func (t *Traffic) BlobRange(hash string, offset, length int64) (data []byte, tot
// ExchangeMeta is one row of the index (returned by Search).
type ExchangeMeta struct {
ID string `json:"id"`
TS int64 `json:"ts"`
Host string `json:"host"`
Method string `json:"method"`
URLTemplate string `json:"url_template"`
URL string `json:"url"`
Status int `json:"status"`
ContentType string `json:"content_type"`
RespLen int `json:"resp_len"`
Path string `json:"path"`
ID string `json:"id"`
TS int64 `json:"ts"`
Host string `json:"host"`
Method string `json:"method"`
URLTemplate string `json:"url_template"`
URL string `json:"url"`
Status int `json:"status"`
ContentType string `json:"content_type"`
RespLen int `json:"resp_len"`
Path string `json:"path"`
SandboxScope string `json:"sandbox_scope,omitempty"`
SandboxOwnerID 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"`
}
// Search returns paged exchange metadata (never bodies).
@@ -907,7 +1083,7 @@ func (t *Traffic) Search(host string, page, size int) ([]ExchangeMeta, error) {
if size <= 0 || size > 500 {
size = 100
}
q := `SELECT id,ts,host,method,url_template,url,status,content_type,resp_len,path FROM exchanges`
q := `SELECT id,ts,host,method,url_template,url,status,content_type,resp_len,path,COALESCE(sandbox_scope,''),COALESCE(sandbox_owner_id,''),COALESCE(container_id,''),COALESCE(session_id,''),COALESCE(intent_id,0),COALESCE(src_ip,'') FROM exchanges`
args := []any{}
if host != "" {
q += ` WHERE host=?`
@@ -923,7 +1099,7 @@ func (t *Traffic) Search(host string, page, size int) ([]ExchangeMeta, error) {
var out []ExchangeMeta
for rows.Next() {
var m ExchangeMeta
if err := rows.Scan(&m.ID, &m.TS, &m.Host, &m.Method, &m.URLTemplate, &m.URL, &m.Status, &m.ContentType, &m.RespLen, &m.Path); err != nil {
if err := rows.Scan(&m.ID, &m.TS, &m.Host, &m.Method, &m.URLTemplate, &m.URL, &m.Status, &m.ContentType, &m.RespLen, &m.Path, &m.SandboxScope, &m.SandboxOwnerID, &m.ContainerID, &m.SessionID, &m.IntentID, &m.SrcIP); err != nil {
return nil, err
}
out = append(out, m)
@@ -955,17 +1131,23 @@ func ftsQuote(s string) string {
// of -1 skip the response-size bounds. An empty Sort/Order defaults to
// newest-first by timestamp.
type PageQuery struct {
Host string // host substring
Hosts []string // task-scoped host candidates (exact host or host:port)
Method string // exact method (case-insensitive)
Query string // broad search box: metadata columns OR captured text
Body string // content box: captured request/response text only (full-text)
Path string // url_template substring — the vulnerability's path
Status string // exact code ("404") or class bucket ("4xx")
RespMin int64 // minimum resp_len, or -1 when unset
RespMax int64 // maximum resp_len, or -1 when unset
Sort string // ts | status | resp_len (default ts)
Order string // asc | desc (default desc)
Host string // host substring
Hosts []string // task-scoped host candidates (exact host or host:port)
OwnerTaskID string // task ID for strict attribution matching (+ legacy unattributed fallback on Hosts)
SandboxScope string // exact sandbox_scope ("task" | "session")
SandboxOwnerID string // exact sandbox_owner_id
ContainerID string // container_id prefix match
SessionID string // exact session_id
IntentID int64 // exact intent_id (>0)
Method string // exact method (case-insensitive)
Query string // broad search box: metadata columns OR captured text
Body string // content box: captured request/response text only (full-text)
Path string // url_template substring — the vulnerability's path
Status string // exact code ("404") or class bucket ("4xx")
RespMin int64 // minimum resp_len, or -1 when unset
RespMax int64 // maximum resp_len, or -1 when unset
Sort string // ts | status | resp_len (default ts)
Order string // asc | desc (default desc)
}
// hostScopeClause limits traffic to the hosts attached to a task. Captures
@@ -1052,9 +1234,33 @@ func (t *Traffic) Page(f PageQuery, page, size int) (rows []ExchangeMeta, total
if h := strings.TrimSpace(f.Host); h != "" {
add("host LIKE ?", "%"+h+"%")
}
if cond, scopeArgs := hostScopeClause(f.Hosts); cond != "" {
if ownerTaskID := strings.TrimSpace(f.OwnerTaskID); ownerTaskID != "" {
if cond, scopeArgs := hostScopeClause(f.Hosts); cond != "" {
allArgs := make([]any, 0, 1+len(scopeArgs))
allArgs = append(allArgs, ownerTaskID)
allArgs = append(allArgs, scopeArgs...)
add("((sandbox_scope='task' AND sandbox_owner_id=?) OR (COALESCE(sandbox_owner_id,'')='' AND "+cond+"))", allArgs...)
} else {
add("(sandbox_scope='task' AND sandbox_owner_id=?)", ownerTaskID)
}
} else if cond, scopeArgs := hostScopeClause(f.Hosts); cond != "" {
add(cond, scopeArgs...)
}
if sc := strings.TrimSpace(f.SandboxScope); sc != "" {
add("sandbox_scope=?", sc)
}
if ow := strings.TrimSpace(f.SandboxOwnerID); ow != "" {
add("sandbox_owner_id=?", ow)
}
if cid := strings.TrimSpace(f.ContainerID); cid != "" {
add("container_id LIKE ?", cid+"%")
}
if sid := strings.TrimSpace(f.SessionID); sid != "" {
add("session_id=?", sid)
}
if f.IntentID > 0 {
add("intent_id=?", f.IntentID)
}
if m := strings.TrimSpace(f.Method); m != "" {
add("method=?", strings.ToUpper(m))
}
@@ -1103,7 +1309,7 @@ func (t *Traffic) Page(f PageQuery, page, size int) (rows []ExchangeMeta, total
}
// id embeds capture timestamp + sequence, so a trailing id DESC makes the order
// total and pagination stable even when the sort column has many ties.
sel := `SELECT id,ts,host,method,url_template,url,status,content_type,resp_len,path FROM exchanges` +
sel := `SELECT id,ts,host,method,url_template,url,status,content_type,resp_len,path,COALESCE(sandbox_scope,''),COALESCE(sandbox_owner_id,''),COALESCE(container_id,''),COALESCE(session_id,''),COALESCE(intent_id,0),COALESCE(src_ip,'') FROM exchanges` +
where + ` ORDER BY ` + col + ` ` + dir + `, id DESC LIMIT ? OFFSET ?`
qargs := append(append([]any{}, args...), size, page*size)
rs, err := t.db.Query(sel, qargs...)
@@ -1113,7 +1319,7 @@ func (t *Traffic) Page(f PageQuery, page, size int) (rows []ExchangeMeta, total
defer rs.Close()
for rs.Next() {
var m ExchangeMeta
if err := rs.Scan(&m.ID, &m.TS, &m.Host, &m.Method, &m.URLTemplate, &m.URL, &m.Status, &m.ContentType, &m.RespLen, &m.Path); err != nil {
if err := rs.Scan(&m.ID, &m.TS, &m.Host, &m.Method, &m.URLTemplate, &m.URL, &m.Status, &m.ContentType, &m.RespLen, &m.Path, &m.SandboxScope, &m.SandboxOwnerID, &m.ContainerID, &m.SessionID, &m.IntentID, &m.SrcIP); err != nil {
return nil, 0, err
}
rows = append(rows, m)
@@ -1216,6 +1422,39 @@ func (t *Traffic) HostsForScope(scope []string) ([]HostCount, error) {
return out, rows.Err()
}
// HostsForTask returns distinct recorded hosts attributed to ownerTaskID OR
// matching legacy unattributed exchanges in scope.
func (t *Traffic) HostsForTask(ownerTaskID string, scope []string) ([]HostCount, error) {
ownerTaskID = strings.TrimSpace(ownerTaskID)
if ownerTaskID == "" {
return t.HostsForScope(scope)
}
var where string
var args []any
if cond, scopeArgs := hostScopeClause(scope); cond != "" {
where = "((sandbox_scope='task' AND sandbox_owner_id=?) OR (COALESCE(sandbox_owner_id,'')='' AND " + cond + "))"
args = append(args, ownerTaskID)
args = append(args, scopeArgs...)
} else {
where = "(sandbox_scope='task' AND sandbox_owner_id=?)"
args = append(args, ownerTaskID)
}
rows, err := t.db.Query(`SELECT host, COUNT(*) AS n, MAX(ts) AS last FROM exchanges WHERE `+where+` GROUP BY host ORDER BY last DESC`, args...)
if err != nil {
return nil, err
}
defer rows.Close()
var out []HostCount
for rows.Next() {
var h HostCount
var last int64
if err := rows.Scan(&h.Host, &h.Count, &last); err != nil {
return nil, err
}
out = append(out, h)
}
return out, rows.Err()
}
// Count returns total recorded exchanges.
func (t *Traffic) Count() (int, error) {
var n int
@@ -1298,6 +1537,8 @@ func (t *Traffic) DeleteAll() (deleted int64, reclaimed int64, err error) {
if deleted, err = t.deleteWhere(tx, `1=1`); err != nil {
return 0, 0, err
}
_, _ = tx.Exec(`DELETE FROM net_flows`)
_, _ = tx.Exec(`DELETE FROM dns_queries`)
// Staged before the commit so a filesystem failure can still abort the whole
// deletion, exactly as in DeleteHost.
stageDir, moves, err := t.stageTrees(trees)
@@ -2211,48 +2452,104 @@ func (t *Traffic) Tools() []actool.CoreTool {
Schema: map[string]any{
"type": "object",
"properties": map[string]any{
"host": map[string]any{"type": "string", "description": "按主机过滤(必填;如 '107.172.96.177'、'107.172.96.177:8082' 或 'http://107.172.96.177:8082/path')"},
"contains": map[string]any{"type": "string", "description": "URL 子串过滤(可选,如 'api' / 'login')"},
"body_contains": map[string]any{"type": "string", "description": "正文全文搜索(可选,至少 3 个字符),匹配请求/响应的头与正文,如 'password' / 'root:x:0' / '内网测试'"},
"protocol": map[string]any{"type": "string", "description": "协议类型:http(默认,含 HTTPS)、tcp、tls、udp、dns"},
"host": map[string]any{"type": "string", "description": "HTTP 协议下必填(如 '107.172.96.177'、'107.172.96.177:8082' 或完整 URL);非 HTTP 协议下可选,按目标主机/IP/域名过滤"},
"contains": map[string]any{"type": "string", "description": "URL 子串或非 HTTP 关键词过滤(可选,如 'api' / 'login')"},
"body_contains": map[string]any{"type": "string", "description": "HTTP 正文全文搜索(可选,至少 3 个字符),匹配请求/响应头与正文"},
"action": map[string]any{"type": "string", "description": "非 HTTP 动作过滤(可选):allow / block / error / passthrough"},
"task_id": map[string]any{"type": "string", "description": "按任务 ID 过滤(可选)"},
"limit": map[string]any{"type": "integer", "description": "每页条数,默认 3,最大 10"},
"page": map[string]any{"type": "integer", "description": "页码,从 0 开始,默认 0(按 ts 倒序分页)"},
},
"required": []any{"host"},
},
ReadOnly: ro,
Permissions: allow,
Run: func(_ context.Context, in json.RawMessage, _ *actool.ToolContext) (actool.Result, error) {
var a struct {
Host, Contains string
BodyContains string `json:"body_contains"`
Limit int
Page int
Protocol string
Host string
Contains string
BodyContains string `json:"body_contains"`
Action string
TaskID string `json:"task_id"`
Limit int
Page int
}
_ = json.Unmarshal(in, &a)
if strings.TrimSpace(a.Host) == "" {
return actool.Errorf("host 为必填参数:请指定裸主机、主机:端口或完整 URL,避免全库扫描。"), nil
proto := strings.ToLower(strings.TrimSpace(a.Protocol))
if proto == "" {
proto = "http"
}
rows, err := t.query(a.Host, a.Contains, a.BodyContains, a.Page, a.Limit)
if err != nil {
return actool.Errorf(err.Error()), nil
limit := a.Limit
if limit <= 0 {
limit = 3
}
if len(rows) == 0 {
return actool.Text("无匹配流量。"), nil
if limit > 10 {
limit = 10
}
// 精简为最小索引:仅保留定位所需字段 + 响应码/长度,不带任何响应内容。
type liteRow struct {
ID string `json:"id"`
Method string `json:"method"`
URL string `json:"url"`
Status int `json:"status"`
RespLen int `json:"resp_len"`
switch proto {
case "dns":
kw := strings.TrimSpace(a.Host)
if kw == "" {
kw = strings.TrimSpace(a.Contains)
}
rows, _, err := t.PageDNSQueries(DNSQueryFilter{
Action: a.Action,
OwnerTaskID: a.TaskID,
Query: kw,
}, a.Page, limit)
if err != nil {
return actool.Errorf(err.Error()), nil
}
if len(rows) == 0 {
return actool.Text("无匹配 DNS 记录。"), nil
}
b, _ := json.Marshal(rows)
return actool.Text(string(b)), nil
case "tcp", "tls", "udp":
kw := strings.TrimSpace(a.Host)
if kw == "" {
kw = strings.TrimSpace(a.Contains)
}
rows, _, err := t.PageNetFlows(NetFlowQuery{
Protocol: proto,
Action: a.Action,
OwnerTaskID: a.TaskID,
Query: kw,
}, a.Page, limit)
if err != nil {
return actool.Errorf(err.Error()), nil
}
if len(rows) == 0 {
return actool.Text("无匹配非 HTTP 流量。"), nil
}
b, _ := json.Marshal(rows)
return actool.Text(string(b)), nil
default:
if strings.TrimSpace(a.Host) == "" {
return actool.Errorf("host 为必填参数:请指定裸主机、主机:端口或完整 URL,避免全库扫描。"), nil
}
rows, err := t.query(a.Host, a.Contains, a.BodyContains, a.Page, a.Limit)
if err != nil {
return actool.Errorf(err.Error()), nil
}
if len(rows) == 0 {
return actool.Text("无匹配流量。"), nil
}
type liteRow struct {
ID string `json:"id"`
Method string `json:"method"`
URL string `json:"url"`
Status int `json:"status"`
RespLen int `json:"resp_len"`
}
lite := make([]liteRow, 0, len(rows))
for _, r := range rows {
lite = append(lite, liteRow{ID: r.ID, Method: r.Method, URL: r.URL, Status: r.Status, RespLen: r.RespLen})
}
b, _ := json.Marshal(lite)
return actool.Text(string(b)), nil
}
lite := make([]liteRow, 0, len(rows))
for _, r := range rows {
lite = append(lite, liteRow{ID: r.ID, Method: r.Method, URL: r.URL, Status: r.Status, RespLen: r.RespLen})
}
b, _ := json.Marshal(lite)
return actool.Text(string(b)), nil
},
})
File diff suppressed because it is too large. Load diff
+523
View File
@@ -0,0 +1,523 @@
package traffic
import (
"bytes"
"crypto/tls"
"encoding/binary"
"encoding/json"
"io"
"net"
"net/http"
"net/http/httptest"
"net/url"
"strconv"
"strings"
"testing"
"time"
"github.com/miekg/dns"
)
func buildTestClientHello(sni string) []byte {
// Build minimal valid TLS 1.2 ClientHello with server_name extension.
var ext []byte
if sni != "" {
nameBytes := []byte(sni)
entry := make([]byte, 3+len(nameBytes))
entry[0] = 0x00 // host_name
binary.BigEndian.PutUint16(entry[1:3], uint16(len(nameBytes)))
copy(entry[3:], nameBytes)
list := make([]byte, 2+len(entry))
binary.BigEndian.PutUint16(list[0:2], uint16(len(entry)))
copy(list[2:], entry)
ext = make([]byte, 4+len(list))
binary.BigEndian.PutUint16(ext[0:2], 0x0000) // server_name ext type
binary.BigEndian.PutUint16(ext[2:4], uint16(len(list)))
copy(ext[4:], list)
}
var body bytes.Buffer
body.Write([]byte{0x03, 0x03}) // TLS 1.2
body.Write(make([]byte, 32)) // random
body.WriteByte(0x00) // session id len
body.Write([]byte{0x00, 0x02, 0x13, 0x01}) // cipher suites
body.Write([]byte{0x01, 0x00}) // compression methods
var extLen [2]byte
binary.BigEndian.PutUint16(extLen[:], uint16(len(ext)))
body.Write(extLen[:])
body.Write(ext)
hs := make([]byte, 4+body.Len())
hs[0] = 0x01 // ClientHello
hs[1] = byte((body.Len() >> 16) & 0xff)
hs[2] = byte((body.Len() >> 8) & 0xff)
hs[3] = byte(body.Len() & 0xff)
copy(hs[4:], body.Bytes())
rec := make([]byte, 5+len(hs))
rec[0] = 0x16 // Handshake
rec[1] = 0x03
rec[2] = 0x01
binary.BigEndian.PutUint16(rec[3:5], uint16(len(hs)))
copy(rec[5:], hs)
return rec
}
func TestSniffProtocol(t *testing.T) {
t.Run("TLS ClientHello SNI", func(t *testing.T) {
c1, c2 := net.Pipe()
defer c1.Close()
defer c2.Close()
ch := buildTestClientHello("api.target.example")
go func() { _, _ = c1.Write(ch) }()
res, wrapped := SniffProtocol(c2, 200*time.Millisecond)
if res.Proto != ProtoTLS || res.SNI != "api.target.example" {
t.Fatalf("expected TLS with SNI api.target.example, got %+v", res)
}
buf := make([]byte, len(ch))
if _, err := io.ReadFull(wrapped, buf); err != nil {
t.Fatalf("read replayed bytes: %v", err)
}
if !bytes.Equal(buf, ch) {
t.Fatalf("peeked bytes mismatch")
}
})
t.Run("Plaintext HTTP", func(t *testing.T) {
c1, c2 := net.Pipe()
defer c1.Close()
defer c2.Close()
req := []byte("GET /admin HTTP/1.1\r\nHost: web.target.local:8080\r\n\r\n")
go func() { _, _ = c1.Write(req) }()
res, wrapped := SniffProtocol(c2, 200*time.Millisecond)
if res.Proto != ProtoHTTP || res.Host != "web.target.local:8080" {
t.Fatalf("expected HTTP host web.target.local:8080, got %+v", res)
}
buf := make([]byte, len(req))
if _, err := io.ReadFull(wrapped, buf); err != nil {
t.Fatalf("read replayed bytes: %v", err)
}
if !bytes.Equal(buf, req) {
t.Fatalf("replayed HTTP mismatch")
}
})
t.Run("Raw TCP server-speaks-first timeout", func(t *testing.T) {
c1, c2 := net.Pipe()
defer c1.Close()
defer c2.Close()
start := time.Now()
res, _ := SniffProtocol(c2, 40*time.Millisecond)
if res.Proto != ProtoTCP {
t.Fatalf("expected ProtoTCP on timeout, got %+v", res)
}
if time.Since(start) > 500*time.Millisecond {
t.Fatalf("peek timeout took too long: %v", time.Since(start))
}
})
t.Run("Raw TCP binary protocol", func(t *testing.T) {
c1, c2 := net.Pipe()
defer c1.Close()
defer c2.Close()
payload := []byte("SSH-2.0-OpenSSH_9.6\r\n")
go func() { _, _ = c1.Write(payload) }()
res, _ := SniffProtocol(c2, 200*time.Millisecond)
if res.Proto != ProtoTCP {
t.Fatalf("expected ProtoTCP for SSH banner, got %+v", res)
}
})
}
func TestTransparentTCPAndBlacklistAndNetFlows(t *testing.T) {
tr, err := Open(t.TempDir(), "127.0.0.1:0")
if err != nil {
t.Fatalf("open traffic: %v", err)
}
defer tr.Close()
// Pretend loopback client belongs to task 77 container.
tr.SetSourceResolver(func(srcIP string) (SourceIdentity, bool) {
if srcIP == "127.0.0.1" {
return SourceIdentity{
Scope: "task",
OwnerID: "77",
ContainerID: "deadbeef12345678",
SrcIP: "172.30.0.9",
}, true
}
return SourceIdentity{}, false
})
// Start a raw TCP echo server (simulating Redis/nc/custom TCP service).
echoLn, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen echo: %v", err)
}
defer echoLn.Close()
go func() {
for {
c, err := echoLn.Accept()
if err != nil {
return
}
go func(conn net.Conn) {
defer conn.Close()
_, _ = conn.Write([]byte("+PONG-BANNER\r\n"))
buf := make([]byte, 64)
n, _ := conn.Read(buf)
if n > 0 {
_, _ = conn.Write([]byte("ECHO:" + string(buf[:n])))
}
}(c)
}
}()
echoAddr := echoLn.Addr().(*net.TCPAddr)
// Map echo IP to a domain in reverse DNS cache and test allow + block.
tr.RememberDNS(echoAddr.IP.String(), "redis.internal.test")
gw := NewTransparentGateway(TransparentConfig{
TCPAddr: "127.0.0.1:0",
PeekTimeout: 60 * time.Millisecond,
OrigDstResolver: func(_ net.Conn) (net.IP, int, error) {
return echoAddr.IP, echoAddr.Port, nil
},
}, LocalTransparentBackend{T: tr})
if err := gw.Start(); err != nil {
t.Fatalf("start transparent gateway: %v", err)
}
defer gw.Close()
// 1) Allowed raw TCP connection.
conn, err := net.DialTimeout("tcp", gw.TCPAddr(), 2*time.Second)
if err != nil {
t.Fatalf("dial gateway: %v", err)
}
_, _ = conn.Write([]byte("PING\r\n"))
got, _ := io.ReadAll(conn)
_ = conn.Close()
if !strings.Contains(string(got), "+PONG-BANNER") || !strings.Contains(string(got), "ECHO:PING") {
t.Fatalf("unexpected TCP relay response: %q", string(got))
}
// Wait briefly for flow persistence.
var flows []NetFlowRecord
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
rows, _, _ := tr.PageNetFlows(NetFlowQuery{OwnerTaskID: "77"}, 0, 10)
if len(rows) > 0 {
flows = rows
break
}
time.Sleep(20 * time.Millisecond)
}
if len(flows) != 1 {
t.Fatalf("expected 1 net_flow row, got %d", len(flows))
}
if flows[0].Protocol != "tcp" || flows[0].Action != "allow" || flows[0].DstHost != "redis.internal.test" {
t.Fatalf("unexpected flow row: %+v", flows[0])
}
if flows[0].BytesTX == 0 || flows[0].BytesRX == 0 {
t.Fatalf("expected non-zero bytes TX/RX: %+v", flows[0])
}
detail, err := tr.GetNetFlow(flows[0].ID)
if err != nil {
t.Fatalf("GetNetFlow: %v", err)
}
if !strings.Contains(detail.TXPreviewText, "PING") || !strings.Contains(detail.RXPreviewText, "PONG-BANNER") {
t.Fatalf("unexpected previews: tx=%q rx=%q", detail.TXPreviewText, detail.RXPreviewText)
}
// 2) Add egress blacklist for redis.internal.test -> next TCP flow must be blocked and recorded.
tr.SetEgressBlacklist([]EgressBlacklistRule{{
ID: "r1",
Enabled: true,
Kind: "suffix",
Pattern: "internal.test",
}})
conn2, err := net.DialTimeout("tcp", gw.TCPAddr(), 2*time.Second)
if err != nil {
t.Fatalf("dial gateway (blocked): %v", err)
}
_, _ = conn2.Write([]byte("PING\r\n"))
got2, _ := io.ReadAll(conn2)
_ = conn2.Close()
if len(got2) != 0 {
t.Fatalf("expected blocked TCP connection to receive 0 bytes, got %q", string(got2))
}
deadline = time.Now().Add(2 * time.Second)
var blockedFlows []NetFlowRecord
for time.Now().Before(deadline) {
rows, _, _ := tr.PageNetFlows(NetFlowQuery{Action: "block"}, 0, 10)
if len(rows) > 0 {
blockedFlows = rows
break
}
time.Sleep(20 * time.Millisecond)
}
if len(blockedFlows) != 1 || blockedFlows[0].BlockReason == "" {
t.Fatalf("expected 1 blocked net_flow, got %+v", blockedFlows)
}
// 3) Verify traffic_search tool queries tcp flows.
tools := tr.Tools()
rawArgs, _ := json.Marshal(map[string]any{"protocol": "tcp", "host": "redis.internal.test", "task_id": "77"})
res, err := tools[0].Call(t.Context(), rawArgs, nil)
if err != nil {
t.Fatalf("traffic_search tcp: %v", err)
}
if !strings.Contains(res.Flatten(), "redis.internal.test") {
t.Fatalf("expected traffic_search tcp to return flow, got %s", res.Flatten())
}
// 4) DeleteNonHTTPByOwner cleans up task 77's flows.
deleted, err := tr.DeleteNonHTTPByOwner("task", "77")
if err != nil || deleted < 2 {
t.Fatalf("expected >=2 deleted rows, got %d err=%v", deleted, err)
}
}
func TestTransparentDNSInterceptionAndBlocking(t *testing.T) {
tr, err := Open(t.TempDir(), "127.0.0.1:0")
if err != nil {
t.Fatalf("open traffic: %v", err)
}
defer tr.Close()
tr.SetSourceResolver(func(srcIP string) (SourceIdentity, bool) {
if srcIP == "127.0.0.1" {
return SourceIdentity{Scope: "task", OwnerID: "88", ContainerID: "cafebabe9999", SrcIP: "172.30.0.8"}, true
}
return SourceIdentity{}, false
})
tr.SetEgressBlacklist([]EgressBlacklistRule{
{ID: "b-dom", Enabled: true, Kind: "suffix", Pattern: "blocked.gov"},
{ID: "b-ip", Enabled: true, Kind: "ip", Pattern: "198.51.100.77"},
})
// Mock upstream authoritative DNS server on localhost.
upPC, err := net.ListenPacket("udp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen mock upstream dns: %v", err)
}
defer upPC.Close()
upMux := dns.NewServeMux()
upMux.HandleFunc(".", func(w dns.ResponseWriter, r *dns.Msg) {
m := new(dns.Msg)
m.SetReply(r)
if len(r.Question) > 0 {
q := r.Question[0]
ip := "93.184.216.34"
if strings.Contains(strings.ToLower(q.Name), "rebind.example") {
ip = "198.51.100.77"
}
m.Answer = append(m.Answer, &dns.A{
Hdr: dns.RR_Header{Name: q.Name, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 60},
A: net.ParseIP(ip),
})
}
_ = w.WriteMsg(m)
})
upSrv := &dns.Server{PacketConn: upPC, Handler: upMux}
go func() { _ = upSrv.ActivateAndServe() }()
defer upSrv.Shutdown()
tr.SetGatewaySettings(UDPPolicyBlockOnProxy, upPC.LocalAddr().String())
// Pick a free UDP+TCP port for the transparent DNS listener.
probeLn, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("probe port: %v", err)
}
dnsAddr := probeLn.Addr().String()
_ = probeLn.Close()
gw := NewTransparentGateway(TransparentConfig{DNSAddr: dnsAddr}, LocalTransparentBackend{T: tr})
if err := gw.Start(); err != nil {
t.Fatalf("start dns gateway: %v", err)
}
defer gw.Close()
c := &dns.Client{Net: "udp", Timeout: 2 * time.Second}
// 1) Allowed domain resolves and caches IP -> domain.
q1 := new(dns.Msg)
q1.SetQuestion("app.allowed.example.", dns.TypeA)
r1, _, err := c.Exchange(q1, dnsAddr)
if err != nil || r1.Rcode != dns.RcodeSuccess || len(r1.Answer) == 0 {
t.Fatalf("expected allowed DNS reply, got r1=%v err=%v", r1, err)
}
if rev := tr.LookupDNSReverse("93.184.216.34"); rev != "app.allowed.example" {
t.Fatalf("expected reverse DNS cache 'app.allowed.example', got %q", rev)
}
// 2) Blacklisted domain is REFUSED pre-resolution.
q2 := new(dns.Msg)
q2.SetQuestion("secret.blocked.gov.", dns.TypeA)
r2, _, err := c.Exchange(q2, dnsAddr)
if err != nil || r2.Rcode != dns.RcodeRefused {
t.Fatalf("expected REFUSED for blacklisted domain, got r2=%v err=%v", r2, err)
}
// 3) DNS rebinding / resolved blacklisted IP is REFUSED post-resolution.
q3 := new(dns.Msg)
q3.SetQuestion("rebind.example.", dns.TypeA)
r3, _, err := c.Exchange(q3, dnsAddr)
if err != nil || r3.Rcode != dns.RcodeRefused {
t.Fatalf("expected REFUSED for blacklisted resolved IP, got r3=%v err=%v", r3, err)
}
// Verify all 3 queries recorded in dns_queries with task attribution.
rows, total, err := tr.PageDNSQueries(DNSQueryFilter{OwnerTaskID: "88"}, 0, 10)
if err != nil || total != 3 || len(rows) != 3 {
t.Fatalf("expected 3 dns_queries rows, got total=%d len=%d err=%v", total, len(rows), err)
}
}
func TestTransparentUDPPolicy(t *testing.T) {
tr, err := Open(t.TempDir(), "127.0.0.1:0")
if err != nil {
t.Fatalf("open traffic: %v", err)
}
defer tr.Close()
// Set global upstream proxy + OPSEC default UDPPolicyBlockOnProxy.
if err := tr.SetUpstreamProxy("socks5://127.0.0.1:1080"); err != nil {
t.Fatalf("set upstream: %v", err)
}
tr.SetGatewaySettings(UDPPolicyBlockOnProxy, "")
gw := NewTransparentGateway(TransparentConfig{}, LocalTransparentBackend{T: tr})
src := &net.UDPAddr{IP: net.ParseIP("172.30.0.5"), Port: 54321}
dst := &net.UDPAddr{IP: net.ParseIP("93.184.216.34"), Port: 9999}
gw.HandleUDPPacket(src, dst, []byte("hello-udp"))
rows, total, err := tr.PageNetFlows(NetFlowQuery{Protocol: "udp", Action: "block"}, 0, 10)
if err != nil || total != 1 || len(rows) != 1 {
t.Fatalf("expected 1 blocked UDP flow under block_on_proxy, got total=%d err=%v", total, err)
}
if !strings.Contains(rows[0].BlockReason, "OPSEC") {
t.Fatalf("expected OPSEC block reason, got %q", rows[0].BlockReason)
}
}
func TestPerSourceUpstreamOverrideAndTransparentHTTPBridge(t *testing.T) {
// Start recording proxy on an ephemeral port.
probe, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("probe: %v", err)
}
proxyAddr := probe.Addr().String()
_ = probe.Close()
tr, err := Open(t.TempDir(), proxyAddr)
if err != nil {
t.Fatalf("open traffic: %v", err)
}
defer tr.Close()
tr.SetGatewayToken("gw-secret-token")
// Verify per-source upstream resolver precedence.
if err := tr.SetUpstreamProxy("http://127.0.0.1:19999"); err != nil {
t.Fatalf("set global upstream: %v", err)
}
directURL, _ := url.Parse("http://127.0.0.1:29999")
tr.SetUpstreamResolver(func(src SourceIdentity) (*url.URL, bool) {
if src.Scope == "task" && src.OwnerID == "10" {
return nil, true // force direct
}
if src.Scope == "task" && src.OwnerID == "20" {
return directURL, true // custom proxy
}
return nil, false // inherit global
})
if u := tr.resolveUpstreamForSource(SourceIdentity{Scope: "task", OwnerID: "10"}); u != nil {
t.Fatalf("task 10 should resolve to direct (nil), got %v", u)
}
if u := tr.resolveUpstreamForSource(SourceIdentity{Scope: "task", OwnerID: "20"}); u == nil || u.String() != directURL.String() {
t.Fatalf("task 20 should resolve to %v, got %v", directURL, u)
}
if u := tr.resolveUpstreamForSource(SourceIdentity{Scope: "task", OwnerID: "30"}); u == nil || u.Host != "127.0.0.1:19999" {
t.Fatalf("task 30 should inherit global proxy, got %v", u)
}
// Clear global proxy and start real go-mitmproxy to verify HTTP transparent bridge.
_ = tr.SetUpstreamProxy("")
go func() { _ = tr.Start() }()
// Wait for proxy port to listen.
for range 40 {
if c, derr := net.DialTimeout("tcp", proxyAddr, 50*time.Millisecond); derr == nil {
_ = c.Close()
break
}
time.Sleep(25 * time.Millisecond)
}
targetSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Proxy-Authorization") != "" {
w.WriteHeader(http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "text/plain")
_, _ = w.Write([]byte("transparent-http-ok"))
}))
defer targetSrv.Close()
tu, _ := url.Parse(targetSrv.URL)
th, tpStr, _ := net.SplitHostPort(tu.Host)
tp, _ := strconv.Atoi(tpStr)
tr.SetSourceResolver(func(srcIP string) (SourceIdentity, bool) {
if srcIP == "127.0.0.1" {
return SourceIdentity{Scope: "task", OwnerID: "10", ContainerID: "abc123456789", SrcIP: "172.30.0.10"}, true
}
return SourceIdentity{}, false
})
gw := NewTransparentGateway(TransparentConfig{
TCPAddr: "127.0.0.1:0",
MITMProxyAddr: proxyAddr,
OrigDstResolver: func(_ net.Conn) (net.IP, int, error) {
return net.ParseIP(th), tp, nil
},
}, LocalTransparentBackend{T: tr})
if err := gw.Start(); err != nil {
t.Fatalf("start gateway: %v", err)
}
defer gw.Close()
// Send origin-form HTTP directly to transparent gateway (simulating curl after `unset HTTP_PROXY`).
c, err := net.DialTimeout("tcp", gw.TCPAddr(), 2*time.Second)
if err != nil {
t.Fatalf("dial gw: %v", err)
}
_, _ = c.Write([]byte("GET /hello HTTP/1.1\r\nHost: " + tu.Host + "\r\nConnection: close\r\n\r\n"))
respBytes, _ := io.ReadAll(c)
_ = c.Close()
if !strings.Contains(string(respBytes), "transparent-http-ok") {
t.Fatalf("expected transparent HTTP response, got %q", string(respBytes))
}
// Verify exchange recorded with task 10 attribution.
deadline := time.Now().Add(2 * time.Second)
var rows []ExchangeMeta
for time.Now().Before(deadline) {
ex, _, _ := tr.Page(PageQuery{OwnerTaskID: "10", RespMin: -1, RespMax: -1}, 0, 10)
if len(ex) > 0 {
rows = ex
break
}
time.Sleep(25 * time.Millisecond)
}
if len(rows) == 0 || rows[0].SandboxOwnerID != "10" {
t.Fatalf("expected HTTP exchange attributed to task 10, got %+v", rows)
}
// Silence unused tls import check if not needed.
_ = tls.VersionTLS12
}