Files
ARTEX-chixuweihu/cmd/artex-gateway/tun_linux.go
T
ji ruo 07309e4530 feat(deploy,gateway): add dual-edition deployment/migration/rollback and TUN route reconciliation
- 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`.
2026-12-02 13:31:05 +08:00

300 lines
13 KiB
Go

//go:build linux
package main
import (
"fmt"
"io"
"log"
"os"
"os/exec"
"strconv"
"strings"
"time"
"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
}
// rawPreroutingTopAcceptsTun reports whether the first rule in raw PREROUTING
// (immediately after the chain policy) accepts inbound artex-tun0 packets for subnet.
func rawPreroutingTopAcceptsTun(rawRules, tunDev, subnet string) bool {
for _, line := range strings.Split(rawRules, "\n") {
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "-P ") || strings.HasPrefix(line, "#") {
continue
}
return strings.HasPrefix(line, "-A PREROUTING ") &&
strings.Contains(line, "-i "+tunDev+" ") &&
strings.Contains(line, "-d "+subnet+" ") &&
strings.HasSuffix(line, "-j ACCEPT")
}
return false
}
// reconcileTunRouting verifies policy routing and critical anti-drop iptables
// rules stay intact while the gateway is running (guarding against systemd-networkd
// / netplan rule flushes or Docker inserting raw PREROUTING DROP rules above us).
// Returns true when routing is active for cfg.BridgeName.
func reconcileTunRouting(cfg *iptablesConfig) bool {
if cfg == nil {
return false
}
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"
}
if curBr, err := discoverSandboxBridge(subnet, gwIP, 2*time.Second); err == nil && curBr != "" && curBr != cfg.BridgeName {
log.Printf("[gateway] sandbox bridge changed %q -> %q; reapplying TUN routing", cfg.BridgeName, curBr)
if cfg.BridgeName != "" {
cleanupTunRouting(*cfg)
}
cfg.BridgeName = curBr
if err := applyTunRouting(*cfg); err != nil {
log.Printf("[gateway] warn: reapply TUN routing failed: %v", err)
return false
}
return true
}
br := cfg.BridgeName
if br == "" {
return false
}
// 1. Ensure policy rule priority 218 and route table 218 still exist.
ruleOut, _ := exec.Command("ip", "rule", "show", "priority", tunRulePrio).Output()
if !strings.Contains(string(ruleOut), "iif "+br) || !strings.Contains(string(ruleOut), "lookup "+tunRouteTable) {
_ = runCmd("ip", "link", "set", "dev", tunDeviceName, "mtu", "1500", "up")
_ = 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)
_ = runCmd("ip", "route", "replace", subnet, "dev", br, "table", tunRouteTable)
_ = runCmd("ip", "route", "replace", "default", "dev", tunDeviceName, "table", tunRouteTable)
runCmdIgnoreErr("ip", "rule", "del", "iif", br, "lookup", tunRouteTable, "priority", tunRulePrio)
if err := runCmd("ip", "rule", "add", "iif", br, "lookup", tunRouteTable, "priority", tunRulePrio); err != nil {
log.Printf("[gateway] warn: restore ip rule %s failed: %v", tunRulePrio, err)
} else {
log.Printf("[gateway] restored missing policy routing rule priority=%s bridge=%s", tunRulePrio, br)
}
}
// 2. Ensure raw PREROUTING top rule still accepts artex-tun0 -> subnet replies.
rawOut, err := exec.Command("iptables", "-t", "raw", "-S", "PREROUTING").Output()
if err == nil && !rawPreroutingTopAcceptsTun(string(rawOut), tunDeviceName, subnet) {
runCmdIgnoreErr("iptables", "-t", "raw", "-D", "PREROUTING", "-i", tunDeviceName, "-d", subnet, "-j", "ACCEPT")
if err := runCmd("iptables", "-t", "raw", "-I", "PREROUTING", "1", "-i", tunDeviceName, "-d", subnet, "-j", "ACCEPT"); err != nil {
log.Printf("[gateway] warn: restore raw PREROUTING rule failed: %v", err)
} else {
log.Printf("[gateway] restored raw PREROUTING top ACCEPT for %s -> %s", tunDeviceName, subnet)
}
}
// 3. Ensure nat POSTROUTING exemption and DOCKER-USER reply accept exist.
if exec.Command("iptables", "-t", "nat", "-C", "POSTROUTING", "-o", tunDeviceName, "-j", "ACCEPT").Run() != nil {
_ = runCmd("iptables", "-t", "nat", "-I", "POSTROUTING", "1", "-o", tunDeviceName, "-j", "ACCEPT")
}
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")
}
return true
}
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)
}