From 0398e6fe28caed6cd217c8ee37370931f37efddd Mon Sep 17 00:00:00 2001 From: Zeusina Date: Sun, 11 Oct 2026 21:48:06 +0300 Subject: [PATCH] fix(managed): guard dropped-UID queue ownership inspection Require effective SYS_PTRACE only for native owned workers and distinguish denied FD inspection from foreign queue ownership. Keep inode proof authoritative and constrain deployment to its private PID namespace. Co-authored-by: GPT-6 --- cmd/zapret-autotune/managed_asset_runtime.go | 40 +++++++--- .../managed_asset_runtime_test.go | 75 +++++++++++++++++++ deploy/managed-target/README.md | 12 ++- deploy/managed-target/check_static.py | 3 +- deploy/managed-target/compose.yaml | 5 +- 5 files changed, 120 insertions(+), 15 deletions(-) diff --git a/cmd/zapret-autotune/managed_asset_runtime.go b/cmd/zapret-autotune/managed_asset_runtime.go index 621c247..ac4da26 100644 --- a/cmd/zapret-autotune/managed_asset_runtime.go +++ b/cmd/zapret-autotune/managed_asset_runtime.go @@ -50,15 +50,7 @@ func newManagedAssetRuntime(target managedDeps) managedAssetRuntime { if err != nil { return err } - for _, line := range strings.Split(string(status), "\n") { - if strings.HasPrefix(line, "CapEff:") { - bits, err := strconv.ParseUint(strings.TrimSpace(strings.TrimPrefix(line, "CapEff:")), 16, 64) - if err == nil && bits&(1<<5) != 0 && bits&(1<<12) != 0 { - return nil - } - } - } - return errors.New("asset verifier requires CAP_KILL and CAP_NET_ADMIN") + return managedAssetCapabilityGuard(string(status)) } r.nft = func(ctx context.Context, input string) (string, error) { cmd := exec.CommandContext(ctx, "nft", "-f", "-") @@ -89,6 +81,19 @@ func newManagedAssetRuntime(target managedDeps) managedAssetRuntime { return r } +func managedAssetCapabilityGuard(status string) error { + const required = 1<<5 | 1<<12 | 1<<19 // KILL, NET_ADMIN, SYS_PTRACE + for _, line := range strings.Split(status, "\n") { + if strings.HasPrefix(line, "CapEff:") { + bits, err := strconv.ParseUint(strings.TrimSpace(strings.TrimPrefix(line, "CapEff:")), 16, 64) + if err == nil && bits&required == required { + return nil + } + } + } + return errors.New("asset verifier requires CAP_KILL, CAP_NET_ADMIN and CAP_SYS_PTRACE") +} + // Queue peer portid is a netlink socket id, not necessarily a process id. func managedAssetQueueReady(pid int) (bool, error) { queues, err := os.ReadFile("/proc/net/netfilter/nfnetlink_queue") @@ -125,15 +130,28 @@ func managedAssetQueueReady(pid int) (bool, error) { inodes["socket:["+f[9]+"]"] = true } } - fds, err := os.ReadDir(fmt.Sprintf("/proc/%d/fd", pid)) + return managedAssetQueueFDReady(fmt.Sprintf("/proc/%d/fd", pid), inodes, os.Readlink) +} + +func managedAssetQueueFDReady(dir string, inodes map[string]bool, readlink func(string) (string, error)) (bool, error) { + fds, err := os.ReadDir(dir) if err != nil { return false, err } + denied := false for _, fd := range fds { - link, err := os.Readlink(fmt.Sprintf("/proc/%d/fd/%s", pid, fd.Name())) + link, err := readlink(dir + "/" + fd.Name()) if err == nil && inodes[link] { return true, nil } + if errors.Is(err, os.ErrPermission) { + denied = true + } else if err != nil && !errors.Is(err, os.ErrNotExist) { + return false, err + } + } + if denied { + return false, errors.New("asset queue ownership inspection denied") } return false, errors.New("asset queue belongs to another process") } diff --git a/cmd/zapret-autotune/managed_asset_runtime_test.go b/cmd/zapret-autotune/managed_asset_runtime_test.go index 6148c8e..672d134 100644 --- a/cmd/zapret-autotune/managed_asset_runtime_test.go +++ b/cmd/zapret-autotune/managed_asset_runtime_test.go @@ -71,6 +71,81 @@ func assetRuntimeFixture(t *testing.T) (managedAssetRuntime, *[]string, chan err return r, &events, done } +func TestManagedAssetTargetQueueOwnershipCapability(t *testing.T) { + // nfqws drops UID and becomes nondumpable. The queue ownership check must + // still be able to read its socket symlinks, without sharing host processes. + raw, err := os.ReadFile("../../deploy/managed-target/compose.yaml") + if err != nil { + t.Fatal(err) + } + manifest := string(raw) + _, capabilities, ok := strings.Cut(manifest, "cap_add: [") + if !ok { + t.Fatal("target capabilities missing") + } + capabilities, _, ok = strings.Cut(capabilities, "]") + if !ok || !strings.Contains(","+strings.ReplaceAll(capabilities, " ", "")+",", ",SYS_PTRACE,") { + t.Fatal("queue socket ownership requires SYS_PTRACE for dropped-UID workers") + } + if !strings.Contains(manifest, "privileged: false") || strings.Contains(manifest, "pid:") { + t.Fatal("queue inspection must remain confined to an unprivileged private PID namespace") + } +} + +func TestManagedAssetCapabilityGuard(t *testing.T) { + const required uint64 = 1<<5 | 1<<12 | 1<<19 + for _, bits := range []uint64{required, required | 1<<13, required &^ (1 << 5), required &^ (1 << 12), required &^ (1 << 19), 0} { + err := managedAssetCapabilityGuard("CapEff:\t" + strconv.FormatUint(bits, 16) + "\n") + if (err == nil) != (bits&required == required) { + t.Fatalf("capabilities %x: %v", bits, err) + } + } + for _, status := range []string{"", "CapEff: invalid", "CapPrm: 81020"} { + if err := managedAssetCapabilityGuard(status); err == nil { + t.Fatalf("accepted %q", status) + } + } +} + +func TestManagedAssetQueueFDReady(t *testing.T) { + dir := t.TempDir() + for _, fd := range []string{"1", "2"} { + if err := os.WriteFile(filepath.Join(dir, fd), nil, 0600); err != nil { + t.Fatal(err) + } + } + ioErr := errors.New("proc read failure") + for _, tc := range []struct { + name string + firstErr error + secondLink string + wantReady bool + wantErr string + }{ + {"foreign", nil, "socket:[other]", false, "asset queue belongs to another process"}, + {"denied", os.ErrPermission, "socket:[other]", false, "asset queue ownership inspection denied"}, + {"missing transient", os.ErrNotExist, "socket:[owned]", true, ""}, + {"match despite denial", os.ErrPermission, "socket:[owned]", true, ""}, + {"missing foreign", os.ErrNotExist, "socket:[other]", false, "asset queue belongs to another process"}, + {"read failure", ioErr, "socket:[other]", false, ioErr.Error()}, + } { + t.Run(tc.name, func(t *testing.T) { + ready, err := managedAssetQueueFDReady(dir, map[string]bool{"socket:[owned]": true}, func(path string) (string, error) { + if filepath.Base(path) == "1" { + return "socket:[other]", tc.firstErr + } + return tc.secondLink, nil + }) + if ready != tc.wantReady || (err == nil) != (tc.wantErr == "") || err != nil && err.Error() != tc.wantErr { + t.Fatalf("ready=%v err=%v", ready, err) + } + }) + } + if _, err := managedAssetQueueFDReady(filepath.Join(dir, "absent"), nil, os.Readlink); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("directory error lost: %v", err) + } +} + func TestManagedAssetRuntimeOwnedCollector(t *testing.T) { d, front, _ := recoveryFixture(t, true) if err := d.transaction.Apply(d.db, []int64{front}); err != nil { diff --git a/deploy/managed-target/README.md b/deploy/managed-target/README.md index 61a25f7..88bc9e6 100644 --- a/deploy/managed-target/README.md +++ b/deploy/managed-target/README.md @@ -113,10 +113,20 @@ password before starting child processes. The dedicated bridge is not shared with existing services. No host networking, Docker socket, existing mounts, host Lua/fakes or privileged mode; all -capabilities are dropped except `NET_ADMIN`, `NET_RAW`, `SETUID`, `SETGID`, `KILL`. +capabilities are dropped except `NET_ADMIN`, `NET_RAW`, `SETUID`, `SETGID`, `KILL`, +`SYS_PTRACE`. `NET_ADMIN` covers nft/NFQUEUE; `NET_RAW` covers nfqws2 raw sends. Zapret2's `nfqws2 --user=tpws` needs `SETUID`/`SETGID` for UID/GID switching. `KILL` allows bounded cleanup of workers that have dropped their UID. +`SYS_PTRACE` permits inspecting socket FD symlinks of privilege-dropped, +nondumpable nfqws workers to prove NFQUEUE ownership by inode. The native owned +worker path fails fast without effective `KILL`, `NET_ADMIN` and `SYS_PTRACE`; +legacy modes do not gain this requirement. Permission denial is an inspection +failure, not evidence that another process owns the queue. +This capability is confined to the target's **private PID namespace**: never +use host or shared/container PID namespaces. It does not grant inspection of +broader host processes. The full service/adaptive hardware gate remains +**pending**, not PASS; this ownership fix alone does not qualify it. Startup order: ss-server/ss-local → listener 1080 → guarded managed init on fresh state → `managed reconcile` on every startup → target-local `zapret2 start` diff --git a/deploy/managed-target/check_static.py b/deploy/managed-target/check_static.py index 4f842af..fd17cc9 100644 --- a/deploy/managed-target/check_static.py +++ b/deploy/managed-target/check_static.py @@ -13,7 +13,8 @@ readme = (directory / "README.md").read_text() assert " privileged: false\n" in compose assert " image: ${ZAPRET_AUTOTUNE_IMAGE:-zapret-autotune-managed-target:local}\n" in compose assert " cap_drop: [ALL]\n" in compose -assert " cap_add: [NET_ADMIN, NET_RAW, SETUID, SETGID, KILL]\n" in compose +assert " cap_add: [NET_ADMIN, NET_RAW, SETUID, SETGID, KILL, SYS_PTRACE]\n" in compose +assert "pid:" not in compose # Keep inspection confined to the private PID namespace. assert compose.count(" - type: bind\n") == 1 assert " source: ./target-state\n" in compose assert " target: /var/lib/zapret-autotune/target\n" in compose diff --git a/deploy/managed-target/compose.yaml b/deploy/managed-target/compose.yaml index 2089231..948d565 100644 --- a/deploy/managed-target/compose.yaml +++ b/deploy/managed-target/compose.yaml @@ -7,8 +7,9 @@ services: dockerfile: Dockerfile.target privileged: false cap_drop: [ALL] - # nft/NFQUEUE, raw sends, UID/GID switching, cleanup of dropped-UID workers. - cap_add: [NET_ADMIN, NET_RAW, SETUID, SETGID, KILL] + # SYS_PTRACE permits /proc//fd ownership checks after nfqws drops UID. + # Confined to this target's private PID namespace; never share host processes. + cap_add: [NET_ADMIN, NET_RAW, SETUID, SETGID, KILL, SYS_PTRACE] environment: SS_PASSWORD: ${SS_PASSWORD:?Set SS_PASSWORD in the deployment environment} SS_DNS_SERVER: ${SS_DNS_SERVER-}