Files
ARTEX-chixuweihu/traffic/egress_blacklist.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

394 lines
10 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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 "", ""
}