mirror of
https://github.com/RuoJi6/ARTEX.git
synced 2026-12-03 04:11:51 +08:00
- Add standalone edition (`Dockerfile.standalone`, `docker-compose.standalone.yml`) alongside sandbox edition and publish both in `.github/workflows/release.yml`. - Implement `scripts/deploy-lib.sh`, `install.sh`, `update.sh`, and `scripts/artex-sandbox-firewall.sh --cleanup` with edition detection, legacy standalone -> sandbox migration (symlink-safe workspace permissions), automatic snapshots with pinned `artex-rollback/*` images + PG dump, auto/manual cross-edition rollback, and post-rollback upstream unpinning. - Update `ensureWritableDir` in `internal/sandbox/manager.go` to safely migrate nested root-owned workspace files without following symlinks. - Expose `deploy_edition` in `/api/update/check` and update `UpdateCard` UI/i18n warnings for sandbox vs standalone in-app update/rollback. - Reconcile `artex-gateway` TUN policy routing (`priority 218`, `raw PREROUTING`, `nat POSTROUTING`, `DOCKER-USER`) every 15s to self-heal after host network rule flushes or bridge changes. - Add unit and shell tests (`scripts/deploy_test.sh`, `cmd/artex-gateway/tun_linux_test.go`, `internal/sandbox/sandbox_test.go`, `server/update_test.go`) and update `README.md` / `.env.example`.
316 lines
8.4 KiB
Go
316 lines
8.4 KiB
Go
// 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 {
|
|
iptCfg = iptablesConfig{
|
|
Subnet: subnet,
|
|
GatewayIP: gatewayIP,
|
|
TCPPort: tcpPort,
|
|
UDPPort: udpPort,
|
|
DNSPort: dnsPort,
|
|
ProxyPort: proxyPort,
|
|
AdminPort: adminPort,
|
|
}
|
|
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.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)
|
|
routeTicker := time.NewTicker(15 * time.Second)
|
|
defer policyTicker.Stop()
|
|
defer flushTicker.Stop()
|
|
defer routeTicker.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()
|
|
case <-routeTicker.C:
|
|
if applyRules && tunModeActive {
|
|
if reconcileTunRouting(&iptCfg) {
|
|
iptablesApplied = true
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|