Fix desktop TUN address leak that broke VPN rebuilds

sing-tun creates its utun control socket without SOCK_CLOEXEC
(tun_darwin.go), so any child the unified helper spawns while the
engine runs - the DnsGuard scutil process, route commands - inherits
that socket and pins the utun interface past engine stop. The
announcement-driven rebuild then fails with "desktop TUN address
already in use" and tears down the whole VPN session.

Mark every utun socket in the process close-on-exec as soon as the
engine starts. Stop now only warns when Darwin still holds the
retiring address (classified via cleanupFailure), and Start waits
bounded for an address this engine itself retained while failing fast
on any other owner.

Adds a root-only drain diagnostic with a real-profile pass, a
child-guard regression test that reproduced the production failure
before the fix, and a --self-test-unified-rebuild helper self-test
that forces stop/start cycles in combined mode end to end.

Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
shenlei
2026-10-15 13:47:52 +09:00
co-authored by Claude Code
parent 50cfbb6867
commit 5b7523fc4f
8 changed files with 698 additions and 12 deletions
+74 -10
View File
@@ -13,6 +13,7 @@ import (
"os"
"path/filepath"
"runtime"
"strconv"
"sync"
"time"
@@ -26,6 +27,7 @@ import (
"github.com/sagernet/sing-box/dns/transport"
"github.com/sagernet/sing-box/dns/transport/fakeip"
"github.com/sagernet/sing-box/dns/transport/local"
"github.com/sagernet/sing-box/log"
"github.com/sagernet/sing-box/option"
"github.com/sagernet/sing-box/protocol/direct"
"github.com/sagernet/sing-box/protocol/http"
@@ -35,6 +37,7 @@ import (
"github.com/sagernet/sing-box/protocol/vless"
"github.com/sagernet/sing-box/protocol/vmess"
sjson "github.com/sagernet/sing/common/json"
"golang.org/x/sys/unix"
)
func registryContext(ctx context.Context) context.Context {
@@ -79,6 +82,8 @@ type Engine struct {
cancel context.CancelFunc
ctx context.Context
desktopTun bool
// Set when Stop returned while Darwin still held the retiring utun address.
tunRetained bool
}
func (e *Engine) Snapshot() Snapshot {
@@ -107,12 +112,8 @@ func (e *Engine) Start(parent context.Context, config Config) error {
return errors.New("desktop TUN requires macOS privileged helper")
}
if config.DesktopTun {
attached, err := desktopTunAddressAttached()
if err != nil {
return errors.New("cannot inspect desktop TUN address")
}
if attached {
return errors.New("desktop TUN address already in use")
if err := e.awaitDesktopTunAddress(desktopTunRetainedWait); err != nil {
return err
}
}
data, err := config.managedJSON()
@@ -171,10 +172,44 @@ func (e *Engine) Start(parent context.Context, config Config) error {
e.state = "Failed"
return startupFailure("start_engine", err)
}
if config.DesktopTun {
markDesktopTunCloseOnExec()
}
e.box, e.cancel, e.ctx, e.state = instance, cancel, ctx, "Running"
return nil
}
// sing-tun creates its utun control socket without SOCK_CLOEXEC (tun_darwin).
// Any process the host spawns while the engine runs — the unified helper's
// scutil DNS guard or route commands — inherits that socket and pins the utun
// interface past engine stop, so announcement-driven rebuilds cannot reattach
// the desktop address. Mark every utun socket in this process close-on-exec
// as soon as the engine owns it.
func markDesktopTunCloseOnExec() {
if runtime.GOOS != "darwin" {
return
}
directory, err := os.Open("/dev/fd")
if err != nil {
return
}
defer directory.Close()
entries, err := directory.Readdirnames(-1)
if err != nil {
return
}
for _, entry := range entries {
fd, err := strconv.Atoi(entry)
if err != nil || fd <= 2 {
continue
}
if _, err := unix.GetsockoptString(fd,
2 /* SYSPROTO_CONTROL */, 2 /* UTUN_OPT_IFNAME */); err == nil {
unix.CloseOnExec(fd)
}
}
}
func (e *Engine) Stop() error {
e.mu.Lock()
defer e.mu.Unlock()
@@ -194,14 +229,17 @@ func (e *Engine) Stop() error {
for {
attached, inspectErr := desktopTunAddressAttached()
if inspectErr != nil {
err = inspectErr
err = fmt.Errorf("%w: %v", errTunAddressInspect, inspectErr)
break
}
if !attached {
break
}
if time.Now().After(deadline) {
err = errors.New("desktop TUN address did not detach")
// The engine is already closed, so a retained address only delays reusing
// 172.19.0.1; the next Start waits for it. Warn instead of failing the stop.
e.tunRetained = true
e.runtimeLogs.WriteMessage(log.LevelWarn, "desktop TUN address still retained after stop")
break
}
time.Sleep(20 * time.Millisecond)
@@ -212,13 +250,39 @@ func (e *Engine) Stop() error {
if e.selfTestTrace {
fmt.Fprintf(os.Stderr, "self-test cleanup cause: %v\n", err)
}
return errors.New("proxy engine cleanup failed")
return cleanupFailure(err)
}
e.state = "Stopped"
return nil
}
func desktopTunAddressAttached() (bool, error) {
// Announcement-driven rebuilds stop and start immediately. If the address
// belongs to this engine's own retiring utun, wait for the kernel to drain it;
// any other owner still fails fast.
func (e *Engine) awaitDesktopTunAddress(wait time.Duration) error {
deadline := time.Now().Add(wait)
for {
attached, err := desktopTunAddressAttached()
if err != nil {
return errors.New("cannot inspect desktop TUN address")
}
if !attached {
e.tunRetained = false
return nil
}
if !e.tunRetained || time.Now().After(deadline) {
return errors.New("desktop TUN address already in use")
}
time.Sleep(50 * time.Millisecond)
}
}
// Bounded so a utun that never drains still surfaces as a startup failure
// well inside the helper's 30s reply and 60s watchdog limits.
const desktopTunRetainedWait = 10 * time.Second
// Variable so lifecycle tests can simulate Darwin's delayed address release.
var desktopTunAddressAttached = func() (bool, error) {
addresses, err := net.InterfaceAddrs()
if err != nil {
return false, err