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

164 lines
4.7 KiB
Go

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
}