mirror of
https://github.com/RuoJi6/ARTEX.git
synced 2026-12-02 12:01:50 +08:00
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:
1 parent
9c43e694a3
commit
d786de90af
69 files changed
+13082
-1433
No files matched your search
@@ -45,7 +45,16 @@ ARTEX_SANDBOX_PIDS_LIMIT=256
|
||||
ARTEX_SANDBOX_SHM_MB=512
|
||||
ARTEX_SANDBOX_AUTO_STOP=true
|
||||
ARTEX_SANDBOX_SESSION_IDLE_MIN=20
|
||||
# 允许沙箱中经 file-cap (cap_net_raw+ep) 授权的 nmap / nping / ping 发起 SYN/UDP/ICMP 探测(所有 SUID/SGID 已剥离);
|
||||
# 如使用不受信任的第三方自定义镜像,请设为 false 以强制 no-new-privileges:true
|
||||
ARTEX_SANDBOX_ALLOW_NET_RAW=true
|
||||
# 抓包代理 SSRF 防护:本机/云元数据/ARTEX 自身与 postgres 网段始终禁止;设为 true 时额外拦截其他私有网段(内网渗透保持 false)
|
||||
ARTEX_PROXY_BLOCK_PRIVATE=false
|
||||
# 宿主机自己的局域网 IP(可逗号分隔)。这些地址上的 :8787/:8788 会被代理拒绝,其他端口仍可当作扫描目标
|
||||
ARTEX_PROXY_PROTECT_IPS=
|
||||
# 全流量透明代理网关(#218 Phase 3):开启后自动将沙箱容器的裸 TCP / UDP / DNS 全部收口到 artex-gateway
|
||||
ARTEX_SANDBOX_TRANSPARENT=true
|
||||
# artex 与 artex-gateway 之间的内部鉴权密钥(建议设为随机长字符串)
|
||||
ARTEX_GATEWAY_TOKEN=
|
||||
# 可选:覆盖沙箱容器默认 DNS(留空时自动使用 artex-sandbox 网桥网关 IP)
|
||||
ARTEX_SANDBOX_DNS=
|
||||
@@ -0,0 +1,19 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
#
|
||||
# ARTEX 沙箱全流量透明代理网关镜像(#218 Phase 3):
|
||||
# 仅本轻量容器持有 CAP_NET_ADMIN + network_mode: host,负责接管 artex-sandbox 网桥的
|
||||
# 全量 TCP / DNS / UDP 流量,消除环境变量绕过;沙箱容器继续保持非 root + CapDrop: ALL。
|
||||
FROM golang:1.26-bookworm AS builder
|
||||
WORKDIR /src
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
COPY . .
|
||||
RUN CGO_ENABLED=0 go build -ldflags="-s -w" -o /out/artex-gateway ./cmd/artex-gateway
|
||||
|
||||
FROM debian:bookworm-slim
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
ca-certificates iptables iproute2 tzdata \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
ENV TZ=Asia/Shanghai
|
||||
COPY --from=builder /out/artex-gateway /usr/local/bin/artex-gateway
|
||||
ENTRYPOINT ["/usr/local/bin/artex-gateway"]
|
||||
+22
-4
@@ -13,7 +13,7 @@ ENV TZ=Asia/Shanghai \
|
||||
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
ca-certificates ripgrep curl wget vim git jq unzip \
|
||||
tzdata procps \
|
||||
tzdata procps libcap2-bin \
|
||||
dnsutils iputils-ping netcat-openbsd inetutils-telnet whois nmap \
|
||||
&& curl -fsSL https://deb.nodesource.com/setup_22.x | bash - \
|
||||
&& apt-get install -y --no-install-recommends nodejs \
|
||||
@@ -24,8 +24,13 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
# 国内构建可传 --build-arg PLAYWRIGHT_DOWNLOAD_HOST=https://npmmirror.com/mirrors/playwright 加速。
|
||||
ARG PLAYWRIGHT_DOWNLOAD_HOST=""
|
||||
ENV PLAYWRIGHT_BROWSERS_PATH=/ms-playwright \
|
||||
PLAYWRIGHT_DOWNLOAD_HOST=${PLAYWRIGHT_DOWNLOAD_HOST}
|
||||
RUN mkdir -p /ms-playwright /workspace /etc/artex \
|
||||
PLAYWRIGHT_DOWNLOAD_HOST=${PLAYWRIGHT_DOWNLOAD_HOST} \
|
||||
SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt \
|
||||
CURL_CA_BUNDLE=/etc/ssl/certs/ca-certificates.crt \
|
||||
REQUESTS_CA_BUNDLE=/etc/ssl/certs/ca-certificates.crt \
|
||||
NODE_EXTRA_CA_CERTS=/etc/artex/ca.crt \
|
||||
NMAP_PRIVILEGED=1
|
||||
RUN mkdir -p /ms-playwright /workspace /etc/artex /usr/local/share/ca-certificates \
|
||||
&& npm install -g @playwright/mcp@latest @playwright/cli@latest \
|
||||
&& playwright-mcp --version \
|
||||
&& playwright-cli --help \
|
||||
@@ -36,11 +41,24 @@ RUN mkdir -p /ms-playwright /workspace /etc/artex \
|
||||
# 常用渗透/脚本 Python 依赖
|
||||
RUN pip install --no-cache-dir requests httpx beautifulsoup4 pyyaml
|
||||
|
||||
# 可选系统 CA 刷新辅助脚本(默认运行模式下由主服务直接只读挂载合并后的
|
||||
# /etc/ssl/certs/ca-certificates.crt,无需容器内 root 权限;若以 root 调试
|
||||
# 或自定义镜像启动,可运行此脚本通过 update-ca-certificates 注入 /etc/artex/ca.crt)。
|
||||
RUN printf '#!/bin/sh\nif [ -f /etc/artex/ca.crt ] && [ -w /usr/local/share/ca-certificates ]; then\n cp /etc/artex/ca.crt /usr/local/share/ca-certificates/artex-mitm-ca.crt\n update-ca-certificates >/dev/null 2>&1 || true\nfi\n' > /usr/local/bin/artex-update-ca.sh \
|
||||
&& chmod +x /usr/local/bin/artex-update-ca.sh
|
||||
|
||||
# 非 root 运行用户(UID/GID 1000,与 ARTEX_SANDBOX_USER 默认值对齐)。
|
||||
RUN groupadd -g 1000 sandbox \
|
||||
&& useradd -u 1000 -g 1000 -m -s /bin/bash sandbox \
|
||||
&& chown -R 1000:1000 /workspace
|
||||
|
||||
# 剥离所有 SUID/SGID 位防止提权,仅授予 nmap / nping / ping 最小必需的 cap_net_raw+ep
|
||||
# 文件能力(注意仅 +ep 而非 +eip,确保子进程/NSE os.execute 不继承任何 capability),
|
||||
# 使非 root 沙箱用户(uid 1000)无需 sudo 即可执行 nmap -sU/-sS、nping 与 ping,
|
||||
# 同时普通脚本与进程依然保持 CapEff=0。
|
||||
RUN find / -xdev -perm /6000 -type f -exec chmod a-s {} + 2>/dev/null || true \
|
||||
&& setcap cap_net_raw+ep /usr/bin/nmap \
|
||||
&& (setcap cap_net_raw+ep /usr/bin/nping 2>/dev/null || true) \
|
||||
&& (setcap cap_net_raw+ep /usr/bin/ping 2>/dev/null || setcap cap_net_raw+ep /bin/ping 2>/dev/null || true)
|
||||
USER 1000:1000
|
||||
WORKDIR /workspace
|
||||
CMD ["sleep", "infinity"]
|
||||
+17
-4
@@ -10,6 +10,7 @@ import (
|
||||
"github.com/Autumn-27/artex/guard"
|
||||
"github.com/Autumn-27/artex/intercept"
|
||||
"github.com/Autumn-27/artex/internal/sandbox"
|
||||
"github.com/Autumn-27/artex/traffic"
|
||||
"github.com/Autumn-27/norma/agentcore"
|
||||
"github.com/Autumn-27/norma/llm"
|
||||
"github.com/Autumn-27/norma/permission"
|
||||
@@ -153,9 +154,22 @@ func (c *ChatAgent) Chat(ctx context.Context, agentKey, sessionID, message strin
|
||||
if c.proxyAddrFn != nil {
|
||||
proxyAddr = c.proxyAddrFn()
|
||||
}
|
||||
bashEnv := proxyEnv(proxyAddr, c.proxyCACert)
|
||||
srcID := traffic.SourceIdentity{
|
||||
Scope: string(sbTarget.Scope),
|
||||
OwnerID: sbTarget.OwnerID,
|
||||
SessionID: sessionID,
|
||||
}
|
||||
webFetchProxy := proxyAddr
|
||||
if c.proxyCACert != "" && proxyAddr != "" {
|
||||
webFetchProxy = traffic.FormatProxyContextURL(proxyAddr, srcID)
|
||||
}
|
||||
bashEnv := proxyEnv(webFetchProxy, c.proxyCACert)
|
||||
if sandboxActive {
|
||||
bashEnv = sbMgr.ProxyEnv(proxyAddr != "")
|
||||
if proxyAddr != "" && c.proxyCACert != "" && sbMgr.Config().ProxyURL != "" {
|
||||
bashEnv = sbMgr.ProxyEnvWithURL(traffic.FormatProxyContextURL(sbMgr.Config().ProxyURL, srcID))
|
||||
} else {
|
||||
bashEnv = sbMgr.ProxyEnv(proxyAddr != "")
|
||||
}
|
||||
}
|
||||
opts := agentcore.Options{
|
||||
Provider: c.prov,
|
||||
@@ -166,9 +180,8 @@ func (c *ChatAgent) Chat(ctx context.Context, agentKey, sessionID, message strin
|
||||
UnlockSet: def.Unlock,
|
||||
PermissionMode: permission.ModeBypass,
|
||||
EnableWebFetch: true, // 走记录代理留痕;载入代理 CA 验证 MITM 重签的 HTTPS 证书
|
||||
WebFetchProxy: proxyAddr,
|
||||
WebFetchProxy: webFetchProxy,
|
||||
WebFetchCACert: c.proxyCACert,
|
||||
// 联网搜索(可选)。ddgs 无需 key;brave-free 需 BraveKey;tavily 需 TavilyKey。
|
||||
// WebSearchProxy 是独立出口代理(http/https/socks5),与记录流量的 MITM 代理无关;空则直连。
|
||||
EnableWebSearch: ws.Enabled && ws.Backend != "deepseek",
|
||||
WebSearchBackend: ws.Backend,
|
||||
|
||||
+16
-4
@@ -8,6 +8,7 @@ import (
|
||||
"github.com/Autumn-27/artex/db"
|
||||
"github.com/Autumn-27/artex/intercept"
|
||||
"github.com/Autumn-27/artex/internal/sandbox"
|
||||
"github.com/Autumn-27/artex/traffic"
|
||||
"github.com/Autumn-27/norma/agentcore"
|
||||
"github.com/Autumn-27/norma/llm"
|
||||
"github.com/Autumn-27/norma/permission"
|
||||
@@ -155,9 +156,21 @@ func (m *MainAgent) Chat(ctx context.Context, taskID int64, mainSeg int, as *db.
|
||||
if m.proxyAddrFn != nil {
|
||||
proxyAddr = m.proxyAddrFn()
|
||||
}
|
||||
bashEnv := proxyEnv(proxyAddr, m.proxyCACert)
|
||||
srcID := traffic.SourceIdentity{
|
||||
Scope: "task",
|
||||
OwnerID: strconv.FormatInt(taskID, 10),
|
||||
}
|
||||
webFetchProxy := proxyAddr
|
||||
if m.proxyCACert != "" && proxyAddr != "" && taskID > 0 {
|
||||
webFetchProxy = traffic.FormatProxyContextURL(proxyAddr, srcID)
|
||||
}
|
||||
bashEnv := proxyEnv(webFetchProxy, m.proxyCACert)
|
||||
if sandboxActive {
|
||||
bashEnv = sbMgr.ProxyEnv(proxyAddr != "")
|
||||
if proxyAddr != "" && m.proxyCACert != "" && sbMgr.Config().ProxyURL != "" {
|
||||
bashEnv = sbMgr.ProxyEnvWithURL(traffic.FormatProxyContextURL(sbMgr.Config().ProxyURL, srcID))
|
||||
} else {
|
||||
bashEnv = sbMgr.ProxyEnv(proxyAddr != "")
|
||||
}
|
||||
}
|
||||
opts := agentcore.Options{
|
||||
Provider: m.prov,
|
||||
@@ -168,9 +181,8 @@ func (m *MainAgent) Chat(ctx context.Context, taskID int64, mainSeg int, as *db.
|
||||
UnlockSet: def.Unlock,
|
||||
PermissionMode: permission.ModeBypass,
|
||||
EnableWebFetch: true, // 走记录代理留痕;载入代理 CA 验证 MITM 重签的 HTTPS 证书
|
||||
WebFetchProxy: proxyAddr,
|
||||
WebFetchProxy: webFetchProxy,
|
||||
WebFetchCACert: m.proxyCACert,
|
||||
// 联网搜索(可选)。ddgs 无需 key;brave-free 需 BraveKey;tavily 需 TavilyKey。
|
||||
// WebSearchProxy 是独立出口代理(http/https/socks5),与记录流量的 MITM 代理无关;空则直连。
|
||||
EnableWebSearch: m.webSearch.Enabled && m.webSearch.Backend != "deepseek",
|
||||
WebSearchBackend: m.webSearch.Backend,
|
||||
|
||||
+13
-5
@@ -4,11 +4,13 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
"github.com/Autumn-27/artex/intercept"
|
||||
"github.com/Autumn-27/artex/traffic"
|
||||
"github.com/Autumn-27/norma/agentcore"
|
||||
"github.com/Autumn-27/norma/llm"
|
||||
"github.com/Autumn-27/norma/permission"
|
||||
@@ -408,6 +410,13 @@ func (p *Planner) Plan(ctx context.Context, taskID int64, as *db.AssetStore, ts
|
||||
if p.proxyAddrFn != nil {
|
||||
proxyAddr = p.proxyAddrFn()
|
||||
}
|
||||
webFetchProxy := proxyAddr
|
||||
if p.proxyCACert != "" && proxyAddr != "" && taskID > 0 {
|
||||
webFetchProxy = traffic.FormatProxyContextURL(proxyAddr, traffic.SourceIdentity{
|
||||
Scope: "task",
|
||||
OwnerID: strconv.FormatInt(taskID, 10),
|
||||
})
|
||||
}
|
||||
opts := agentcore.Options{
|
||||
Provider: p.prov,
|
||||
SystemPrompt: system,
|
||||
@@ -417,18 +426,17 @@ func (p *Planner) Plan(ctx context.Context, taskID int64, as *db.AssetStore, ts
|
||||
UnlockSet: def.Unlock,
|
||||
PermissionMode: permission.ModeBypass,
|
||||
EnableWebFetch: true, // 走记录代理留痕;载入代理 CA 验证 MITM 重签的 HTTPS 证书
|
||||
WebFetchProxy: proxyAddr,
|
||||
WebFetchProxy: webFetchProxy,
|
||||
WebFetchCACert: p.proxyCACert,
|
||||
// 联网搜索(可选)。ddgs 无需 key;brave-free 需 BraveKey;tavily 需 TavilyKey。
|
||||
// WebSearchProxy 是独立出口代理(http/https/socks5),与记录流量的 MITM 代理无关;空则直连。
|
||||
// WebSearchProxy 是独立的出口代理(http/https/socks5),与记录流量的 MITM 代理无关;空则直连。
|
||||
EnableWebSearch: p.webSearch.Enabled && p.webSearch.Backend != "deepseek",
|
||||
WebSearchBackend: p.webSearch.Backend,
|
||||
BraveSearchAPIKey: p.webSearch.BraveKey,
|
||||
TavilySearchAPIKey: p.webSearch.TavilyKey,
|
||||
WebSearchProxy: p.webSearch.Proxy,
|
||||
BashEnv: proxyEnv(proxyAddr, p.proxyCACert), // Bash 子命令默认走代理+信任 CA
|
||||
WorkingDir: taskDir, // 本任务工作目录 <workDir>/tasks/<taskID>
|
||||
ToolOutputDir: cmdOutDir(taskDir),
|
||||
BashEnv: proxyEnv(webFetchProxy, p.proxyCACert), // Bash 子命令默认走代理+信任 CA
|
||||
WorkingDir: taskDir, // 本任务工作目录 <workDir>/tasks/<taskID>
|
||||
MaxTurns: p.maxTurns, // 0 = unlimited (configurable in agent management)
|
||||
MaxDuration: maxDur, // 0=不限;有 deadline 时=距 deadline 剩余
|
||||
Compaction: compactionConfig(p.compactionWindow()),
|
||||
|
||||
+17
-4
@@ -13,6 +13,7 @@ import (
|
||||
"github.com/Autumn-27/artex/db"
|
||||
"github.com/Autumn-27/artex/intercept"
|
||||
"github.com/Autumn-27/artex/internal/sandbox"
|
||||
"github.com/Autumn-27/artex/traffic"
|
||||
"github.com/Autumn-27/norma/agentcore"
|
||||
"github.com/Autumn-27/norma/harness"
|
||||
"github.com/Autumn-27/norma/llm"
|
||||
@@ -398,14 +399,27 @@ func (w *Worker) execute(ctx context.Context, name string, taskID int64, as *db.
|
||||
proxyAddr = w.proxyAddrFn()
|
||||
}
|
||||
sysProxyAddr, sysCACert, sysDataDir := proxyAddr, w.proxyCACert, w.workDir
|
||||
bashEnv := proxyEnv(proxyAddr, w.proxyCACert)
|
||||
srcID := traffic.SourceIdentity{
|
||||
Scope: "task",
|
||||
OwnerID: strconv.FormatInt(taskID, 10),
|
||||
IntentID: intent.ID,
|
||||
}
|
||||
webFetchProxy := proxyAddr
|
||||
if w.proxyCACert != "" && proxyAddr != "" {
|
||||
webFetchProxy = traffic.FormatProxyContextURL(proxyAddr, srcID)
|
||||
}
|
||||
bashEnv := proxyEnv(webFetchProxy, w.proxyCACert)
|
||||
if sandboxActive {
|
||||
if proxyAddr != "" && sbMgr.Config().ProxyURL != "" {
|
||||
sysProxyAddr = sbMgr.Config().ProxyURL
|
||||
sysCACert = sandbox.ContainerCACertPath
|
||||
}
|
||||
sysDataDir = sandbox.ContainerWorkDir
|
||||
bashEnv = sbMgr.ProxyEnv(proxyAddr != "")
|
||||
if proxyAddr != "" && w.proxyCACert != "" && sbMgr.Config().ProxyURL != "" {
|
||||
bashEnv = sbMgr.ProxyEnvWithURL(traffic.FormatProxyContextURL(sbMgr.Config().ProxyURL, srcID))
|
||||
} else {
|
||||
bashEnv = sbMgr.ProxyEnv(proxyAddr != "")
|
||||
}
|
||||
}
|
||||
sysBody := workerSystem(sysProxyAddr, sysCACert, sysDataDir, displayRunDir)
|
||||
if w.wantConstraints() {
|
||||
@@ -450,9 +464,8 @@ func (w *Worker) execute(ctx context.Context, name string, taskID int64, as *db.
|
||||
// WebFetch 走记录代理,其 HTTP 与 curl 一样被留痕;载入代理 CA 让经 MITM
|
||||
// 重签的 HTTPS 证书能【正常校验通过】(而非关掉校验)。proxy 空则直连。
|
||||
EnableWebFetch: true,
|
||||
WebFetchProxy: proxyAddr,
|
||||
WebFetchProxy: webFetchProxy,
|
||||
WebFetchCACert: w.proxyCACert,
|
||||
// 联网搜索(可选)。ddgs 无需 key;brave-free 需 BraveKey;tavily 需 TavilyKey。
|
||||
// WebSearchProxy 是独立的出口代理(http/https/socks5),与记录流量的 MITM 代理无关;空则直连。
|
||||
EnableWebSearch: w.webSearch.Enabled && w.webSearch.Backend != "deepseek",
|
||||
WebSearchBackend: w.webSearch.Backend,
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
//go:build linux
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
"os/exec"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
chainNAT = "ARTEX_GW_NAT"
|
||||
chainMangle = "ARTEX_GW_MANGLE"
|
||||
chainFwd = "ARTEX_GW_FWD"
|
||||
chainInput = "ARTEX_GW_INPUT"
|
||||
tproxyMark = "0x218"
|
||||
tproxyTable = "218"
|
||||
)
|
||||
|
||||
type iptablesConfig struct {
|
||||
Subnet string
|
||||
GatewayIP string
|
||||
TCPPort int
|
||||
UDPPort int
|
||||
DNSPort int
|
||||
ProxyPort int // explicit MITM proxy port (8788) allowed direct to artex
|
||||
AdminPort int // admin UI/API port (8787) explicitly rejected from sandbox
|
||||
BridgeName string
|
||||
}
|
||||
|
||||
// discoverSandboxBridge finds the Linux bridge interface owning gatewayIP or
|
||||
// subnet (e.g. br-xxxxxxxxxxxx for artex-sandbox).
|
||||
func discoverSandboxBridge(subnet, gatewayIP string, wait time.Duration) (string, error) {
|
||||
_, cidr, _ := net.ParseCIDR(strings.TrimSpace(subnet))
|
||||
gwIP := net.ParseIP(strings.TrimSpace(gatewayIP))
|
||||
if gwIP != nil {
|
||||
gwIP = gwIP.To4()
|
||||
}
|
||||
|
||||
deadline := time.Now().Add(wait)
|
||||
for {
|
||||
ifaces, err := net.Interfaces()
|
||||
if err == nil {
|
||||
for _, iface := range ifaces {
|
||||
addrs, aerr := iface.Addrs()
|
||||
if aerr != nil {
|
||||
continue
|
||||
}
|
||||
for _, a := range addrs {
|
||||
ipnet, ok := a.(*net.IPNet)
|
||||
if !ok || ipnet.IP == nil {
|
||||
continue
|
||||
}
|
||||
v4 := ipnet.IP.To4()
|
||||
if v4 == nil {
|
||||
continue
|
||||
}
|
||||
if gwIP != nil && v4.Equal(gwIP) {
|
||||
return iface.Name, nil
|
||||
}
|
||||
if cidr != nil && cidr.Contains(v4) {
|
||||
return iface.Name, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
break
|
||||
}
|
||||
time.Sleep(1 * time.Second)
|
||||
}
|
||||
return "", fmt.Errorf("sandbox bridge interface not found for subnet=%q gateway=%q", subnet, gatewayIP)
|
||||
}
|
||||
|
||||
func runCmd(name string, args ...string) error {
|
||||
out, err := exec.Command(name, args...).CombinedOutput()
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s %s: %w (%s)", name, strings.Join(args, " "), err, strings.TrimSpace(string(out)))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func runCmdIgnoreErr(name string, args ...string) {
|
||||
_ = exec.Command(name, args...).Run()
|
||||
}
|
||||
|
||||
func ensureJump(table, parent, chain string, matchArgs ...string) error {
|
||||
checkArgs := append([]string{"-t", table, "-C", parent}, matchArgs...)
|
||||
checkArgs = append(checkArgs, "-j", chain)
|
||||
if exec.Command("iptables", checkArgs...).Run() == nil {
|
||||
return nil
|
||||
}
|
||||
insArgs := append([]string{"-t", table, "-I", parent, "1"}, matchArgs...)
|
||||
insArgs = append(insArgs, "-j", chain)
|
||||
return runCmd("iptables", insArgs...)
|
||||
}
|
||||
|
||||
func ensureChain(table, chain string) error {
|
||||
_ = exec.Command("iptables", "-t", table, "-N", chain).Run()
|
||||
return runCmd("iptables", "-t", table, "-F", chain)
|
||||
}
|
||||
|
||||
// applyIPTables installs transparent TCP/DNS/UDP interception and anti-bypass
|
||||
// egress lockdown rules scoped strictly to the sandbox bridge interface.
|
||||
func applyIPTables(cfg iptablesConfig) error {
|
||||
br := cfg.BridgeName
|
||||
if br == "" {
|
||||
return fmt.Errorf("bridge name is empty")
|
||||
}
|
||||
subnet := strings.TrimSpace(cfg.Subnet)
|
||||
if subnet == "" {
|
||||
subnet = "172.30.0.0/16"
|
||||
}
|
||||
|
||||
// 1. Policy routing for UDP TPROXY (fwmark 0x218 -> local table 218).
|
||||
if cfg.UDPPort > 0 {
|
||||
runCmdIgnoreErr("ip", "rule", "del", "fwmark", tproxyMark, "lookup", tproxyTable)
|
||||
if err := runCmd("ip", "rule", "add", "fwmark", tproxyMark, "lookup", tproxyTable); err != nil {
|
||||
log.Printf("[gateway] warn: ip rule for UDP TPROXY failed (TCP/DNS still active): %v", err)
|
||||
} else {
|
||||
if err := runCmd("ip", "route", "replace", "local", "0.0.0.0/0", "dev", "lo", "table", tproxyTable); err != nil {
|
||||
log.Printf("[gateway] warn: ip route local for UDP TPROXY failed: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. NAT PREROUTING: redirect ALL DNS (UDP/TCP 53) and ALL non-sandbox TCP to gateway.
|
||||
if err := ensureChain("nat", chainNAT); err != nil {
|
||||
return err
|
||||
}
|
||||
// Allow explicit HTTP MITM proxy traffic straight to ARTEX (:8788) inside the sandbox subnet
|
||||
// so Phase 2 Proxy-Authorization tags and SNAT-free attribution keep working.
|
||||
if cfg.ProxyPort > 0 {
|
||||
if err := runCmd("iptables", "-t", "nat", "-A", chainNAT,
|
||||
"-d", subnet, "-p", "tcp", "--dport", strconv.Itoa(cfg.ProxyPort), "-j", "RETURN"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
// Never redirect :8787 admin traffic (explicitly rejected by INPUT / DOCKER-USER).
|
||||
if cfg.AdminPort > 0 {
|
||||
if err := runCmd("iptables", "-t", "nat", "-A", chainNAT,
|
||||
"-d", subnet, "-p", "tcp", "--dport", strconv.Itoa(cfg.AdminPort), "-j", "RETURN"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
// Intercept ALL DNS queries (both to bridge gateway and to external DNS like 8.8.8.8:53).
|
||||
if cfg.DNSPort > 0 {
|
||||
if err := runCmd("iptables", "-t", "nat", "-A", chainNAT,
|
||||
"-p", "udp", "--dport", "53", "-j", "REDIRECT", "--to-ports", strconv.Itoa(cfg.DNSPort)); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := runCmd("iptables", "-t", "nat", "-A", chainNAT,
|
||||
"-p", "tcp", "--dport", "53", "-j", "REDIRECT", "--to-ports", strconv.Itoa(cfg.DNSPort)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
// Intercept ALL external TCP traffic (HTTP, HTTPS, SSH, MySQL, Redis, nmap -sT, nc, raw sockets).
|
||||
if cfg.TCPPort > 0 {
|
||||
if err := runCmd("iptables", "-t", "nat", "-A", chainNAT,
|
||||
"-p", "tcp", "!", "-d", subnet, "-j", "REDIRECT", "--to-ports", strconv.Itoa(cfg.TCPPort)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := ensureJump("nat", "PREROUTING", chainNAT, "-i", br); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 3. MANGLE PREROUTING: TPROXY all non-DNS external UDP packets to gateway UDP listener.
|
||||
if cfg.UDPPort > 0 {
|
||||
if err := ensureChain("mangle", chainMangle); err != nil {
|
||||
log.Printf("[gateway] warn: create mangle chain failed: %v", err)
|
||||
} else {
|
||||
_ = runCmd("iptables", "-t", "mangle", "-A", chainMangle, "-d", subnet, "-j", "RETURN")
|
||||
_ = runCmd("iptables", "-t", "mangle", "-A", chainMangle, "-p", "udp", "--dport", "53", "-j", "RETURN")
|
||||
if err := runCmd("iptables", "-t", "mangle", "-A", chainMangle,
|
||||
"-p", "udp", "-j", "TPROXY", "--on-port", strconv.Itoa(cfg.UDPPort),
|
||||
"--on-ip", "127.0.0.1", "--tproxy-mark", tproxyMark+"/"+tproxyMark); err != nil {
|
||||
log.Printf("[gateway] warn: UDP TPROXY rule failed (TCP/DNS unaffected): %v", err)
|
||||
} else {
|
||||
_ = ensureJump("mangle", "PREROUTING", chainMangle, "-i", br)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 4. INPUT: allow redirected gateway listeners on sandbox bridge, reject :8787 admin port.
|
||||
if err := ensureChain("filter", chainInput); err != nil {
|
||||
return err
|
||||
}
|
||||
if cfg.AdminPort > 0 {
|
||||
_ = runCmd("iptables", "-t", "filter", "-A", chainInput, "-p", "tcp", "--dport", strconv.Itoa(cfg.AdminPort), "-j", "REJECT")
|
||||
}
|
||||
if cfg.TCPPort > 0 {
|
||||
_ = runCmd("iptables", "-t", "filter", "-A", chainInput, "-p", "tcp", "--dport", strconv.Itoa(cfg.TCPPort), "-j", "ACCEPT")
|
||||
}
|
||||
if cfg.DNSPort > 0 {
|
||||
_ = runCmd("iptables", "-t", "filter", "-A", chainInput, "-p", "udp", "--dport", strconv.Itoa(cfg.DNSPort), "-j", "ACCEPT")
|
||||
_ = runCmd("iptables", "-t", "filter", "-A", chainInput, "-p", "tcp", "--dport", strconv.Itoa(cfg.DNSPort), "-j", "ACCEPT")
|
||||
}
|
||||
if cfg.UDPPort > 0 {
|
||||
_ = runCmd("iptables", "-t", "filter", "-A", chainInput, "-p", "udp", "--dport", strconv.Itoa(cfg.UDPPort), "-j", "ACCEPT")
|
||||
}
|
||||
if err := ensureJump("filter", "INPUT", chainInput, "-i", br); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 5. DOCKER-USER: hard anti-bypass kill switch. Any packet from the sandbox bridge
|
||||
// trying to leave to another interface (direct NAT egress, artex-internal, metadata)
|
||||
// is REJECTED so sandbox containers can NEVER bypass the transparent gateway.
|
||||
if err := ensureChain("filter", chainFwd); err != nil {
|
||||
return err
|
||||
}
|
||||
_ = runCmd("iptables", "-t", "filter", "-A", chainFwd, "-d", "169.254.169.254/32", "-j", "REJECT")
|
||||
if cfg.AdminPort > 0 {
|
||||
_ = runCmd("iptables", "-t", "filter", "-A", chainFwd, "-p", "tcp", "--dport", strconv.Itoa(cfg.AdminPort), "-j", "REJECT")
|
||||
}
|
||||
// Reject any packet leaving the sandbox bridge to the outside / other Docker networks.
|
||||
if err := runCmd("iptables", "-t", "filter", "-A", chainFwd, "!", "-o", br, "-j", "REJECT"); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := ensureJump("filter", "DOCKER-USER", chainFwd, "-i", br); err != nil {
|
||||
log.Printf("[gateway] warn: attach DOCKER-USER failed (chain may not exist yet): %v", err)
|
||||
}
|
||||
|
||||
log.Printf("[gateway] iptables transparent interception active on bridge=%s subnet=%s tcp=:%d dns=:%d udp=:%d",
|
||||
br, subnet, cfg.TCPPort, cfg.DNSPort, cfg.UDPPort)
|
||||
return nil
|
||||
}
|
||||
|
||||
// cleanupIPTables removes all gateway-owned iptables jumps and chains on shutdown.
|
||||
func cleanupIPTables(cfg iptablesConfig) {
|
||||
br := cfg.BridgeName
|
||||
if br != "" {
|
||||
runCmdIgnoreErr("iptables", "-t", "nat", "-D", "PREROUTING", "-i", br, "-j", chainNAT)
|
||||
runCmdIgnoreErr("iptables", "-t", "mangle", "-D", "PREROUTING", "-i", br, "-j", chainMangle)
|
||||
runCmdIgnoreErr("iptables", "-t", "filter", "-D", "INPUT", "-i", br, "-j", chainInput)
|
||||
runCmdIgnoreErr("iptables", "-t", "filter", "-D", "DOCKER-USER", "-i", br, "-j", chainFwd)
|
||||
}
|
||||
for _, tc := range [][2]string{
|
||||
{"nat", chainNAT},
|
||||
{"mangle", chainMangle},
|
||||
{"filter", chainInput},
|
||||
{"filter", chainFwd},
|
||||
} {
|
||||
runCmdIgnoreErr("iptables", "-t", tc[0], "-F", tc[1])
|
||||
runCmdIgnoreErr("iptables", "-t", tc[0], "-X", tc[1])
|
||||
}
|
||||
runCmdIgnoreErr("ip", "rule", "del", "fwmark", tproxyMark, "lookup", tproxyTable)
|
||||
runCmdIgnoreErr("ip", "route", "flush", "table", tproxyTable)
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
//go:build !linux
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
type iptablesConfig struct {
|
||||
Subnet string
|
||||
GatewayIP string
|
||||
TCPPort int
|
||||
UDPPort int
|
||||
DNSPort int
|
||||
ProxyPort int
|
||||
AdminPort int
|
||||
BridgeName string
|
||||
}
|
||||
|
||||
func discoverSandboxBridge(_, _ string, _ time.Duration) (string, error) {
|
||||
return "", fmt.Errorf("iptables bridge discovery is only supported on Linux")
|
||||
}
|
||||
|
||||
func applyIPTables(_ iptablesConfig) error {
|
||||
return fmt.Errorf("iptables transparent interception is only supported on Linux")
|
||||
}
|
||||
|
||||
func cleanupIPTables(_ iptablesConfig) {}
|
||||
@@ -0,0 +1,307 @@
|
||||
// Command artex-gateway runs the dedicated transparent proxy gateway for ARTEX
|
||||
// sandbox containers (#218 Phase 3). Only this lightweight container holds
|
||||
// CAP_NET_ADMIN; sandbox containers remain non-root with CapDrop: ALL.
|
||||
//
|
||||
// In default TUN mode (ARTEX_GATEWAY_MODE=tun), all non-sandbox-subnet traffic
|
||||
// from artex-sandbox is policy-routed into artex-tun0 and processed by gVisor
|
||||
// netstack with deferred TCP handshakes so nmap/nc observe accurate open,
|
||||
// closed (RST), and filtered (timeout) port states with zero false positives.
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/Autumn-27/artex/traffic"
|
||||
)
|
||||
|
||||
func envStr(key, def string) string {
|
||||
if v := strings.TrimSpace(os.Getenv(key)); v != "" {
|
||||
return v
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
func envInt(key string, def int) int {
|
||||
raw := strings.TrimSpace(os.Getenv(key))
|
||||
if raw == "" {
|
||||
return def
|
||||
}
|
||||
n, err := strconv.Atoi(raw)
|
||||
if err != nil {
|
||||
return def
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func envBool(key string, def bool) bool {
|
||||
raw := strings.ToLower(strings.TrimSpace(os.Getenv(key)))
|
||||
if raw == "" {
|
||||
return def
|
||||
}
|
||||
return raw == "1" || raw == "true" || raw == "yes"
|
||||
}
|
||||
|
||||
type eventBuffer struct {
|
||||
mu sync.Mutex
|
||||
netFlows []traffic.NetFlowRecord
|
||||
dnsQueries []traffic.DNSQueryRecord
|
||||
blockEvents []traffic.EgressBlockEvent
|
||||
}
|
||||
|
||||
func (b *eventBuffer) addFlow(r traffic.NetFlowRecord) {
|
||||
b.mu.Lock()
|
||||
if len(b.netFlows) < 2048 {
|
||||
b.netFlows = append(b.netFlows, r)
|
||||
}
|
||||
b.mu.Unlock()
|
||||
}
|
||||
|
||||
func (b *eventBuffer) addDNS(r traffic.DNSQueryRecord) {
|
||||
b.mu.Lock()
|
||||
if len(b.dnsQueries) < 2048 {
|
||||
b.dnsQueries = append(b.dnsQueries, r)
|
||||
}
|
||||
b.mu.Unlock()
|
||||
}
|
||||
|
||||
func (b *eventBuffer) addBlock(ev traffic.EgressBlockEvent) {
|
||||
b.mu.Lock()
|
||||
if len(b.blockEvents) < 512 {
|
||||
b.blockEvents = append(b.blockEvents, ev)
|
||||
}
|
||||
b.mu.Unlock()
|
||||
}
|
||||
|
||||
func (b *eventBuffer) drain(gatewayID string) (traffic.GatewayEventBatch, bool) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
if len(b.netFlows) == 0 && len(b.dnsQueries) == 0 && len(b.blockEvents) == 0 {
|
||||
return traffic.GatewayEventBatch{}, false
|
||||
}
|
||||
batch := traffic.GatewayEventBatch{
|
||||
GatewayID: gatewayID,
|
||||
NetFlows: b.netFlows,
|
||||
DNSQueries: b.dnsQueries,
|
||||
BlockEvents: b.blockEvents,
|
||||
}
|
||||
b.netFlows = nil
|
||||
b.dnsQueries = nil
|
||||
b.blockEvents = nil
|
||||
return batch, true
|
||||
}
|
||||
|
||||
func main() {
|
||||
controlURL := strings.TrimRight(envStr("ARTEX_GATEWAY_CONTROL_URL", "http://127.0.0.1:8787"), "/")
|
||||
mitmAddr := envStr("ARTEX_GATEWAY_MITM_ADDR", "127.0.0.1:8788")
|
||||
token := envStr("ARTEX_GATEWAY_TOKEN", "")
|
||||
subnet := envStr("ARTEX_SANDBOX_SUBNET", "172.30.0.0/16")
|
||||
gatewayIP := envStr("ARTEX_SANDBOX_GATEWAY", "172.30.0.1")
|
||||
mode := strings.ToLower(envStr("ARTEX_GATEWAY_MODE", "tun"))
|
||||
tcpPort := envInt("ARTEX_GATEWAY_TCP_PORT", 15001)
|
||||
udpPort := envInt("ARTEX_GATEWAY_UDP_PORT", 15002)
|
||||
dnsPort := envInt("ARTEX_GATEWAY_DNS_PORT", 15053)
|
||||
proxyPort := envInt("ARTEX_GATEWAY_MITM_PORT", 8788)
|
||||
adminPort := envInt("ARTEX_GATEWAY_ADMIN_PORT", 8787)
|
||||
dialTimeoutSec := envInt("ARTEX_GATEWAY_DIAL_TIMEOUT_S", 5)
|
||||
applyRules := envBool("ARTEX_GATEWAY_APPLY_IPTABLES", runtime.GOOS == "linux")
|
||||
gatewayID, _ := os.Hostname()
|
||||
if gatewayID == "" {
|
||||
gatewayID = "artex-gateway"
|
||||
}
|
||||
|
||||
buf := &eventBuffer{}
|
||||
state := traffic.NewRemotePolicyState(token, buf.addFlow, buf.addDNS, buf.addBlock)
|
||||
|
||||
httpClient := &http.Client{Timeout: 5 * time.Second}
|
||||
syncPolicy := func() {
|
||||
req, err := http.NewRequest(http.MethodGet, controlURL+"/api/internal/gateway/policy?gateway_id="+gatewayID, nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if token != "" {
|
||||
req.Header.Set("X-Artex-Gateway-Token", token)
|
||||
}
|
||||
resp, err := httpClient.Do(req)
|
||||
if err != nil {
|
||||
log.Printf("[gateway] policy sync failed: %v", err)
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
log.Printf("[gateway] policy sync HTTP %d", resp.StatusCode)
|
||||
return
|
||||
}
|
||||
var snap traffic.GatewayPolicySnapshot
|
||||
if err := json.NewDecoder(resp.Body).Decode(&snap); err != nil {
|
||||
log.Printf("[gateway] policy decode failed: %v", err)
|
||||
return
|
||||
}
|
||||
state.Apply(snap)
|
||||
}
|
||||
|
||||
flushEvents := func() {
|
||||
batch, ok := buf.drain(gatewayID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
payload, err := json.Marshal(batch)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
req, err := http.NewRequest(http.MethodPost, controlURL+"/api/internal/gateway/events", bytes.NewReader(payload))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
if token != "" {
|
||||
req.Header.Set("X-Artex-Gateway-Token", token)
|
||||
}
|
||||
resp, err := httpClient.Do(req)
|
||||
if err != nil {
|
||||
log.Printf("[gateway] flush events failed: %v", err)
|
||||
return
|
||||
}
|
||||
_ = resp.Body.Close()
|
||||
}
|
||||
|
||||
// Initial policy fetch (best effort; retries continuously in background).
|
||||
syncPolicy()
|
||||
|
||||
var (
|
||||
gw *traffic.TransparentGateway
|
||||
netstackGW *traffic.NetstackGateway
|
||||
iptCfg iptablesConfig
|
||||
tunModeActive bool
|
||||
iptablesApplied bool
|
||||
)
|
||||
|
||||
if mode == "tun" && runtime.GOOS == "linux" {
|
||||
tunDev, tunErr := openTUN(tunDeviceName)
|
||||
if tunErr != nil {
|
||||
log.Printf("[gateway] warn: open TUN failed (%v); falling back to iptables REDIRECT mode", tunErr)
|
||||
mode = "redirect"
|
||||
} else {
|
||||
ns, nsErr := traffic.NewNetstackGateway(tunDev, traffic.NetstackConfig{
|
||||
MITMProxyAddr: mitmAddr,
|
||||
DialTimeout: time.Duration(dialTimeoutSec) * time.Second,
|
||||
AllowedSrcCIDR: subnet,
|
||||
DeniedSrcIPs: []string{gatewayIP},
|
||||
}, state)
|
||||
if nsErr != nil {
|
||||
_ = tunDev.Close()
|
||||
log.Fatalf("[gateway] init netstack failed: %v", nsErr)
|
||||
}
|
||||
netstackGW = ns
|
||||
tunModeActive = true
|
||||
|
||||
// Also listen on DNS port (:15053) for bridge-gateway DNS queries (172.30.0.1:53).
|
||||
gw = traffic.NewTransparentGateway(traffic.TransparentConfig{
|
||||
DNSAddr: fmt.Sprintf("0.0.0.0:%d", dnsPort),
|
||||
MITMProxyAddr: mitmAddr,
|
||||
}, state)
|
||||
if err := gw.Start(); err != nil {
|
||||
_ = netstackGW.Close()
|
||||
log.Fatalf("[gateway] start dns listener failed: %v", err)
|
||||
}
|
||||
log.Printf("[gateway] mode=tun (gVisor netstack deferred-handshake) tun=%s dns=:%d mitm=%s control=%s",
|
||||
tunDeviceName, dnsPort, mitmAddr, controlURL)
|
||||
}
|
||||
}
|
||||
|
||||
if !tunModeActive {
|
||||
gw = traffic.NewTransparentGateway(traffic.TransparentConfig{
|
||||
TCPAddr: fmt.Sprintf("0.0.0.0:%d", tcpPort),
|
||||
DNSAddr: fmt.Sprintf("0.0.0.0:%d", dnsPort),
|
||||
UDPAddr: fmt.Sprintf("0.0.0.0:%d", udpPort),
|
||||
MITMProxyAddr: mitmAddr,
|
||||
DialTimeout: time.Duration(dialTimeoutSec) * time.Second,
|
||||
}, state)
|
||||
if err := gw.Start(); err != nil {
|
||||
log.Fatalf("[gateway] start failed: %v", err)
|
||||
}
|
||||
log.Printf("[gateway] mode=redirect listeners active tcp=:%d dns=:%d udp=:%d mitm=%s control=%s",
|
||||
tcpPort, dnsPort, udpPort, mitmAddr, controlURL)
|
||||
}
|
||||
|
||||
if applyRules {
|
||||
br, err := discoverSandboxBridge(subnet, gatewayIP, 30*time.Second)
|
||||
if err != nil {
|
||||
log.Printf("[gateway] warn: %v (listeners running; check ARTEX_SANDBOX_SUBNET)", err)
|
||||
} else {
|
||||
iptCfg = iptablesConfig{
|
||||
Subnet: subnet,
|
||||
GatewayIP: gatewayIP,
|
||||
TCPPort: tcpPort,
|
||||
UDPPort: udpPort,
|
||||
DNSPort: dnsPort,
|
||||
ProxyPort: proxyPort,
|
||||
AdminPort: adminPort,
|
||||
BridgeName: br,
|
||||
}
|
||||
if tunModeActive {
|
||||
if err := applyTunRouting(iptCfg); err != nil {
|
||||
log.Printf("[gateway] warn: apply TUN routing failed: %v", err)
|
||||
} else {
|
||||
iptablesApplied = true
|
||||
}
|
||||
} else {
|
||||
if err := applyIPTables(iptCfg); err != nil {
|
||||
log.Printf("[gateway] warn: apply iptables failed: %v", err)
|
||||
} else {
|
||||
iptablesApplied = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Start netstack TUN packet pumps AFTER applyTunRouting brings artex-tun0 UP.
|
||||
if netstackGW != nil {
|
||||
netstackGW.Start()
|
||||
}
|
||||
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
policyTicker := time.NewTicker(2 * time.Second)
|
||||
flushTicker := time.NewTicker(500 * time.Millisecond)
|
||||
defer policyTicker.Stop()
|
||||
defer flushTicker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
log.Println("[gateway] shutting down...")
|
||||
if iptablesApplied {
|
||||
if tunModeActive {
|
||||
cleanupTunRouting(iptCfg)
|
||||
} else {
|
||||
cleanupIPTables(iptCfg)
|
||||
}
|
||||
}
|
||||
if netstackGW != nil {
|
||||
_ = netstackGW.Close()
|
||||
}
|
||||
if gw != nil {
|
||||
_ = gw.Close()
|
||||
}
|
||||
flushEvents()
|
||||
return
|
||||
case <-policyTicker.C:
|
||||
syncPolicy()
|
||||
case <-flushTicker.C:
|
||||
flushEvents()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
//go:build linux
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unsafe"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
const (
|
||||
tunDeviceName = "artex-tun0"
|
||||
tunRouteTable = "218"
|
||||
tunRulePrio = "218"
|
||||
tunLinkIP = "198.18.0.1/32"
|
||||
)
|
||||
|
||||
type ifReq struct {
|
||||
Name [unix.IFNAMSIZ]byte
|
||||
Flags uint16
|
||||
_ [22]byte
|
||||
}
|
||||
|
||||
// openTUN creates a Linux TUN interface (IFF_TUN | IFF_NO_PI) named devName.
|
||||
// Perform open + TUNSETIFF + SetNonblock(true) BEFORE wrapping with os.NewFile
|
||||
// so Go's netpoller registers the fd AFTER the TUN device is bound and keeps
|
||||
// O_NONBLOCK enabled (calling os.File.Fd() clears O_NONBLOCK and breaks epoll
|
||||
// readiness on /dev/net/tun).
|
||||
func openTUN(devName string) (io.ReadWriteCloser, error) {
|
||||
fd, err := unix.Open("/dev/net/tun", unix.O_RDWR|unix.O_CLOEXEC, 0)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open /dev/net/tun: %w", err)
|
||||
}
|
||||
var req ifReq
|
||||
copy(req.Name[:], devName)
|
||||
req.Flags = unix.IFF_TUN | unix.IFF_NO_PI
|
||||
_, _, errno := unix.Syscall(
|
||||
unix.SYS_IOCTL,
|
||||
uintptr(fd),
|
||||
uintptr(unix.TUNSETIFF),
|
||||
uintptr(unsafe.Pointer(&req)),
|
||||
)
|
||||
if errno != 0 {
|
||||
_ = unix.Close(fd)
|
||||
return nil, fmt.Errorf("ioctl TUNSETIFF %s: %w", devName, errno)
|
||||
}
|
||||
if err := unix.SetNonblock(fd, true); err != nil {
|
||||
_ = unix.Close(fd)
|
||||
return nil, fmt.Errorf("setnonblock %s: %w", devName, err)
|
||||
}
|
||||
return os.NewFile(uintptr(fd), "/dev/net/tun"), nil
|
||||
}
|
||||
|
||||
// applyTunRouting configures policy routing and minimal anti-bypass iptables
|
||||
// rules so ALL non-sandbox-subnet traffic from bridge br enters artex-tun0
|
||||
// without SNAT/MASQUERADE (preserving real sandbox container source IPs) and
|
||||
// without TCP REDIRECT (preserving deferred-handshake open/closed/filtered semantics).
|
||||
func applyTunRouting(cfg iptablesConfig) error {
|
||||
br := cfg.BridgeName
|
||||
if br == "" {
|
||||
return fmt.Errorf("bridge name is empty")
|
||||
}
|
||||
subnet := strings.TrimSpace(cfg.Subnet)
|
||||
if subnet == "" {
|
||||
subnet = "172.30.0.0/16"
|
||||
}
|
||||
gwIP := strings.TrimSpace(cfg.GatewayIP)
|
||||
if gwIP == "" {
|
||||
gwIP = "172.30.0.1"
|
||||
}
|
||||
|
||||
// Clean any stale redirect/mangle rules from a prior gateway mode first.
|
||||
cleanupIPTables(cfg)
|
||||
|
||||
// 1. Bring up TUN interface and disable rp_filter so gVisor-spoofed reply
|
||||
// packets from external IPs back to sandbox containers are never dropped.
|
||||
if err := runCmd("ip", "link", "set", "dev", tunDeviceName, "mtu", "1500", "up"); err != nil {
|
||||
return err
|
||||
}
|
||||
_ = runCmd("ip", "addr", "replace", tunLinkIP, "dev", tunDeviceName)
|
||||
_ = os.WriteFile("/proc/sys/net/ipv4/conf/"+tunDeviceName+"/rp_filter", []byte("0\n"), 0o644)
|
||||
_ = os.WriteFile("/proc/sys/net/ipv4/conf/"+br+"/rp_filter", []byte("0\n"), 0o644)
|
||||
_ = os.WriteFile("/proc/sys/net/ipv4/ip_forward", []byte("1\n"), 0o644)
|
||||
|
||||
// 2. Policy routing table 218: keep sandbox-subnet traffic on bridge, route
|
||||
// everything else from sandbox bridge into artex-tun0.
|
||||
if err := runCmd("ip", "route", "replace", subnet, "dev", br, "table", tunRouteTable); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := runCmd("ip", "route", "replace", "default", "dev", tunDeviceName, "table", tunRouteTable); err != nil {
|
||||
return err
|
||||
}
|
||||
runCmdIgnoreErr("ip", "rule", "del", "iif", br, "lookup", tunRouteTable, "priority", tunRulePrio)
|
||||
if err := runCmd("ip", "rule", "add", "iif", br, "lookup", tunRouteTable, "priority", tunRulePrio); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 2b. Docker 28+ adds `raw PREROUTING ! -i <br> -d <container_ip> -j DROP`
|
||||
// for every running container on a bridge. Reply packets written back by
|
||||
// gVisor on artex-tun0 arrive with iif=artex-tun0 (!= br) destined for the
|
||||
// sandbox subnet, so accept them at the top of raw PREROUTING.
|
||||
if exec.Command("iptables", "-t", "raw", "-C", "PREROUTING", "-i", tunDeviceName, "-d", subnet, "-j", "ACCEPT").Run() != nil {
|
||||
if err := runCmd("iptables", "-t", "raw", "-I", "PREROUTING", "1", "-i", tunDeviceName, "-d", subnet, "-j", "ACCEPT"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
// 3. Exempt artex-tun0 from Docker's NAT POSTROUTING MASQUERADE rule so
|
||||
// packets entering netstack retain each sandbox container's real source IP.
|
||||
if exec.Command("iptables", "-t", "nat", "-C", "POSTROUTING", "-o", tunDeviceName, "-j", "ACCEPT").Run() != nil {
|
||||
if err := runCmd("iptables", "-t", "nat", "-I", "POSTROUTING", "1", "-o", tunDeviceName, "-j", "ACCEPT"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// 4. NAT PREROUTING: ONLY redirect DNS queries addressed directly to the
|
||||
// bridge gateway IP (Docker embedded DNS 127.0.0.11 -> 172.30.0.1:53) to
|
||||
// our DNS listener (:15053). External DNS (@8.8.8.8) and all external TCP/UDP
|
||||
// flow natively into artex-tun0 without REDIRECT.
|
||||
if cfg.DNSPort > 0 {
|
||||
if err := ensureChain("nat", chainNAT); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := runCmd("iptables", "-t", "nat", "-A", chainNAT,
|
||||
"-d", gwIP+"/32", "-p", "udp", "--dport", "53", "-j", "REDIRECT", "--to-ports", strconv.Itoa(cfg.DNSPort)); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := runCmd("iptables", "-t", "nat", "-A", chainNAT,
|
||||
"-d", gwIP+"/32", "-p", "tcp", "--dport", "53", "-j", "REDIRECT", "--to-ports", strconv.Itoa(cfg.DNSPort)); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := ensureJump("nat", "PREROUTING", chainNAT, "-i", br); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// 5. INPUT: block :8787 admin port from sandbox bridge, accept bridge DNS (:15053).
|
||||
if err := ensureChain("filter", chainInput); err != nil {
|
||||
return err
|
||||
}
|
||||
// Anti-spoofing: reject packets from the sandbox bridge claiming a source IP
|
||||
// outside the sandbox subnet or impersonating the bridge gateway IP.
|
||||
_ = runCmd("iptables", "-t", "filter", "-A", chainInput, "!", "-s", subnet, "-j", "DROP")
|
||||
_ = runCmd("iptables", "-t", "filter", "-A", chainInput, "-s", gwIP+"/32", "-j", "DROP")
|
||||
if cfg.AdminPort > 0 {
|
||||
_ = runCmd("iptables", "-t", "filter", "-A", chainInput, "-p", "tcp", "--dport", strconv.Itoa(cfg.AdminPort), "-j", "REJECT")
|
||||
}
|
||||
if cfg.DNSPort > 0 {
|
||||
_ = runCmd("iptables", "-t", "filter", "-A", chainInput, "-p", "udp", "--dport", strconv.Itoa(cfg.DNSPort), "-j", "ACCEPT")
|
||||
_ = runCmd("iptables", "-t", "filter", "-A", chainInput, "-p", "tcp", "--dport", strconv.Itoa(cfg.DNSPort), "-j", "ACCEPT")
|
||||
}
|
||||
if err := ensureJump("filter", "INPUT", chainInput, "-i", br); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 6. DOCKER-USER: allow br <-> artex-tun0 and explicit proxy :8788; reject
|
||||
// spoofed source IPs (CAP_NET_RAW mitigation), cloud metadata, :8787, and any
|
||||
// direct NAT bypass off the sandbox bridge.
|
||||
if err := ensureChain("filter", chainFwd); err != nil {
|
||||
return err
|
||||
}
|
||||
_ = runCmd("iptables", "-t", "filter", "-A", chainFwd, "!", "-s", subnet, "-j", "DROP")
|
||||
_ = runCmd("iptables", "-t", "filter", "-A", chainFwd, "-s", gwIP+"/32", "-j", "DROP")
|
||||
_ = runCmd("iptables", "-t", "filter", "-A", chainFwd, "-d", "169.254.169.254/32", "-j", "REJECT")
|
||||
if cfg.AdminPort > 0 {
|
||||
_ = runCmd("iptables", "-t", "filter", "-A", chainFwd, "-p", "tcp", "--dport", strconv.Itoa(cfg.AdminPort), "-j", "REJECT")
|
||||
}
|
||||
if err := runCmd("iptables", "-t", "filter", "-A", chainFwd, "-o", tunDeviceName, "-j", "ACCEPT"); err != nil {
|
||||
return err
|
||||
}
|
||||
if cfg.ProxyPort > 0 {
|
||||
_ = runCmd("iptables", "-t", "filter", "-A", chainFwd, "-o", br, "-d", subnet, "-p", "tcp", "--dport", strconv.Itoa(cfg.ProxyPort), "-j", "ACCEPT")
|
||||
_ = runCmd("iptables", "-t", "filter", "-A", chainFwd, "-o", br, "-s", subnet, "-m", "conntrack", "--ctstate", "ESTABLISHED,RELATED", "-j", "ACCEPT")
|
||||
}
|
||||
if err := runCmd("iptables", "-t", "filter", "-A", chainFwd, "!", "-o", br, "-j", "REJECT"); err != nil {
|
||||
return err
|
||||
}
|
||||
// Ensure reply packets from artex-tun0 back to sandbox containers are accepted before DOCKER-ISOLATION.
|
||||
if exec.Command("iptables", "-t", "filter", "-C", "DOCKER-USER", "-i", tunDeviceName, "-o", br, "-j", "ACCEPT").Run() != nil {
|
||||
_ = runCmd("iptables", "-t", "filter", "-I", "DOCKER-USER", "1", "-i", tunDeviceName, "-o", br, "-j", "ACCEPT")
|
||||
}
|
||||
if err := ensureJump("filter", "DOCKER-USER", chainFwd, "-i", br); err != nil {
|
||||
log.Printf("[gateway] warn: attach DOCKER-USER failed: %v", err)
|
||||
}
|
||||
|
||||
log.Printf("[gateway] TUN + gVisor netstack routing active bridge=%s tun=%s subnet=%s dns=:%d",
|
||||
br, tunDeviceName, subnet, cfg.DNSPort)
|
||||
return nil
|
||||
}
|
||||
|
||||
func cleanupTunRouting(cfg iptablesConfig) {
|
||||
br := cfg.BridgeName
|
||||
if br != "" {
|
||||
runCmdIgnoreErr("ip", "rule", "del", "iif", br, "lookup", tunRouteTable, "priority", tunRulePrio)
|
||||
runCmdIgnoreErr("iptables", "-t", "filter", "-D", "DOCKER-USER", "-i", tunDeviceName, "-o", br, "-j", "ACCEPT")
|
||||
}
|
||||
runCmdIgnoreErr("ip", "route", "flush", "table", tunRouteTable)
|
||||
runCmdIgnoreErr("iptables", "-t", "nat", "-D", "POSTROUTING", "-o", tunDeviceName, "-j", "ACCEPT")
|
||||
subnet := strings.TrimSpace(cfg.Subnet)
|
||||
if subnet == "" {
|
||||
subnet = "172.30.0.0/16"
|
||||
}
|
||||
runCmdIgnoreErr("iptables", "-t", "raw", "-D", "PREROUTING", "-i", tunDeviceName, "-d", subnet, "-j", "ACCEPT")
|
||||
cleanupIPTables(cfg)
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
//go:build !linux
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
)
|
||||
|
||||
const tunDeviceName = "artex-tun0"
|
||||
|
||||
func openTUN(_ string) (io.ReadWriteCloser, error) {
|
||||
return nil, fmt.Errorf("TUN interface is only supported on Linux")
|
||||
}
|
||||
|
||||
func applyTunRouting(_ iptablesConfig) error {
|
||||
return fmt.Errorf("TUN policy routing is only supported on Linux")
|
||||
}
|
||||
|
||||
func cleanupTunRouting(_ iptablesConfig) {}
|
||||
@@ -72,9 +72,16 @@ services:
|
||||
ARTEX_SANDBOX_SHM_MB: ${ARTEX_SANDBOX_SHM_MB:-512}
|
||||
ARTEX_SANDBOX_AUTO_STOP: ${ARTEX_SANDBOX_AUTO_STOP:-true}
|
||||
ARTEX_SANDBOX_SESSION_IDLE_MIN: ${ARTEX_SANDBOX_SESSION_IDLE_MIN:-20}
|
||||
# 允许沙箱内经 file-cap 授权的 nmap/nping/ping 使用 CAP_NET_RAW(普通进程 CapEff=0);
|
||||
# 若运行不受信任的自定义镜像可设为 false 以强制开启 no-new-privileges:true
|
||||
ARTEX_SANDBOX_ALLOW_NET_RAW: ${ARTEX_SANDBOX_ALLOW_NET_RAW:-true}
|
||||
ARTEX_PROXY_BLOCK_PRIVATE: ${ARTEX_PROXY_BLOCK_PRIVATE:-false}
|
||||
# 宿主机局域网地址。这些地址上的其他端口仍可扫描;:8787 / :8788 由抓包代理拒绝,避免沙箱借代理回连管理口。
|
||||
ARTEX_PROXY_PROTECT_IPS: ${ARTEX_PROXY_PROTECT_IPS:-}
|
||||
# 全流量透明代理网关配置(#218 Phase 3:与 artex-gateway 共享鉴权令牌)
|
||||
ARTEX_SANDBOX_TRANSPARENT: ${ARTEX_SANDBOX_TRANSPARENT:-true}
|
||||
ARTEX_SANDBOX_DNS: ${ARTEX_SANDBOX_DNS:-}
|
||||
ARTEX_GATEWAY_TOKEN: ${ARTEX_GATEWAY_TOKEN:-}
|
||||
ports:
|
||||
- "8787:8787"
|
||||
- "8788:8788"
|
||||
@@ -87,12 +94,47 @@ services:
|
||||
- ./skills:/app/skills
|
||||
networks:
|
||||
- artex-internal
|
||||
# 直接接入 artex-sandbox 二层网段以消除网桥 SNAT,让抓包代理拿到真实沙箱容器源 IP(#218)。
|
||||
# 需配合 scripts/artex-sandbox-firewall.sh 仅放行沙箱网桥到本容器 :8788,并阻断 :8787 管理口。
|
||||
- artex-sandbox
|
||||
# 主服务已剥离重工具链,资源上限主要用于控制面进程
|
||||
mem_limit: ${ARTEX_MEMORY_LIMIT:-2g}
|
||||
memswap_limit: ${ARTEX_MEMORY_LIMIT:-2g}
|
||||
pids_limit: ${ARTEX_PIDS_LIMIT:-512}
|
||||
restart: unless-stopped
|
||||
|
||||
# 独立透明代理网关(#218 Phase 3):仅本容器持有 CAP_NET_ADMIN,接管 artex-sandbox 网桥的
|
||||
# 全部 TCP / DNS / UDP 流量并阻断直连外网 NAT,沙箱容器继续保持非 root + CapDrop: ALL。
|
||||
artex-gateway:
|
||||
image: ${ARTEX_GATEWAY_IMAGE:-ruoji6/artex-gateway}:${ARTEX_TAG:-latest}
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile.gateway
|
||||
depends_on:
|
||||
artex:
|
||||
condition: service_started
|
||||
network_mode: host
|
||||
cap_add:
|
||||
- NET_ADMIN
|
||||
- NET_RAW
|
||||
devices:
|
||||
- /dev/net/tun:/dev/net/tun
|
||||
environment:
|
||||
TZ: Asia/Shanghai
|
||||
ARTEX_GATEWAY_CONTROL_URL: http://127.0.0.1:8787
|
||||
ARTEX_GATEWAY_MITM_ADDR: 127.0.0.1:8788
|
||||
ARTEX_GATEWAY_TOKEN: ${ARTEX_GATEWAY_TOKEN:-}
|
||||
ARTEX_GATEWAY_MODE: ${ARTEX_GATEWAY_MODE:-tun}
|
||||
ARTEX_SANDBOX_SUBNET: ${ARTEX_SANDBOX_SUBNET:-172.30.0.0/16}
|
||||
ARTEX_SANDBOX_GATEWAY: ${ARTEX_SANDBOX_GATEWAY:-172.30.0.1}
|
||||
ARTEX_GATEWAY_TCP_PORT: ${ARTEX_GATEWAY_TCP_PORT:-15001}
|
||||
ARTEX_GATEWAY_UDP_PORT: ${ARTEX_GATEWAY_UDP_PORT:-15002}
|
||||
ARTEX_GATEWAY_DNS_PORT: ${ARTEX_GATEWAY_DNS_PORT:-15053}
|
||||
ARTEX_GATEWAY_APPLY_IPTABLES: ${ARTEX_GATEWAY_APPLY_IPTABLES:-true}
|
||||
mem_limit: 256m
|
||||
pids_limit: 128
|
||||
restart: unless-stopped
|
||||
|
||||
networks:
|
||||
artex-internal:
|
||||
driver: bridge
|
||||
|
||||
@@ -13,7 +13,9 @@ require (
|
||||
github.com/projectdiscovery/dnsx v1.2.3
|
||||
golang.org/x/crypto v0.58.0
|
||||
golang.org/x/net v0.61.0
|
||||
golang.org/x/sys v0.49.0
|
||||
golang.org/x/text v0.43.0
|
||||
gvisor.dev/gvisor v0.0.0-20260224225140-573d5e7127a8
|
||||
modernc.org/sqlite v1.52.0
|
||||
mvdan.cc/sh/v3 v3.10.0
|
||||
)
|
||||
@@ -26,13 +28,13 @@ require (
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/gaissmai/bart v0.26.0 // indirect
|
||||
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
|
||||
github.com/google/btree v1.1.2 // indirect
|
||||
github.com/gorilla/css v1.0.1 // indirect
|
||||
github.com/gorilla/websocket v1.5.3 // indirect
|
||||
github.com/hinshun/vt10x v0.0.0-20220301184237-5011da428d02 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
github.com/kr/pretty v0.3.1 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/microcosm-cc/bluemonday v1.0.27 // indirect
|
||||
github.com/ncruces/go-strftime v1.0.0 // indirect
|
||||
@@ -43,18 +45,16 @@ require (
|
||||
github.com/projectdiscovery/utils v0.7.3 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
github.com/saintfish/chardet v0.0.0-20230101081208-5e3ef4b5456d // indirect
|
||||
github.com/satori/go.uuid v1.2.0 // indirect
|
||||
github.com/sirupsen/logrus v1.9.4 // indirect
|
||||
github.com/tidwall/gjson v1.18.0 // indirect
|
||||
github.com/tidwall/match v1.2.0 // indirect
|
||||
github.com/tidwall/pretty v1.2.1 // indirect
|
||||
github.com/weppos/publicsuffix-go v0.40.3-0.20250408071509-6074bbe7fd39 // indirect
|
||||
go.uber.org/atomic v1.11.0 // indirect
|
||||
go.uber.org/multierr v1.11.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20250106191152-7588d65b2ba8 // indirect
|
||||
golang.org/x/mod v0.41.0 // indirect
|
||||
golang.org/x/sync v0.24.0 // indirect
|
||||
golang.org/x/sys v0.49.0 // indirect
|
||||
golang.org/x/time v0.12.0 // indirect
|
||||
golang.org/x/tools v0.51.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
modernc.org/libc v1.72.3 // indirect
|
||||
|
||||
@@ -6,7 +6,6 @@ github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3d
|
||||
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw=
|
||||
github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk=
|
||||
github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4=
|
||||
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||
github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s=
|
||||
github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
@@ -16,12 +15,16 @@ github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkp
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/gaissmai/bart v0.26.0 h1:xOZ57E9hJLBiQaSyeZa9wgWhGuzfGACgqp4BE77OkO0=
|
||||
github.com/gaissmai/bart v0.26.0/go.mod h1:GREWQfTLRWz/c5FTOsIw+KkscuFkIV5t8Rp7Nd1Td5c=
|
||||
github.com/go-quicktest/qt v1.101.0 h1:O1K29Txy5P2OK0dGo59b7b0LR6wKfIhttaAhHUyn7eI=
|
||||
github.com/go-quicktest/qt v1.101.0/go.mod h1:14Bz/f7NwaXPtdYEgzsx46kqSxVwTbzVZsDC26tQJow=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
||||
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE=
|
||||
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
|
||||
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/btree v1.1.2 h1:xf4v41cLI2Z6FxbKm+8Bu+m8ifhj15JuZ9sa0jZCMUU=
|
||||
github.com/google/btree v1.1.2/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
|
||||
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
@@ -58,7 +61,6 @@ github.com/miekg/dns v1.1.72 h1:vhmr+TF2A3tuoGNkLDFK9zi36F2LS+hKTRW0Uf8kbzI=
|
||||
github.com/miekg/dns v1.1.72/go.mod h1:+EuEPhdHOsfk6Wk5TT2CzssZdqkmFhf8r+aVyDEToIs=
|
||||
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
|
||||
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
|
||||
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
@@ -76,13 +78,10 @@ github.com/projectdiscovery/utils v0.7.3 h1:kX+77AA58yK6EZgkTRJEnK9V/7AZYzlXdcu/
|
||||
github.com/projectdiscovery/utils v0.7.3/go.mod h1:uDdQ3/VWomai98l+a3Ye/srDXdJ4xUIar/mSXlQ9gBM=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
|
||||
github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8=
|
||||
github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4=
|
||||
github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=
|
||||
github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=
|
||||
github.com/saintfish/chardet v0.0.0-20230101081208-5e3ef4b5456d h1:hrujxIzL1woJ7AwssoOcM/tq5JjjG2yYOc8odClEiXA=
|
||||
github.com/saintfish/chardet v0.0.0-20230101081208-5e3ef4b5456d/go.mod h1:uugorj2VCxiV1x+LzaIdVa9b4S4qGAcH6cbhh4qVxOU=
|
||||
github.com/satori/go.uuid v1.2.0 h1:0uYX9dsZ2yD7q2RtLRtPSdGDWzjeM3TbMJP9utgA0ww=
|
||||
github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0=
|
||||
github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w=
|
||||
github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
@@ -102,39 +101,25 @@ github.com/weppos/publicsuffix-go v0.40.3-0.20250408071509-6074bbe7fd39 h1:Bz/zV
|
||||
github.com/weppos/publicsuffix-go v0.40.3-0.20250408071509-6074bbe7fd39/go.mod h1:2oFzEwGYI7lhiqG0YkkcKa6VcpjVinQbWxaPzytDmLA=
|
||||
github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
|
||||
github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=
|
||||
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
|
||||
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
|
||||
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
|
||||
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
|
||||
golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M=
|
||||
golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis=
|
||||
golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
|
||||
golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
|
||||
golang.org/x/exp v0.0.0-20250106191152-7588d65b2ba8 h1:yqrTHse8TCMW1M1ZCP+VAR/l0kKxwaAIqN/il7x4voA=
|
||||
golang.org/x/exp v0.0.0-20250106191152-7588d65b2ba8/go.mod h1:tujkw807nyEEAamNbDrEGzRav+ilXA7PCRAd6xsmwiU=
|
||||
golang.org/x/mod v0.40.0 h1:hUv+3cXcdRHz08UmSiOob7sadHig73uo5bkXxQ/tvUs=
|
||||
golang.org/x/mod v0.40.0/go.mod h1:0/weTWkPWGBikyTWAX3dkjVztMmBA5hM0DH6BElSupE=
|
||||
golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c=
|
||||
golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o=
|
||||
golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
|
||||
golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=
|
||||
golang.org/x/net v0.61.0 h1:RR+6j/BTBCrggOLugxa+66R8FvoN6MHlzDlZIbN9YFw=
|
||||
golang.org/x/net v0.61.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
|
||||
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
|
||||
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
|
||||
golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
|
||||
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
|
||||
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
|
||||
golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
|
||||
golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
|
||||
golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
|
||||
golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI=
|
||||
golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo=
|
||||
golang.org/x/time v0.12.0 h1:ScB/8o8olJvc+CQPWrK3fPZNfh7qgwCrY0zJmoEQLSE=
|
||||
golang.org/x/time v0.12.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=
|
||||
golang.org/x/tools v0.51.0 h1:k4Xc/1Om9jwkBJBo4NVLMSARBoWtK10mx+W5BnXCeAI=
|
||||
golang.org/x/tools v0.51.0/go.mod h1:9eEncMayCV6zRMGhR5eZEC2iBx98qWcF1HZ9Z7wJOoA=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
@@ -143,6 +128,8 @@ gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EV
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gvisor.dev/gvisor v0.0.0-20260224225140-573d5e7127a8 h1:Zy8IV/+FMLxy6j6p87vk/vQGKcdnbprwjTxc8UiUtsA=
|
||||
gvisor.dev/gvisor v0.0.0-20260224225140-573d5e7127a8/go.mod h1:QkHjoMIBaYtpVufgwv3keYAbln78mBoCuShZrPrer1Q=
|
||||
modernc.org/cc/v4 v4.28.2 h1:3tQ0lf2ADtoby2EtSP+J7IE2SHwEJdP8ioR59wx7XpY=
|
||||
modernc.org/cc/v4 v4.28.2/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=
|
||||
modernc.org/ccgo/v4 v4.34.0 h1:yRLPFZieg532OT4rp4JFNIVcquwalMX26G95WQDqwCQ=
|
||||
|
||||
@@ -212,6 +212,26 @@ type dockerContainerInspect struct {
|
||||
NetworkMode string `json:"NetworkMode"`
|
||||
Memory int64 `json:"Memory"`
|
||||
} `json:"HostConfig"`
|
||||
NetworkSettings struct {
|
||||
Networks map[string]struct {
|
||||
IPAddress string `json:"IPAddress"`
|
||||
} `json:"Networks"`
|
||||
} `json:"NetworkSettings"`
|
||||
}
|
||||
|
||||
func (i *dockerContainerInspect) IPOnNetwork(network string) string {
|
||||
if i == nil {
|
||||
return ""
|
||||
}
|
||||
if nw, ok := i.NetworkSettings.Networks[network]; ok && strings.TrimSpace(nw.IPAddress) != "" {
|
||||
return strings.TrimSpace(nw.IPAddress)
|
||||
}
|
||||
for _, nw := range i.NetworkSettings.Networks {
|
||||
if strings.TrimSpace(nw.IPAddress) != "" {
|
||||
return strings.TrimSpace(nw.IPAddress)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (c *dockerClient) InspectContainer(ctx context.Context, idOrName string) (*dockerContainerInspect, error) {
|
||||
@@ -224,15 +244,34 @@ func (c *dockerClient) InspectContainer(ctx context.Context, idOrName string) (*
|
||||
}
|
||||
|
||||
type dockerContainerListItem struct {
|
||||
ID string `json:"Id"`
|
||||
Names []string `json:"Names"`
|
||||
Image string `json:"Image"`
|
||||
State string `json:"State"`
|
||||
Status string `json:"Status"`
|
||||
Created int64 `json:"Created"`
|
||||
Labels map[string]string `json:"Labels"`
|
||||
ID string `json:"Id"`
|
||||
Names []string `json:"Names"`
|
||||
Image string `json:"Image"`
|
||||
State string `json:"State"`
|
||||
Status string `json:"Status"`
|
||||
Created int64 `json:"Created"`
|
||||
Labels map[string]string `json:"Labels"`
|
||||
NetworkSettings struct {
|
||||
Networks map[string]struct {
|
||||
IPAddress string `json:"IPAddress"`
|
||||
} `json:"Networks"`
|
||||
} `json:"NetworkSettings"`
|
||||
}
|
||||
|
||||
func (i *dockerContainerListItem) IPOnNetwork(network string) string {
|
||||
if i == nil {
|
||||
return ""
|
||||
}
|
||||
if nw, ok := i.NetworkSettings.Networks[network]; ok && strings.TrimSpace(nw.IPAddress) != "" {
|
||||
return strings.TrimSpace(nw.IPAddress)
|
||||
}
|
||||
for _, nw := range i.NetworkSettings.Networks {
|
||||
if strings.TrimSpace(nw.IPAddress) != "" {
|
||||
return strings.TrimSpace(nw.IPAddress)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
func (c *dockerClient) ListContainersByLabel(ctx context.Context, labels map[string]string) ([]dockerContainerListItem, error) {
|
||||
labelList := make([]string, 0, len(labels))
|
||||
for k, v := range labels {
|
||||
|
||||
+259
-33
@@ -50,10 +50,14 @@ type Manager struct {
|
||||
statsMu sync.Mutex
|
||||
statsCache map[string]cachedStats
|
||||
statsInFlight map[string]struct{}
|
||||
// Detected sandbox network CIDRs (used by HTTP server to block :8787 access).
|
||||
// Detected sandbox network CIDRs & bridge gateway IP.
|
||||
netCIDRMu sync.RWMutex
|
||||
netCIDRs []*net.IPNet
|
||||
gatewayIP string
|
||||
|
||||
// Real-time container IP -> sandbox owner identity map for SNAT-free traffic attribution (#218).
|
||||
ipMu sync.RWMutex
|
||||
ipMap map[string]ContainerIdentity
|
||||
stopReaper context.CancelFunc
|
||||
reaperWG sync.WaitGroup
|
||||
}
|
||||
@@ -84,6 +88,7 @@ func New(cfg Config) (*Manager, error) {
|
||||
states: map[string]*targetState{},
|
||||
statsCache: map[string]cachedStats{},
|
||||
statsInFlight: map[string]struct{}{},
|
||||
ipMap: map[string]ContainerIdentity{},
|
||||
}
|
||||
if cfg.Mode == ModeDocker {
|
||||
dc, err := newDockerClient(cfg.DockerHost)
|
||||
@@ -163,32 +168,88 @@ func (m *Manager) SetProxyConfig(proxyURL, caCertPath string) {
|
||||
}
|
||||
}
|
||||
|
||||
// SetSystemCABundlePath sets the host path to the merged system + ARTEX MITM CA
|
||||
// bundle mounted read-only into sandbox containers at /etc/ssl/certs/ca-certificates.crt.
|
||||
func (m *Manager) SetSystemCABundlePath(bundlePath string) {
|
||||
if m == nil {
|
||||
return
|
||||
}
|
||||
m.mu.Lock()
|
||||
m.cfg.SystemCABundlePath = strings.TrimSpace(bundlePath)
|
||||
m.mu.Unlock()
|
||||
}
|
||||
|
||||
// GatewayIP returns the detected bridge gateway IP of the sandbox network (e.g. "172.30.0.1").
|
||||
func (m *Manager) GatewayIP() string {
|
||||
if m == nil {
|
||||
return ""
|
||||
}
|
||||
m.netCIDRMu.RLock()
|
||||
defer m.netCIDRMu.RUnlock()
|
||||
return m.gatewayIP
|
||||
}
|
||||
|
||||
// ContainerIPSnapshot returns a copy of the live container IP -> identity map
|
||||
// for transparent gateway policy sync (#218 Phase 3).
|
||||
func (m *Manager) ContainerIPSnapshot() map[string]ContainerIdentity {
|
||||
if m == nil {
|
||||
return nil
|
||||
}
|
||||
m.ipMu.RLock()
|
||||
defer m.ipMu.RUnlock()
|
||||
out := make(map[string]ContainerIdentity, len(m.ipMap))
|
||||
for k, v := range m.ipMap {
|
||||
out[k] = v
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ProxyEnv returns HTTP(S)_PROXY + CA cert environment variables for processes
|
||||
// running inside a sandbox container. Empty when capture/proxy is disabled.
|
||||
func (m *Manager) ProxyEnv(proxyActive bool) []string {
|
||||
if m == nil || !proxyActive {
|
||||
return nil
|
||||
}
|
||||
cfg := m.Config()
|
||||
if strings.TrimSpace(cfg.ProxyURL) == "" {
|
||||
return m.ProxyEnvWithURL(m.Config().ProxyURL)
|
||||
}
|
||||
|
||||
// ProxyEnvWithURL returns HTTP(S)_PROXY + CA cert environment variables for
|
||||
// processes inside a sandbox container using an explicit proxy URL (e.g. a
|
||||
// Proxy-Authorization tagged recording proxy URL for per-intent attribution).
|
||||
func (m *Manager) ProxyEnvWithURL(proxyURL string) []string {
|
||||
if m == nil {
|
||||
return nil
|
||||
}
|
||||
proxyURL = strings.TrimSpace(proxyURL)
|
||||
if proxyURL == "" {
|
||||
return nil
|
||||
}
|
||||
cfg := m.Config()
|
||||
env := []string{
|
||||
"HTTP_PROXY=" + cfg.ProxyURL,
|
||||
"HTTPS_PROXY=" + cfg.ProxyURL,
|
||||
"http_proxy=" + cfg.ProxyURL,
|
||||
"https_proxy=" + cfg.ProxyURL,
|
||||
"ALL_PROXY=" + cfg.ProxyURL,
|
||||
"all_proxy=" + cfg.ProxyURL,
|
||||
"HTTP_PROXY=" + proxyURL,
|
||||
"HTTPS_PROXY=" + proxyURL,
|
||||
"http_proxy=" + proxyURL,
|
||||
"https_proxy=" + proxyURL,
|
||||
"ALL_PROXY=" + proxyURL,
|
||||
"all_proxy=" + proxyURL,
|
||||
"NODE_USE_ENV_PROXY=1",
|
||||
}
|
||||
caBundle := ""
|
||||
if cfg.SystemCABundlePath != "" {
|
||||
if _, err := os.Stat(cfg.SystemCABundlePath); err == nil {
|
||||
caBundle = ContainerSystemCABundlePath
|
||||
}
|
||||
}
|
||||
if cfg.CACertPath != "" {
|
||||
if _, err := os.Stat(cfg.CACertPath); err == nil {
|
||||
if caBundle == "" {
|
||||
caBundle = ContainerCACertPath
|
||||
}
|
||||
env = append(env,
|
||||
"SSL_CERT_FILE="+ContainerCACertPath,
|
||||
"CURL_CA_BUNDLE="+ContainerCACertPath,
|
||||
"REQUESTS_CA_BUNDLE="+ContainerCACertPath,
|
||||
"GIT_SSL_CAINFO="+ContainerCACertPath,
|
||||
"SSL_CERT_FILE="+caBundle,
|
||||
"CURL_CA_BUNDLE="+caBundle,
|
||||
"REQUESTS_CA_BUNDLE="+caBundle,
|
||||
"GIT_SSL_CAINFO="+caBundle,
|
||||
"NODE_EXTRA_CA_CERTS="+ContainerCACertPath,
|
||||
)
|
||||
}
|
||||
@@ -486,16 +547,108 @@ func (m *Manager) recordNetworkCIDRs(netInfo *dockerNetworkInspect) {
|
||||
}
|
||||
m.netCIDRMu.Lock()
|
||||
m.netCIDRs = cidrs
|
||||
m.netCIDRMu.Unlock()
|
||||
if gateway != "" {
|
||||
m.gatewayIP = gateway
|
||||
}
|
||||
m.netCIDRMu.Unlock()
|
||||
// attached directly to artex-sandbox (eliminates bridge SNAT so the proxy
|
||||
// observes each sandbox container's real source IP). Fall back to the
|
||||
// bridge gateway on single-network setups.
|
||||
proxyHost := detectLocalIPInSubnets(cidrs)
|
||||
if proxyHost == "" {
|
||||
proxyHost = gateway
|
||||
}
|
||||
if proxyHost != "" {
|
||||
m.mu.Lock()
|
||||
if m.cfg.ProxyURL == "" || strings.EqualFold(m.cfg.ProxyURL, "auto") {
|
||||
m.cfg.ProxyURL = "http://" + gateway + ":8788"
|
||||
m.cfg.ProxyURL = "http://" + proxyHost + ":8788"
|
||||
}
|
||||
m.mu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
func detectLocalIPInSubnets(cidrs []*net.IPNet) string {
|
||||
if len(cidrs) == 0 {
|
||||
return ""
|
||||
}
|
||||
addrs, err := net.InterfaceAddrs()
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
for _, a := range addrs {
|
||||
ipnet, ok := a.(*net.IPNet)
|
||||
if !ok || ipnet.IP == nil {
|
||||
continue
|
||||
}
|
||||
ip := ipnet.IP.To4()
|
||||
if ip == nil {
|
||||
continue
|
||||
}
|
||||
for _, sub := range cidrs {
|
||||
if sub.Contains(ip) {
|
||||
return ip.String()
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// ResolveContainerByIP returns the managed sandbox container owning srcIP.
|
||||
func (m *Manager) ResolveContainerByIP(srcIP string) (ContainerIdentity, bool) {
|
||||
if m == nil {
|
||||
return ContainerIdentity{}, false
|
||||
}
|
||||
raw := strings.TrimSpace(srcIP)
|
||||
if h, _, err := net.SplitHostPort(raw); err == nil {
|
||||
raw = h
|
||||
}
|
||||
ip := net.ParseIP(strings.Trim(raw, "[]"))
|
||||
if ip == nil {
|
||||
return ContainerIdentity{}, false
|
||||
}
|
||||
if v4 := ip.To4(); v4 != nil {
|
||||
ip = v4
|
||||
}
|
||||
m.ipMu.RLock()
|
||||
id, ok := m.ipMap[ip.String()]
|
||||
m.ipMu.RUnlock()
|
||||
return id, ok
|
||||
}
|
||||
|
||||
func (m *Manager) registerContainerIP(ip string, id ContainerIdentity) {
|
||||
parsed := net.ParseIP(strings.TrimSpace(ip))
|
||||
if parsed == nil {
|
||||
return
|
||||
}
|
||||
if v4 := parsed.To4(); v4 != nil {
|
||||
parsed = v4
|
||||
}
|
||||
ipStr := parsed.String()
|
||||
id.IP = ipStr
|
||||
m.ipMu.Lock()
|
||||
// Evict stale IP entries for the same container name/id first.
|
||||
for k, existing := range m.ipMap {
|
||||
if k != ipStr && ((id.ContainerName != "" && existing.ContainerName == id.ContainerName) || (id.ContainerID != "" && existing.ContainerID == id.ContainerID)) {
|
||||
delete(m.ipMap, k)
|
||||
}
|
||||
}
|
||||
m.ipMap[ipStr] = id
|
||||
m.ipMu.Unlock()
|
||||
}
|
||||
|
||||
func (m *Manager) evictContainerIP(name string) {
|
||||
if name == "" {
|
||||
return
|
||||
}
|
||||
m.ipMu.Lock()
|
||||
for k, existing := range m.ipMap {
|
||||
if existing.ContainerName == name {
|
||||
delete(m.ipMap, k)
|
||||
}
|
||||
}
|
||||
m.ipMu.Unlock()
|
||||
}
|
||||
|
||||
// Ensure guarantees that target's sandbox container exists and is running.
|
||||
func (m *Manager) Ensure(ctx context.Context, t Target) (string, error) {
|
||||
if !m.Enabled() {
|
||||
@@ -523,6 +676,18 @@ func (m *Manager) Ensure(ctx context.Context, t Target) (string, error) {
|
||||
if err := m.docker.StartContainer(ctx, info.ID); err != nil {
|
||||
return "", fmt.Errorf("start sandbox container %s: %w", name, err)
|
||||
}
|
||||
if refreshed, ierr := m.docker.InspectContainer(ctx, info.ID); ierr == nil {
|
||||
info = refreshed
|
||||
}
|
||||
}
|
||||
if ip := info.IPOnNetwork(cfg.Network); ip != "" {
|
||||
m.registerContainerIP(ip, ContainerIdentity{
|
||||
Scope: t.Scope,
|
||||
OwnerID: t.OwnerID,
|
||||
ContainerID: info.ID,
|
||||
ShortID: shortID(info.ID),
|
||||
ContainerName: name,
|
||||
})
|
||||
}
|
||||
return info.ID, nil
|
||||
} else if !isDockerNotFound(err) {
|
||||
@@ -537,10 +702,32 @@ func (m *Manager) Ensure(ctx context.Context, t Target) (string, error) {
|
||||
|
||||
hostRoot := cfg.MapDataPathToHost(localRoot)
|
||||
binds := []string{hostRoot + ":" + ContainerWorkDir + ":rw"}
|
||||
baseEnv := []string{
|
||||
"HOME=/tmp",
|
||||
"TERM=dumb",
|
||||
"ARTEX_SANDBOX=1",
|
||||
"ARTEX_WORKSPACE=" + ContainerWorkDir,
|
||||
}
|
||||
if cfg.AllowNetRaw {
|
||||
baseEnv = append(baseEnv, "NMAP_PRIVILEGED=1")
|
||||
}
|
||||
if cfg.CACertPath != "" {
|
||||
if _, err := os.Stat(cfg.CACertPath); err == nil {
|
||||
hostCA := cfg.MapDataPathToHost(cfg.CACertPath)
|
||||
binds = append(binds, hostCA+":"+ContainerCACertPath+":ro")
|
||||
baseEnv = append(baseEnv, "NODE_EXTRA_CA_CERTS="+ContainerCACertPath)
|
||||
}
|
||||
}
|
||||
if cfg.SystemCABundlePath != "" {
|
||||
if _, err := os.Stat(cfg.SystemCABundlePath); err == nil {
|
||||
hostBundle := cfg.MapDataPathToHost(cfg.SystemCABundlePath)
|
||||
binds = append(binds, hostBundle+":"+ContainerSystemCABundlePath+":ro")
|
||||
baseEnv = append(baseEnv,
|
||||
"SSL_CERT_FILE="+ContainerSystemCABundlePath,
|
||||
"CURL_CA_BUNDLE="+ContainerSystemCABundlePath,
|
||||
"REQUESTS_CA_BUNDLE="+ContainerSystemCABundlePath,
|
||||
"GIT_SSL_CAINFO="+ContainerSystemCABundlePath,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -550,18 +737,38 @@ func (m *Manager) Ensure(ctx context.Context, t Target) (string, error) {
|
||||
pidsLimit := int64(cfg.PidsLimit)
|
||||
|
||||
hostCfg := map[string]any{
|
||||
"Binds": binds,
|
||||
"NetworkMode": cfg.Network,
|
||||
"Memory": memBytes,
|
||||
"MemorySwap": memBytes, // disable swap thrashing
|
||||
"NanoCpus": nanoCPUs,
|
||||
"PidsLimit": pidsLimit,
|
||||
"ShmSize": shmBytes,
|
||||
"CapDrop": []string{"ALL"},
|
||||
"SecurityOpt": []string{"no-new-privileges:true"},
|
||||
"Init": true, // tini/docker-init reaps zombies inside container
|
||||
"Tmpfs": map[string]string{"/tmp": fmt.Sprintf("rw,nosuid,size=%dm", cfg.TmpSizeMB)},
|
||||
"RestartPolicy": map[string]any{"Name": "no"},
|
||||
"Binds": binds,
|
||||
"NetworkMode": cfg.Network,
|
||||
"Memory": memBytes,
|
||||
"MemorySwap": memBytes, // disable swap thrashing
|
||||
"NanoCpus": nanoCPUs,
|
||||
"PidsLimit": pidsLimit,
|
||||
"ShmSize": shmBytes,
|
||||
"CapDrop": []string{"ALL"},
|
||||
"Init": true, // tini/docker-init reaps zombies inside container
|
||||
"Tmpfs": map[string]string{"/tmp": fmt.Sprintf("rw,nosuid,nodev,size=%dm", cfg.TmpSizeMB)},
|
||||
"Sysctls": map[string]string{"net.ipv4.ping_group_range": "0 2147483647"},
|
||||
"RestartPolicy": map[string]any{"Name": "no"},
|
||||
}
|
||||
if cfg.AllowNetRaw {
|
||||
// Permit CAP_NET_RAW in the bounding set ONLY (paired with file-cap cap_net_raw+ep
|
||||
// on /usr/bin/nmap, /usr/bin/nping, and /usr/bin/ping in Dockerfile.sandbox, with
|
||||
// all SUID/SGID bits stripped). Ordinary non-root processes keep CapEff=0.
|
||||
hostCfg["CapAdd"] = []string{"NET_RAW"}
|
||||
} else {
|
||||
// Strict lockdown for untrusted custom images that may contain SUID binaries.
|
||||
hostCfg["SecurityOpt"] = []string{"no-new-privileges:true"}
|
||||
}
|
||||
// Route container DNS through the sandbox gateway IP when transparent mode is enabled
|
||||
// so Docker's embedded DNS forwards queries across the sandbox bridge with real container src_ip.
|
||||
if cfg.TransparentGateway {
|
||||
dnsIP := strings.TrimSpace(cfg.GatewayDNSIP)
|
||||
if dnsIP == "" {
|
||||
dnsIP = m.GatewayIP()
|
||||
}
|
||||
if dnsIP != "" {
|
||||
hostCfg["Dns"] = []string{dnsIP}
|
||||
}
|
||||
}
|
||||
if cfg.Runtime != "" {
|
||||
hostCfg["Runtime"] = cfg.Runtime
|
||||
@@ -577,12 +784,7 @@ func (m *Manager) Ensure(ctx context.Context, t Target) (string, error) {
|
||||
"AttachStdout": false,
|
||||
"AttachStderr": false,
|
||||
"Tty": false,
|
||||
"Env": []string{
|
||||
"HOME=/tmp",
|
||||
"TERM=dumb",
|
||||
"ARTEX_SANDBOX=1",
|
||||
"ARTEX_WORKSPACE=" + ContainerWorkDir,
|
||||
},
|
||||
"Env": baseEnv,
|
||||
"Labels": map[string]string{
|
||||
labelManaged: "true",
|
||||
labelInstance: cfg.InstanceID,
|
||||
@@ -600,6 +802,17 @@ func (m *Manager) Ensure(ctx context.Context, t Target) (string, error) {
|
||||
_ = m.docker.RemoveContainer(ctx, id)
|
||||
return "", fmt.Errorf("start sandbox container %s: %w", name, err)
|
||||
}
|
||||
if info, ierr := m.docker.InspectContainer(ctx, id); ierr == nil {
|
||||
if ip := info.IPOnNetwork(cfg.Network); ip != "" {
|
||||
m.registerContainerIP(ip, ContainerIdentity{
|
||||
Scope: t.Scope,
|
||||
OwnerID: t.OwnerID,
|
||||
ContainerID: id,
|
||||
ShortID: shortID(id),
|
||||
ContainerName: name,
|
||||
})
|
||||
}
|
||||
}
|
||||
log.Printf("[sandbox] created & started %s (%s, image=%s, mem=%dMiB, cpus=%.2f)", name, shortID(id), cfg.Image, cfg.MemoryMB, cfg.CPUs)
|
||||
return id, nil
|
||||
}
|
||||
@@ -617,6 +830,7 @@ func (m *Manager) Stop(ctx context.Context, t Target) error {
|
||||
return err
|
||||
}
|
||||
m.dropStatsCache(name)
|
||||
m.evictContainerIP(name)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -633,6 +847,7 @@ func (m *Manager) Remove(ctx context.Context, t Target) error {
|
||||
return err
|
||||
}
|
||||
m.dropStatsCache(name)
|
||||
m.evictContainerIP(name)
|
||||
m.stateMu.Lock()
|
||||
delete(m.states, t.Key())
|
||||
m.stateMu.Unlock()
|
||||
@@ -790,12 +1005,14 @@ func (m *Manager) StatusWithStats(ctx context.Context, withStats bool) GlobalSta
|
||||
if len(item.Names) > 0 {
|
||||
name = strings.TrimPrefix(item.Names[0], "/")
|
||||
}
|
||||
ipAddr := item.IPOnNetwork(cfg.Network)
|
||||
ci := ContainerInfo{
|
||||
Scope: t.Scope,
|
||||
OwnerID: t.OwnerID,
|
||||
Name: name,
|
||||
ContainerID: item.ID,
|
||||
ShortID: shortID(item.ID),
|
||||
IPAddress: ipAddr,
|
||||
Image: item.Image,
|
||||
State: item.State,
|
||||
StatusText: item.Status,
|
||||
@@ -805,6 +1022,15 @@ func (m *Manager) StatusWithStats(ctx context.Context, withStats bool) GlobalSta
|
||||
Network: cfg.Network,
|
||||
Runtime: cfg.Runtime,
|
||||
}
|
||||
if item.State == "running" && ipAddr != "" {
|
||||
m.registerContainerIP(ipAddr, ContainerIdentity{
|
||||
Scope: t.Scope,
|
||||
OwnerID: t.OwnerID,
|
||||
ContainerID: item.ID,
|
||||
ShortID: shortID(item.ID),
|
||||
ContainerName: name,
|
||||
})
|
||||
}
|
||||
if item.State == "running" {
|
||||
if st, fresh, ok := m.peekStatsCacheAny(name); ok {
|
||||
ci.CPUPercent = st.CPUPercent
|
||||
|
||||
@@ -134,3 +134,48 @@ func TestHostToContainerAndDataPathMapping(t *testing.T) {
|
||||
t.Fatalf("HostToContainerPath root = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestManagerContainerIPMap(t *testing.T) {
|
||||
m := &Manager{ipMap: map[string]ContainerIdentity{}}
|
||||
m.registerContainerIP("172.28.0.5", ContainerIdentity{
|
||||
Scope: ScopeTask,
|
||||
OwnerID: "12",
|
||||
ContainerID: "abc123def456",
|
||||
ContainerName: "artex-sbx-inst-task-12",
|
||||
IP: "172.28.0.5",
|
||||
})
|
||||
got, ok := m.ResolveContainerByIP("172.28.0.5:54321")
|
||||
if !ok || got.Scope != ScopeTask || got.OwnerID != "12" || got.ContainerID != "abc123def456" {
|
||||
t.Fatalf("ResolveContainerByIP failed: ok=%v got=%+v", ok, got)
|
||||
}
|
||||
// Re-registering same container with a new IP must evict the stale IP.
|
||||
m.registerContainerIP("172.28.0.9", ContainerIdentity{
|
||||
Scope: ScopeTask,
|
||||
OwnerID: "12",
|
||||
ContainerID: "new999888777",
|
||||
ContainerName: "artex-sbx-inst-task-12",
|
||||
IP: "172.28.0.9",
|
||||
})
|
||||
if _, stale := m.ResolveContainerByIP("172.28.0.5"); stale {
|
||||
t.Fatalf("stale IP 172.28.0.5 should have been evicted")
|
||||
}
|
||||
if got2, ok2 := m.ResolveContainerByIP("172.28.0.9"); !ok2 || got2.ContainerID != "new999888777" {
|
||||
t.Fatalf("new IP 172.28.0.9 lookup failed: ok=%v got=%+v", ok2, got2)
|
||||
}
|
||||
// Explicit eviction by container name.
|
||||
m.evictContainerIP("artex-sbx-inst-task-12")
|
||||
if _, ok3 := m.ResolveContainerByIP("172.28.0.9"); ok3 {
|
||||
t.Fatalf("evicted container IP should no longer resolve")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigFromEnvAllowNetRaw(t *testing.T) {
|
||||
t.Setenv("ARTEX_SANDBOX_ALLOW_NET_RAW", "")
|
||||
if cfg := ConfigFromEnv(t.TempDir(), ""); !cfg.AllowNetRaw {
|
||||
t.Fatalf("AllowNetRaw should default to true")
|
||||
}
|
||||
t.Setenv("ARTEX_SANDBOX_ALLOW_NET_RAW", "false")
|
||||
if cfg := ConfigFromEnv(t.TempDir(), ""); cfg.AllowNetRaw {
|
||||
t.Fatalf("AllowNetRaw should respect ARTEX_SANDBOX_ALLOW_NET_RAW=false")
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,10 @@ const ContainerWorkDir = "/workspace"
|
||||
// ContainerCACertPath is where the recording MITM proxy CA cert is mounted read-only.
|
||||
const ContainerCACertPath = "/etc/artex/ca.crt"
|
||||
|
||||
// ContainerSystemCABundlePath is where the merged system + ARTEX MITM CA bundle
|
||||
// is mounted read-only so static Go binaries and system TLS libraries trust the
|
||||
// recording proxy without needing root or runtime update-ca-certificates (#218 Phase 3).
|
||||
const ContainerSystemCABundlePath = "/etc/ssl/certs/ca-certificates.crt"
|
||||
// Target identifies a logical sandbox instance.
|
||||
type Target struct {
|
||||
Scope Scope
|
||||
@@ -62,12 +66,16 @@ type Config struct {
|
||||
HostDataDir string
|
||||
ProxyURL string
|
||||
CACertPath string
|
||||
SystemCABundlePath string
|
||||
TransparentGateway bool
|
||||
GatewayDNSIP string
|
||||
MemoryMB int
|
||||
CPUs float64
|
||||
PidsLimit int
|
||||
ShmSizeMB int
|
||||
TmpSizeMB int
|
||||
User string
|
||||
AllowNetRaw bool
|
||||
AutoStopOnComplete bool
|
||||
SessionIdleMinutes int
|
||||
InstanceID string
|
||||
@@ -129,12 +137,15 @@ func ConfigFromEnv(dataDir, caCertPath string) Config {
|
||||
HostDataDir: filepath.Clean(hostDataDir),
|
||||
ProxyURL: strings.TrimSpace(os.Getenv("ARTEX_SANDBOX_PROXY_URL")),
|
||||
CACertPath: strings.TrimSpace(caCertPath),
|
||||
TransparentGateway: envBool("ARTEX_SANDBOX_TRANSPARENT", true),
|
||||
GatewayDNSIP: strings.TrimSpace(os.Getenv("ARTEX_SANDBOX_DNS")),
|
||||
MemoryMB: envInt("ARTEX_SANDBOX_MEMORY_MB", 2048, 256),
|
||||
CPUs: envFloat("ARTEX_SANDBOX_CPUS", 2.0, 0.25),
|
||||
PidsLimit: envInt("ARTEX_SANDBOX_PIDS_LIMIT", 256, 32),
|
||||
ShmSizeMB: envInt("ARTEX_SANDBOX_SHM_MB", 512, 64),
|
||||
TmpSizeMB: envInt("ARTEX_SANDBOX_TMP_MB", 512, 64),
|
||||
User: user,
|
||||
AllowNetRaw: envBool("ARTEX_SANDBOX_ALLOW_NET_RAW", true),
|
||||
AutoStopOnComplete: envBool("ARTEX_SANDBOX_AUTO_STOP", true),
|
||||
SessionIdleMinutes: envInt("ARTEX_SANDBOX_SESSION_IDLE_MIN", 20, 1),
|
||||
InstanceID: instanceID,
|
||||
@@ -178,6 +189,15 @@ func envBool(key string, def bool) bool {
|
||||
}
|
||||
|
||||
// ContainerInfo describes one sandbox container for API/UI reporting.
|
||||
type ContainerIdentity struct {
|
||||
Scope Scope `json:"scope"`
|
||||
OwnerID string `json:"owner_id"`
|
||||
ContainerID string `json:"container_id"`
|
||||
ShortID string `json:"short_id"`
|
||||
ContainerName string `json:"container_name"`
|
||||
IP string `json:"ip"`
|
||||
}
|
||||
|
||||
type ContainerInfo struct {
|
||||
Scope Scope `json:"scope"`
|
||||
OwnerID string `json:"owner_id"`
|
||||
@@ -186,6 +206,7 @@ type ContainerInfo struct {
|
||||
Name string `json:"name"`
|
||||
ContainerID string `json:"container_id,omitempty"`
|
||||
ShortID string `json:"short_id,omitempty"`
|
||||
IPAddress string `json:"ip_address,omitempty"`
|
||||
Image string `json:"image"`
|
||||
State string `json:"state"` // running | exited | created | missing | local | error
|
||||
StatusText string `json:"status_text,omitempty"`
|
||||
|
||||
@@ -32,9 +32,22 @@ if ! docker network inspect "$sandbox_net" >/dev/null 2>&1; then
|
||||
fi
|
||||
|
||||
sandbox_br=$(bridge_for "$sandbox_net")
|
||||
|
||||
ensure INPUT -i "$sandbox_br" -p tcp --dport 8787 -j REJECT
|
||||
|
||||
# If the ARTEX control-plane container is directly attached to artex-sandbox
|
||||
# (SNAT-free source IP attribution, #218), allow ONLY sandbox -> ARTEX :8788
|
||||
# (plus established return packets) while keeping enable_icc=false between
|
||||
# sandbox containers and explicitly rejecting :8787.
|
||||
artex_ct=$(docker ps --filter "network=$sandbox_net" --format '{{.Names}}' | awk '/artex/ && !/artex-sbx-/ {print; exit}')
|
||||
if [ -n "$artex_ct" ]; then
|
||||
artex_sbx_ip=$(docker inspect "$artex_ct" --format "{{with index .NetworkSettings.Networks \"$sandbox_net\"}}{{.IPAddress}}{{end}}")
|
||||
if [ -n "$artex_sbx_ip" ]; then
|
||||
ensure DOCKER-USER -i "$sandbox_br" -o "$sandbox_br" -d "$artex_sbx_ip/32" -p tcp --dport 8787 -j REJECT
|
||||
ensure DOCKER-USER -i "$sandbox_br" -o "$sandbox_br" -s "$artex_sbx_ip/32" -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
|
||||
ensure DOCKER-USER -i "$sandbox_br" -o "$sandbox_br" -d "$artex_sbx_ip/32" -p tcp --dport 8788 -j ACCEPT
|
||||
fi
|
||||
fi
|
||||
|
||||
# Compose prefixes the internal network with the project name.
|
||||
internal_net=$(docker network ls --format '{{.Name}}' | awk '/artex-internal$/ {print; exit}')
|
||||
if [ -n "$internal_net" ]; then
|
||||
@@ -50,4 +63,12 @@ fi
|
||||
|
||||
ensure DOCKER-USER -i "$sandbox_br" -d 169.254.169.254/32 -j REJECT
|
||||
|
||||
# Optional transparent gateway mode (#218 Phase 3): allow traffic routed into
|
||||
# artex-tun0 (gVisor netstack) and reject any direct outbound NAT bypass.
|
||||
if [ "${ARTEX_SANDBOX_TRANSPARENT:-false}" = "true" ] || [ "${ARTEX_SANDBOX_TRANSPARENT:-0}" = "1" ]; then
|
||||
ensure DOCKER-USER -i "$sandbox_br" ! -o "$sandbox_br" -j REJECT
|
||||
ensure DOCKER-USER -i "$sandbox_br" -o artex-tun0 -j ACCEPT
|
||||
ensure DOCKER-USER -i artex-tun0 -o "$sandbox_br" -j ACCEPT
|
||||
fi
|
||||
|
||||
echo "sandbox firewall applied on $sandbox_br"
|
||||
@@ -49,6 +49,7 @@ func (s *Server) assetInterceptCreateRule(w http.ResponseWriter, r *http.Request
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
s.syncEgressBlacklist()
|
||||
writeJSON(w, 200, rule)
|
||||
}
|
||||
|
||||
@@ -76,6 +77,7 @@ func (s *Server) assetInterceptUpdateRule(w http.ResponseWriter, r *http.Request
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
s.syncEgressBlacklist()
|
||||
writeJSON(w, 200, rule)
|
||||
}
|
||||
|
||||
@@ -93,6 +95,7 @@ func (s *Server) assetInterceptDeleteRule(w http.ResponseWriter, r *http.Request
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
s.syncEgressBlacklist()
|
||||
writeJSON(w, 200, map[string]any{"deleted": id})
|
||||
}
|
||||
|
||||
@@ -117,6 +120,7 @@ func (s *Server) assetInterceptToggleRule(w http.ResponseWriter, r *http.Request
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
s.syncEgressBlacklist()
|
||||
writeJSON(w, 200, map[string]any{"ok": true, "enabled": req.Enabled})
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -120,7 +120,7 @@ func extractToken(r *http.Request) string {
|
||||
func (s *Server) requireAuth(h http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
p := r.URL.Path
|
||||
if strings.HasPrefix(p, "/api/auth/") || p == "/api/health" || p == "/api/basic-auth/check" {
|
||||
if strings.HasPrefix(p, "/api/auth/") || strings.HasPrefix(p, "/api/internal/gateway/") || p == "/api/health" || p == "/api/basic-auth/check" {
|
||||
h.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -12,8 +12,8 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
"github.com/Autumn-27/artex/internal/sandbox"
|
||||
)
|
||||
|
||||
func TestEnsureBrowserMCPArgs(t *testing.T) {
|
||||
@@ -178,3 +178,72 @@ func TestDefaultEnabledSettingsAndScreenshotTimestampHeader(t *testing.T) {
|
||||
t.Fatal("expected X-Report-Screenshot-Timestamp header when setting is unset (default true)")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdaptSandboxMCPArgsAndEnv(t *testing.T) {
|
||||
// 1. Loopback --proxy-server (split and =) rewritten to sandbox-reachable proxy URL.
|
||||
in := []string{"--browser", "chromium", "--headless", "--no-sandbox", "--proxy-server", "http://127.0.0.1:8788"}
|
||||
got := adaptSandboxMCPArgs(in, "http://172.30.0.2:8788")
|
||||
want := []string{"--browser", "chromium", "--headless", "--no-sandbox", "--proxy-server", "http://172.30.0.2:8788"}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("adaptSandboxMCPArgs(split) = %v, want %v", got, want)
|
||||
}
|
||||
|
||||
inEq := []string{"--headless", "--proxy-server=http://localhost:8788"}
|
||||
gotEq := adaptSandboxMCPArgs(inEq, "http://172.30.0.2:8788")
|
||||
wantEq := []string{"--headless", "--proxy-server=http://172.30.0.2:8788"}
|
||||
if !reflect.DeepEqual(gotEq, wantEq) {
|
||||
t.Fatalf("adaptSandboxMCPArgs(=) = %v, want %v", gotEq, wantEq)
|
||||
}
|
||||
|
||||
// 2. Empty sandboxProxyURL strips unusable loopback proxy flag cleanly.
|
||||
gotStrip := adaptSandboxMCPArgs(in, "")
|
||||
wantStrip := []string{"--browser", "chromium", "--headless", "--no-sandbox"}
|
||||
if !reflect.DeepEqual(gotStrip, wantStrip) {
|
||||
t.Fatalf("adaptSandboxMCPArgs(strip) = %v, want %v", gotStrip, wantStrip)
|
||||
}
|
||||
|
||||
// 3. Explicit non-loopback user proxy passes through untouched.
|
||||
inCustom := []string{"--headless", "--proxy-server", "http://10.0.0.5:8080"}
|
||||
gotCustom := adaptSandboxMCPArgs(inCustom, "http://172.30.0.2:8788")
|
||||
if !reflect.DeepEqual(gotCustom, inCustom) {
|
||||
t.Fatalf("adaptSandboxMCPArgs(custom) = %v, want %v", gotCustom, inCustom)
|
||||
}
|
||||
|
||||
// 4. stripURLCredentials drops userinfo so Chromium accepts --proxy-server.
|
||||
if got := stripURLCredentials("http://artexctx_sc=task:[email protected]:8788"); got != "http://172.30.0.2:8788" {
|
||||
t.Fatalf("stripURLCredentials = %q", got)
|
||||
}
|
||||
|
||||
// 5. buildSandboxMCPEnv never lets host CA path clobber /etc/artex/ca.crt.
|
||||
caFile := filepath.Join(t.TempDir(), "mitmproxy-ca-cert.pem")
|
||||
if err := os.WriteFile(caFile, []byte("FAKE-CA"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mgr, err := sandbox.New(sandbox.Config{
|
||||
Mode: sandbox.ModeLocal,
|
||||
ProxyURL: "http://172.30.0.2:8788",
|
||||
CACertPath: caFile,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
env := buildSandboxMCPEnv(mgr, map[string]string{
|
||||
"NODE_EXTRA_CA_CERTS": "/app/data/traffic/_ca/mitmproxy-ca-cert.pem",
|
||||
"CUSTOM_KEY": "custom-val",
|
||||
})
|
||||
envMap := map[string]string{}
|
||||
for _, kv := range env {
|
||||
if k, v, ok := strings.Cut(kv, "="); ok {
|
||||
envMap[k] = v
|
||||
}
|
||||
}
|
||||
if envMap["NODE_EXTRA_CA_CERTS"] != sandbox.ContainerCACertPath {
|
||||
t.Fatalf("NODE_EXTRA_CA_CERTS = %q, want %q", envMap["NODE_EXTRA_CA_CERTS"], sandbox.ContainerCACertPath)
|
||||
}
|
||||
if envMap["CUSTOM_KEY"] != "custom-val" {
|
||||
t.Fatalf("CUSTOM_KEY = %q, want custom-val", envMap["CUSTOM_KEY"])
|
||||
}
|
||||
if envMap["HTTP_PROXY"] != "http://172.30.0.2:8788" {
|
||||
t.Fatalf("HTTP_PROXY = %q, want http://172.30.0.2:8788", envMap["HTTP_PROXY"])
|
||||
}
|
||||
}
|
||||
+28
-16
@@ -191,28 +191,40 @@ func completedRFC(unix int64) string {
|
||||
|
||||
// ---- TrafficExchange (frontend "TrafficExchange") ---- ts as RFC3339.
|
||||
type TrafficExchangeDTO struct {
|
||||
ID string `json:"id"`
|
||||
TS string `json:"ts"`
|
||||
Host string `json:"host"`
|
||||
Method string `json:"method"`
|
||||
URL string `json:"url"`
|
||||
Status int `json:"status"`
|
||||
ContentType string `json:"content_type"`
|
||||
RespLen int `json:"resp_len"`
|
||||
ID string `json:"id"`
|
||||
TS string `json:"ts"`
|
||||
Host string `json:"host"`
|
||||
Method string `json:"method"`
|
||||
URL string `json:"url"`
|
||||
Status int `json:"status"`
|
||||
ContentType string `json:"content_type"`
|
||||
RespLen int `json:"resp_len"`
|
||||
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"`
|
||||
}
|
||||
|
||||
func trafficDTOs(ex []traffic.ExchangeMeta) []TrafficExchangeDTO {
|
||||
out := make([]TrafficExchangeDTO, 0, len(ex))
|
||||
for _, e := range ex {
|
||||
out = append(out, TrafficExchangeDTO{
|
||||
ID: e.ID,
|
||||
TS: rfc3339(time.Unix(e.TS, 0)),
|
||||
Host: e.Host,
|
||||
Method: e.Method,
|
||||
URL: e.URL,
|
||||
Status: e.Status,
|
||||
ContentType: e.ContentType,
|
||||
RespLen: e.RespLen,
|
||||
ID: e.ID,
|
||||
TS: rfc3339(time.Unix(e.TS, 0)),
|
||||
Host: e.Host,
|
||||
Method: e.Method,
|
||||
URL: e.URL,
|
||||
Status: e.Status,
|
||||
ContentType: e.ContentType,
|
||||
RespLen: e.RespLen,
|
||||
SandboxScope: e.SandboxScope,
|
||||
SandboxOwnerID: e.SandboxOwnerID,
|
||||
ContainerID: e.ContainerID,
|
||||
SessionID: e.SessionID,
|
||||
IntentID: e.IntentID,
|
||||
SrcIP: e.SrcIP,
|
||||
})
|
||||
}
|
||||
return out
|
||||
|
||||
@@ -0,0 +1,410 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
"github.com/Autumn-27/artex/traffic"
|
||||
)
|
||||
|
||||
const (
|
||||
settingEgressBlacklistRules = "egress_blacklist_rules_json"
|
||||
settingEgressBlacklistSync = "egress_blacklist_sync_asset_intercept"
|
||||
)
|
||||
|
||||
func (s *Server) loadCustomEgressBlacklist() []traffic.EgressBlacklistRule {
|
||||
if s.m.pg == nil {
|
||||
return []traffic.EgressBlacklistRule{}
|
||||
}
|
||||
raw, ok, err := s.m.pg.GetSetting(settingEgressBlacklistRules)
|
||||
if err != nil || !ok || strings.TrimSpace(raw) == "" {
|
||||
return []traffic.EgressBlacklistRule{}
|
||||
}
|
||||
var rules []traffic.EgressBlacklistRule
|
||||
if err := json.Unmarshal([]byte(raw), &rules); err != nil {
|
||||
return []traffic.EgressBlacklistRule{}
|
||||
}
|
||||
if rules == nil {
|
||||
return []traffic.EgressBlacklistRule{}
|
||||
}
|
||||
for i := range rules {
|
||||
rules[i].Source = "custom"
|
||||
}
|
||||
return rules
|
||||
}
|
||||
|
||||
func (s *Server) saveCustomEgressBlacklist(rules []traffic.EgressBlacklistRule) error {
|
||||
if s.m.pg == nil {
|
||||
return fmt.Errorf("database unavailable")
|
||||
}
|
||||
if rules == nil {
|
||||
rules = []traffic.EgressBlacklistRule{}
|
||||
}
|
||||
b, err := json.Marshal(rules)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return s.m.pg.SetSetting(settingEgressBlacklistRules, string(b))
|
||||
}
|
||||
|
||||
func (s *Server) egressBlacklistSyncAssetEnabled() bool {
|
||||
if s.m.pg == nil {
|
||||
return false
|
||||
}
|
||||
return s.m.pg.GetBool(settingEgressBlacklistSync, false)
|
||||
}
|
||||
|
||||
// translateAssetInterceptRules converts enabled global asset_intercept_rules
|
||||
// into network-layer egress blacklist rules. Rules that only match URL paths
|
||||
// without a concrete host are skipped because network-layer checks operate on
|
||||
// destination host/IP/CIDR.
|
||||
func translateAssetInterceptRules(in []db.AssetInterceptRule) []traffic.EgressBlacklistRule {
|
||||
out := make([]traffic.EgressBlacklistRule, 0, len(in))
|
||||
for _, r := range in {
|
||||
if !r.Enabled {
|
||||
continue
|
||||
}
|
||||
pat := strings.TrimSpace(r.Pattern)
|
||||
if pat == "" {
|
||||
continue
|
||||
}
|
||||
var kind, normalized string
|
||||
switch r.Kind {
|
||||
case "exact_domain":
|
||||
kind = "domain"
|
||||
normalized = pat
|
||||
case "fuzzy_domain":
|
||||
kind = "suffix"
|
||||
normalized = pat
|
||||
case "exact_ip":
|
||||
kind = "ip"
|
||||
normalized = pat
|
||||
case "cidr":
|
||||
kind = "cidr"
|
||||
normalized = pat
|
||||
case "exact_url", "fuzzy_url":
|
||||
raw := pat
|
||||
if !strings.Contains(raw, "://") {
|
||||
raw = "http://" + raw
|
||||
}
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil || strings.TrimSpace(u.Hostname()) == "" {
|
||||
continue
|
||||
}
|
||||
h := u.Hostname()
|
||||
if net.ParseIP(h) != nil {
|
||||
kind = "ip"
|
||||
normalized = h
|
||||
} else if r.Kind == "fuzzy_url" {
|
||||
kind = "suffix"
|
||||
normalized = h
|
||||
} else {
|
||||
kind = "domain"
|
||||
normalized = h
|
||||
}
|
||||
default:
|
||||
continue
|
||||
}
|
||||
er := traffic.EgressBlacklistRule{
|
||||
ID: fmt.Sprintf("asset-%d", r.ID),
|
||||
Enabled: true,
|
||||
Kind: kind,
|
||||
Pattern: normalized,
|
||||
Note: r.Note,
|
||||
Source: "asset_intercept",
|
||||
}
|
||||
if err := traffic.NormalizeEgressRule(&er); err != nil {
|
||||
continue
|
||||
}
|
||||
out = append(out, er)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// syncEgressBlacklist compiles and hot-loads custom egress blacklist rules plus
|
||||
// optionally synced global asset_intercept_rules into the recording proxy.
|
||||
func (s *Server) syncEgressBlacklist() {
|
||||
if s.m.traffic == nil {
|
||||
return
|
||||
}
|
||||
custom := s.loadCustomEgressBlacklist()
|
||||
effective := make([]traffic.EgressBlacklistRule, 0, len(custom))
|
||||
effective = append(effective, custom...)
|
||||
if s.egressBlacklistSyncAssetEnabled() && s.m.pg != nil {
|
||||
if assetRules, err := s.m.pg.ListAssetInterceptRules(); err == nil {
|
||||
effective = append(effective, translateAssetInterceptRules(assetRules)...)
|
||||
}
|
||||
}
|
||||
s.m.traffic.SetEgressBlacklist(effective)
|
||||
}
|
||||
|
||||
// GET /api/proxy/blacklist
|
||||
func (s *Server) getEgressBlacklist(w http.ResponseWriter, r *http.Request) {
|
||||
custom := s.loadCustomEgressBlacklist()
|
||||
syncOn := s.egressBlacklistSyncAssetEnabled()
|
||||
synced := []traffic.EgressBlacklistRule{}
|
||||
if s.m.pg != nil {
|
||||
if assetRules, err := s.m.pg.ListAssetInterceptRules(); err == nil {
|
||||
synced = translateAssetInterceptRules(assetRules)
|
||||
}
|
||||
}
|
||||
events := []traffic.EgressBlockEvent{}
|
||||
if s.m.traffic != nil {
|
||||
events = s.m.traffic.BlockEvents(100)
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{
|
||||
"rules": custom,
|
||||
"synced_rules": synced,
|
||||
"sync_asset_intercept": syncOn,
|
||||
"events": events,
|
||||
})
|
||||
}
|
||||
|
||||
// PUT /api/proxy/blacklist/settings
|
||||
func (s *Server) updateEgressBlacklistSettings(w http.ResponseWriter, r *http.Request) {
|
||||
pg := s.pg(w)
|
||||
if pg == nil {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
SyncAssetIntercept bool `json:"sync_asset_intercept"`
|
||||
}
|
||||
if err := decode(r, &req); err != nil {
|
||||
writeErr(w, 400, err.Error())
|
||||
return
|
||||
}
|
||||
val := "false"
|
||||
if req.SyncAssetIntercept {
|
||||
val = "true"
|
||||
}
|
||||
if err := pg.SetSetting(settingEgressBlacklistSync, val); err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
s.syncEgressBlacklist()
|
||||
s.getEgressBlacklist(w, r)
|
||||
}
|
||||
|
||||
// POST /api/proxy/blacklist/rules
|
||||
func (s *Server) createEgressBlacklistRule(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Enabled *bool `json:"enabled"`
|
||||
Kind string `json:"kind"`
|
||||
Pattern string `json:"pattern"`
|
||||
Port int `json:"port"`
|
||||
Note string `json:"note"`
|
||||
}
|
||||
if err := decode(r, &req); err != nil {
|
||||
writeErr(w, 400, err.Error())
|
||||
return
|
||||
}
|
||||
enabled := true
|
||||
if req.Enabled != nil {
|
||||
enabled = *req.Enabled
|
||||
}
|
||||
now := time.Now().UTC().Format(time.RFC3339)
|
||||
rule := traffic.EgressBlacklistRule{
|
||||
ID: fmt.Sprintf("eb-%d", time.Now().UnixNano()),
|
||||
Enabled: enabled,
|
||||
Kind: req.Kind,
|
||||
Pattern: req.Pattern,
|
||||
Port: req.Port,
|
||||
Note: req.Note,
|
||||
Source: "custom",
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
}
|
||||
if err := traffic.NormalizeEgressRule(&rule); err != nil {
|
||||
writeErr(w, 400, err.Error())
|
||||
return
|
||||
}
|
||||
rules := s.loadCustomEgressBlacklist()
|
||||
for _, existing := range rules {
|
||||
if existing.Kind == rule.Kind && existing.Pattern == rule.Pattern && existing.Port == rule.Port {
|
||||
writeErr(w, 409, "相同规则已存在")
|
||||
return
|
||||
}
|
||||
}
|
||||
rules = append([]traffic.EgressBlacklistRule{rule}, rules...)
|
||||
if err := s.saveCustomEgressBlacklist(rules); err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
s.syncEgressBlacklist()
|
||||
writeJSON(w, 200, rule)
|
||||
}
|
||||
|
||||
// PUT /api/proxy/blacklist/rules/{id}
|
||||
func (s *Server) updateEgressBlacklistRule(w http.ResponseWriter, r *http.Request) {
|
||||
id := strings.TrimSpace(r.PathValue("id"))
|
||||
if id == "" {
|
||||
writeErr(w, 400, "invalid rule id")
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Enabled *bool `json:"enabled"`
|
||||
Kind *string `json:"kind"`
|
||||
Pattern *string `json:"pattern"`
|
||||
Port *int `json:"port"`
|
||||
Note *string `json:"note"`
|
||||
}
|
||||
if err := decode(r, &req); err != nil {
|
||||
writeErr(w, 400, err.Error())
|
||||
return
|
||||
}
|
||||
rules := s.loadCustomEgressBlacklist()
|
||||
idx := -1
|
||||
for i := range rules {
|
||||
if rules[i].ID == id {
|
||||
idx = i
|
||||
break
|
||||
}
|
||||
}
|
||||
if idx < 0 {
|
||||
writeErr(w, 404, "规则不存在")
|
||||
return
|
||||
}
|
||||
updated := rules[idx]
|
||||
if req.Enabled != nil {
|
||||
updated.Enabled = *req.Enabled
|
||||
}
|
||||
if req.Kind != nil {
|
||||
updated.Kind = *req.Kind
|
||||
}
|
||||
if req.Pattern != nil {
|
||||
updated.Pattern = *req.Pattern
|
||||
}
|
||||
if req.Port != nil {
|
||||
updated.Port = *req.Port
|
||||
}
|
||||
if req.Note != nil {
|
||||
updated.Note = *req.Note
|
||||
}
|
||||
updated.Source = "custom"
|
||||
updated.UpdatedAt = time.Now().UTC().Format(time.RFC3339)
|
||||
if err := traffic.NormalizeEgressRule(&updated); err != nil {
|
||||
writeErr(w, 400, err.Error())
|
||||
return
|
||||
}
|
||||
rules[idx] = updated
|
||||
if err := s.saveCustomEgressBlacklist(rules); err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
s.syncEgressBlacklist()
|
||||
writeJSON(w, 200, updated)
|
||||
}
|
||||
|
||||
// DELETE /api/proxy/blacklist/rules/{id}
|
||||
func (s *Server) deleteEgressBlacklistRule(w http.ResponseWriter, r *http.Request) {
|
||||
id := strings.TrimSpace(r.PathValue("id"))
|
||||
if id == "" {
|
||||
writeErr(w, 400, "invalid rule id")
|
||||
return
|
||||
}
|
||||
rules := s.loadCustomEgressBlacklist()
|
||||
next := make([]traffic.EgressBlacklistRule, 0, len(rules))
|
||||
found := false
|
||||
for _, rule := range rules {
|
||||
if rule.ID == id {
|
||||
found = true
|
||||
continue
|
||||
}
|
||||
next = append(next, rule)
|
||||
}
|
||||
if !found {
|
||||
writeErr(w, 404, "规则不存在")
|
||||
return
|
||||
}
|
||||
if err := s.saveCustomEgressBlacklist(next); err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
s.syncEgressBlacklist()
|
||||
writeJSON(w, 200, map[string]any{"deleted": id})
|
||||
}
|
||||
|
||||
// DELETE /api/proxy/blacklist/events
|
||||
func (s *Server) clearEgressBlockEvents(w http.ResponseWriter, _ *http.Request) {
|
||||
if s.m.traffic != nil {
|
||||
s.m.traffic.ClearBlockEvents()
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"cleared": true})
|
||||
}
|
||||
|
||||
type cachedTaskEgressRules struct {
|
||||
block []traffic.EgressBlacklistRule
|
||||
allow []traffic.EgressBlacklistRule
|
||||
fetchedAt time.Time
|
||||
}
|
||||
|
||||
var taskEgressRulesCache sync.Map // int64(taskID) -> cachedTaskEgressRules
|
||||
|
||||
const taskEgressCacheTTL = 3 * time.Second
|
||||
|
||||
// checkTaskEgressBlacklist evaluates task-scoped task_intercept_rules at the
|
||||
// recording proxy egress boundary (#218 Phase 2). Built-in SSRF guard is always
|
||||
// evaluated before this callback and cannot be bypassed by task allow rules.
|
||||
func (s *Server) checkTaskEgressBlacklist(taskIDStr, rawHost, scheme string) (string, string) {
|
||||
if s == nil || s.m == nil || s.m.Assets() == nil {
|
||||
return "", ""
|
||||
}
|
||||
taskID, err := strconv.ParseInt(strings.TrimSpace(taskIDStr), 10, 64)
|
||||
if err != nil || taskID <= 0 {
|
||||
return "", ""
|
||||
}
|
||||
var entry cachedTaskEgressRules
|
||||
if v, ok := taskEgressRulesCache.Load(taskID); ok {
|
||||
if c, ok2 := v.(cachedTaskEgressRules); ok2 && time.Since(c.fetchedAt) < taskEgressCacheTTL {
|
||||
entry = c
|
||||
}
|
||||
}
|
||||
if entry.fetchedAt.IsZero() {
|
||||
blockRaw, allowRaw, err := s.m.Assets().TaskInterceptRulesSplit(taskID)
|
||||
if err != nil {
|
||||
return "", ""
|
||||
}
|
||||
entry = cachedTaskEgressRules{
|
||||
block: translateAssetInterceptRules(blockRaw),
|
||||
allow: translateAssetInterceptRules(allowRaw),
|
||||
fetchedAt: time.Now(),
|
||||
}
|
||||
taskEgressRulesCache.Store(taskID, entry)
|
||||
}
|
||||
if len(entry.block) == 0 {
|
||||
return "", ""
|
||||
}
|
||||
if len(entry.allow) > 0 {
|
||||
if reason, _ := traffic.MatchEgressRules(entry.allow, rawHost, scheme); reason != "" {
|
||||
return "", ""
|
||||
}
|
||||
}
|
||||
if reason, pat := traffic.MatchEgressRules(entry.block, rawHost, scheme); reason != "" {
|
||||
return fmt.Sprintf("task #%d intercept rule: %s", taskID, reason), pat
|
||||
}
|
||||
return "", ""
|
||||
}
|
||||
|
||||
// loadTaskEgressRules returns translated block rules for one task (used for gateway sync).
|
||||
func (s *Server) loadTaskEgressRules(taskIDStr string) []traffic.EgressBlacklistRule {
|
||||
if s == nil || s.m == nil || s.m.Assets() == nil {
|
||||
return nil
|
||||
}
|
||||
taskID, err := strconv.ParseInt(strings.TrimSpace(taskIDStr), 10, 64)
|
||||
if err != nil || taskID <= 0 {
|
||||
return nil
|
||||
}
|
||||
blockRaw, _, err := s.m.Assets().TaskInterceptRulesSplit(taskID)
|
||||
if err != nil || len(blockRaw) == 0 {
|
||||
return nil
|
||||
}
|
||||
return translateAssetInterceptRules(blockRaw)
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
)
|
||||
|
||||
func TestTranslateAssetInterceptRules(t *testing.T) {
|
||||
in := []db.AssetInterceptRule{
|
||||
{ID: 1, Enabled: true, Kind: "exact_domain", Pattern: "Admin.Example.com", Note: "prod"},
|
||||
{ID: 2, Enabled: true, Kind: "fuzzy_domain", Pattern: "gov.cn", Note: "gov"},
|
||||
{ID: 3, Enabled: true, Kind: "exact_ip", Pattern: "198.51.100.9"},
|
||||
{ID: 4, Enabled: true, Kind: "cidr", Pattern: "203.0.113.0/24"},
|
||||
{ID: 5, Enabled: true, Kind: "exact_url", Pattern: "https://pay.example.org:8443/checkout"},
|
||||
{ID: 6, Enabled: false, Kind: "exact_domain", Pattern: "disabled.example.com"},
|
||||
{ID: 7, Enabled: true, Kind: "fuzzy_url", Pattern: "/admin/delete"},
|
||||
}
|
||||
got := translateAssetInterceptRules(in)
|
||||
if len(got) != 5 {
|
||||
t.Fatalf("translated %d rules, want 5: %+v", len(got), got)
|
||||
}
|
||||
want := []struct {
|
||||
kind string
|
||||
pattern string
|
||||
}{
|
||||
{"domain", "admin.example.com"},
|
||||
{"suffix", "*.gov.cn"},
|
||||
{"ip", "198.51.100.9"},
|
||||
{"cidr", "203.0.113.0/24"},
|
||||
{"domain", "pay.example.org"},
|
||||
}
|
||||
for i, w := range want {
|
||||
if got[i].Kind != w.kind || got[i].Pattern != w.pattern || got[i].Source != "asset_intercept" {
|
||||
t.Fatalf("rule[%d] = %+v, want kind=%s pattern=%s source=asset_intercept", i, got[i], w.kind, w.pattern)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"crypto/subtle"
|
||||
"encoding/json"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Autumn-27/artex/internal/sandbox"
|
||||
"github.com/Autumn-27/artex/traffic"
|
||||
)
|
||||
|
||||
// authorizeGatewayRequest authenticates internal requests from artex-gateway.
|
||||
// When ARTEX_GATEWAY_TOKEN is configured, X-Artex-Gateway-Token must match
|
||||
// exactly (constant-time). When unset, only loopback callers are permitted.
|
||||
func (s *Server) authorizeGatewayRequest(r *http.Request) bool {
|
||||
expected := strings.TrimSpace(os.Getenv("ARTEX_GATEWAY_TOKEN"))
|
||||
if expected != "" {
|
||||
got := strings.TrimSpace(r.Header.Get("X-Artex-Gateway-Token"))
|
||||
return len(got) == len(expected) && subtle.ConstantTimeCompare([]byte(got), []byte(expected)) == 1
|
||||
}
|
||||
host := r.RemoteAddr
|
||||
if h, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
|
||||
host = h
|
||||
}
|
||||
ip := net.ParseIP(strings.Trim(strings.TrimSpace(host), "[]"))
|
||||
return ip != nil && ip.IsLoopback()
|
||||
}
|
||||
|
||||
// GET /api/internal/gateway/policy
|
||||
func (s *Server) getGatewayPolicy(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorizeGatewayRequest(r) {
|
||||
writeErr(w, http.StatusUnauthorized, "unauthorized gateway request")
|
||||
return
|
||||
}
|
||||
rt := s.ensureRouteRuntime()
|
||||
gwID := strings.TrimSpace(r.URL.Query().Get("gateway_id"))
|
||||
rt.mu.Lock()
|
||||
rt.gwLastSeen = time.Now()
|
||||
if gwID != "" {
|
||||
rt.gwID = gwID
|
||||
}
|
||||
gs := rt.gwSettings
|
||||
routesCopy := make(map[string]ContainerProxyRoute, len(rt.routes))
|
||||
for k, v := range rt.routes {
|
||||
routesCopy[k] = v
|
||||
}
|
||||
rt.mu.Unlock()
|
||||
|
||||
snap := traffic.GatewayPolicySnapshot{
|
||||
GlobalUpstreamURL: strings.TrimSpace(s.m.GlobalProxy()),
|
||||
ContainerRoutes: make(map[string]traffic.GatewayContainerRoute, len(routesCopy)),
|
||||
UDPPolicy: traffic.NormalizeUDPPolicy(gs.UDPPolicy),
|
||||
DNSUpstream: gs.DNSUpstream,
|
||||
}
|
||||
|
||||
if s.m.traffic != nil {
|
||||
if ssrf := s.m.traffic.SSRFGuardConfigSnapshot(); ssrf != nil && ssrf.Enabled {
|
||||
gp := &traffic.GatewaySSRFPolicy{
|
||||
Enabled: true,
|
||||
BlockPrivate: ssrf.BlockPrivate,
|
||||
BlockedHosts: ssrf.BlockedHosts,
|
||||
}
|
||||
for _, c := range ssrf.BlockedCIDRs {
|
||||
if c != nil {
|
||||
gp.BlockedCIDRs = append(gp.BlockedCIDRs, c.String())
|
||||
}
|
||||
}
|
||||
for _, ip := range ssrf.InfraIPs {
|
||||
if ip != nil {
|
||||
gp.InfraIPs = append(gp.InfraIPs, ip.String())
|
||||
}
|
||||
}
|
||||
snap.SSRF = gp
|
||||
}
|
||||
snap.PassthroughHosts = s.m.traffic.PassthroughHosts()
|
||||
}
|
||||
|
||||
// Global + synced egress blacklist rules.
|
||||
rules := s.loadCustomEgressBlacklist()
|
||||
if s.egressBlacklistSyncAssetEnabled() && s.m.pg != nil {
|
||||
if globalAssets, err := s.m.pg.ListAssetInterceptRules(); err == nil {
|
||||
rules = append(rules, translateAssetInterceptRules(globalAssets)...)
|
||||
}
|
||||
}
|
||||
snap.BlacklistRules = rules
|
||||
|
||||
// Active sandbox container IP map + task-level asset intercept rules.
|
||||
if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() {
|
||||
ipSnap := mgr.ContainerIPSnapshot()
|
||||
snap.ContainerIPs = make(map[string]traffic.SourceIdentity, len(ipSnap))
|
||||
taskIDs := map[string]struct{}{}
|
||||
for ip, ci := range ipSnap {
|
||||
snap.ContainerIPs[ip] = traffic.SourceIdentity{
|
||||
Scope: string(ci.Scope),
|
||||
OwnerID: ci.OwnerID,
|
||||
ContainerID: ci.ContainerID,
|
||||
SrcIP: ip,
|
||||
}
|
||||
if ci.Scope == sandbox.ScopeTask && ci.OwnerID != "" {
|
||||
taskIDs[ci.OwnerID] = struct{}{}
|
||||
}
|
||||
}
|
||||
if s.egressBlacklistSyncAssetEnabled() && s.m.pg != nil && len(taskIDs) > 0 {
|
||||
snap.TaskRules = make(map[string][]traffic.EgressBlacklistRule, len(taskIDs))
|
||||
for tid := range taskIDs {
|
||||
if tr := s.loadTaskEgressRules(tid); len(tr) > 0 {
|
||||
snap.TaskRules[tid] = tr
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for key, route := range routesCopy {
|
||||
snap.ContainerRoutes[key] = traffic.GatewayContainerRoute{
|
||||
Scope: route.Scope,
|
||||
OwnerID: route.OwnerID,
|
||||
Mode: route.Mode,
|
||||
ProxyPoolID: route.ProxyPoolID,
|
||||
ProxyURL: maskSecrets(route.ProxyURL),
|
||||
EffectiveURL: s.resolveRouteEffectiveRawURL(route),
|
||||
Note: route.Note,
|
||||
UpdatedAt: route.UpdatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
writeJSON(w, 200, snap)
|
||||
}
|
||||
|
||||
// POST /api/internal/gateway/events
|
||||
func (s *Server) postGatewayEvents(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorizeGatewayRequest(r) {
|
||||
writeErr(w, http.StatusUnauthorized, "unauthorized gateway request")
|
||||
return
|
||||
}
|
||||
var batch traffic.GatewayEventBatch
|
||||
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4<<20)).Decode(&batch); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "invalid batch payload")
|
||||
return
|
||||
}
|
||||
rt := s.ensureRouteRuntime()
|
||||
rt.mu.Lock()
|
||||
rt.gwLastSeen = time.Now()
|
||||
if strings.TrimSpace(batch.GatewayID) != "" {
|
||||
rt.gwID = strings.TrimSpace(batch.GatewayID)
|
||||
}
|
||||
rt.mu.Unlock()
|
||||
|
||||
tr := s.m.Traffic()
|
||||
if tr == nil {
|
||||
writeJSON(w, 200, map[string]any{"ingested": 0})
|
||||
return
|
||||
}
|
||||
ingested := 0
|
||||
for _, nf := range batch.NetFlows {
|
||||
if err := tr.RecordNetFlow(nf); err == nil {
|
||||
ingested++
|
||||
}
|
||||
}
|
||||
for _, dq := range batch.DNSQueries {
|
||||
if err := tr.RecordDNSQuery(dq); err == nil {
|
||||
ingested++
|
||||
}
|
||||
}
|
||||
for _, ev := range batch.BlockEvents {
|
||||
tr.RecordBlockEvent(ev)
|
||||
ingested++
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"ingested": ingested})
|
||||
}
|
||||
|
||||
// startEmbeddedTransparentGatewayIfConfigured optionally launches an in-process
|
||||
// TransparentGateway when bare-metal Linux operators set ARTEX_EMBEDDED_TRANSPARENT_TCP
|
||||
// / ARTEX_EMBEDDED_TRANSPARENT_DNS / ARTEX_EMBEDDED_TRANSPARENT_UDP directly on artex.
|
||||
func (s *Server) startEmbeddedTransparentGatewayIfConfigured() {
|
||||
if s.m.traffic == nil {
|
||||
return
|
||||
}
|
||||
tcpAddr := strings.TrimSpace(os.Getenv("ARTEX_EMBEDDED_TRANSPARENT_TCP"))
|
||||
dnsAddr := strings.TrimSpace(os.Getenv("ARTEX_EMBEDDED_TRANSPARENT_DNS"))
|
||||
udpAddr := strings.TrimSpace(os.Getenv("ARTEX_EMBEDDED_TRANSPARENT_UDP"))
|
||||
if tcpAddr == "" && dnsAddr == "" && udpAddr == "" {
|
||||
return
|
||||
}
|
||||
mitmAddr := strings.TrimSpace(s.m.ProxyAddr())
|
||||
if strings.HasPrefix(mitmAddr, ":") {
|
||||
mitmAddr = "127.0.0.1" + mitmAddr
|
||||
}
|
||||
gw := traffic.NewTransparentGateway(traffic.TransparentConfig{
|
||||
TCPAddr: tcpAddr,
|
||||
DNSAddr: dnsAddr,
|
||||
UDPAddr: udpAddr,
|
||||
MITMProxyAddr: mitmAddr,
|
||||
}, traffic.LocalTransparentBackend{T: s.m.traffic})
|
||||
if err := gw.Start(); err != nil {
|
||||
log.Printf("[gateway] embedded transparent gateway start failed: %v", err)
|
||||
return
|
||||
}
|
||||
rt := s.ensureRouteRuntime()
|
||||
rt.mu.Lock()
|
||||
rt.embeddedGW = gw
|
||||
rt.gwID = "embedded"
|
||||
rt.gwLastSeen = time.Now()
|
||||
rt.mu.Unlock()
|
||||
log.Printf("[gateway] embedded transparent gateway started tcp=%q dns=%q udp=%q", tcpAddr, dnsAddr, udpAddr)
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Autumn-27/artex/traffic"
|
||||
)
|
||||
|
||||
func TestGatewaySyncAndNonHTTPTrafficAPIs(t *testing.T) {
|
||||
t.Setenv("ARTEX_GATEWAY_TOKEN", "test-gw-token-218")
|
||||
|
||||
tr, err := traffic.Open(t.TempDir(), "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("open traffic: %v", err)
|
||||
}
|
||||
defer tr.Close()
|
||||
|
||||
s := &Server{
|
||||
m: &Manager{
|
||||
traffic: tr,
|
||||
tasks: map[string]*Task{},
|
||||
},
|
||||
}
|
||||
s.initProxyRoutesAndGateway()
|
||||
|
||||
// 1. Unauthorized gateway policy request must be rejected with 401.
|
||||
reqUnauth := httptest.NewRequest(http.MethodGet, "/api/internal/gateway/policy", nil)
|
||||
recUnauth := httptest.NewRecorder()
|
||||
s.getGatewayPolicy(recUnauth, reqUnauth)
|
||||
if recUnauth.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("expected 401 for missing token, got %d", recUnauth.Code)
|
||||
}
|
||||
|
||||
// 2. Configure per-container proxy route + gateway settings.
|
||||
putRouteBody := `{"mode":"proxy","proxy_url":"socks5://127.0.0.1:1080","note":"task 5 socks5"}`
|
||||
reqRoute := httptest.NewRequest(http.MethodPut, "/api/proxy/routes/task/5", bytes.NewBufferString(putRouteBody))
|
||||
reqRoute.SetPathValue("scope", "task")
|
||||
reqRoute.SetPathValue("owner_id", "5")
|
||||
recRoute := httptest.NewRecorder()
|
||||
s.putProxyRoute(recRoute, reqRoute)
|
||||
if recRoute.Code != http.StatusOK {
|
||||
t.Fatalf("putProxyRoute failed: %d %s", recRoute.Code, recRoute.Body.String())
|
||||
}
|
||||
|
||||
reqGW := httptest.NewRequest(http.MethodPut, "/api/proxy/gateway/settings", bytes.NewBufferString(`{"udp_policy":"block","dns_upstream":"1.1.1.1:53"}`))
|
||||
recGW := httptest.NewRecorder()
|
||||
s.updateGatewaySettings(recGW, reqGW)
|
||||
if recGW.Code != http.StatusOK {
|
||||
t.Fatalf("updateGatewaySettings failed: %d %s", recGW.Code, recGW.Body.String())
|
||||
}
|
||||
|
||||
// 3. Authorized gateway policy fetch returns route & settings.
|
||||
reqPol := httptest.NewRequest(http.MethodGet, "/api/internal/gateway/policy?gateway_id=gw-test", nil)
|
||||
reqPol.Header.Set("X-Artex-Gateway-Token", "test-gw-token-218")
|
||||
recPol := httptest.NewRecorder()
|
||||
s.getGatewayPolicy(recPol, reqPol)
|
||||
if recPol.Code != http.StatusOK {
|
||||
t.Fatalf("getGatewayPolicy failed: %d %s", recPol.Code, recPol.Body.String())
|
||||
}
|
||||
var snap traffic.GatewayPolicySnapshot
|
||||
if err := json.Unmarshal(recPol.Body.Bytes(), &snap); err != nil {
|
||||
t.Fatalf("decode policy snapshot: %v", err)
|
||||
}
|
||||
if snap.UDPPolicy != traffic.UDPPolicyBlock || snap.DNSUpstream != "1.1.1.1:53" {
|
||||
t.Fatalf("unexpected gateway policy: %+v", snap)
|
||||
}
|
||||
if r, ok := snap.ContainerRoutes["task:5"]; !ok || r.EffectiveURL != "socks5://127.0.0.1:1080" {
|
||||
t.Fatalf("expected task:5 route in snapshot, got %+v", snap.ContainerRoutes)
|
||||
}
|
||||
|
||||
// 4. Ingest gateway events (net_flows + dns_queries + block_events).
|
||||
batch := traffic.GatewayEventBatch{
|
||||
GatewayID: "gw-test",
|
||||
NetFlows: []traffic.NetFlowRecord{{
|
||||
ID: "nf-test-1",
|
||||
TS: time.Now().Unix(),
|
||||
Protocol: "tcp",
|
||||
DstIP: "10.0.0.8",
|
||||
DstPort: 3306,
|
||||
DstHost: "db.target.local",
|
||||
Action: "allow",
|
||||
BytesTX: 64,
|
||||
BytesRX: 128,
|
||||
TXPreview: []byte("SELECT 1"),
|
||||
RXPreview: []byte("5.7.40-mysql"),
|
||||
SandboxScope: "task",
|
||||
SandboxOwnerID: "5",
|
||||
SrcIP: "172.30.0.5",
|
||||
}},
|
||||
DNSQueries: []traffic.DNSQueryRecord{{
|
||||
ID: "dns-test-1",
|
||||
TS: time.Now().Unix(),
|
||||
QName: "db.target.local",
|
||||
QType: "A",
|
||||
RCode: "NOERROR",
|
||||
Answers: []string{"10.0.0.8"},
|
||||
Action: "allow",
|
||||
Upstream: "direct:1.1.1.1:53",
|
||||
SandboxScope: "task",
|
||||
SandboxOwnerID: "5",
|
||||
SrcIP: "172.30.0.5",
|
||||
}},
|
||||
}
|
||||
rawBatch, _ := json.Marshal(batch)
|
||||
reqEv := httptest.NewRequest(http.MethodPost, "/api/internal/gateway/events", bytes.NewReader(rawBatch))
|
||||
reqEv.Header.Set("X-Artex-Gateway-Token", "test-gw-token-218")
|
||||
recEv := httptest.NewRecorder()
|
||||
s.postGatewayEvents(recEv, reqEv)
|
||||
if recEv.Code != http.StatusOK {
|
||||
t.Fatalf("postGatewayEvents failed: %d %s", recEv.Code, recEv.Body.String())
|
||||
}
|
||||
|
||||
// 5. Query flows + flow detail + DNS via public API handlers.
|
||||
recFlows := httptest.NewRecorder()
|
||||
s.getTrafficFlows(recFlows, httptest.NewRequest(http.MethodGet, "/api/traffic/flows?protocol=tcp", nil))
|
||||
if recFlows.Code != http.StatusOK {
|
||||
t.Fatalf("getTrafficFlows: %d %s", recFlows.Code, recFlows.Body.String())
|
||||
}
|
||||
var flowsResp struct {
|
||||
Total int `json:"total"`
|
||||
Flows []traffic.NetFlowRecord `json:"flows"`
|
||||
}
|
||||
_ = json.Unmarshal(recFlows.Body.Bytes(), &flowsResp)
|
||||
if flowsResp.Total != 1 || len(flowsResp.Flows) != 1 || flowsResp.Flows[0].DstPort != 3306 {
|
||||
t.Fatalf("unexpected flowsResp: %+v", flowsResp)
|
||||
}
|
||||
|
||||
reqDet := httptest.NewRequest(http.MethodGet, "/api/traffic/flows/nf-test-1", nil)
|
||||
reqDet.SetPathValue("id", "nf-test-1")
|
||||
recDet := httptest.NewRecorder()
|
||||
s.getTrafficFlowDetail(recDet, reqDet)
|
||||
if recDet.Code != http.StatusOK || !bytes.Contains(recDet.Body.Bytes(), []byte("SELECT 1")) {
|
||||
t.Fatalf("unexpected flow detail: %d %s", recDet.Code, recDet.Body.String())
|
||||
}
|
||||
|
||||
recDNS := httptest.NewRecorder()
|
||||
s.getTrafficDNS(recDNS, httptest.NewRequest(http.MethodGet, "/api/traffic/dns?q=db.target", nil))
|
||||
if recDNS.Code != http.StatusOK {
|
||||
t.Fatalf("getTrafficDNS: %d %s", recDNS.Code, recDNS.Body.String())
|
||||
}
|
||||
var dnsResp struct {
|
||||
Total int `json:"total"`
|
||||
Queries []traffic.DNSQueryRecord `json:"queries"`
|
||||
}
|
||||
_ = json.Unmarshal(recDNS.Body.Bytes(), &dnsResp)
|
||||
if dnsResp.Total != 1 || len(dnsResp.Queries) != 1 || dnsResp.Queries[0].QName != "db.target.local" {
|
||||
t.Fatalf("unexpected dnsResp: %+v", dnsResp)
|
||||
}
|
||||
|
||||
// 6. GET /api/proxy/routes reflects gateway connected=true and task:5 override.
|
||||
recRoutes := httptest.NewRecorder()
|
||||
s.getProxyRoutes(recRoutes, httptest.NewRequest(http.MethodGet, "/api/proxy/routes", nil))
|
||||
if recRoutes.Code != http.StatusOK {
|
||||
t.Fatalf("getProxyRoutes: %d %s", recRoutes.Code, recRoutes.Body.String())
|
||||
}
|
||||
body := recRoutes.Body.String()
|
||||
if !bytes.Contains([]byte(body), []byte(`"connected":true`)) || !bytes.Contains([]byte(body), []byte(`"socks5://127.0.0.1:1080"`)) {
|
||||
t.Fatalf("unexpected getProxyRoutes body: %s", body)
|
||||
}
|
||||
if bytes.Contains([]byte(body), []byte("全局")) {
|
||||
t.Fatalf("getProxyRoutes must not hardcode Chinese labels in API response: %s", body)
|
||||
}
|
||||
}
|
||||
@@ -2181,6 +2181,13 @@ func (m *Manager) DeleteTask(id string, opts DeleteTaskOptions) (DeleteTaskResul
|
||||
finalizeErrs = append(finalizeErrs, fmt.Errorf("finalize traffic deletion: %w", err))
|
||||
}
|
||||
}
|
||||
if opts.DeleteTraffic && m.traffic != nil {
|
||||
if deletedNonHTTP, err := m.traffic.DeleteNonHTTPByOwner("task", id); err != nil {
|
||||
finalizeErrs = append(finalizeErrs, fmt.Errorf("finalize non-http traffic deletion: %w", err))
|
||||
} else {
|
||||
result.TrafficDeleted += deletedNonHTTP
|
||||
}
|
||||
}
|
||||
if fileStage != nil {
|
||||
if err := fileStage.commit(); err != nil {
|
||||
finalizeErrs = append(finalizeErrs, fmt.Errorf("finalize task file deletion: %w", err))
|
||||
|
||||
+133
-5
@@ -8,11 +8,13 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/exec"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/Autumn-27/artex/internal/sandbox"
|
||||
"github.com/Autumn-27/norma/llm"
|
||||
"github.com/Autumn-27/norma/mcp"
|
||||
@@ -186,12 +188,14 @@ func newSandboxStdioMCPClient(ctx context.Context, mgr *sandbox.Manager, target
|
||||
if strings.TrimSpace(workDir) != "" {
|
||||
containerWorkDir = sandbox.HostToContainerPath(mgr.Config().LocalRootFor(target), workDir)
|
||||
}
|
||||
envSlice := append([]string{}, mgr.ProxyEnv(true)...)
|
||||
for k, v := range env {
|
||||
envSlice = append(envSlice, k+"="+v)
|
||||
sandboxProxyURL := ""
|
||||
if mgr != nil {
|
||||
sandboxProxyURL = stripURLCredentials(mgr.Config().ProxyURL)
|
||||
}
|
||||
adaptedArgs := adaptSandboxMCPArgs(args, sandboxProxyURL)
|
||||
envSlice := buildSandboxMCPEnv(mgr, env)
|
||||
stream, err := mgr.ExecStream(ctx, target, sandbox.ExecSpec{
|
||||
Cmd: append([]string{command}, args...),
|
||||
Cmd: append([]string{command}, adaptedArgs...),
|
||||
WorkDir: containerWorkDir,
|
||||
Env: envSlice,
|
||||
})
|
||||
@@ -221,6 +225,130 @@ func newSandboxStdioMCPClient(ctx context.Context, mgr *sandbox.Manager, target
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// adaptSandboxMCPArgs rewrites loopback --proxy-server flags (such as
|
||||
// http://127.0.0.1:8788 persisted for local mode by syncBrowserMCPProxy) to the
|
||||
// sandbox-reachable recording proxy URL (e.g. http://172.30.0.2:8788).
|
||||
// Chromium rejects inline credentials in --proxy-server, so sandboxProxyURL must
|
||||
// be credential-free; Layer-1 container source IP provides attribution.
|
||||
func adaptSandboxMCPArgs(args []string, sandboxProxyURL string) []string {
|
||||
out := make([]string, 0, len(args))
|
||||
for i := 0; i < len(args); i++ {
|
||||
arg := args[i]
|
||||
if arg == "--proxy-server" && i+1 < len(args) {
|
||||
val := args[i+1]
|
||||
i++
|
||||
if isLoopbackProxyTarget(val) {
|
||||
if sandboxProxyURL != "" {
|
||||
out = append(out, "--proxy-server", sandboxProxyURL)
|
||||
}
|
||||
continue
|
||||
}
|
||||
out = append(out, "--proxy-server", val)
|
||||
continue
|
||||
}
|
||||
if strings.HasPrefix(arg, "--proxy-server=") {
|
||||
val := strings.TrimPrefix(arg, "--proxy-server=")
|
||||
if isLoopbackProxyTarget(val) {
|
||||
if sandboxProxyURL != "" {
|
||||
out = append(out, "--proxy-server="+sandboxProxyURL)
|
||||
}
|
||||
continue
|
||||
}
|
||||
out = append(out, arg)
|
||||
continue
|
||||
}
|
||||
out = append(out, arg)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func isLoopbackProxyTarget(raw string) bool {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
return false
|
||||
}
|
||||
if !strings.Contains(raw, "://") {
|
||||
raw = "http://" + raw
|
||||
}
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
h := strings.ToLower(strings.Trim(strings.TrimSpace(u.Hostname()), "[]"))
|
||||
if h == "localhost" || h == "0.0.0.0" || h == "::" {
|
||||
return true
|
||||
}
|
||||
if ip := net.ParseIP(h); ip != nil && (ip.IsLoopback() || ip.IsUnspecified()) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func stripURLCredentials(raw string) string {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
return ""
|
||||
}
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil {
|
||||
return raw
|
||||
}
|
||||
u.User = nil
|
||||
return u.String()
|
||||
}
|
||||
|
||||
// buildSandboxMCPEnv merges MCP-configured env vars with sandbox proxy/CA env
|
||||
// vars so host-side CA paths (like /app/data/traffic/_ca/mitmproxy-ca-cert.pem)
|
||||
// never clobber the in-container mounted CA path (/etc/artex/ca.crt).
|
||||
func buildSandboxMCPEnv(mgr *sandbox.Manager, userEnv map[string]string) []string {
|
||||
merged := make(map[string]string, len(userEnv)+12)
|
||||
hostCA := ""
|
||||
if mgr != nil {
|
||||
hostCA = strings.TrimSpace(mgr.Config().CACertPath)
|
||||
}
|
||||
for k, v := range userEnv {
|
||||
if isHostCAPathOverride(k, v, hostCA) {
|
||||
continue
|
||||
}
|
||||
merged[k] = v
|
||||
}
|
||||
if mgr != nil {
|
||||
for _, kv := range mgr.ProxyEnv(true) {
|
||||
if k, v, ok := strings.Cut(kv, "="); ok {
|
||||
merged[k] = v
|
||||
}
|
||||
}
|
||||
}
|
||||
keys := make([]string, 0, len(merged))
|
||||
for k := range merged {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
out := make([]string, 0, len(keys))
|
||||
for _, k := range keys {
|
||||
out = append(out, k+"="+merged[k])
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func isHostCAPathOverride(key, val, hostCA string) bool {
|
||||
switch key {
|
||||
case "NODE_EXTRA_CA_CERTS", "SSL_CERT_FILE", "CURL_CA_BUNDLE", "REQUESTS_CA_BUNDLE", "GIT_SSL_CAINFO":
|
||||
v := strings.TrimSpace(val)
|
||||
if v == "" {
|
||||
return true
|
||||
}
|
||||
if hostCA != "" && v == hostCA {
|
||||
return true
|
||||
}
|
||||
// Persisted control-plane paths do not exist inside sandbox containers.
|
||||
if strings.HasPrefix(v, "/app/data/") || strings.Contains(v, "mitmproxy-ca-cert.pem") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (c *stdioMCPClient) readLoop(r io.Reader) {
|
||||
br := bufio.NewReaderSize(r, 64*1024)
|
||||
for {
|
||||
|
||||
@@ -0,0 +1,469 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Autumn-27/artex/internal/sandbox"
|
||||
"github.com/Autumn-27/artex/traffic"
|
||||
)
|
||||
|
||||
const (
|
||||
settingContainerProxyRoutes = "proxy_container_routes_json"
|
||||
settingGatewayPolicy = "proxy_gateway_settings_json"
|
||||
)
|
||||
|
||||
// ContainerProxyRoute persists a per-sandbox-owner upstream proxy override (#218 Phase 4).
|
||||
type ContainerProxyRoute struct {
|
||||
Scope string `json:"scope"` // task, session
|
||||
OwnerID string `json:"owner_id"` // task ID or session ID
|
||||
Mode string `json:"mode"` // inherit, direct, proxy
|
||||
ProxyPoolID string `json:"proxy_pool_id,omitempty"` // optional proxy pool entry ID
|
||||
ProxyURL string `json:"proxy_url,omitempty"` // raw custom URL in storage; masked in API output
|
||||
Note string `json:"note,omitempty"`
|
||||
UpdatedAt string `json:"updated_at,omitempty"`
|
||||
}
|
||||
|
||||
// GatewaySettings persists transparent gateway runtime policy knobs.
|
||||
type GatewaySettings struct {
|
||||
UDPPolicy string `json:"udp_policy"`
|
||||
DNSUpstream string `json:"dns_upstream"`
|
||||
}
|
||||
|
||||
type proxyRouteRuntime struct {
|
||||
mu sync.RWMutex
|
||||
routes map[string]ContainerProxyRoute // key: "scope:owner_id"
|
||||
gwSettings GatewaySettings
|
||||
gwID string
|
||||
gwLastSeen time.Time
|
||||
embeddedGW *traffic.TransparentGateway
|
||||
}
|
||||
|
||||
func (s *Server) ensureRouteRuntime() *proxyRouteRuntime {
|
||||
s.cfgMu.Lock()
|
||||
defer s.cfgMu.Unlock()
|
||||
if s.proxyRoutes == nil {
|
||||
s.proxyRoutes = &proxyRouteRuntime{
|
||||
routes: map[string]ContainerProxyRoute{},
|
||||
gwSettings: GatewaySettings{
|
||||
UDPPolicy: traffic.UDPPolicyBlockOnProxy,
|
||||
},
|
||||
}
|
||||
}
|
||||
return s.proxyRoutes
|
||||
}
|
||||
|
||||
func (s *Server) initProxyRoutesAndGateway() {
|
||||
rt := s.ensureRouteRuntime()
|
||||
// Load persisted per-container proxy routes.
|
||||
if s.m.pg != nil {
|
||||
if raw, ok, err := s.m.pg.GetSetting(settingContainerProxyRoutes); err == nil && ok && strings.TrimSpace(raw) != "" {
|
||||
var list []ContainerProxyRoute
|
||||
if json.Unmarshal([]byte(raw), &list) == nil {
|
||||
rt.mu.Lock()
|
||||
for _, r := range list {
|
||||
if r.Scope != "" && r.OwnerID != "" {
|
||||
rt.routes[r.Scope+":"+r.OwnerID] = r
|
||||
}
|
||||
}
|
||||
rt.mu.Unlock()
|
||||
}
|
||||
}
|
||||
if raw, ok, err := s.m.pg.GetSetting(settingGatewayPolicy); err == nil && ok && strings.TrimSpace(raw) != "" {
|
||||
var gs GatewaySettings
|
||||
if json.Unmarshal([]byte(raw), &gs) == nil {
|
||||
gs.UDPPolicy = traffic.NormalizeUDPPolicy(gs.UDPPolicy)
|
||||
gs.DNSUpstream = strings.TrimSpace(gs.DNSUpstream)
|
||||
rt.mu.Lock()
|
||||
rt.gwSettings = gs
|
||||
rt.mu.Unlock()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if s.m.traffic != nil {
|
||||
rt.mu.RLock()
|
||||
gs := rt.gwSettings
|
||||
rt.mu.RUnlock()
|
||||
s.m.traffic.SetGatewaySettings(gs.UDPPolicy, gs.DNSUpstream)
|
||||
s.m.traffic.SetUpstreamResolver(s.resolveContainerUpstream)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) resolvePoolEntryRawURL(poolID string) string {
|
||||
poolID = strings.TrimSpace(poolID)
|
||||
if poolID == "" {
|
||||
return ""
|
||||
}
|
||||
for _, e := range s.m.proxyPoolEntries() {
|
||||
if e.ID == poolID {
|
||||
return strings.TrimSpace(e.RawURL)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (s *Server) resolveRouteEffectiveRawURL(r ContainerProxyRoute) string {
|
||||
if strings.ToLower(strings.TrimSpace(r.Mode)) != "proxy" {
|
||||
return ""
|
||||
}
|
||||
if r.ProxyPoolID != "" {
|
||||
if raw := s.resolvePoolEntryRawURL(r.ProxyPoolID); raw != "" {
|
||||
return raw
|
||||
}
|
||||
}
|
||||
return strings.TrimSpace(r.ProxyURL)
|
||||
}
|
||||
|
||||
func (s *Server) resolveContainerUpstream(src traffic.SourceIdentity) (*url.URL, bool) {
|
||||
if src.Scope == "" || src.OwnerID == "" {
|
||||
return nil, false
|
||||
}
|
||||
rt := s.ensureRouteRuntime()
|
||||
rt.mu.RLock()
|
||||
r, ok := rt.routes[src.Scope+":"+src.OwnerID]
|
||||
rt.mu.RUnlock()
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
switch strings.ToLower(strings.TrimSpace(r.Mode)) {
|
||||
case "direct":
|
||||
return nil, true
|
||||
case "proxy":
|
||||
raw := s.resolveRouteEffectiveRawURL(r)
|
||||
if raw == "" {
|
||||
return nil, false
|
||||
}
|
||||
u, err := traffic.ValidateProxyURL(raw)
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
return u, true
|
||||
default:
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) saveContainerProxyRoutesLocked(rt *proxyRouteRuntime) error {
|
||||
if s.m.pg == nil {
|
||||
return nil
|
||||
}
|
||||
list := make([]ContainerProxyRoute, 0, len(rt.routes))
|
||||
for _, r := range rt.routes {
|
||||
list = append(list, r)
|
||||
}
|
||||
sort.Slice(list, func(i, j int) bool {
|
||||
if list[i].Scope != list[j].Scope {
|
||||
return list[i].Scope < list[j].Scope
|
||||
}
|
||||
return list[i].OwnerID < list[j].OwnerID
|
||||
})
|
||||
b, err := json.Marshal(list)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return s.m.pg.SetSetting(settingContainerProxyRoutes, string(b))
|
||||
}
|
||||
|
||||
func (s *Server) maskedRouteView(r ContainerProxyRoute) ContainerProxyRoute {
|
||||
out := r
|
||||
if out.ProxyURL != "" {
|
||||
out.ProxyURL = maskSecrets(out.ProxyURL)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
type containerRouteStatusItem struct {
|
||||
Scope string `json:"scope"`
|
||||
OwnerID string `json:"owner_id"`
|
||||
ContainerName string `json:"container_name,omitempty"`
|
||||
ContainerID string `json:"container_id,omitempty"`
|
||||
State string `json:"state,omitempty"`
|
||||
IP string `json:"ip,omitempty"`
|
||||
Mode string `json:"mode"` // inherit, direct, proxy
|
||||
ProxyPoolID string `json:"proxy_pool_id,omitempty"`
|
||||
ProxyURL string `json:"proxy_url,omitempty"`
|
||||
EffectiveProxy string `json:"effective_proxy"`
|
||||
Note string `json:"note,omitempty"`
|
||||
UpdatedAt string `json:"updated_at,omitempty"`
|
||||
}
|
||||
|
||||
// GET /api/proxy/routes
|
||||
func (s *Server) getProxyRoutes(w http.ResponseWriter, r *http.Request) {
|
||||
rt := s.ensureRouteRuntime()
|
||||
rt.mu.RLock()
|
||||
routesMap := make(map[string]ContainerProxyRoute, len(rt.routes))
|
||||
for k, v := range rt.routes {
|
||||
routesMap[k] = v
|
||||
}
|
||||
gs := rt.gwSettings
|
||||
gwID := rt.gwID
|
||||
gwLast := rt.gwLastSeen
|
||||
embedded := rt.embeddedGW != nil
|
||||
rt.mu.RUnlock()
|
||||
|
||||
globalRaw := strings.TrimSpace(s.m.GlobalProxy())
|
||||
globalDisplay := "direct"
|
||||
if globalRaw != "" {
|
||||
globalDisplay = maskSecrets(globalRaw)
|
||||
}
|
||||
|
||||
effectiveFor := func(route *ContainerProxyRoute) string {
|
||||
if route == nil || route.Mode == "" || route.Mode == "inherit" {
|
||||
return globalDisplay
|
||||
}
|
||||
if route.Mode == "direct" {
|
||||
return "direct"
|
||||
}
|
||||
if raw := s.resolveRouteEffectiveRawURL(*route); raw != "" {
|
||||
return maskSecrets(raw)
|
||||
}
|
||||
return globalDisplay
|
||||
}
|
||||
|
||||
seen := map[string]bool{}
|
||||
items := make([]containerRouteStatusItem, 0, len(routesMap)+4)
|
||||
|
||||
if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
|
||||
st := mgr.StatusWithStats(ctx, false)
|
||||
cancel()
|
||||
ipSnap := mgr.ContainerIPSnapshot()
|
||||
ipByName := map[string]string{}
|
||||
for ip, id := range ipSnap {
|
||||
ipByName[id.ContainerName] = ip
|
||||
}
|
||||
for _, c := range st.Containers {
|
||||
key := string(c.Scope) + ":" + c.OwnerID
|
||||
seen[key] = true
|
||||
var rPtr *ContainerProxyRoute
|
||||
mode := "inherit"
|
||||
var poolID, proxyURL, note, updatedAt string
|
||||
if existing, ok := routesMap[key]; ok {
|
||||
cp := existing
|
||||
rPtr = &cp
|
||||
mode = existing.Mode
|
||||
poolID = existing.ProxyPoolID
|
||||
proxyURL = maskSecrets(existing.ProxyURL)
|
||||
note = existing.Note
|
||||
updatedAt = existing.UpdatedAt
|
||||
}
|
||||
items = append(items, containerRouteStatusItem{
|
||||
Scope: string(c.Scope),
|
||||
OwnerID: c.OwnerID,
|
||||
ContainerName: c.Name,
|
||||
ContainerID: c.ShortID,
|
||||
State: c.State,
|
||||
IP: ipByName[c.Name],
|
||||
Mode: mode,
|
||||
ProxyPoolID: poolID,
|
||||
ProxyURL: proxyURL,
|
||||
EffectiveProxy: effectiveFor(rPtr),
|
||||
Note: note,
|
||||
UpdatedAt: updatedAt,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Include persisted route rules for tasks/sessions without a currently present container.
|
||||
for key, route := range routesMap {
|
||||
if seen[key] {
|
||||
continue
|
||||
}
|
||||
cp := route
|
||||
items = append(items, containerRouteStatusItem{
|
||||
Scope: route.Scope,
|
||||
OwnerID: route.OwnerID,
|
||||
State: "inactive",
|
||||
Mode: route.Mode,
|
||||
ProxyPoolID: route.ProxyPoolID,
|
||||
ProxyURL: maskSecrets(route.ProxyURL),
|
||||
EffectiveProxy: effectiveFor(&cp),
|
||||
Note: route.Note,
|
||||
UpdatedAt: route.UpdatedAt,
|
||||
})
|
||||
}
|
||||
sort.Slice(items, func(i, j int) bool {
|
||||
if items[i].Scope != items[j].Scope {
|
||||
return items[i].Scope < items[j].Scope
|
||||
}
|
||||
return items[i].OwnerID < items[j].OwnerID
|
||||
})
|
||||
|
||||
routesList := make([]ContainerProxyRoute, 0, len(routesMap))
|
||||
for _, route := range routesMap {
|
||||
routesList = append(routesList, s.maskedRouteView(route))
|
||||
}
|
||||
sort.Slice(routesList, func(i, j int) bool {
|
||||
if routesList[i].Scope != routesList[j].Scope {
|
||||
return routesList[i].Scope < routesList[j].Scope
|
||||
}
|
||||
return routesList[i].OwnerID < routesList[j].OwnerID
|
||||
})
|
||||
|
||||
connected := embedded || (!gwLast.IsZero() && time.Since(gwLast) < 15*time.Second)
|
||||
var lastSeenStr string
|
||||
if !gwLast.IsZero() {
|
||||
lastSeenStr = gwLast.UTC().Format(time.RFC3339)
|
||||
}
|
||||
|
||||
writeJSON(w, 200, map[string]any{
|
||||
"global_proxy": globalDisplay,
|
||||
"routes": routesList,
|
||||
"containers": items,
|
||||
"gateway": map[string]any{
|
||||
"connected": connected,
|
||||
"embedded": embedded,
|
||||
"gateway_id": gwID,
|
||||
"last_seen": lastSeenStr,
|
||||
"udp_policy": traffic.NormalizeUDPPolicy(gs.UDPPolicy),
|
||||
"dns_upstream": gs.DNSUpstream,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// PUT /api/proxy/routes/{scope}/{owner_id}
|
||||
func (s *Server) putProxyRoute(w http.ResponseWriter, r *http.Request) {
|
||||
scope := strings.ToLower(strings.TrimSpace(r.PathValue("scope")))
|
||||
ownerID := strings.TrimSpace(r.PathValue("owner_id"))
|
||||
if (scope != "task" && scope != "session") || ownerID == "" {
|
||||
writeErr(w, http.StatusBadRequest, "invalid scope or owner_id (scope must be task or session)")
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Mode string `json:"mode"`
|
||||
ProxyPoolID string `json:"proxy_pool_id"`
|
||||
ProxyURL string `json:"proxy_url"`
|
||||
Note string `json:"note"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "invalid JSON body")
|
||||
return
|
||||
}
|
||||
mode := strings.ToLower(strings.TrimSpace(req.Mode))
|
||||
if mode == "" {
|
||||
mode = "inherit"
|
||||
}
|
||||
if mode != "inherit" && mode != "direct" && mode != "proxy" {
|
||||
writeErr(w, http.StatusBadRequest, "mode must be inherit, direct, or proxy")
|
||||
return
|
||||
}
|
||||
|
||||
rt := s.ensureRouteRuntime()
|
||||
key := scope + ":" + ownerID
|
||||
|
||||
if mode == "inherit" {
|
||||
rt.mu.Lock()
|
||||
delete(rt.routes, key)
|
||||
err := s.saveContainerProxyRoutesLocked(rt)
|
||||
rt.mu.Unlock()
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, ContainerProxyRoute{Scope: scope, OwnerID: ownerID, Mode: "inherit"})
|
||||
return
|
||||
}
|
||||
|
||||
route := ContainerProxyRoute{
|
||||
Scope: scope,
|
||||
OwnerID: ownerID,
|
||||
Mode: mode,
|
||||
ProxyPoolID: strings.TrimSpace(req.ProxyPoolID),
|
||||
ProxyURL: strings.TrimSpace(req.ProxyURL),
|
||||
Note: strings.TrimSpace(req.Note),
|
||||
UpdatedAt: time.Now().UTC().Format(time.RFC3339),
|
||||
}
|
||||
|
||||
if mode == "proxy" {
|
||||
if route.ProxyPoolID != "" {
|
||||
if s.resolvePoolEntryRawURL(route.ProxyPoolID) == "" {
|
||||
writeErr(w, http.StatusBadRequest, fmt.Sprintf("proxy_pool_id %q not found", route.ProxyPoolID))
|
||||
return
|
||||
}
|
||||
route.ProxyURL = ""
|
||||
} else {
|
||||
// If user left masked placeholder unchanged, preserve existing raw URL.
|
||||
if strings.Contains(route.ProxyURL, "***") {
|
||||
rt.mu.RLock()
|
||||
if prev, ok := rt.routes[key]; ok && prev.ProxyURL != "" {
|
||||
route.ProxyURL = prev.ProxyURL
|
||||
}
|
||||
rt.mu.RUnlock()
|
||||
}
|
||||
if _, err := traffic.ValidateProxyURL(route.ProxyURL); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
} else {
|
||||
route.ProxyPoolID = ""
|
||||
route.ProxyURL = ""
|
||||
}
|
||||
|
||||
rt.mu.Lock()
|
||||
rt.routes[key] = route
|
||||
err := s.saveContainerProxyRoutesLocked(rt)
|
||||
rt.mu.Unlock()
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, s.maskedRouteView(route))
|
||||
}
|
||||
|
||||
// DELETE /api/proxy/routes/{scope}/{owner_id}
|
||||
func (s *Server) deleteProxyRoute(w http.ResponseWriter, r *http.Request) {
|
||||
scope := strings.ToLower(strings.TrimSpace(r.PathValue("scope")))
|
||||
ownerID := strings.TrimSpace(r.PathValue("owner_id"))
|
||||
if scope == "" || ownerID == "" {
|
||||
writeErr(w, http.StatusBadRequest, "missing scope or owner_id")
|
||||
return
|
||||
}
|
||||
rt := s.ensureRouteRuntime()
|
||||
rt.mu.Lock()
|
||||
delete(rt.routes, scope+":"+ownerID)
|
||||
err := s.saveContainerProxyRoutesLocked(rt)
|
||||
rt.mu.Unlock()
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"deleted": scope + ":" + ownerID})
|
||||
}
|
||||
|
||||
// PUT /api/proxy/gateway/settings
|
||||
func (s *Server) updateGatewaySettings(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
UDPPolicy string `json:"udp_policy"`
|
||||
DNSUpstream string `json:"dns_upstream"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "invalid JSON body")
|
||||
return
|
||||
}
|
||||
gs := GatewaySettings{
|
||||
UDPPolicy: traffic.NormalizeUDPPolicy(req.UDPPolicy),
|
||||
DNSUpstream: strings.TrimSpace(req.DNSUpstream),
|
||||
}
|
||||
rt := s.ensureRouteRuntime()
|
||||
rt.mu.Lock()
|
||||
rt.gwSettings = gs
|
||||
rt.mu.Unlock()
|
||||
if s.m.pg != nil {
|
||||
if b, err := json.Marshal(gs); err == nil {
|
||||
_ = s.m.pg.SetSetting(settingGatewayPolicy, string(b))
|
||||
}
|
||||
}
|
||||
if s.m.traffic != nil {
|
||||
s.m.traffic.SetGatewaySettings(gs.UDPPolicy, gs.DNSUpstream)
|
||||
}
|
||||
writeJSON(w, 200, gs)
|
||||
}
|
||||
+28
-1
@@ -42,11 +42,26 @@ func (s *Server) initSandbox() {
|
||||
}
|
||||
}
|
||||
sandbox.SetDefault(mgr)
|
||||
// Build merged system + MITM CA bundle so sandbox containers trust the recording
|
||||
// proxy at the system CA store level (/etc/ssl/certs/ca-certificates.crt) without root.
|
||||
if s.m.traffic != nil {
|
||||
if bundle := s.m.traffic.EnsureSystemCABundle(); bundle != "" {
|
||||
mgr.SetSystemCABundlePath(bundle)
|
||||
}
|
||||
s.m.traffic.SetGatewayToken(os.Getenv("ARTEX_GATEWAY_TOKEN"))
|
||||
}
|
||||
// Always load persisted egress blacklist rules, per-container proxy routes,
|
||||
// gateway settings, and task-level egress checker (works in both local & Docker modes).
|
||||
s.syncEgressBlacklist()
|
||||
s.initProxyRoutesAndGateway()
|
||||
if s.m.traffic != nil {
|
||||
s.m.traffic.SetTaskBlacklistChecker(s.checkTaskEgressBlacklist)
|
||||
}
|
||||
s.startEmbeddedTransparentGatewayIfConfigured()
|
||||
if !mgr.Enabled() {
|
||||
log.Printf("[sandbox] mode=local (set ARTEX_SANDBOX_MODE=docker to enable container isolation)")
|
||||
return
|
||||
}
|
||||
|
||||
validTasks := map[string]bool{}
|
||||
for _, t := range s.m.List() {
|
||||
validTasks[t.ID] = true
|
||||
@@ -86,6 +101,18 @@ func (s *Server) initSandbox() {
|
||||
BlockedCIDRs: mgr.SandboxSubnets(),
|
||||
InfraIPs: parseProtectIPs(os.Getenv("ARTEX_PROXY_PROTECT_IPS")),
|
||||
})
|
||||
s.m.traffic.SetSourceResolver(func(srcIP string) (traffic.SourceIdentity, bool) {
|
||||
id, ok := mgr.ResolveContainerByIP(srcIP)
|
||||
if !ok {
|
||||
return traffic.SourceIdentity{}, false
|
||||
}
|
||||
return traffic.SourceIdentity{
|
||||
Scope: string(id.Scope),
|
||||
OwnerID: id.OwnerID,
|
||||
ContainerID: id.ContainerID,
|
||||
SrcIP: srcIP,
|
||||
}, true
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+53
-27
@@ -144,8 +144,9 @@ type Server struct {
|
||||
proxyPoolTickMu sync.Mutex
|
||||
// proxyProbe is injectable for deterministic reconnect race tests. Production
|
||||
// servers leave it nil and use probeEgress directly.
|
||||
proxyProbe func(context.Context, string, string, []string, time.Duration) egressProbeResult
|
||||
side *sideQuestionState
|
||||
proxyProbe func(context.Context, string, string, []string, time.Duration) egressProbeResult
|
||||
proxyRoutes *proxyRouteRuntime
|
||||
side *sideQuestionState
|
||||
}
|
||||
|
||||
// provEntry is a cached provider + its config for one LLM profile id.
|
||||
@@ -332,6 +333,15 @@ func New(ctx context.Context, m *Manager, skillDir string, dataDir string, keyDi
|
||||
func (s *Server) Close() {
|
||||
if s != nil {
|
||||
s.proxyPoolWG.Wait()
|
||||
if s.proxyRoutes != nil {
|
||||
s.proxyRoutes.mu.Lock()
|
||||
gw := s.proxyRoutes.embeddedGW
|
||||
s.proxyRoutes.embeddedGW = nil
|
||||
s.proxyRoutes.mu.Unlock()
|
||||
if gw != nil {
|
||||
_ = gw.Close()
|
||||
}
|
||||
}
|
||||
if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() {
|
||||
sctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
mgr.Shutdown(sctx)
|
||||
@@ -998,6 +1008,11 @@ func (s *Server) Handler() http.Handler {
|
||||
mux.HandleFunc("DELETE /api/traffic/all", s.deleteAllTraffic)
|
||||
mux.HandleFunc("GET /api/traffic/exchange", s.getTrafficExchange)
|
||||
mux.HandleFunc("GET /api/traffic/blob", s.getTrafficBlob)
|
||||
mux.HandleFunc("GET /api/traffic/flows", s.getTrafficFlows)
|
||||
mux.HandleFunc("GET /api/traffic/flows/{id}", s.getTrafficFlowDetail)
|
||||
mux.HandleFunc("DELETE /api/traffic/flows", s.deleteTrafficFlows)
|
||||
mux.HandleFunc("GET /api/traffic/dns", s.getTrafficDNS)
|
||||
mux.HandleFunc("DELETE /api/traffic/dns", s.deleteTrafficDNS)
|
||||
mux.HandleFunc("GET /api/commands", s.pgListCommands)
|
||||
mux.HandleFunc("GET /api/commands/stats", s.pgToolStats) // 按工具聚合调用次数
|
||||
mux.HandleFunc("GET /api/llm/records", s.pgListLLMRecords)
|
||||
@@ -1043,8 +1058,19 @@ func (s *Server) Handler() http.Handler {
|
||||
mux.HandleFunc("DELETE /api/settings/proxy-pool/{id}", s.deleteProxyPool)
|
||||
mux.HandleFunc("POST /api/settings/proxy-pool/{id}/test", s.testProxyPoolEntry)
|
||||
mux.HandleFunc("POST /api/settings/proxy-pool/test-all", s.testAllProxyPool)
|
||||
mux.HandleFunc("GET /api/proxy/blacklist", s.getEgressBlacklist)
|
||||
mux.HandleFunc("PUT /api/proxy/blacklist/settings", s.updateEgressBlacklistSettings)
|
||||
mux.HandleFunc("POST /api/proxy/blacklist/rules", s.createEgressBlacklistRule)
|
||||
mux.HandleFunc("PUT /api/proxy/blacklist/rules/{id}", s.updateEgressBlacklistRule)
|
||||
mux.HandleFunc("DELETE /api/proxy/blacklist/rules/{id}", s.deleteEgressBlacklistRule)
|
||||
mux.HandleFunc("DELETE /api/proxy/blacklist/events", s.clearEgressBlockEvents)
|
||||
mux.HandleFunc("GET /api/proxy/routes", s.getProxyRoutes)
|
||||
mux.HandleFunc("PUT /api/proxy/routes/{scope}/{owner_id}", s.putProxyRoute)
|
||||
mux.HandleFunc("DELETE /api/proxy/routes/{scope}/{owner_id}", s.deleteProxyRoute)
|
||||
mux.HandleFunc("PUT /api/proxy/gateway/settings", s.updateGatewaySettings)
|
||||
mux.HandleFunc("GET /api/internal/gateway/policy", s.getGatewayPolicy)
|
||||
mux.HandleFunc("POST /api/internal/gateway/events", s.postGatewayEvents)
|
||||
mux.HandleFunc("POST /api/settings/proxy-pool/{id}/activate", s.activateProxyPool)
|
||||
mux.HandleFunc("POST /api/tasks/{id}/proxy/test", s.testTaskProxy)
|
||||
mux.HandleFunc("GET /api/report", s.getReport)
|
||||
mux.HandleFunc("GET /api/chat/mentions", s.searchChatMentions)
|
||||
mux.HandleFunc("POST /api/chat", s.chat)
|
||||
@@ -3717,8 +3743,9 @@ func (s *Server) getTraffic(w http.ResponseWriter, r *http.Request) {
|
||||
page := atoiDefault(q.Get("page"), 0)
|
||||
size := atoiDefault(q.Get("size"), 100)
|
||||
var taskHosts []string
|
||||
var rawTaskID string
|
||||
taskScoped := false
|
||||
if rawTaskID := strings.TrimSpace(q.Get("task_id")); rawTaskID != "" {
|
||||
if rawTaskID = strings.TrimSpace(q.Get("task_id")); rawTaskID != "" {
|
||||
taskScoped = true
|
||||
taskID, err := strconv.ParseInt(rawTaskID, 10, 64)
|
||||
if err != nil || taskID <= 0 || s.m.ResolveTask(rawTaskID) == nil {
|
||||
@@ -3731,25 +3758,25 @@ func (s *Server) getTraffic(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
}
|
||||
if taskScoped && len(taskHosts) == 0 {
|
||||
writeJSON(w, 200, map[string]any{
|
||||
"enabled": s.m.TrafficEnabled(), "proxy": s.m.ProxyAddr(), "count": 0,
|
||||
"total": 0, "page": page, "size": size, "exchanges": []any{},
|
||||
})
|
||||
return
|
||||
}
|
||||
intentID, _ := strconv.ParseInt(strings.TrimSpace(q.Get("intent_id")), 10, 64)
|
||||
pageQuery := traffic.PageQuery{
|
||||
Hosts: taskHosts,
|
||||
Host: q.Get("host"),
|
||||
Method: q.Get("method"),
|
||||
Query: q.Get("q"),
|
||||
Body: q.Get("body"),
|
||||
Path: q.Get("path"),
|
||||
Status: q.Get("status"),
|
||||
RespMin: int64(atoiDefault(q.Get("resp_min"), -1)),
|
||||
RespMax: int64(atoiDefault(q.Get("resp_max"), -1)),
|
||||
Sort: q.Get("sort"),
|
||||
Order: q.Get("order"),
|
||||
Hosts: taskHosts,
|
||||
OwnerTaskID: rawTaskID,
|
||||
SandboxScope: q.Get("scope"),
|
||||
SandboxOwnerID: q.Get("owner_id"),
|
||||
ContainerID: q.Get("container_id"),
|
||||
SessionID: q.Get("session_id"),
|
||||
IntentID: intentID,
|
||||
Host: q.Get("host"),
|
||||
Method: q.Get("method"),
|
||||
Query: q.Get("q"),
|
||||
Body: q.Get("body"),
|
||||
Path: q.Get("path"),
|
||||
Status: q.Get("status"),
|
||||
RespMin: int64(atoiDefault(q.Get("resp_min"), -1)),
|
||||
RespMax: int64(atoiDefault(q.Get("resp_max"), -1)),
|
||||
Sort: q.Get("sort"),
|
||||
Order: q.Get("order"),
|
||||
}
|
||||
ex, matched, _ := tr.Page(pageQuery, page, size)
|
||||
count, _ := tr.Count() // global total, for the stat card
|
||||
@@ -3778,7 +3805,8 @@ func (s *Server) getTrafficHosts(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
var hosts []string
|
||||
if rawTaskID := strings.TrimSpace(r.URL.Query().Get("task_id")); rawTaskID != "" {
|
||||
rawTaskID := strings.TrimSpace(r.URL.Query().Get("task_id"))
|
||||
if rawTaskID != "" {
|
||||
taskID, err := strconv.ParseInt(rawTaskID, 10, 64)
|
||||
if err != nil || taskID <= 0 || s.m.ResolveTask(rawTaskID) == nil {
|
||||
writeErr(w, http.StatusNotFound, "task not found")
|
||||
@@ -3792,10 +3820,8 @@ func (s *Server) getTrafficHosts(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
var result []traffic.HostCount
|
||||
var err error
|
||||
if len(hosts) > 0 {
|
||||
result, err = tr.HostsForScope(hosts)
|
||||
} else if r.URL.Query().Get("task_id") != "" {
|
||||
result = []traffic.HostCount{}
|
||||
if rawTaskID != "" {
|
||||
result, err = tr.HostsForTask(rawTaskID, hosts)
|
||||
} else {
|
||||
result, err = tr.Hosts()
|
||||
}
|
||||
|
||||
@@ -101,6 +101,7 @@ func (s *Server) taskInterceptCreateRule(w http.ResponseWriter, r *http.Request)
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
taskEgressRulesCache.Delete(taskID)
|
||||
writeJSON(w, 200, rule)
|
||||
}
|
||||
|
||||
@@ -133,6 +134,7 @@ func (s *Server) taskInterceptUpdateRule(w http.ResponseWriter, r *http.Request)
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
taskEgressRulesCache.Delete(taskID)
|
||||
writeJSON(w, 200, rule)
|
||||
}
|
||||
|
||||
@@ -156,6 +158,7 @@ func (s *Server) taskInterceptDeleteRule(w http.ResponseWriter, r *http.Request)
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
taskEgressRulesCache.Delete(taskID)
|
||||
writeJSON(w, 200, map[string]any{"deleted": deleted})
|
||||
}
|
||||
|
||||
@@ -185,5 +188,6 @@ func (s *Server) taskInterceptToggleRule(w http.ResponseWriter, r *http.Request)
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
taskEgressRulesCache.Delete(taskID)
|
||||
writeJSON(w, 200, map[string]any{"ok": true, "enabled": req.Enabled})
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/Autumn-27/artex/traffic"
|
||||
)
|
||||
|
||||
// GET /api/traffic/flows
|
||||
func (s *Server) getTrafficFlows(w http.ResponseWriter, r *http.Request) {
|
||||
tr := s.m.Traffic()
|
||||
if tr == nil {
|
||||
writeJSON(w, 200, map[string]any{"enabled": false, "flows": []any{}, "total": 0, "count": 0})
|
||||
return
|
||||
}
|
||||
q := r.URL.Query()
|
||||
page := atoiDefault(q.Get("page"), 0)
|
||||
size := atoiDefault(q.Get("size"), 100)
|
||||
rawTaskID := strings.TrimSpace(q.Get("task_id"))
|
||||
if rawTaskID != "" && s.m.ResolveTask(rawTaskID) == nil {
|
||||
writeErr(w, http.StatusNotFound, "task not found")
|
||||
return
|
||||
}
|
||||
rows, total, err := tr.PageNetFlows(traffic.NetFlowQuery{
|
||||
Protocol: q.Get("protocol"),
|
||||
Action: q.Get("action"),
|
||||
OwnerTaskID: rawTaskID,
|
||||
SandboxScope: q.Get("scope"),
|
||||
SandboxOwnerID: q.Get("owner_id"),
|
||||
ContainerID: q.Get("container_id"),
|
||||
Query: q.Get("q"),
|
||||
}, page, size)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
count, _ := tr.CountNetFlows()
|
||||
if rawTaskID != "" {
|
||||
count = total
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{
|
||||
"enabled": s.m.TrafficEnabled(),
|
||||
"count": count,
|
||||
"total": total,
|
||||
"page": page,
|
||||
"size": size,
|
||||
"flows": rows,
|
||||
})
|
||||
}
|
||||
|
||||
// GET /api/traffic/flows/{id}
|
||||
func (s *Server) getTrafficFlowDetail(w http.ResponseWriter, r *http.Request) {
|
||||
tr := s.m.Traffic()
|
||||
if tr == nil {
|
||||
writeErr(w, http.StatusNotFound, "traffic disabled")
|
||||
return
|
||||
}
|
||||
id := strings.TrimSpace(r.PathValue("id"))
|
||||
if id == "" {
|
||||
writeErr(w, http.StatusBadRequest, "missing id")
|
||||
return
|
||||
}
|
||||
flow, err := tr.GetNetFlow(id)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusNotFound, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, flow)
|
||||
}
|
||||
|
||||
// DELETE /api/traffic/flows
|
||||
func (s *Server) deleteTrafficFlows(w http.ResponseWriter, r *http.Request) {
|
||||
tr := s.m.Traffic()
|
||||
if tr == nil {
|
||||
writeErr(w, http.StatusNotFound, "traffic disabled")
|
||||
return
|
||||
}
|
||||
q := r.URL.Query()
|
||||
scope := strings.TrimSpace(q.Get("scope"))
|
||||
ownerID := strings.TrimSpace(q.Get("owner_id"))
|
||||
if tid := strings.TrimSpace(q.Get("task_id")); tid != "" && scope == "" {
|
||||
scope = "task"
|
||||
ownerID = tid
|
||||
}
|
||||
n, err := tr.DeleteNetFlows(scope, ownerID)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"deleted": n})
|
||||
}
|
||||
|
||||
// GET /api/traffic/dns
|
||||
func (s *Server) getTrafficDNS(w http.ResponseWriter, r *http.Request) {
|
||||
tr := s.m.Traffic()
|
||||
if tr == nil {
|
||||
writeJSON(w, 200, map[string]any{"enabled": false, "queries": []any{}, "total": 0, "count": 0})
|
||||
return
|
||||
}
|
||||
q := r.URL.Query()
|
||||
page := atoiDefault(q.Get("page"), 0)
|
||||
size := atoiDefault(q.Get("size"), 100)
|
||||
rawTaskID := strings.TrimSpace(q.Get("task_id"))
|
||||
if rawTaskID != "" && s.m.ResolveTask(rawTaskID) == nil {
|
||||
writeErr(w, http.StatusNotFound, "task not found")
|
||||
return
|
||||
}
|
||||
rows, total, err := tr.PageDNSQueries(traffic.DNSQueryFilter{
|
||||
QType: q.Get("qtype"),
|
||||
RCode: q.Get("rcode"),
|
||||
Action: q.Get("action"),
|
||||
OwnerTaskID: rawTaskID,
|
||||
SandboxScope: q.Get("scope"),
|
||||
SandboxOwnerID: q.Get("owner_id"),
|
||||
ContainerID: q.Get("container_id"),
|
||||
Query: q.Get("q"),
|
||||
}, page, size)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
count, _ := tr.CountDNSQueries()
|
||||
if rawTaskID != "" {
|
||||
count = total
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{
|
||||
"enabled": s.m.TrafficEnabled(),
|
||||
"count": count,
|
||||
"total": total,
|
||||
"page": page,
|
||||
"size": size,
|
||||
"queries": rows,
|
||||
})
|
||||
}
|
||||
|
||||
// DELETE /api/traffic/dns
|
||||
func (s *Server) deleteTrafficDNS(w http.ResponseWriter, r *http.Request) {
|
||||
tr := s.m.Traffic()
|
||||
if tr == nil {
|
||||
writeErr(w, http.StatusNotFound, "traffic disabled")
|
||||
return
|
||||
}
|
||||
q := r.URL.Query()
|
||||
scope := strings.TrimSpace(q.Get("scope"))
|
||||
ownerID := strings.TrimSpace(q.Get("owner_id"))
|
||||
if tid := strings.TrimSpace(q.Get("task_id")); tid != "" && scope == "" {
|
||||
scope = "task"
|
||||
ownerID = tid
|
||||
}
|
||||
n, err := tr.DeleteDNSQueries(scope, ownerID)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"deleted": n})
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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 "", ""
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
File diff suppressed because it is too large.
Load diff
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
@@ -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
@@ -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, ¬Null, &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
@@ -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
|
||||
}
|
||||
@@ -69,8 +69,7 @@ export function SessionSandboxControl({
|
||||
conversationId: number;
|
||||
running: boolean;
|
||||
}) {
|
||||
const { i18n } = useLiveTranslation();
|
||||
const isEn = i18n.language.startsWith("en");
|
||||
const { isEn } = useLiveTranslation();
|
||||
const L = (zh: string, en: string) => (isEn ? en : zh);
|
||||
|
||||
const ownerID = `conv-${conversationId}`;
|
||||
|
||||
@@ -63,8 +63,7 @@ function fmtUptime(startedAt?: string): string {
|
||||
}
|
||||
|
||||
export function TaskSandboxControl({ task, onTaskUpdated }: { task: Task; onTaskUpdated: () => void }) {
|
||||
const { i18n } = useLiveTranslation();
|
||||
const isEn = i18n.language.startsWith("en");
|
||||
const { isEn } = useLiveTranslation();
|
||||
const L = (zh: string, en: string) => (isEn ? en : zh);
|
||||
|
||||
const [open, setOpen] = React.useState(false);
|
||||
|
||||
@@ -0,0 +1,445 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
|
||||
import { PlusIcon, RefreshCwIcon, RouteIcon, SaveIcon, Trash2Icon } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import { useLiveTranslation } from "@/i18n/use-live-translation";
|
||||
import { api } from "@/lib/api";
|
||||
import type { ContainerRouteStatusItem, ProxyPoolEntry, ProxyRoutesState } from "@/lib/types";
|
||||
|
||||
export function ContainerRoutesTab({
|
||||
proxyPool,
|
||||
routesState,
|
||||
onRefresh,
|
||||
}: {
|
||||
proxyPool: ProxyPoolEntry[];
|
||||
routesState: ProxyRoutesState | null;
|
||||
onRefresh: () => Promise<void>;
|
||||
}) {
|
||||
const { isEn, locale } = useLiveTranslation();
|
||||
const L = (zh: string, en: string) => (isEn ? en : zh);
|
||||
const formatProxyValue = (raw?: string) => {
|
||||
const clean = (raw ?? "").replace(/\s*\((全局|Global)\)\s*$/i, "").trim();
|
||||
if (!clean || clean === "direct") return L("直连", "Direct");
|
||||
return clean;
|
||||
};
|
||||
const formatEffectiveProxy = (c: ContainerRouteStatusItem) => {
|
||||
const base = formatProxyValue(c.effective_proxy);
|
||||
if (!c.mode || c.mode === "inherit") {
|
||||
return `${base} (${L("全局", "Global")})`;
|
||||
}
|
||||
return base;
|
||||
};
|
||||
const formatScope = (scope: string) => {
|
||||
if (scope === "task") return L("任务", "Task");
|
||||
if (scope === "session") return L("对话", "Session");
|
||||
return scope;
|
||||
};
|
||||
const formatState = (state?: string) => {
|
||||
const normalized = (state ?? "").trim().toLowerCase();
|
||||
const labels: Record<string, string> = {
|
||||
running: L("运行中", "Running"),
|
||||
exited: L("已停止", "Stopped"),
|
||||
stopped: L("已停止", "Stopped"),
|
||||
created: L("已创建", "Created"),
|
||||
paused: L("已暂停", "Paused"),
|
||||
inactive: L("未运行", "Inactive"),
|
||||
};
|
||||
return labels[normalized] ?? (normalized ? (state ?? "") : L("未运行", "Inactive"));
|
||||
};
|
||||
|
||||
const [udpPolicy, setUdpPolicy] = React.useState(routesState?.gateway.udp_policy ?? "block_on_proxy");
|
||||
const [dnsUpstream, setDnsUpstream] = React.useState(routesState?.gateway.dns_upstream ?? "");
|
||||
const [savingGW, setSavingGW] = React.useState(false);
|
||||
|
||||
const [newScope, setNewScope] = React.useState<"task" | "session">("task");
|
||||
const [newOwnerID, setNewOwnerID] = React.useState("");
|
||||
const [newMode, setNewMode] = React.useState<"direct" | "proxy">("proxy");
|
||||
const [newPoolID, setNewPoolID] = React.useState("__custom__");
|
||||
const [newProxyURL, setNewProxyURL] = React.useState("");
|
||||
const [newNote, setNewNote] = React.useState("");
|
||||
const [savingRoute, setSavingRoute] = React.useState(false);
|
||||
const [busyKey, setBusyKey] = React.useState<string | null>(null);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (routesState) {
|
||||
setUdpPolicy(routesState.gateway.udp_policy || "block_on_proxy");
|
||||
setDnsUpstream(routesState.gateway.dns_upstream || "");
|
||||
}
|
||||
}, [routesState]);
|
||||
|
||||
const saveGatewaySettings = async () => {
|
||||
setSavingGW(true);
|
||||
try {
|
||||
await api.updateGatewaySettings({ udp_policy: udpPolicy, dns_upstream: dnsUpstream.trim() });
|
||||
await onRefresh();
|
||||
toast.success(L("透明网关策略已更新并热下发", "Transparent gateway policy updated"));
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
setSavingGW(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleAddRoute = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
const owner = newOwnerID.trim();
|
||||
if (!owner) {
|
||||
toast.error(L("请填写任务 ID 或会话 ID", "Enter a task ID or session ID"));
|
||||
return;
|
||||
}
|
||||
setSavingRoute(true);
|
||||
try {
|
||||
await api.putProxyRoute(newScope, owner, {
|
||||
mode: newMode,
|
||||
proxy_pool_id: newMode === "proxy" && newPoolID !== "__custom__" ? newPoolID : undefined,
|
||||
proxy_url: newMode === "proxy" && newPoolID === "__custom__" ? newProxyURL.trim() : undefined,
|
||||
note: newNote.trim(),
|
||||
});
|
||||
setNewOwnerID("");
|
||||
setNewProxyURL("");
|
||||
setNewNote("");
|
||||
await onRefresh();
|
||||
toast.success(L("容器出口路由已生效", "Container egress route saved"));
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : String(err));
|
||||
} finally {
|
||||
setSavingRoute(false);
|
||||
}
|
||||
};
|
||||
|
||||
const quickUpdateRow = async (item: ContainerRouteStatusItem, selection: string) => {
|
||||
const key = `${item.scope}:${item.owner_id}`;
|
||||
setBusyKey(key);
|
||||
try {
|
||||
if (selection === "__inherit__") {
|
||||
await api.deleteProxyRoute(item.scope, item.owner_id);
|
||||
} else if (selection === "__direct__") {
|
||||
await api.putProxyRoute(item.scope, item.owner_id, { mode: "direct", note: item.note });
|
||||
} else if (selection.startsWith("pool:")) {
|
||||
await api.putProxyRoute(item.scope, item.owner_id, {
|
||||
mode: "proxy",
|
||||
proxy_pool_id: selection.slice(5),
|
||||
note: item.note,
|
||||
});
|
||||
}
|
||||
await onRefresh();
|
||||
toast.success(L("已更新容器出口路由", "Container egress route updated"));
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
setBusyKey(null);
|
||||
}
|
||||
};
|
||||
|
||||
const deleteRowRoute = async (item: ContainerRouteStatusItem) => {
|
||||
const key = `${item.scope}:${item.owner_id}`;
|
||||
setBusyKey(key);
|
||||
try {
|
||||
await api.deleteProxyRoute(item.scope, item.owner_id);
|
||||
await onRefresh();
|
||||
toast.success(L("已恢复继承全局代理", "Reverted to global proxy"));
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
setBusyKey(null);
|
||||
}
|
||||
};
|
||||
|
||||
const gw = routesState?.gateway;
|
||||
const containers = routesState?.containers ?? [];
|
||||
|
||||
return (
|
||||
<div className="min-w-0 space-y-4">
|
||||
{/* Transparent Gateway Status & Policy Card */}
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row flex-wrap items-start justify-between gap-3">
|
||||
<div>
|
||||
<CardTitle className="flex items-center gap-2 text-base">
|
||||
<RouteIcon className="size-4" />
|
||||
{L("全流量透明网关状态与策略", "Transparent Gateway Status & Policy")}
|
||||
<Badge
|
||||
variant={gw?.connected ? "default" : "secondary"}
|
||||
className={gw?.connected ? "bg-emerald-600 text-white hover:bg-emerald-600" : "text-muted-foreground"}
|
||||
>
|
||||
{(() => {
|
||||
if (!gw?.connected) return L("未连接网关", "Gateway Offline");
|
||||
return gw.embedded ? L("内置运行中", "Embedded Online") : L("网关在线", "Gateway Online");
|
||||
})()}
|
||||
</Badge>
|
||||
</CardTitle>
|
||||
<CardDescription className="mt-1">
|
||||
{L(
|
||||
"artex-gateway 通过网桥透明接管沙箱容器全部 TCP / DNS / UDP 出站流量,杜绝环境变量绕过,并统一应用出口黑名单与上游代理。",
|
||||
"artex-gateway transparently intercepts all sandbox TCP, DNS, and UDP egress at the bridge layer to prevent proxy-env bypass.",
|
||||
)}
|
||||
</CardDescription>
|
||||
</div>
|
||||
<Button size="sm" variant="outline" onClick={() => void onRefresh()}>
|
||||
<RefreshCwIcon className="mr-1.5 size-3.5" />
|
||||
{L("刷新", "Refresh")}
|
||||
</Button>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs">{L("非 DNS UDP 出口策略", "Non-DNS UDP Policy")}</Label>
|
||||
<Select value={udpPolicy} onValueChange={setUdpPolicy}>
|
||||
<SelectTrigger className="h-9 text-xs">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="block_on_proxy">
|
||||
{L(
|
||||
"启用代理时阻断 UDP(OPSEC 推荐,防真实 IP 泄露)",
|
||||
"Block UDP when proxy active (OPSEC default)",
|
||||
)}
|
||||
</SelectItem>
|
||||
<SelectItem value="block">{L("始终阻断非 DNS UDP", "Always block non-DNS UDP")}</SelectItem>
|
||||
<SelectItem value="direct">
|
||||
{L("允许 UDP 直连(仍受黑名单/SSRF 限制)", "Allow direct UDP (still filtered)")}
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs">
|
||||
{L("上游 DNS 服务器(留空使用宿主机/8.8.8.8:53)", "Upstream DNS (empty = system / 8.8.8.8:53)")}
|
||||
</Label>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
value={dnsUpstream}
|
||||
onChange={(e) => setDnsUpstream(e.target.value)}
|
||||
placeholder="8.8.8.8:53 / 1.1.1.1:53"
|
||||
className="h-9 font-mono text-xs"
|
||||
/>
|
||||
<Button
|
||||
size="sm"
|
||||
className="h-9 shrink-0"
|
||||
disabled={savingGW}
|
||||
onClick={() => void saveGatewaySettings()}
|
||||
>
|
||||
<SaveIcon className="mr-1.5 size-3.5" />
|
||||
{L("保存策略", "Save")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{gw?.last_seen ? (
|
||||
<p className="font-mono text-muted-foreground text-xs">
|
||||
{L("网关标识:", "Gateway ID: ")}
|
||||
{gw.gateway_id || "artex-gateway"} · {L("最近心跳:", "Last heartbeat: ")}
|
||||
{new Date(gw.last_seen).toLocaleString(locale)}
|
||||
</p>
|
||||
) : null}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Add Per-Container / Task Proxy Route Override */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">
|
||||
{L("按任务 / 容器覆盖出口代理", "Per-Task / Container Egress Override")}
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{L("默认继承全局出口代理(当前:", "Containers inherit the global egress proxy by default (current: ")}
|
||||
<span className="font-mono">{formatProxyValue(routesState?.global_proxy)}</span>
|
||||
{L(
|
||||
")。可为特定任务或会话容器单独指定代理池节点、自定义代理或强制直连,HTTP / TCP / DNS 均实时生效。",
|
||||
"). Override any task or session container with a pool node, custom proxy, or direct egress.",
|
||||
)}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<form onSubmit={handleAddRoute} className="grid gap-2 md:grid-cols-12">
|
||||
<div className="md:col-span-2">
|
||||
<Select value={newScope} onValueChange={(v) => setNewScope(v as "task" | "session")}>
|
||||
<SelectTrigger className="h-8 text-xs">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="task">{L("任务 (task)", "Task")}</SelectItem>
|
||||
<SelectItem value="session">{L("对话 (session)", "Session")}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="md:col-span-2">
|
||||
<Input
|
||||
value={newOwnerID}
|
||||
onChange={(e) => setNewOwnerID(e.target.value)}
|
||||
placeholder={newScope === "task" ? L("任务 ID,如 42", "Task ID, e.g. 42") : L("会话 ID", "Session ID")}
|
||||
className="h-8 font-mono text-xs"
|
||||
/>
|
||||
</div>
|
||||
<div className="md:col-span-2">
|
||||
<Select value={newMode} onValueChange={(v) => setNewMode(v as "direct" | "proxy")}>
|
||||
<SelectTrigger className="h-8 text-xs">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="proxy">{L("指定代理", "Use proxy")}</SelectItem>
|
||||
<SelectItem value="direct">{L("强制直连", "Force direct")}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
{newMode === "proxy" ? (
|
||||
<div className="md:col-span-3">
|
||||
<Select value={newPoolID} onValueChange={setNewPoolID}>
|
||||
<SelectTrigger className="h-8 text-xs">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="__custom__">{L("手动输入代理 URL", "Custom proxy URL")}</SelectItem>
|
||||
{proxyPool.map((p) => (
|
||||
<SelectItem key={p.id} value={p.id}>
|
||||
{p.name || p.url}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
) : null}
|
||||
{newMode === "proxy" && newPoolID === "__custom__" ? (
|
||||
<div className="md:col-span-3">
|
||||
<Input
|
||||
value={newProxyURL}
|
||||
onChange={(e) => setNewProxyURL(e.target.value)}
|
||||
placeholder="socks5://127.0.0.1:1080"
|
||||
className="h-8 font-mono text-xs"
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div className={newMode === "proxy" ? "md:col-span-3" : "md:col-span-6"}>
|
||||
<Input
|
||||
value={newNote}
|
||||
onChange={(e) => setNewNote(e.target.value)}
|
||||
placeholder={L("备注(可选)", "Note (optional)")}
|
||||
className="h-8 text-xs"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex justify-end md:col-span-12">
|
||||
<Button type="submit" size="sm" className="h-8" disabled={savingRoute}>
|
||||
<PlusIcon className="mr-1.5 size-3.5" />
|
||||
{L("应用覆盖规则", "Save Override")}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
{/* Active Containers & Persisted Route Rules Table */}
|
||||
<div className="w-full min-w-0 overflow-x-auto rounded-lg border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>{L("归属", "Owner")}</TableHead>
|
||||
<TableHead>{L("容器 / IP", "Container / IP")}</TableHead>
|
||||
<TableHead>{L("状态", "State")}</TableHead>
|
||||
<TableHead>{L("当前生效出口", "Effective Egress")}</TableHead>
|
||||
<TableHead className="w-[220px]">{L("快捷切换", "Quick Override")}</TableHead>
|
||||
<TableHead className="w-[70px] text-right">{L("操作", "Action")}</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{containers.length === 0 ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={6} className="py-10 text-center text-muted-foreground text-sm">
|
||||
{L(
|
||||
"暂无运行中的沙箱容器或自定义路由规则",
|
||||
"No active sandbox containers or custom egress route overrides",
|
||||
)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : (
|
||||
containers.map((c) => {
|
||||
const key = `${c.scope}:${c.owner_id}`;
|
||||
let currentVal = "__custom__";
|
||||
if (c.mode === "inherit") {
|
||||
currentVal = "__inherit__";
|
||||
} else if (c.mode === "direct") {
|
||||
currentVal = "__direct__";
|
||||
} else if (c.proxy_pool_id) {
|
||||
currentVal = `pool:${c.proxy_pool_id}`;
|
||||
}
|
||||
return (
|
||||
<TableRow key={key}>
|
||||
<TableCell className="font-mono text-xs">
|
||||
<Badge variant={c.scope === "task" ? "secondary" : "outline"} className="mr-1.5">
|
||||
{formatScope(c.scope)}
|
||||
</Badge>
|
||||
{c.owner_id}
|
||||
</TableCell>
|
||||
<TableCell className="font-mono text-muted-foreground text-xs">
|
||||
<div>{c.container_name || "—"}</div>
|
||||
{c.ip ? <div className="text-[11px]">{c.ip}</div> : null}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant="outline" className="font-mono text-[11px]">
|
||||
{formatState(c.state)}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell className="max-w-[260px] truncate font-mono text-xs" title={formatEffectiveProxy(c)}>
|
||||
{formatEffectiveProxy(c)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Select
|
||||
value={currentVal}
|
||||
disabled={busyKey === key}
|
||||
onValueChange={(val) => {
|
||||
if (val !== "__custom__") {
|
||||
void quickUpdateRow(c, val);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="h-8 text-xs">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="__inherit__">{L("继承全局代理", "Inherit global")}</SelectItem>
|
||||
<SelectItem value="__direct__">{L("强制直连", "Force direct")}</SelectItem>
|
||||
{currentVal === "__custom__" ? (
|
||||
<SelectItem value="__custom__">{L("自定义代理 URL", "Custom proxy URL")}</SelectItem>
|
||||
) : null}
|
||||
{proxyPool.map((p) => (
|
||||
<SelectItem key={p.id} value={`pool:${p.id}`}>
|
||||
{L("节点:", "Node: ")}
|
||||
{p.name || p.url}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
{c.mode !== "inherit" ? (
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
className="size-7 text-muted-foreground hover:text-destructive"
|
||||
disabled={busyKey === key}
|
||||
title={L("恢复继承全局", "Revert to global")}
|
||||
onClick={() => void deleteRowRoute(c)}
|
||||
>
|
||||
<Trash2Icon className="size-3.5" />
|
||||
</Button>
|
||||
) : null}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -78,8 +78,7 @@ function fmtCreatedAt(iso?: string): string {
|
||||
}
|
||||
|
||||
export default function SandboxPage() {
|
||||
const { i18n } = useLiveTranslation();
|
||||
const isEn = i18n.language.startsWith("en");
|
||||
const { isEn } = useLiveTranslation();
|
||||
const L = (zh: string, en: string) => (isEn ? en : zh);
|
||||
|
||||
const [status, setStatus] = React.useState<SandboxGlobalStatus | null>(null);
|
||||
|
||||
@@ -45,8 +45,7 @@ function ownerHref(c: SandboxContainerInfo): string | null {
|
||||
}
|
||||
|
||||
export function SandboxCard() {
|
||||
const { i18n } = useLiveTranslation();
|
||||
const isEn = i18n.language.startsWith("en");
|
||||
const { isEn } = useLiveTranslation();
|
||||
const L = (zh: string, en: string) => (isEn ? en : zh);
|
||||
|
||||
const [status, setStatus] = React.useState<SandboxGlobalStatus | null>(null);
|
||||
|
||||
@@ -2,9 +2,12 @@
|
||||
|
||||
import * as React from "react";
|
||||
|
||||
import Link from "next/link";
|
||||
|
||||
import {
|
||||
CameraIcon,
|
||||
CpuIcon,
|
||||
ExternalLinkIcon,
|
||||
FlaskConicalIcon,
|
||||
KeyboardIcon,
|
||||
RadioTowerIcon,
|
||||
@@ -27,9 +30,8 @@ import { matchesSettingsQuery } from "@/i18n/settings-search";
|
||||
import { useLiveTranslation } from "@/i18n/use-live-translation";
|
||||
import { api } from "@/lib/api";
|
||||
import { CHAT_SEND_MODE_OPTIONS, type ChatSendMode, setChatSendMode, useChatSendMode } from "@/lib/chat-send-mode";
|
||||
import type { EgressReport, LLMProfile, ProxyPoolEntry, Settings, WorkerPool } from "@/lib/types";
|
||||
import type { LLMProfile, Settings, WorkerPool } from "@/lib/types";
|
||||
|
||||
import { useEgressIp } from "../../_components/egress-ip-banner";
|
||||
import { BackupCard } from "./_components/backup-card";
|
||||
import { BasicAuthCard } from "./_components/basic-auth-card";
|
||||
import { McpServerCard } from "./_components/mcp-server-card";
|
||||
@@ -63,39 +65,8 @@ export default function SystemSettingsPage() {
|
||||
const [savingTavilyKey, setSavingTavilyKey] = React.useState(false);
|
||||
const [proxyInput, setProxyInput] = React.useState("");
|
||||
const [savingProxy, setSavingProxy] = React.useState(false);
|
||||
const [globalProxyInput, setGlobalProxyInput] = React.useState("");
|
||||
const [savingGlobalProxy, setSavingGlobalProxy] = React.useState(false);
|
||||
const [proxyPool, setProxyPool] = React.useState<ProxyPoolEntry[]>([]);
|
||||
const [proxyPoolActiveId, setProxyPoolActiveId] = React.useState("");
|
||||
const [proxyPoolText, setProxyPoolText] = React.useState("");
|
||||
const [proxyPoolTimed, setProxyPoolTimed] = React.useState(false);
|
||||
const [proxyPoolInterval, setProxyPoolInterval] = React.useState("30");
|
||||
const [proxyPoolFailure, setProxyPoolFailure] = React.useState(false);
|
||||
const [proxyPoolStrategy, setProxyPoolStrategy] = React.useState<"sequential" | "random">("sequential");
|
||||
const [proxyPoolThreshold, setProxyPoolThreshold] = React.useState("3");
|
||||
const [proxyPoolCooldown, setProxyPoolCooldown] = React.useState("60");
|
||||
const [proxyPoolHealthInterval, setProxyPoolHealthInterval] = React.useState("30");
|
||||
const [proxyPoolLogs, setProxyPoolLogs] = React.useState<
|
||||
Array<{ at: string; from: string; to: string; reason: string }>
|
||||
>([]);
|
||||
const [proxyReconnectMax, setProxyReconnectMax] = React.useState("5");
|
||||
const [proxyReconnectInterval, setProxyReconnectInterval] = React.useState("30");
|
||||
const [savingEgressVisibility, setSavingEgressVisibility] = React.useState(false);
|
||||
// 出口探测:测一次真实请求,拿到"直连 / 经全局代理"两条出口 IP。
|
||||
const [egressTesting, setEgressTesting] = React.useState(false);
|
||||
const [egressReport, setEgressReport] = React.useState<EgressReport | null>(null);
|
||||
// 请求序号:改了输入/保存/切捕获之后,在途请求回来时序号已经变了,直接丢弃。
|
||||
// 不这么做会出现"结果刚被清空,又被上一次的响应填回来"。
|
||||
const egressSeq = React.useRef(0);
|
||||
// 清空结果并作废在途请求。
|
||||
const clearEgressReport = () => {
|
||||
egressSeq.current += 1;
|
||||
setEgressReport(null);
|
||||
setEgressTesting(false);
|
||||
};
|
||||
// 探测地址:留空用公网回显;隔离网填内网回显服务。
|
||||
const [egressProbeUrl, setEgressProbeUrl] = React.useState("");
|
||||
const [savingEgressProbeUrl, setSavingEgressProbeUrl] = React.useState(false);
|
||||
const [globalProxySummary, setGlobalProxySummary] = React.useState("");
|
||||
const [proxyPoolCount, setProxyPoolCount] = React.useState(0);
|
||||
const [testing, setTesting] = React.useState(false);
|
||||
const [loaded, setLoaded] = React.useState(false);
|
||||
const [settingsLoaded, setSettingsLoaded] = React.useState(false);
|
||||
@@ -113,12 +84,6 @@ export default function SystemSettingsPage() {
|
||||
const [noaCompaction, setNoaCompaction] = React.useState(false);
|
||||
// 纯前端偏好:不走 /api/settings,直接读写 localStorage。
|
||||
const sendMode = useChatSendMode();
|
||||
const {
|
||||
enabled: showEgressIp,
|
||||
isLoading: egressProbeLoading,
|
||||
setEnabled: setShowEgressIp,
|
||||
probeEgress,
|
||||
} = useEgressIp();
|
||||
|
||||
const apply = React.useCallback((s: Settings) => {
|
||||
setCredentialAgent(!!s.credential_agent_enabled);
|
||||
@@ -137,21 +102,8 @@ export default function SystemSettingsPage() {
|
||||
setTavilyKeySet(!!s.tavily_key_set);
|
||||
setDeepSeekKeySet(!!s.deepseek_search_key_set);
|
||||
setProxyInput(s.web_search_proxy ?? "");
|
||||
const savedProxy = s.global_proxy ?? "";
|
||||
setGlobalProxyInput(savedProxy);
|
||||
setProxyPool(s.proxy_pool ?? []);
|
||||
setProxyPoolActiveId(s.proxy_pool_active_id ?? "");
|
||||
setProxyPoolTimed(!!s.proxy_rotate_timed_enabled);
|
||||
setProxyPoolInterval(String(s.proxy_rotate_interval_seconds ?? 30));
|
||||
setProxyPoolFailure(!!s.proxy_rotate_on_failure);
|
||||
setProxyPoolStrategy(s.proxy_rotate_strategy === "random" ? "random" : "sequential");
|
||||
setProxyPoolThreshold(String(s.proxy_health_fail_threshold ?? 3));
|
||||
setProxyPoolCooldown(String(s.proxy_health_cooldown_seconds ?? 60));
|
||||
setProxyPoolHealthInterval(String(s.proxy_health_check_interval_seconds ?? 30));
|
||||
setProxyPoolLogs(s.proxy_pool_switch_log ?? []);
|
||||
setProxyReconnectMax(String(s.proxy_reconnect_max_attempts ?? 5));
|
||||
setProxyReconnectInterval(String(s.proxy_reconnect_interval_seconds ?? 30));
|
||||
setEgressProbeUrl(s.egress_probe_url ?? "");
|
||||
setGlobalProxySummary(s.global_proxy ?? "");
|
||||
setProxyPoolCount((s.proxy_pool ?? []).length);
|
||||
setPyInterp(s.python_interpreter ?? "");
|
||||
setWorkers(String(s.workers ?? 3));
|
||||
setWorkerPools(s.worker_pools ?? []);
|
||||
@@ -242,14 +194,6 @@ export default function SystemSettingsPage() {
|
||||
.then((s) => {
|
||||
apply(s);
|
||||
setSettingsLoaded(true);
|
||||
void api
|
||||
.proxyPool()
|
||||
.then((pool) => {
|
||||
setProxyPool(pool.entries);
|
||||
setProxyPoolActiveId(pool.active_id);
|
||||
setProxyPoolLogs(pool.switch_log);
|
||||
})
|
||||
.catch(() => undefined);
|
||||
})
|
||||
.catch(() => {
|
||||
setSettingsLoaded(false);
|
||||
@@ -272,8 +216,6 @@ export default function SystemSettingsPage() {
|
||||
.setSettings({ traffic_capture: v })
|
||||
.then((s) => {
|
||||
apply(s);
|
||||
// 捕获开关一变,② 的链路就变了,旧结果不能留。
|
||||
clearEgressReport();
|
||||
})
|
||||
.catch(() => setTrafficCapture(!v)) // revert on failure
|
||||
.finally(() => setSaving(false));
|
||||
@@ -484,174 +426,6 @@ export default function SystemSettingsPage() {
|
||||
.finally(() => setSavingProxy(false));
|
||||
};
|
||||
|
||||
const saveGlobalProxy = () => {
|
||||
if (proxyPool.length > 0) {
|
||||
toast.info(t("settings.poolOverridesProxy"));
|
||||
return;
|
||||
}
|
||||
setSavingGlobalProxy(true);
|
||||
api
|
||||
.setSettings({ global_proxy: globalProxyInput.trim() })
|
||||
.then((s) => {
|
||||
apply(s);
|
||||
// 保存后链路变了,旧结果(尤其"尚未保存")立刻失效。
|
||||
clearEgressReport();
|
||||
if (showEgressIp) void probeEgress().catch(() => undefined);
|
||||
toast.success(globalProxyInput.trim() ? t("settings.globalProxySaved") : t("settings.globalProxyCleared"));
|
||||
})
|
||||
.catch((e) => toast.error(t("settings.saveFailedPrefix") + localizedError(e, t)))
|
||||
.finally(() => setSavingGlobalProxy(false));
|
||||
};
|
||||
|
||||
const importProxyPool = () => {
|
||||
api
|
||||
.importProxyPool({ text: proxyPoolText })
|
||||
.then((r) => {
|
||||
setProxyPool(r.entries);
|
||||
setProxyPoolActiveId(r.active_id);
|
||||
setProxyPoolLogs(r.switch_log);
|
||||
setProxyPoolText("");
|
||||
if (r.errors.length)
|
||||
toast.error(
|
||||
r.errors.map((e) => t("settings.importLineError", { line: e.line, message: e.error })).join(";"),
|
||||
);
|
||||
else toast.success(t("settings.proxyPoolImported"));
|
||||
})
|
||||
.catch((e) => toast.error(t("settings.importFailedPrefix") + localizedError(e, t)));
|
||||
};
|
||||
const saveProxyPoolStrategy = () => {
|
||||
const interval = Number(proxyPoolInterval);
|
||||
if (!Number.isFinite(interval) || !Number.isInteger(interval) || interval < 3) {
|
||||
toast.error(t("settings.invalidRotationInterval"));
|
||||
return;
|
||||
}
|
||||
api
|
||||
.setSettings({
|
||||
proxy_rotate_timed_enabled: proxyPoolTimed,
|
||||
proxy_rotate_interval_seconds: Number(proxyPoolInterval),
|
||||
proxy_rotate_on_failure: proxyPoolFailure,
|
||||
proxy_rotate_strategy: proxyPoolStrategy,
|
||||
proxy_health_fail_threshold: Number(proxyPoolThreshold),
|
||||
proxy_health_cooldown_seconds: Number(proxyPoolCooldown),
|
||||
proxy_health_check_interval_seconds: Number(proxyPoolHealthInterval),
|
||||
})
|
||||
.then((s) => {
|
||||
apply(s);
|
||||
toast.success(t("settings.rotationSaved"));
|
||||
})
|
||||
.catch((e) => toast.error(t("settings.saveFailedPrefix") + localizedError(e, t)));
|
||||
};
|
||||
const testAllProxyPool = () =>
|
||||
api
|
||||
.testAllProxyPool()
|
||||
.then((r) => {
|
||||
setProxyPool(r.entries);
|
||||
setProxyPoolActiveId(r.active_id);
|
||||
setProxyPoolLogs(r.switch_log);
|
||||
toast.success(t("settings.allProxiesTested"));
|
||||
})
|
||||
.catch((e) => toast.error(t("settings.probeFailedPrefix") + localizedError(e, t)));
|
||||
const testOneProxyPool = (id: string) =>
|
||||
api
|
||||
.testProxyPoolEntry(id)
|
||||
.then(() => api.proxyPool())
|
||||
.then((r) => {
|
||||
setProxyPool(r.entries);
|
||||
setProxyPoolActiveId(r.active_id);
|
||||
setProxyPoolLogs(r.switch_log);
|
||||
})
|
||||
.catch((e) => toast.error(t("settings.probeFailedPrefix") + localizedError(e, t)));
|
||||
const refreshProxyPool = () =>
|
||||
api.proxyPool().then((r) => {
|
||||
setProxyPool(r.entries);
|
||||
setProxyPoolActiveId(r.active_id);
|
||||
setProxyPoolLogs(r.switch_log);
|
||||
});
|
||||
const toggleProxyPoolEntry = (entry: ProxyPoolEntry) =>
|
||||
api
|
||||
.updateProxyPool(entry.id, { enabled: !entry.enabled })
|
||||
.then(() => refreshProxyPool())
|
||||
.catch((e) => toast.error(t("settings.updateFailedPrefix") + localizedError(e, t)));
|
||||
const deleteProxyPoolEntry = (id: string) =>
|
||||
api
|
||||
.deleteProxyPool(id)
|
||||
.then(() => refreshProxyPool())
|
||||
.catch((e) => toast.error(t("settings.deleteFailedPrefix") + localizedError(e, t)));
|
||||
|
||||
const saveProxyReconnect = () => {
|
||||
api
|
||||
.setSettings({
|
||||
proxy_reconnect_max_attempts: Number(proxyReconnectMax),
|
||||
proxy_reconnect_interval_seconds: Number(proxyReconnectInterval),
|
||||
})
|
||||
.then((s) => {
|
||||
apply(s);
|
||||
toast.success(t("settings.reconnectSaved"));
|
||||
})
|
||||
.catch((e) => toast.error(t("settings.saveFailedPrefix") + localizedError(e, t)));
|
||||
};
|
||||
|
||||
const saveEgressProbeUrl = async () => {
|
||||
setSavingEgressProbeUrl(true);
|
||||
try {
|
||||
const settings = await api.setSettings({ egress_probe_url: egressProbeUrl.trim() });
|
||||
setEgressProbeUrl(settings.egress_probe_url ?? "");
|
||||
clearEgressReport();
|
||||
toast.success(settings.egress_probe_url ? t("settings.probeServiceSaved") : t("settings.probeServiceReset"));
|
||||
if (showEgressIp) void probeEgress().catch(() => undefined);
|
||||
} catch (e) {
|
||||
toast.error(t("settings.probeServiceSaveFailed", { message: localizedError(e, t) }));
|
||||
} finally {
|
||||
setSavingEgressProbeUrl(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 测表单里当前的值,不要求先保存;后端返回直连 / 经代理两条。
|
||||
const testEgress = () => {
|
||||
const seq = ++egressSeq.current;
|
||||
setEgressTesting(true);
|
||||
setEgressReport(null);
|
||||
api
|
||||
.testEgressProxy({
|
||||
global_proxy: globalProxyInput.trim(),
|
||||
resume: true,
|
||||
probe_url: egressProbeUrl.trim(),
|
||||
})
|
||||
.then((rep) => {
|
||||
if (seq !== egressSeq.current) return; // 期间改过配置,这份结果已经过期
|
||||
setEgressReport(rep);
|
||||
if (rep.ok) {
|
||||
// 先取 ②:直连那行永远成功,先命中它会把直连 IP 当成出口报出去。
|
||||
const hit =
|
||||
rep.checks.find((c) => c.key === "global" && !c.skipped && c.result.ok) ??
|
||||
rep.checks.find((c) => !c.skipped && c.result.ok);
|
||||
toast.success(
|
||||
hit?.result.exit_ip ? t("settings.egressResult", { ip: hit.result.exit_ip }) : t("settings.probeSucceeded"),
|
||||
);
|
||||
} else {
|
||||
toast.error(t("settings.egressFailed"));
|
||||
}
|
||||
})
|
||||
.catch((e) => {
|
||||
if (seq === egressSeq.current) toast.error(t("settings.probeFailedPrefix") + localizedError(e, t));
|
||||
})
|
||||
.finally(() => {
|
||||
if (seq === egressSeq.current) setEgressTesting(false);
|
||||
});
|
||||
};
|
||||
|
||||
const toggleEgressVisibility = async (nextEnabled: boolean) => {
|
||||
setSavingEgressVisibility(true);
|
||||
try {
|
||||
await setShowEgressIp(nextEnabled);
|
||||
toast.success(nextEnabled ? t("settings.egressShown") : t("settings.egressHidden"));
|
||||
} catch (e) {
|
||||
toast.error(t("settings.egressVisibilityFailed") + localizedError(e, t));
|
||||
} finally {
|
||||
setSavingEgressVisibility(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Run a real "test" search ("test") against the CURRENT form values (backend +
|
||||
// proxy + entered key), falling back to saved values server-side. Toasts result.
|
||||
const runTest = () => {
|
||||
@@ -890,440 +664,27 @@ export default function SystemSettingsPage() {
|
||||
<Card
|
||||
className={`${isSettingVisible("traffic", "settings.keywords.globalProxy") ? "" : "hidden"} mb-4 break-inside-avoid md:mb-6`}
|
||||
>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2 text-base">
|
||||
<RadioTowerIcon className="size-4" />
|
||||
{t("settings.globalProxy")}
|
||||
</CardTitle>
|
||||
<CardDescription>{t("settings.globalProxyHelp")}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-5">
|
||||
<section className="space-y-2">
|
||||
<Label htmlFor="global-proxy" className="text-sm font-normal text-muted-foreground">
|
||||
{t("settings.proxyAddress")}
|
||||
</Label>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Input
|
||||
id="global-proxy"
|
||||
className="min-w-0 flex-1"
|
||||
autoComplete="off"
|
||||
placeholder={t("settings.globalProxyPlaceholder")}
|
||||
value={globalProxyInput}
|
||||
disabled={!loaded || savingGlobalProxy}
|
||||
onChange={(e) => {
|
||||
setGlobalProxyInput(e.target.value);
|
||||
// 旧结果对应的是上一次的地址,留着会让人以为新值已经测过。
|
||||
clearEgressReport();
|
||||
}}
|
||||
/>
|
||||
<Button type="button" onClick={saveGlobalProxy} disabled={!loaded || savingGlobalProxy}>
|
||||
{t("settings.save")}
|
||||
</Button>
|
||||
{/* 测表单里当前的值,不要求先保存。 */}
|
||||
<Button type="button" variant="outline" onClick={testEgress} disabled={!loaded || egressTesting}>
|
||||
{egressTesting ? t("settings.testing") : t("settings.testProxy")}
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-muted-foreground text-xs">
|
||||
{globalProxyInput.trim() ? t("settings.proxyConfigured") : t("settings.proxyUnconfigured")}
|
||||
</p>
|
||||
<details className="text-xs">
|
||||
<summary className="text-muted-foreground cursor-pointer select-none">
|
||||
{t("settings.howProxyWorks")}
|
||||
</summary>
|
||||
<p className="text-muted-foreground mt-2 max-w-4xl leading-relaxed">
|
||||
{t("settings.howProxyWorksHelp")}
|
||||
</p>
|
||||
</details>
|
||||
</section>
|
||||
<details className="text-xs">
|
||||
<summary className="text-muted-foreground cursor-pointer select-none">
|
||||
{t("settings.reconnection")}
|
||||
</summary>
|
||||
<div className="mt-3 space-y-3 rounded-md border p-3 sm:p-4">
|
||||
<p className="text-muted-foreground">{t("settings.reconnectionHelp")}</p>
|
||||
<div className="grid grid-cols-1 items-end gap-3 sm:grid-cols-[minmax(0,1fr)_minmax(0,1fr)_auto]">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="proxy-reconnect-max">{t("settings.reconnectAttempts")}</Label>
|
||||
<Input
|
||||
id="proxy-reconnect-max"
|
||||
type="number"
|
||||
min={1}
|
||||
value={proxyReconnectMax}
|
||||
onChange={(e) => setProxyReconnectMax(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="proxy-reconnect-interval">{t("settings.reconnectInterval")}</Label>
|
||||
<Input
|
||||
id="proxy-reconnect-interval"
|
||||
type="number"
|
||||
min={1}
|
||||
value={proxyReconnectInterval}
|
||||
onChange={(e) => setProxyReconnectInterval(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<Button type="button" variant="outline" className="w-full sm:w-auto" onClick={saveProxyReconnect}>
|
||||
{t("settings.savePolicy")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
<div className="flex items-center justify-between gap-4 rounded-md border px-3 py-2">
|
||||
<div className="min-w-0">
|
||||
<Label htmlFor="show-egress-ip" className="text-sm font-normal">
|
||||
{t("settings.showEgress")}
|
||||
</Label>
|
||||
<p className="text-muted-foreground text-xs">{t("settings.showEgressHelp")}</p>
|
||||
</div>
|
||||
<Switch
|
||||
id="show-egress-ip"
|
||||
checked={showEgressIp}
|
||||
disabled={!settingsLoaded || savingEgressVisibility || egressProbeLoading}
|
||||
onCheckedChange={(checked) => void toggleEgressVisibility(checked)}
|
||||
/>
|
||||
<CardHeader className="flex flex-row flex-wrap items-center justify-between gap-3">
|
||||
<div className="space-y-1">
|
||||
<CardTitle className="flex items-center gap-2 text-base">
|
||||
<RadioTowerIcon className="size-4" />
|
||||
{t("settings.globalProxy")}
|
||||
</CardTitle>
|
||||
<CardDescription>{t("settings.proxyMovedDesc")}</CardDescription>
|
||||
</div>
|
||||
{/* 紧贴结果区:用户看两行时正好需要它。细节放文档。 */}
|
||||
<details className="text-xs">
|
||||
<summary className="text-muted-foreground cursor-pointer select-none">
|
||||
{t("settings.egressTestDetails")}
|
||||
</summary>
|
||||
<p className="text-muted-foreground mt-2 leading-relaxed">{t("settings.egressTestHelp")}</p>
|
||||
</details>
|
||||
{/* 内网里公网回显不可达,两行都会失败——不是代理坏了。 */}
|
||||
<details className="text-xs">
|
||||
<summary className="text-muted-foreground cursor-pointer select-none">
|
||||
{t("settings.customProbe")}
|
||||
</summary>
|
||||
<div className="mt-2 flex flex-col gap-2">
|
||||
<Label htmlFor="egress-probe-url">{t("settings.probeUrl")}</Label>
|
||||
<div className="flex flex-col gap-2 sm:flex-row">
|
||||
<Input
|
||||
id="egress-probe-url"
|
||||
autoComplete="off"
|
||||
placeholder={t("settings.probePlaceholder")}
|
||||
value={egressProbeUrl}
|
||||
disabled={!settingsLoaded || savingEgressProbeUrl}
|
||||
onChange={(e) => {
|
||||
setEgressProbeUrl(e.target.value);
|
||||
clearEgressReport();
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
disabled={!settingsLoaded || savingEgressProbeUrl}
|
||||
onClick={() => void saveEgressProbeUrl()}
|
||||
>
|
||||
{savingEgressProbeUrl ? t("settings.saving") : t("settings.saveProbe")}
|
||||
</Button>
|
||||
</div>
|
||||
<span className="text-muted-foreground leading-relaxed">{t("settings.probePersistenceHelp")}</span>
|
||||
<span className="text-muted-foreground leading-relaxed">
|
||||
{t("settings.probeResponseStart")}
|
||||
<code>{'{"ip":"1.2.3.4"}'}</code>
|
||||
{t("settings.probeResponseEnd")}
|
||||
</span>
|
||||
</div>
|
||||
</details>
|
||||
{egressReport && (
|
||||
<div className="flex flex-col gap-1 text-xs">
|
||||
{egressReport.checks.map((c) => {
|
||||
// 经 MITM 时 via 是 HTTP(MITM 自己是代理),标出来会让人以为填错了。
|
||||
const viaCapture = !!c.path && c.path !== egressReport.configured;
|
||||
return (
|
||||
<div key={c.key} className="flex flex-wrap items-center gap-x-2">
|
||||
<span
|
||||
className={
|
||||
c.skipped
|
||||
? "text-muted-foreground"
|
||||
: c.result.ok
|
||||
? "text-emerald-600"
|
||||
: "text-destructive"
|
||||
}
|
||||
>
|
||||
{c.skipped ? "—" : c.result.ok ? "✓" : "✗"}
|
||||
</span>
|
||||
|
||||
<span
|
||||
className="w-56 shrink-0"
|
||||
title={
|
||||
c.key === "direct"
|
||||
? t("settings.directProbeHint")
|
||||
: viaCapture
|
||||
? t("settings.captureProbeHint", { path: c.path })
|
||||
: t("settings.proxyProbeHint")
|
||||
}
|
||||
>
|
||||
{t(`settings.egressCheck.${c.key}`, { defaultValue: c.label })}
|
||||
</span>
|
||||
{c.skipped ? (
|
||||
<span className="text-muted-foreground">
|
||||
{c.skip_code
|
||||
? t(`settings.egressSkip.${c.skip_code}`, { defaultValue: c.skip_reason })
|
||||
: c.skip_reason}
|
||||
</span>
|
||||
) : c.result.ok ? (
|
||||
<span className="font-mono">
|
||||
<span title={t("settings.outboundIpHint")}>{c.result.exit_ip}</span> ·{" "}
|
||||
<span title={t("settings.latencyHint")}>{c.result.latency_ms}ms</span>
|
||||
{c.result.via && c.result.via !== "direct" && !viaCapture && (
|
||||
<span className="text-muted-foreground">
|
||||
{" "}
|
||||
{t("settings.viaPrefix")}
|
||||
{c.result.via.toUpperCase()}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
) : (
|
||||
// 只显示第一个地址的原因:refused=代理没开,timeout=出不了网。
|
||||
<span className="text-destructive">
|
||||
{c.result.probes?.find((p) => p.error)?.error ?? c.result.error}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{(
|
||||
egressReport.warning_details ??
|
||||
egressReport.warnings?.map((message) => ({ code: "", message, params: {} }))
|
||||
)?.map((notice) => (
|
||||
<p key={notice.code || notice.message} className="text-amber-700">
|
||||
⚠{" "}
|
||||
{notice.code
|
||||
? t(`settings.egressWarning.${notice.code}`, {
|
||||
...notice.params,
|
||||
defaultValue: notice.message,
|
||||
})
|
||||
: notice.message}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<section className="space-y-3 border-t pt-4">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<div>
|
||||
<p className="text-sm font-medium">
|
||||
{t("settings.proxyPool")}{" "}
|
||||
<span className="text-muted-foreground font-normal">{proxyPool.length}</span>
|
||||
</p>
|
||||
<p className="text-muted-foreground mt-1 text-xs">
|
||||
{t("settings.currentProxyPrefix")}
|
||||
{proxyPool.find((entry) => entry.id === proxyPoolActiveId)?.name ??
|
||||
(proxyPoolActiveId ? t("settings.selectedProxy") : t("settings.direct"))}
|
||||
</p>
|
||||
</div>
|
||||
<Button type="button" variant="outline" size="sm" onClick={testAllProxyPool}>
|
||||
{t("settings.testAll")}
|
||||
</Button>
|
||||
</div>
|
||||
<details className="rounded-md border px-3 py-2 text-xs">
|
||||
<summary className="text-muted-foreground cursor-pointer select-none">
|
||||
{t("settings.importProxies")}
|
||||
</summary>
|
||||
<Textarea
|
||||
className="mt-3 font-mono"
|
||||
rows={3}
|
||||
placeholder={t("settings.importPlaceholder")}
|
||||
value={proxyPoolText}
|
||||
onChange={(e) => setProxyPoolText(e.target.value)}
|
||||
/>
|
||||
<div className="mt-2 flex flex-wrap items-center gap-2">
|
||||
<Button type="button" size="sm" onClick={importProxyPool} disabled={!proxyPoolText.trim()}>
|
||||
{t("settings.import")}
|
||||
</Button>
|
||||
<span className="text-muted-foreground">{t("settings.proxyCredentialsHidden")}</span>
|
||||
</div>
|
||||
</details>
|
||||
<div className="space-y-2">
|
||||
{proxyPool.length === 0 ? (
|
||||
<p className="text-muted-foreground text-xs">{t("settings.emptyProxyPool")}</p>
|
||||
) : (
|
||||
proxyPool.map((entry) => (
|
||||
<div
|
||||
key={entry.id}
|
||||
className="grid gap-3 rounded-md border p-3 sm:grid-cols-[minmax(0,1fr)_auto] sm:items-center"
|
||||
>
|
||||
<div className="flex min-w-0 items-start gap-3">
|
||||
<Switch
|
||||
checked={entry.enabled}
|
||||
onCheckedChange={() => toggleProxyPoolEntry(entry)}
|
||||
aria-label={t("settings.enableProxy")}
|
||||
/>
|
||||
<div className="grid min-w-0 flex-1 gap-x-5 gap-y-2 text-xs sm:grid-cols-2">
|
||||
<div className="min-w-0">
|
||||
<p className="text-muted-foreground">{t("settings.proxyAddress")}</p>
|
||||
<p className="truncate font-mono" title={entry.url}>
|
||||
{entry.name ? `${entry.name} · ` : ""}
|
||||
{entry.url}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-muted-foreground">{t("settings.testOutboundIp")}</p>
|
||||
<p className="break-all font-mono">
|
||||
{entry.egress_ip ||
|
||||
(entry.last_error ? t("settings.probeFailed") : t("settings.notTested"))}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-x-2 gap-y-1">
|
||||
<span
|
||||
className={
|
||||
entry.health === "healthy"
|
||||
? "text-emerald-600"
|
||||
: entry.health === "disabled"
|
||||
? "text-muted-foreground"
|
||||
: "text-amber-600"
|
||||
}
|
||||
>
|
||||
{!entry.enabled
|
||||
? t("settings.disabled")
|
||||
: entry.health === "healthy"
|
||||
? t("settings.healthy")
|
||||
: entry.health === "unhealthy-cooling"
|
||||
? t("settings.coolingDown")
|
||||
: t("settings.pendingCheck")}
|
||||
</span>
|
||||
{entry.id === proxyPoolActiveId && (
|
||||
<span className="text-primary">{t("settings.activeProxy")}</span>
|
||||
)}
|
||||
<span className="text-muted-foreground">
|
||||
{t("settings.failureCount", { count: entry.consecutive_failures })}
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-muted-foreground">
|
||||
{entry.latency_ms != null ? `${entry.latency_ms} ms` : t("settings.noLatency")}
|
||||
{entry.last_checked_at &&
|
||||
!entry.last_checked_at.startsWith("0001-") &&
|
||||
` · ${new Date(entry.last_checked_at).toLocaleTimeString(i18n.resolvedLanguage)}`}
|
||||
{entry.last_error && <span className="text-destructive"> · {entry.last_error}</span>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-end gap-1">
|
||||
<Button type="button" variant="ghost" size="sm" onClick={() => testOneProxyPool(entry.id)}>
|
||||
{t("settings.test")}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => deleteProxyPoolEntry(entry.id)}
|
||||
>
|
||||
{t("settings.delete")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
<details className="rounded-md border px-3 py-2 text-xs">
|
||||
<summary className="text-muted-foreground cursor-pointer select-none">
|
||||
{t("settings.rotationHealth")}
|
||||
</summary>
|
||||
<div className="mt-3 space-y-3">
|
||||
<p className="text-muted-foreground">{t("settings.rotationHealthHelp")}</p>
|
||||
<div className="flex flex-wrap items-center gap-x-8 gap-y-3 border-b pb-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<Label htmlFor="proxy-pool-timed">{t("settings.timedRotation")}</Label>
|
||||
<Switch id="proxy-pool-timed" checked={proxyPoolTimed} onCheckedChange={setProxyPoolTimed} />
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<Label htmlFor="proxy-pool-failure">{t("settings.failureRotation")}</Label>
|
||||
<Switch
|
||||
id="proxy-pool-failure"
|
||||
checked={proxyPoolFailure}
|
||||
onCheckedChange={setProxyPoolFailure}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid max-w-2xl grid-cols-1 gap-x-5 gap-y-4 sm:grid-cols-2">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="proxy-pool-strategy">{t("settings.rotationOrder")}</Label>
|
||||
<Select
|
||||
value={proxyPoolStrategy}
|
||||
onValueChange={(v) => setProxyPoolStrategy(v as "sequential" | "random")}
|
||||
>
|
||||
<SelectTrigger id="proxy-pool-strategy" className="w-full">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="sequential">{t("settings.sequential")}</SelectItem>
|
||||
<SelectItem value="random">{t("settings.random")}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="proxy-pool-interval">{t("settings.rotationInterval")}</Label>
|
||||
<Input
|
||||
id="proxy-pool-interval"
|
||||
type="number"
|
||||
min={3}
|
||||
value={proxyPoolInterval}
|
||||
onChange={(e) => setProxyPoolInterval(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="proxy-pool-threshold">{t("settings.failureThreshold")}</Label>
|
||||
<Input
|
||||
id="proxy-pool-threshold"
|
||||
type="number"
|
||||
min={1}
|
||||
value={proxyPoolThreshold}
|
||||
onChange={(e) => setProxyPoolThreshold(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="proxy-pool-cooldown">{t("settings.cooldown")}</Label>
|
||||
<Input
|
||||
id="proxy-pool-cooldown"
|
||||
type="number"
|
||||
min={1}
|
||||
value={proxyPoolCooldown}
|
||||
onChange={(e) => setProxyPoolCooldown(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="proxy-pool-health-interval">{t("settings.healthInterval")}</Label>
|
||||
<Input
|
||||
id="proxy-pool-health-interval"
|
||||
type="number"
|
||||
min={1}
|
||||
value={proxyPoolHealthInterval}
|
||||
onChange={(e) => setProxyPoolHealthInterval(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-end border-t pt-3">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="w-full sm:w-auto"
|
||||
onClick={saveProxyPoolStrategy}
|
||||
>
|
||||
{t("settings.saveRotation")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
{proxyPoolLogs.length > 0 && (
|
||||
<details className="text-xs">
|
||||
<summary className="text-muted-foreground cursor-pointer select-none">
|
||||
{t("settings.switchHistory", { count: proxyPoolLogs.length })}
|
||||
</summary>
|
||||
<div className="mt-2 space-y-1">
|
||||
{proxyPoolLogs
|
||||
.slice(-5)
|
||||
.reverse()
|
||||
.map((log) => (
|
||||
<p key={`${log.at}-${log.to}`} className="text-muted-foreground">
|
||||
{new Date(log.at).toLocaleTimeString(i18n.resolvedLanguage)} ·{" "}
|
||||
{log.from || t("settings.direct")} → {log.to || t("settings.direct")} · {log.reason}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
</details>
|
||||
)}
|
||||
</section>
|
||||
<Button type="button" variant="outline" size="sm" asChild>
|
||||
<Link href="/system/proxy" className="gap-1.5">
|
||||
{t("settings.openProxyPage")}
|
||||
<ExternalLinkIcon className="size-3.5" />
|
||||
</Link>
|
||||
</Button>
|
||||
</CardHeader>
|
||||
<CardContent className="text-muted-foreground text-xs">
|
||||
{proxyPoolCount > 0
|
||||
? `${t("settings.proxyPool")} (${proxyPoolCount})`
|
||||
: globalProxySummary.trim()
|
||||
? t("settings.proxyConfigured")
|
||||
: t("settings.proxyUnconfigured")}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
|
||||
@@ -0,0 +1,618 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
|
||||
import {
|
||||
ChevronLeftIcon,
|
||||
ChevronRightIcon,
|
||||
GlobeIcon,
|
||||
Loader2Icon,
|
||||
NetworkIcon,
|
||||
RefreshCwIcon,
|
||||
SearchIcon,
|
||||
ShieldBanIcon,
|
||||
Trash2Icon,
|
||||
} from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { useLiveTranslation } from "@/i18n/use-live-translation";
|
||||
import { api } from "@/lib/api";
|
||||
import type { TrafficDNSQuery, TrafficNetFlow } from "@/lib/types";
|
||||
|
||||
function fmtUnix(ts: number, locale?: string) {
|
||||
if (!ts) return "—";
|
||||
return new Date(ts * 1000).toLocaleString(locale, {
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
second: "2-digit",
|
||||
});
|
||||
}
|
||||
|
||||
function fmtBytes(n: number) {
|
||||
if (!n || n <= 0) return "0 B";
|
||||
const units = ["B", "KB", "MB", "GB"];
|
||||
const i = Math.min(Math.floor(Math.log(n) / Math.log(1024)), units.length - 1);
|
||||
const v = n / 1024 ** i;
|
||||
return `${i === 0 ? v : v.toFixed(1)} ${units[i]}`;
|
||||
}
|
||||
|
||||
function FlowSourceBadge({
|
||||
scope,
|
||||
ownerId,
|
||||
containerId,
|
||||
srcIp,
|
||||
isEn,
|
||||
}: {
|
||||
scope?: string;
|
||||
ownerId?: string;
|
||||
containerId?: string;
|
||||
srcIp?: string;
|
||||
isEn: boolean;
|
||||
}) {
|
||||
if (!scope && !ownerId && !containerId && !srcIp) {
|
||||
return <span className="text-muted-foreground text-xs">—</span>;
|
||||
}
|
||||
let label = isEn ? "Host" : "主进程";
|
||||
if (srcIp) label = srcIp;
|
||||
let variant: "default" | "secondary" | "outline" = "outline";
|
||||
if (scope === "task" && ownerId) {
|
||||
label = isEn ? `Task #${ownerId}` : `任务 #${ownerId}`;
|
||||
variant = "secondary";
|
||||
} else if (scope === "session" && ownerId) {
|
||||
label = isEn ? `Chat ${ownerId.slice(0, 8)}` : `对话 ${ownerId.slice(0, 8)}`;
|
||||
variant = "outline";
|
||||
}
|
||||
const details: string[] = [];
|
||||
if (srcIp) details.push(`IP: ${srcIp}`);
|
||||
if (containerId) details.push(`${isEn ? "Container" : "容器"}: ${containerId.slice(0, 12)}`);
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Badge variant={variant} className="max-w-[8.5rem] truncate font-mono text-[11px]">
|
||||
{label}
|
||||
</Badge>
|
||||
</TooltipTrigger>
|
||||
{details.length > 0 ? (
|
||||
<TooltipContent side="top" className="font-mono text-xs">
|
||||
{details.map((line) => (
|
||||
<div key={line}>{line}</div>
|
||||
))}
|
||||
</TooltipContent>
|
||||
) : null}
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
export function NonHTTPTrafficPanel({ mode, taskId }: { mode: "flows" | "dns"; taskId?: string }) {
|
||||
const { isEn, locale } = useLiveTranslation();
|
||||
const L = (zh: string, en: string) => (isEn ? en : zh);
|
||||
const formatUpstream = (raw?: string) => (!raw || raw === "direct" ? L("直连", "Direct") : raw);
|
||||
|
||||
const [page, setPage] = React.useState(0);
|
||||
const [size] = React.useState(50);
|
||||
const [query, setQuery] = React.useState("");
|
||||
const [queryDebounced, setQueryDebounced] = React.useState("");
|
||||
const [protoFilter, setProtoFilter] = React.useState("all");
|
||||
const [actionFilter, setActionFilter] = React.useState("all");
|
||||
const [qtypeFilter, setQtypeFilter] = React.useState("ALL");
|
||||
const [loading, setLoading] = React.useState(false);
|
||||
|
||||
const [flows, setFlows] = React.useState<TrafficNetFlow[]>([]);
|
||||
const [dnsRows, setDnsRows] = React.useState<TrafficDNSQuery[]>([]);
|
||||
const [total, setTotal] = React.useState(0);
|
||||
|
||||
const [selectedFlow, setSelectedFlow] = React.useState<TrafficNetFlow | null>(null);
|
||||
const [detailLoading, setDetailLoading] = React.useState(false);
|
||||
|
||||
React.useEffect(() => {
|
||||
const timer = setTimeout(() => {
|
||||
setQueryDebounced(query.trim());
|
||||
setPage(0);
|
||||
}, 250);
|
||||
return () => clearTimeout(timer);
|
||||
}, [query]);
|
||||
|
||||
React.useEffect(() => {
|
||||
void mode;
|
||||
void protoFilter;
|
||||
void actionFilter;
|
||||
void qtypeFilter;
|
||||
void taskId;
|
||||
setPage(0);
|
||||
}, [mode, protoFilter, actionFilter, qtypeFilter, taskId]);
|
||||
|
||||
const load = React.useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
if (mode === "flows") {
|
||||
const res = await api.trafficFlows({
|
||||
protocol: protoFilter,
|
||||
action: actionFilter,
|
||||
task_id: taskId,
|
||||
q: queryDebounced || undefined,
|
||||
page,
|
||||
size,
|
||||
});
|
||||
setFlows(res.flows ?? []);
|
||||
setTotal(res.total ?? 0);
|
||||
} else {
|
||||
const res = await api.trafficDNS({
|
||||
qtype: qtypeFilter,
|
||||
action: actionFilter,
|
||||
task_id: taskId,
|
||||
q: queryDebounced || undefined,
|
||||
page,
|
||||
size,
|
||||
});
|
||||
setDnsRows(res.queries ?? []);
|
||||
setTotal(res.total ?? 0);
|
||||
}
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [mode, protoFilter, actionFilter, qtypeFilter, taskId, queryDebounced, page, size]);
|
||||
|
||||
React.useEffect(() => {
|
||||
void load();
|
||||
const interval = setInterval(() => {
|
||||
void load();
|
||||
}, 5000);
|
||||
return () => clearInterval(interval);
|
||||
}, [load]);
|
||||
|
||||
const openFlowDetail = async (row: TrafficNetFlow) => {
|
||||
setSelectedFlow(row);
|
||||
setDetailLoading(true);
|
||||
try {
|
||||
const full = await api.trafficFlowDetail(row.id);
|
||||
setSelectedFlow(full);
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
setDetailLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleClear = async () => {
|
||||
try {
|
||||
if (mode === "flows") {
|
||||
const res = await api.deleteTrafficFlows(taskId);
|
||||
toast.success(L(`已清空 ${res.deleted} 条 TCP/UDP 流记录`, `Cleared ${res.deleted} TCP/UDP flow records`));
|
||||
} else {
|
||||
const res = await api.deleteTrafficDNS(taskId);
|
||||
toast.success(L(`已清空 ${res.deleted} 条 DNS 查询记录`, `Cleared ${res.deleted} DNS query records`));
|
||||
}
|
||||
setPage(0);
|
||||
await load();
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
};
|
||||
|
||||
const pageCount = Math.max(1, Math.ceil(total / size));
|
||||
|
||||
const actionBadge = (action: string) => {
|
||||
switch (action) {
|
||||
case "block":
|
||||
return (
|
||||
<Badge variant="destructive" className="gap-1 font-mono text-[11px]">
|
||||
<ShieldBanIcon className="size-3" />
|
||||
{L("拦截", "BLOCK")}
|
||||
</Badge>
|
||||
);
|
||||
case "error":
|
||||
return (
|
||||
<Badge variant="outline" className="border-amber-500/40 font-mono text-[11px] text-amber-600">
|
||||
{L("错误", "ERROR")}
|
||||
</Badge>
|
||||
);
|
||||
case "passthrough":
|
||||
return (
|
||||
<Badge variant="secondary" className="font-mono text-[11px]">
|
||||
{L("透传", "PASS")}
|
||||
</Badge>
|
||||
);
|
||||
default:
|
||||
return (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="border-emerald-500/30 bg-emerald-500/10 font-mono text-[11px] text-emerald-600 dark:text-emerald-400"
|
||||
>
|
||||
{L("放行", "ALLOW")}
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1 flex-col gap-3">
|
||||
{/* Filter toolbar */}
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<div className="relative min-w-[200px] max-w-sm flex-1">
|
||||
<SearchIcon className="pointer-events-none absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
placeholder={
|
||||
mode === "flows"
|
||||
? L("搜索目标主机 / IP / 端口 / SNI / 来源 IP…", "Filter by host, IP, port, SNI, src IP…")
|
||||
: L("搜索查询域名 / 解析结果 IP / 来源 IP…", "Filter by domain, answer IP, src IP…")
|
||||
}
|
||||
className="h-8 pl-8 text-xs"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{mode === "flows" ? (
|
||||
<Select value={protoFilter} onValueChange={setProtoFilter}>
|
||||
<SelectTrigger className="h-8 w-[120px] text-xs">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">{L("全部协议", "All protos")}</SelectItem>
|
||||
<SelectItem value="tcp">TCP</SelectItem>
|
||||
<SelectItem value="tls">TLS</SelectItem>
|
||||
<SelectItem value="udp">UDP</SelectItem>
|
||||
<SelectItem value="icmp">ICMP</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
) : (
|
||||
<Select value={qtypeFilter} onValueChange={setQtypeFilter}>
|
||||
<SelectTrigger className="h-8 w-[120px] text-xs">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="ALL">{L("全部类型", "All types")}</SelectItem>
|
||||
<SelectItem value="A">A</SelectItem>
|
||||
<SelectItem value="AAAA">AAAA</SelectItem>
|
||||
<SelectItem value="CNAME">CNAME</SelectItem>
|
||||
<SelectItem value="TXT">TXT</SelectItem>
|
||||
<SelectItem value="MX">MX</SelectItem>
|
||||
<SelectItem value="NS">NS</SelectItem>
|
||||
<SelectItem value="PTR">PTR</SelectItem>
|
||||
<SelectItem value="SRV">SRV</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
|
||||
<Select value={actionFilter} onValueChange={setActionFilter}>
|
||||
<SelectTrigger className="h-8 w-[120px] text-xs">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">{L("全部动作", "All actions")}</SelectItem>
|
||||
<SelectItem value="allow">{L("放行", "Allow")}</SelectItem>
|
||||
<SelectItem value="block">{L("拦截", "Blocked")}</SelectItem>
|
||||
{mode === "flows" ? <SelectItem value="passthrough">{L("透传", "Passthrough")}</SelectItem> : null}
|
||||
<SelectItem value="error">{L("错误", "Error")}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
<div className="ml-auto flex items-center gap-2">
|
||||
<span className="text-muted-foreground text-xs tabular-nums">{L(`共 ${total} 条`, `${total} records`)}</span>
|
||||
<Button size="sm" variant="outline" className="h-8" onClick={() => void load()} disabled={loading}>
|
||||
<RefreshCwIcon className={`mr-1.5 size-3.5 ${loading ? "animate-spin" : ""}`} />
|
||||
{L("刷新", "Refresh")}
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="h-8 text-destructive hover:text-destructive"
|
||||
disabled={total === 0}
|
||||
onClick={() => void handleClear()}
|
||||
>
|
||||
<Trash2Icon className="mr-1.5 size-3.5" />
|
||||
{L("清空", "Clear")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Table */}
|
||||
<Card className="min-h-0 flex-1 overflow-auto p-0">
|
||||
{mode === "flows" ? (
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead className="w-[130px]">{L("时间", "Time")}</TableHead>
|
||||
<TableHead className="w-[70px]">{L("协议", "Proto")}</TableHead>
|
||||
<TableHead className="w-[84px]">{L("动作", "Action")}</TableHead>
|
||||
<TableHead className="w-[120px]">{L("来源", "Source")}</TableHead>
|
||||
<TableHead>{L("目标地址", "Destination")}</TableHead>
|
||||
<TableHead className="w-[130px]">{L("上下行流量", "TX / RX")}</TableHead>
|
||||
<TableHead className="w-[90px]">{L("耗时", "Duration")}</TableHead>
|
||||
<TableHead className="w-[160px]">{L("出口路径 / 原因", "Egress / Reason")}</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{flows.length === 0 ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={8} className="py-12 text-center text-muted-foreground text-sm">
|
||||
<div className="flex flex-col items-center gap-1.5">
|
||||
<NetworkIcon className="size-6 opacity-40" />
|
||||
<span>
|
||||
{L(
|
||||
"暂无 TCP/UDP 非 HTTP 流量(透明网关启用后将自动捕获 nmap / nc / 数据库 / SSH / 自定义 Socket)",
|
||||
"No TCP/UDP flows recorded yet (captured automatically when the transparent gateway is active)",
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : (
|
||||
flows.map((f) => (
|
||||
<TableRow
|
||||
key={f.id}
|
||||
className="cursor-pointer hover:bg-muted/50"
|
||||
onClick={() => void openFlowDetail(f)}
|
||||
>
|
||||
<TableCell className="whitespace-nowrap font-mono text-muted-foreground text-xs">
|
||||
{fmtUnix(f.ts, locale)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant="outline" className="font-mono text-[11px] uppercase">
|
||||
{f.protocol}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell>{actionBadge(f.action)}</TableCell>
|
||||
<TableCell>
|
||||
<FlowSourceBadge
|
||||
scope={f.sandbox_scope}
|
||||
ownerId={f.sandbox_owner_id}
|
||||
containerId={f.container_id}
|
||||
srcIp={f.src_ip}
|
||||
isEn={isEn}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell className="max-w-[300px] truncate font-mono text-xs">
|
||||
<div className="truncate font-medium">
|
||||
{f.dst_host && f.dst_host !== f.dst_ip
|
||||
? `${f.dst_host}:${f.dst_port}`
|
||||
: `${f.dst_ip}:${f.dst_port}`}
|
||||
</div>
|
||||
{f.dst_host && f.dst_host !== f.dst_ip ? (
|
||||
<div className="truncate text-[11px] text-muted-foreground">{f.dst_ip}</div>
|
||||
) : null}
|
||||
</TableCell>
|
||||
<TableCell className="whitespace-nowrap font-mono text-xs tabular-nums">
|
||||
↑ {fmtBytes(f.bytes_tx)} / ↓ {fmtBytes(f.bytes_rx)}
|
||||
</TableCell>
|
||||
<TableCell className="whitespace-nowrap font-mono text-muted-foreground text-xs tabular-nums">
|
||||
{f.duration_ms} ms
|
||||
</TableCell>
|
||||
<TableCell
|
||||
className="max-w-[200px] truncate font-mono text-muted-foreground text-xs"
|
||||
title={f.block_reason || f.error || formatUpstream(f.upstream_proxy)}
|
||||
>
|
||||
{f.block_reason || f.error || formatUpstream(f.upstream_proxy)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
) : (
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead className="w-[130px]">{L("时间", "Time")}</TableHead>
|
||||
<TableHead className="w-[70px]">{L("类型", "Type")}</TableHead>
|
||||
<TableHead className="w-[84px]">{L("动作", "Action")}</TableHead>
|
||||
<TableHead className="w-[120px]">{L("来源", "Source")}</TableHead>
|
||||
<TableHead>{L("查询域名", "Domain")}</TableHead>
|
||||
<TableHead className="w-[96px]">RCODE</TableHead>
|
||||
<TableHead>{L("解析结果 / 拦截原因", "Answers / Reason")}</TableHead>
|
||||
<TableHead className="w-[80px]">{L("耗时", "Time")}</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{dnsRows.length === 0 ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={8} className="py-12 text-center text-muted-foreground text-sm">
|
||||
<div className="flex flex-col items-center gap-1.5">
|
||||
<GlobeIcon className="size-6 opacity-40" />
|
||||
<span>
|
||||
{L(
|
||||
"暂无 DNS 查询记录(透明网关接管 UDP/TCP 53 后自动记录容器全部域名解析)",
|
||||
"No DNS queries recorded yet (captured automatically when the transparent gateway intercepts port 53)",
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : (
|
||||
dnsRows.map((q) => (
|
||||
<TableRow key={q.id}>
|
||||
<TableCell className="whitespace-nowrap font-mono text-muted-foreground text-xs">
|
||||
{fmtUnix(q.ts, locale)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant="outline" className="font-mono text-[11px]">
|
||||
{q.qtype}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell>{actionBadge(q.action)}</TableCell>
|
||||
<TableCell>
|
||||
<FlowSourceBadge
|
||||
scope={q.sandbox_scope}
|
||||
ownerId={q.sandbox_owner_id}
|
||||
containerId={q.container_id}
|
||||
srcIp={q.src_ip}
|
||||
isEn={isEn}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell className="max-w-[260px] truncate font-medium font-mono text-xs" title={q.qname}>
|
||||
{q.qname}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge
|
||||
variant={q.rcode === "NOERROR" ? "secondary" : "outline"}
|
||||
className="font-mono text-[11px]"
|
||||
>
|
||||
{q.rcode || "—"}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell
|
||||
className="max-w-[320px] truncate font-mono text-muted-foreground text-xs"
|
||||
title={q.block_reason || q.error || q.answers.join(", ")}
|
||||
>
|
||||
{q.block_reason || q.error || (q.answers.length > 0 ? q.answers.join(", ") : "—")}
|
||||
</TableCell>
|
||||
<TableCell className="whitespace-nowrap font-mono text-muted-foreground text-xs tabular-nums">
|
||||
{q.duration_ms} ms
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
{/* Pagination */}
|
||||
<div className="flex items-center justify-between text-muted-foreground text-xs">
|
||||
<span>{L(`第 ${page + 1} / ${pageCount} 页`, `Page ${page + 1} / ${pageCount}`)}</span>
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-7 px-2"
|
||||
disabled={page <= 0}
|
||||
onClick={() => setPage((p) => Math.max(0, p - 1))}
|
||||
>
|
||||
<ChevronLeftIcon className="size-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-7 px-2"
|
||||
disabled={page + 1 >= pageCount}
|
||||
onClick={() => setPage((p) => p + 1)}
|
||||
>
|
||||
<ChevronRightIcon className="size-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Flow Detail Sheet */}
|
||||
<Sheet open={Boolean(selectedFlow)} onOpenChange={(o) => !o && setSelectedFlow(null)}>
|
||||
<SheetContent className="w-full overflow-y-auto sm:max-w-2xl">
|
||||
{selectedFlow ? (
|
||||
<>
|
||||
<SheetHeader>
|
||||
<SheetTitle className="flex items-center gap-2 font-mono text-sm">
|
||||
<Badge variant="outline" className="uppercase">
|
||||
{selectedFlow.protocol}
|
||||
</Badge>
|
||||
<span>
|
||||
{selectedFlow.dst_host || selectedFlow.dst_ip}:{selectedFlow.dst_port}
|
||||
</span>
|
||||
{actionBadge(selectedFlow.action)}
|
||||
</SheetTitle>
|
||||
<SheetDescription className="font-mono text-xs">
|
||||
{selectedFlow.src_ip || "?"}:{selectedFlow.src_port || 0} → {selectedFlow.dst_ip}:
|
||||
{selectedFlow.dst_port}
|
||||
{selectedFlow.sni ? ` (SNI: ${selectedFlow.sni})` : ""}
|
||||
</SheetDescription>
|
||||
</SheetHeader>
|
||||
|
||||
<div className="mt-4 space-y-4 px-4 pb-6 text-xs">
|
||||
<div className="grid grid-cols-2 gap-2 rounded-lg border bg-muted/30 p-3 font-mono">
|
||||
<div>
|
||||
<span className="text-muted-foreground">{L("ID:", "ID: ")}</span>
|
||||
{selectedFlow.id}
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted-foreground">{L("耗时:", "Duration: ")}</span>
|
||||
{selectedFlow.duration_ms} ms
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted-foreground">{L("发送:", "TX: ")}</span>
|
||||
{fmtBytes(selectedFlow.bytes_tx)}
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted-foreground">{L("接收:", "RX: ")}</span>
|
||||
{fmtBytes(selectedFlow.bytes_rx)}
|
||||
</div>
|
||||
<div className="col-span-2">
|
||||
<span className="text-muted-foreground">{L("出口代理:", "Upstream: ")}</span>
|
||||
{formatUpstream(selectedFlow.upstream_proxy)}
|
||||
</div>
|
||||
{selectedFlow.block_reason ? (
|
||||
<div className="col-span-2 text-destructive">
|
||||
<span>{L("拦截原因:", "Block reason: ")}</span>
|
||||
{selectedFlow.block_reason}
|
||||
</div>
|
||||
) : null}
|
||||
{selectedFlow.error ? (
|
||||
<div className="col-span-2 text-amber-600">
|
||||
<span>{L("错误:", "Error: ")}</span>
|
||||
{selectedFlow.error}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{detailLoading ? (
|
||||
<div className="flex items-center justify-center py-8 text-muted-foreground">
|
||||
<Loader2Icon className="mr-2 size-4 animate-spin" />
|
||||
{L("加载载荷预览…", "Loading payload preview…")}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="space-y-1.5">
|
||||
<div className="font-medium">
|
||||
{L("上行载荷预览 (TX, 最多 4KB)", "Outbound Payload Preview (TX, up to 4KB)")}
|
||||
</div>
|
||||
<pre className="max-h-60 overflow-auto whitespace-pre-wrap break-all rounded-md border bg-muted/40 p-3 font-mono text-[11px]">
|
||||
{selectedFlow.tx_preview_text || L("(空)", "(empty)")}
|
||||
</pre>
|
||||
{selectedFlow.tx_binary && selectedFlow.tx_preview_hex ? (
|
||||
<details className="rounded-md border p-2">
|
||||
<summary className="cursor-pointer text-muted-foreground">
|
||||
{L("Hex 转储 (TX)", "Hex Dump (TX)")}
|
||||
</summary>
|
||||
<pre className="mt-2 max-h-40 overflow-auto break-all font-mono text-[11px]">
|
||||
{selectedFlow.tx_preview_hex}
|
||||
</pre>
|
||||
</details>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<div className="font-medium">
|
||||
{L("下行载荷预览 (RX, 最多 4KB)", "Inbound Payload Preview (RX, up to 4KB)")}
|
||||
</div>
|
||||
<pre className="max-h-60 overflow-auto whitespace-pre-wrap break-all rounded-md border bg-muted/40 p-3 font-mono text-[11px]">
|
||||
{selectedFlow.rx_preview_text || L("(空)", "(empty)")}
|
||||
</pre>
|
||||
{selectedFlow.rx_binary && selectedFlow.rx_preview_hex ? (
|
||||
<details className="rounded-md border p-2">
|
||||
<summary className="cursor-pointer text-muted-foreground">
|
||||
{L("Hex 转储 (RX)", "Hex Dump (RX)")}
|
||||
</summary>
|
||||
<pre className="mt-2 max-h-40 overflow-auto break-all font-mono text-[11px]">
|
||||
{selectedFlow.rx_preview_hex}
|
||||
</pre>
|
||||
</details>
|
||||
) : null}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
) : null}
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -63,6 +63,7 @@ export const messages = {
|
||||
"nav.asset-intercept": ["资产拦截", "Asset interception"],
|
||||
"nav.approvals": ["审批记录", "Approval history"],
|
||||
"nav.sandbox": ["沙箱容器", "Sandbox"],
|
||||
"nav.proxy": ["代理与出口", "Proxy & Egress"],
|
||||
"nav.logs": ["日志", "Logs"],
|
||||
"nav.settings": ["系统配置", "Settings"],
|
||||
"search.placeholder": ["搜索页面与功能…", "Search pages and features…"],
|
||||
@@ -251,6 +252,15 @@ export const messages = {
|
||||
"No findings eligible for AI auto-merge (at least 2 findings per task required)",
|
||||
],
|
||||
"findingsAutoMerge.failed": ["启动 AI 自动合并失败:{{message}}", "Failed to start AI auto-merge: {{message}}"],
|
||||
"traffic.source": ["来源归属", "Source"],
|
||||
"traffic.scopeAll": ["全部来源", "All sources"],
|
||||
"traffic.scopeTask": ["任务容器", "Task"],
|
||||
"traffic.scopeSession": ["对话容器", "Chat"],
|
||||
"traffic.ownerPlaceholder": ["归属 ID(任务/对话)…", "Owner ID (task/chat)…"],
|
||||
"traffic.containerPlaceholder": ["容器 ID 前缀…", "Container ID…"],
|
||||
"traffic.sourceTask": ["任务 #{{id}}", "Task #{{id}}"],
|
||||
"traffic.sourceSession": ["对话 {{id}}", "Chat {{id}}"],
|
||||
"traffic.sourceHost": ["宿主机", "Host"],
|
||||
} satisfies Record<string, readonly [string, string]>;
|
||||
|
||||
const statuses: Record<string, readonly (readonly [string, string, string])[]> = {
|
||||
|
||||
@@ -367,3 +367,41 @@ test("Repeater renders persisted drafts with translated default group and preser
|
||||
assert.equal(useRepeaterStore.getState().workspace.tabs[0].rawRequest, "GET / HTTP/1.1\nHost: example.test\n\n");
|
||||
useRepeaterStore.setState({ workspace: null });
|
||||
});
|
||||
|
||||
test("ContainerRoutesTab localizes effective egress without mixed Chinese/English", async () => {
|
||||
const { ContainerRoutesTab } = load(base + "/src/app/(main)/system/proxy/_components/container-routes-tab.tsx");
|
||||
const routesState = {
|
||||
global_proxy: "direct",
|
||||
routes: [],
|
||||
containers: [
|
||||
{
|
||||
scope: "session",
|
||||
owner_id: "conv-6",
|
||||
container_name: "artex-sbx-session-conv-6",
|
||||
state: "running",
|
||||
ip: "172.30.0.3",
|
||||
mode: "inherit",
|
||||
effective_proxy: "direct",
|
||||
},
|
||||
{
|
||||
scope: "task",
|
||||
owner_id: "42",
|
||||
container_name: "artex-sbx-task-42",
|
||||
state: "inactive",
|
||||
mode: "inherit",
|
||||
effective_proxy: "direct (全局)",
|
||||
},
|
||||
],
|
||||
gateway: { connected: true, embedded: false, udp_policy: "block_on_proxy", dns_upstream: "" },
|
||||
};
|
||||
await i18n.changeLanguage("en");
|
||||
const enHtml = visible(render(ContainerRoutesTab, { proxyPool: [], routesState, onRefresh: async () => undefined }));
|
||||
assert.doesNotMatch(enHtml, /[\p{Script=Han}]/u, enHtml);
|
||||
assert.match(enHtml, /Effective Egress/);
|
||||
assert.match(enHtml, /Direct \(Global\)/);
|
||||
|
||||
await i18n.changeLanguage("zh-CN");
|
||||
const zhHtml = visible(render(ContainerRoutesTab, { proxyPool: [], routesState, onRefresh: async () => undefined }));
|
||||
assert.match(zhHtml, /当前生效出口/);
|
||||
assert.match(zhHtml, /直连 \(全局\)/);
|
||||
});
|
||||
@@ -168,6 +168,11 @@ export const settingsMessages = {
|
||||
"沙箱 容器 隔离 docker 镜像 内存 cpu 进程 生命周期 停机 清理",
|
||||
"sandbox container isolation docker image memory cpu pids lifecycle stop prune",
|
||||
],
|
||||
"settings.proxyMovedDesc": [
|
||||
"全局出口代理、代理池轮换、出口黑名单与拦截审计已迁移至独立的「代理与出口」管理页。",
|
||||
"Global egress proxy, proxy pool rotation, egress blacklist and block audit have moved to the dedicated Proxy & Egress page.",
|
||||
],
|
||||
"settings.openProxyPage": ["前往代理与出口", "Open Proxy & Egress"],
|
||||
"settings.trafficCapture": ["流量捕获", "Traffic capture"],
|
||||
"settings.trafficCaptureHelp": [
|
||||
"开启后,所有 Agent 的 HTTP 流量经记录代理全量落库,并向 Agent 注入 traffic_search / traffic_get 工具与代理配置(提示词含代理说明)。",
|
||||
|
||||
@@ -2,13 +2,11 @@
|
||||
|
||||
import { enUS } from "date-fns/locale/en-US";
|
||||
import { zhCN } from "date-fns/locale/zh-CN";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { resolveLocale } from "./config";
|
||||
import { useLiveTranslation } from "./use-live-translation";
|
||||
|
||||
export function useDateLocale() {
|
||||
const { i18n } = useTranslation();
|
||||
const locale = resolveLocale(i18n.resolvedLanguage);
|
||||
const { locale } = useLiveTranslation();
|
||||
return {
|
||||
locale,
|
||||
dateLocale: locale === "en" ? enUS : zhCN,
|
||||
|
||||
@@ -9,7 +9,10 @@ import { useTranslation } from "react-i18next";
|
||||
// language change; it reads the current language when each callback runs.
|
||||
export function useLiveTranslation() {
|
||||
const translation = useTranslation();
|
||||
const { i18n } = translation;
|
||||
const { t, i18n } = translation;
|
||||
const liveT = useMemo(() => i18n.t.bind(i18n), [i18n]);
|
||||
return { ...translation, liveT };
|
||||
// Read reactive `t` so React Compiler invalidates memo caches on language switches.
|
||||
const isEn = t.length >= 0 && /^en(?:-|$)/i.test(i18n.resolvedLanguage ?? i18n.language ?? "");
|
||||
const locale = isEn ? "en" : "zh-CN";
|
||||
return { ...translation, liveT, locale, isEn };
|
||||
}
|
||||
+105
-5
@@ -24,6 +24,7 @@ import type {
|
||||
Company,
|
||||
CompanyScopeMutation,
|
||||
CompanyScopeRule,
|
||||
ContainerProxyRoute,
|
||||
Conversation,
|
||||
ConvTokenSummary,
|
||||
CoverageAssetRefs,
|
||||
@@ -33,6 +34,8 @@ import type {
|
||||
DeleteTaskOptions,
|
||||
DeleteTaskResult,
|
||||
Edge,
|
||||
EgressBlacklistRule,
|
||||
EgressBlacklistState,
|
||||
EgressReport,
|
||||
EvidenceBodyPreview,
|
||||
ExplorationNodePage,
|
||||
@@ -80,9 +83,13 @@ import type {
|
||||
PromptVar,
|
||||
PromptVersion,
|
||||
ProxyPoolEntry,
|
||||
ProxyRoutesState,
|
||||
ProxySwitchLog,
|
||||
RepeaterSendRequest,
|
||||
RepeaterSendResponse,
|
||||
SandboxContainerInfo,
|
||||
SandboxGlobalStatus,
|
||||
SandboxRuntimeOverrides,
|
||||
SessionTokenUsage,
|
||||
Settings,
|
||||
Severity,
|
||||
@@ -112,15 +119,15 @@ import type {
|
||||
Tool,
|
||||
ToolStat,
|
||||
TrafficDetail,
|
||||
TrafficDNSResp,
|
||||
TrafficEvidenceRef,
|
||||
TrafficEvidenceRole,
|
||||
TrafficHost,
|
||||
TrafficNetFlow,
|
||||
TrafficNetFlowsResp,
|
||||
TrafficResp,
|
||||
UpdateCheck,
|
||||
UpdateSettings,
|
||||
SandboxContainerInfo,
|
||||
SandboxGlobalStatus,
|
||||
SandboxRuntimeOverrides,
|
||||
UsageStats,
|
||||
WorkspaceFile,
|
||||
WorkspaceListing,
|
||||
@@ -1163,6 +1170,9 @@ export const api = {
|
||||
q = "",
|
||||
opts: {
|
||||
taskId?: string;
|
||||
scope?: string;
|
||||
ownerId?: string;
|
||||
containerId?: string;
|
||||
body?: string;
|
||||
path?: string;
|
||||
status?: string;
|
||||
@@ -1175,6 +1185,9 @@ export const api = {
|
||||
get<TrafficResp>(
|
||||
`/traffic?page=${page}&size=${size}` +
|
||||
(opts.taskId ? `&task_id=${encodeURIComponent(opts.taskId)}` : "") +
|
||||
(opts.scope && opts.scope !== "all" ? `&scope=${encodeURIComponent(opts.scope)}` : "") +
|
||||
(opts.ownerId ? `&owner_id=${encodeURIComponent(opts.ownerId)}` : "") +
|
||||
(opts.containerId ? `&container_id=${encodeURIComponent(opts.containerId)}` : "") +
|
||||
(host ? `&host=${encodeURIComponent(host)}` : "") +
|
||||
(method && method !== "all" ? `&method=${encodeURIComponent(method)}` : "") +
|
||||
(q ? `&q=${encodeURIComponent(q)}` : "") +
|
||||
@@ -1818,8 +1831,7 @@ export const api = {
|
||||
rollbackUpdate: () => post<{ ok: boolean }>(`/update/rollback`),
|
||||
|
||||
// ---- Sandbox container isolation ----
|
||||
sandboxStatus: (withStats = false) =>
|
||||
get<SandboxGlobalStatus>(`/sandbox/status${withStats ? "?stats=1" : ""}`),
|
||||
sandboxStatus: (withStats = false) => get<SandboxGlobalStatus>(`/sandbox/status${withStats ? "?stats=1" : ""}`),
|
||||
updateSandboxSettings: (ov: SandboxRuntimeOverrides) => put<SandboxGlobalStatus>("/sandbox/settings", ov),
|
||||
pruneSandboxContainers: () => post<{ removed: number }>("/sandbox/prune"),
|
||||
sandboxContainer: (scope: string, ownerID: string, withStats = true) =>
|
||||
@@ -1849,4 +1861,92 @@ export const api = {
|
||||
post<SandboxContainerInfo>(`/tasks/${encodeURIComponent(taskID)}/sandbox/stop`, { pause_task: pauseTask }),
|
||||
recreateTaskSandbox: (taskID: string, opts?: { pause_task?: boolean; clear_workspace?: boolean }) =>
|
||||
post<SandboxContainerInfo>(`/tasks/${encodeURIComponent(taskID)}/sandbox/recreate`, opts ?? {}),
|
||||
|
||||
// ---- Proxy Egress Blacklist (#218) ----
|
||||
egressBlacklist: () => get<EgressBlacklistState>("/proxy/blacklist"),
|
||||
updateEgressBlacklistSettings: (syncAssetIntercept: boolean) =>
|
||||
put<EgressBlacklistState>("/proxy/blacklist/settings", { sync_asset_intercept: syncAssetIntercept }),
|
||||
createEgressBlacklistRule: (rule: {
|
||||
enabled?: boolean;
|
||||
kind: string;
|
||||
pattern: string;
|
||||
port?: number;
|
||||
note?: string;
|
||||
}) => post<EgressBlacklistRule>("/proxy/blacklist/rules", rule),
|
||||
updateEgressBlacklistRule: (
|
||||
id: string,
|
||||
patch: { enabled?: boolean; kind?: string; pattern?: string; port?: number; note?: string },
|
||||
) => put<EgressBlacklistRule>(`/proxy/blacklist/rules/${encodeURIComponent(id)}`, patch),
|
||||
deleteEgressBlacklistRule: (id: string) =>
|
||||
del<{ deleted: string }>(`/proxy/blacklist/rules/${encodeURIComponent(id)}`),
|
||||
clearEgressBlockEvents: () => del<{ cleared: boolean }>("/proxy/blacklist/events"),
|
||||
|
||||
// ---- Non-HTTP Traffic (TCP/UDP Flows & DNS Queries, #218 Phase 3/4) ----
|
||||
trafficFlows: (params?: {
|
||||
protocol?: string;
|
||||
action?: string;
|
||||
task_id?: string;
|
||||
scope?: string;
|
||||
owner_id?: string;
|
||||
container_id?: string;
|
||||
q?: string;
|
||||
page?: number;
|
||||
size?: number;
|
||||
}) => {
|
||||
const qs = new URLSearchParams();
|
||||
if (params?.protocol && params.protocol !== "all") qs.set("protocol", params.protocol);
|
||||
if (params?.action && params.action !== "all") qs.set("action", params.action);
|
||||
if (params?.task_id) qs.set("task_id", params.task_id);
|
||||
if (params?.scope) qs.set("scope", params.scope);
|
||||
if (params?.owner_id) qs.set("owner_id", params.owner_id);
|
||||
if (params?.container_id) qs.set("container_id", params.container_id);
|
||||
if (params?.q) qs.set("q", params.q);
|
||||
if (params?.page !== undefined) qs.set("page", String(params.page));
|
||||
if (params?.size !== undefined) qs.set("size", String(params.size));
|
||||
const suffix = qs.toString() ? `?${qs.toString()}` : "";
|
||||
return get<TrafficNetFlowsResp>(`/traffic/flows${suffix}`);
|
||||
},
|
||||
trafficFlowDetail: (id: string) => get<TrafficNetFlow>(`/traffic/flows/${encodeURIComponent(id)}`),
|
||||
deleteTrafficFlows: (taskId?: string) =>
|
||||
del<{ deleted: number }>(`/traffic/flows${taskId ? `?task_id=${encodeURIComponent(taskId)}` : ""}`),
|
||||
trafficDNS: (params?: {
|
||||
qtype?: string;
|
||||
rcode?: string;
|
||||
action?: string;
|
||||
task_id?: string;
|
||||
scope?: string;
|
||||
owner_id?: string;
|
||||
container_id?: string;
|
||||
q?: string;
|
||||
page?: number;
|
||||
size?: number;
|
||||
}) => {
|
||||
const qs = new URLSearchParams();
|
||||
if (params?.qtype && params.qtype !== "ALL") qs.set("qtype", params.qtype);
|
||||
if (params?.rcode && params.rcode !== "ALL") qs.set("rcode", params.rcode);
|
||||
if (params?.action && params.action !== "all") qs.set("action", params.action);
|
||||
if (params?.task_id) qs.set("task_id", params.task_id);
|
||||
if (params?.scope) qs.set("scope", params.scope);
|
||||
if (params?.owner_id) qs.set("owner_id", params.owner_id);
|
||||
if (params?.container_id) qs.set("container_id", params.container_id);
|
||||
if (params?.q) qs.set("q", params.q);
|
||||
if (params?.page !== undefined) qs.set("page", String(params.page));
|
||||
if (params?.size !== undefined) qs.set("size", String(params.size));
|
||||
const suffix = qs.toString() ? `?${qs.toString()}` : "";
|
||||
return get<TrafficDNSResp>(`/traffic/dns${suffix}`);
|
||||
},
|
||||
deleteTrafficDNS: (taskId?: string) =>
|
||||
del<{ deleted: number }>(`/traffic/dns${taskId ? `?task_id=${encodeURIComponent(taskId)}` : ""}`),
|
||||
|
||||
// ---- Per-Container Proxy Routes & Transparent Gateway (#218 Phase 3/4) ----
|
||||
proxyRoutes: () => get<ProxyRoutesState>("/proxy/routes"),
|
||||
putProxyRoute: (
|
||||
scope: string,
|
||||
ownerId: string,
|
||||
body: { mode: string; proxy_pool_id?: string; proxy_url?: string; note?: string },
|
||||
) => put<ContainerProxyRoute>(`/proxy/routes/${encodeURIComponent(scope)}/${encodeURIComponent(ownerId)}`, body),
|
||||
deleteProxyRoute: (scope: string, ownerId: string) =>
|
||||
del<{ deleted: string }>(`/proxy/routes/${encodeURIComponent(scope)}/${encodeURIComponent(ownerId)}`),
|
||||
updateGatewaySettings: (body: { udp_policy: string; dns_upstream: string }) =>
|
||||
put<{ udp_policy: string; dns_upstream: string }>("/proxy/gateway/settings", body),
|
||||
};
|
||||
@@ -961,6 +961,12 @@ export interface TrafficExchange {
|
||||
status: number;
|
||||
content_type: string;
|
||||
resp_len: number;
|
||||
sandbox_scope?: string;
|
||||
sandbox_owner_id?: string;
|
||||
container_id?: string;
|
||||
session_id?: string;
|
||||
intent_id?: number;
|
||||
src_ip?: string;
|
||||
}
|
||||
|
||||
export interface TrafficResp {
|
||||
@@ -2057,3 +2063,144 @@ export interface SandboxRuntimeOverrides {
|
||||
auto_stop_on_complete?: boolean;
|
||||
session_idle_minutes?: number;
|
||||
}
|
||||
|
||||
// ---- Proxy Egress Blacklist (#218) ----
|
||||
export interface EgressBlacklistRule {
|
||||
id: string;
|
||||
enabled: boolean;
|
||||
kind: "domain" | "suffix" | "ip" | "cidr" | string;
|
||||
pattern: string;
|
||||
port?: number;
|
||||
note?: string;
|
||||
source?: "custom" | "asset_intercept" | string;
|
||||
created_at?: string;
|
||||
updated_at?: string;
|
||||
}
|
||||
|
||||
export interface EgressBlockEvent {
|
||||
at: string;
|
||||
host: string;
|
||||
port?: string;
|
||||
method?: string;
|
||||
url?: string;
|
||||
src_ip?: string;
|
||||
scope?: string;
|
||||
owner_id?: string;
|
||||
reason: string;
|
||||
rule_kind?: string;
|
||||
rule_id?: string;
|
||||
pattern?: string;
|
||||
source?: "ssrf_guard" | "custom" | "asset_intercept" | string;
|
||||
}
|
||||
|
||||
export interface EgressBlacklistState {
|
||||
rules: EgressBlacklistRule[];
|
||||
synced_rules: EgressBlacklistRule[];
|
||||
sync_asset_intercept: boolean;
|
||||
events: EgressBlockEvent[];
|
||||
}
|
||||
|
||||
// ---- Non-HTTP Traffic (TCP/UDP/TLS Flows & DNS Queries, #218 Phase 3/4) ----
|
||||
export interface TrafficNetFlow {
|
||||
id: string;
|
||||
ts: number;
|
||||
ended_at?: number;
|
||||
duration_ms: number;
|
||||
protocol: "tcp" | "tls" | "udp" | string;
|
||||
dst_ip: string;
|
||||
dst_port: number;
|
||||
dst_host?: string;
|
||||
sni?: string;
|
||||
action: "allow" | "block" | "error" | "passthrough" | string;
|
||||
block_reason?: string;
|
||||
upstream_proxy?: string;
|
||||
bytes_tx: number;
|
||||
bytes_rx: number;
|
||||
tx_preview_text?: string;
|
||||
tx_preview_hex?: string;
|
||||
tx_binary?: boolean;
|
||||
rx_preview_text?: string;
|
||||
rx_preview_hex?: string;
|
||||
rx_binary?: boolean;
|
||||
sandbox_scope?: string;
|
||||
sandbox_owner_id?: string;
|
||||
container_id?: string;
|
||||
session_id?: string;
|
||||
intent_id?: number;
|
||||
src_ip?: string;
|
||||
src_port?: number;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface TrafficNetFlowsResp {
|
||||
enabled: boolean;
|
||||
count: number;
|
||||
total: number;
|
||||
page: number;
|
||||
size: number;
|
||||
flows: TrafficNetFlow[];
|
||||
}
|
||||
|
||||
export interface TrafficDNSQuery {
|
||||
id: string;
|
||||
ts: number;
|
||||
duration_ms: number;
|
||||
qname: string;
|
||||
qtype: string;
|
||||
rcode: string;
|
||||
answers: string[];
|
||||
action: "allow" | "block" | "error" | string;
|
||||
block_reason?: string;
|
||||
upstream?: string;
|
||||
sandbox_scope?: string;
|
||||
sandbox_owner_id?: string;
|
||||
container_id?: string;
|
||||
session_id?: string;
|
||||
intent_id?: number;
|
||||
src_ip?: string;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface TrafficDNSResp {
|
||||
enabled: boolean;
|
||||
count: number;
|
||||
total: number;
|
||||
page: number;
|
||||
size: number;
|
||||
queries: TrafficDNSQuery[];
|
||||
}
|
||||
|
||||
// ---- Per-Container Proxy Routes & Transparent Gateway (#218 Phase 3/4) ----
|
||||
export interface ContainerProxyRoute {
|
||||
scope: "task" | "session" | string;
|
||||
owner_id: string;
|
||||
mode: "inherit" | "direct" | "proxy" | string;
|
||||
proxy_pool_id?: string;
|
||||
proxy_url?: string;
|
||||
note?: string;
|
||||
updated_at?: string;
|
||||
}
|
||||
|
||||
export interface ContainerRouteStatusItem extends ContainerProxyRoute {
|
||||
container_name?: string;
|
||||
container_id?: string;
|
||||
state?: string;
|
||||
ip?: string;
|
||||
effective_proxy: string;
|
||||
}
|
||||
|
||||
export interface TransparentGatewayStatus {
|
||||
connected: boolean;
|
||||
embedded: boolean;
|
||||
gateway_id?: string;
|
||||
last_seen?: string;
|
||||
udp_policy: "block_on_proxy" | "block" | "direct" | string;
|
||||
dns_upstream?: string;
|
||||
}
|
||||
|
||||
export interface ProxyRoutesState {
|
||||
global_proxy: string;
|
||||
routes: ContainerProxyRoute[];
|
||||
containers: ContainerRouteStatusItem[];
|
||||
gateway: TransparentGatewayStatus;
|
||||
}
|
||||
@@ -97,6 +97,7 @@ export const sidebarItems: NavGroup[] = [
|
||||
{ id: "asset-intercept", title: "资产拦截", url: "/system/intercept/assets", icon: Ban },
|
||||
{ id: "approvals", title: "审批记录", url: "/system/intercept/approvals", icon: ClipboardList },
|
||||
{ id: "sandbox", title: "沙箱容器", url: "/system/sandbox", icon: Box },
|
||||
{ id: "proxy", title: "代理与出口", url: "/system/proxy", icon: Radio },
|
||||
{ id: "logs", title: "日志", url: "/system/logs", icon: ScrollText },
|
||||
{ id: "settings", title: "系统配置", url: "/system/settings", icon: Settings2 },
|
||||
],
|
||||
|
||||
Reference in new issue
Block a user