mirror of
https://github.com/RuoJi6/ARTEX.git
synced 2026-12-02 20:01:51 +08:00
- 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.
411 lines
11 KiB
Go
411 lines
11 KiB
Go
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)
|
|
}
|