diff --git a/service/firewall/interception/nfq/nfq.go b/service/firewall/interception/nfq/nfq.go index 397d18570..ddead1013 100644 --- a/service/firewall/interception/nfq/nfq.go +++ b/service/firewall/interception/nfq/nfq.go @@ -201,7 +201,14 @@ func (q *Queue) packetHandler(ctx context.Context) func(nfqueue.Attribute) int { case <-ctx.Done(): return 0 case <-time.After(time.Second): - log.Warningf("nfqueue: failed to queue packet (%s since it was handed over by the kernel)", time.Since(pkt.Info().SeenAt)) + // The packet did not make it into the handler queue, so no handler + // will ever see it and set a verdict. Drop it now instead of letting + // it wait in the kernel queue until the verdict timeout. + log.Warningf("nfqueue: failed to queue packet %s (%s since it was handed over by the kernel), dropping", pkt.ID(), time.Since(pkt.Info().SeenAt)) + if err := pkt.Drop(); err != nil { + log.Warningf("nfqueue: failed to drop unqueued packet %s: %s", pkt.ID(), err) + } + return 0 } go func() { diff --git a/service/firewall/interception/nfq/packet.go b/service/firewall/interception/nfq/packet.go index f7e77bb21..f6e99d21b 100644 --- a/service/firewall/interception/nfq/packet.go +++ b/service/firewall/interception/nfq/packet.go @@ -56,6 +56,9 @@ func markToString(mark int) string { return "unknown" } +// errVerdictAlreadySet is returned when a verdict was already applied to the packet. +var errVerdictAlreadySet = errors.New("verdict already set") + // packet implements the packet.Packet interface. type packet struct { pmpacket.Base @@ -74,6 +77,12 @@ func (pkt *packet) LoadPacketData() error { return nil } +// VerdictSet returns whether a verdict was already applied (or is being +// applied) to the packet, e.g. the default-drop after the verdict timeout. +func (pkt *packet) VerdictSet() bool { + return pkt.verdictPending.IsSet() +} + // TODO(ppacher): revisit the following behavior: // // The legacy implementation of nfqueue (and the interception) module @@ -90,7 +99,7 @@ func (pkt *packet) mark(mark int) (err error) { return pkt.setMark(mark) } - return errors.New("verdict already set") + return errVerdictAlreadySet } func (pkt *packet) setMark(mark int) error { diff --git a/service/firewall/interception/windowskext/packet.go b/service/firewall/interception/windowskext/packet.go index 4b8ead53a..5fdba4508 100644 --- a/service/firewall/interception/windowskext/packet.go +++ b/service/firewall/interception/windowskext/packet.go @@ -36,6 +36,11 @@ func (pkt *Packet) InfoOnly() bool { return pkt.verdictRequest.flags&VerdictRequestFlagSocketAuth > 0 } +// VerdictSet returns whether a verdict was already applied to the packet. +func (pkt *Packet) VerdictSet() bool { + return pkt.verdictSet.IsSet() +} + // ExpectInfo returns whether the next packet is expected to be informational only. func (pkt *Packet) ExpectInfo() bool { return pkt.verdictRequest.flags&VerdictRequestFlagExpectSocketAuth > 0 diff --git a/service/firewall/interception/windowskext2/packet.go b/service/firewall/interception/windowskext2/packet.go index fcba82f69..23c29edf5 100644 --- a/service/firewall/interception/windowskext2/packet.go +++ b/service/firewall/interception/windowskext2/packet.go @@ -39,6 +39,11 @@ func (pkt *Packet) InfoOnly() bool { return false } +// VerdictSet returns whether a verdict was already applied to the packet. +func (pkt *Packet) VerdictSet() bool { + return pkt.verdictSet.IsSet() +} + // ExpectInfo returns whether the next packet is expected to be informational only. func (pkt *Packet) ExpectInfo() bool { return false diff --git a/service/firewall/packet_handler.go b/service/firewall/packet_handler.go index 17ce79b97..15acb8962 100644 --- a/service/firewall/packet_handler.go +++ b/service/firewall/packet_handler.go @@ -201,6 +201,14 @@ func SetExternalVerdictHandler(fn ExtVerdictHandlerFunc) error { } func handlePacket(pkt packet.Packet) { + // A packet that already received a verdict - e.g. the default-drop after + // the verdict timeout while it waited in the queue - cannot be influenced + // anymore. Do not allocate a connection and a handler worker for it, so + // that a backlog drains instead of growing. + if pkt.VerdictSet() { + return + } + // First, check for an existing connection. conn, ok := network.GetConnection(pkt.GetConnectionID()) if ok { diff --git a/service/network/connection_handler.go b/service/network/connection_handler.go index c98639512..d56b059d6 100644 --- a/service/network/connection_handler.go +++ b/service/network/connection_handler.go @@ -202,6 +202,12 @@ func (conn *Connection) packetHandlerWorker(ctx *mgr.WorkerCtx) error { } func packetHandlerHandleConn(ctx context.Context, conn *Connection, pkt packet.Packet) { + // Skip packets that already received a verdict while waiting in the queue. + // Handling them cannot change anything and would only delay fresh packets. + if pkt.VerdictSet() { + return + } + conn.Lock() defer conn.Unlock() diff --git a/service/network/packet/packet.go b/service/network/packet/packet.go index 57bf1eb2d..973d95c51 100644 --- a/service/network/packet/packet.go +++ b/service/network/packet/packet.go @@ -25,6 +25,13 @@ func (pkt *Base) FastTrackedByIntegration() bool { return false } +// VerdictSet returns whether a verdict was already applied to the packet, so +// that no further verdict can take effect. Packet types that cannot tell +// report false, meaning the packet is treated as still pending. +func (pkt *Base) VerdictSet() bool { + return false +} + // InfoOnly returns whether the packet is informational only and does not // represent an actual packet. func (pkt *Base) InfoOnly() bool { @@ -235,6 +242,7 @@ type Packet interface { FastTrackedByIntegration() bool InfoOnly() bool ExpectInfo() bool + VerdictSet() bool // Info. SetCtx(ctx context.Context) diff --git a/service/network/proc/findpid.go b/service/network/proc/findpid.go index 13cf0aa4a..8330a5494 100644 --- a/service/network/proc/findpid.go +++ b/service/network/proc/findpid.go @@ -46,15 +46,34 @@ func findPID(uid, inode int) (pid int) { return socket.UndefinedProcessID } - // Look through the PIDs in reverse order, because higher/newer PIDs will be more likely to - // be searched for. - for j := len(pids) - 1; j >= 0; j-- { - if pidHasSocket(pids[j], socketName) { - return pids[j] - } + // The cache and the single-flight below only help when the same socket is + // looked up again and again. That happens when one socket carries many + // connections, e.g. a torrent client talking to hundreds of peers through + // one UDP socket, or a server accepting connections on its listening + // socket. Every new connection of such a socket needs the owner, and the + // socket table forgets the PID on every refresh. A socket with a single + // connection is looked up once and simply scans. + + // Reuse the owner found by an earlier scan, if it is still running. + if pid, ok := getCachedSocketOwner(uid, inode, pids); ok { + return pid } - return socket.UndefinedProcessID + // Run at most one scan per socket at a time. If another lookup is already + // scanning for this socket, wait for its result instead of walking /proc + // again. A failed scan is shared too; the caller retries anyway. + result, _, _ := socketScans.Do(socketName, func() (any, error) { + // Look through the PIDs in reverse order, because higher/newer PIDs will be more likely to + // be searched for. + for j := len(pids) - 1; j >= 0; j-- { + if pidHasSocket(pids[j], socketName) { + cacheSocketOwner(uid, inode, pids[j]) + return pids[j], nil + } + } + return socket.UndefinedProcessID, nil + }) + return result.(int) //nolint:forcetypeassert // Can only be an int. } func pidHasSocket(pid int, socketName string) bool { diff --git a/service/network/proc/findpid_test.go b/service/network/proc/findpid_test.go new file mode 100644 index 000000000..472ab7951 --- /dev/null +++ b/service/network/proc/findpid_test.go @@ -0,0 +1,68 @@ +//go:build linux + +package proc + +import ( + "net" + "os" + "sync" + "syscall" + "testing" +) + +// TestFindPIDSharedSocket looks up the owner of a socket held by the test +// process itself, from many goroutines at once. This exercises the real /proc +// walk, the single-flight scan and the owner cache end to end. +func TestFindPIDSharedSocket(t *testing.T) { //nolint:paralleltest // Uses the package-level cache. + resetSocketOwners() + + // Open a UDP socket owned by this process and get its inode. + conn, err := net.ListenUDP("udp4", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1)}) + if err != nil { + t.Fatalf("failed to open udp socket: %s", err) + } + defer func() { _ = conn.Close() }() + + file, err := conn.File() + if err != nil { + t.Fatalf("failed to get socket file: %s", err) + } + defer func() { _ = file.Close() }() + + var stat syscall.Stat_t + if err := syscall.Fstat(int(file.Fd()), &stat); err != nil { + t.Fatalf("failed to stat socket: %s", err) + } + uid := os.Getuid() + inode := int(stat.Ino) //nolint:gosec // Inode numbers fit into an int. + want := os.Getpid() + + // Look the socket up from many goroutines at the same time, like a burst + // of new connections on one socket does. + const lookups = 32 + results := make([]int, lookups) + var wg sync.WaitGroup + for i := range lookups { + wg.Add(1) + go func() { + defer wg.Done() + results[i] = findPID(uid, inode) + }() + } + wg.Wait() + + for i, pid := range results { + if pid != want { + t.Fatalf("lookup %d returned pid %d, expected own pid %d", i, pid, want) + } + } + + // The scan result must now be in the cache. + pids, ok := getPidsByUser(uid) + if !ok { + t.Fatalf("no pid list for uid %d", uid) + } + if pid, ok := getCachedSocketOwner(uid, inode, pids); !ok || pid != want { + t.Fatalf("expected cached owner %d, got %d (ok=%v)", want, pid, ok) + } +} diff --git a/service/network/proc/socket_owners.go b/service/network/proc/socket_owners.go new file mode 100644 index 000000000..0df3c6d69 --- /dev/null +++ b/service/network/proc/socket_owners.go @@ -0,0 +1,113 @@ +//go:build linux + +package proc + +import ( + "slices" + "sync" + "time" + + "golang.org/x/sync/singleflight" + + "github.com/safing/portmaster/service/network/socket" +) + +const ( + // socketOwnerGeneration defines how long the found owner of a socket is + // reused without a new scan. Owners are kept for one to two generations, + // so every socket in use is verified by a full scan at least every two + // generations. + socketOwnerGeneration = 1 * time.Second + + // socketOwnerMaxEntries defines how many owners the current generation may + // hold before an early rotation is forced. This bounds memory usage. + socketOwnerMaxEntries = 20000 +) + +// socketOwner is the result of a successful scan for a socket. +type socketOwner struct { + uid int + pid int +} + +// socketOwners caches socket owners by socket inode. The socket tables are +// re-read up to 100 times per second, and every re-read creates new entries +// without a PID. Without this cache, every connection of a socket would +// trigger a full scan of /proc. +var socketOwners = struct { + lock sync.Mutex + cur map[int]socketOwner // [inode] = socketOwner + prev map[int]socketOwner // [inode] = socketOwner + rotatedAt time.Time +}{ + cur: make(map[int]socketOwner), + prev: make(map[int]socketOwner), + rotatedAt: time.Now(), +} + +// socketScans runs at most one scan of /proc per socket at a time, keyed by +// the socket name ("socket:[inode]"). A scan takes long when processes with +// many descriptors are running, and under a burst of new connections hundreds +// of lookups for the same socket start before the first scan finishes. +// Without this, each of them would walk /proc on its own and the cache would +// never be hit. +var socketScans singleflight.Group + +// getCachedSocketOwner returns the cached owner of the socket if it still runs +// as the same user. pids must be the current PIDs of uid. +func getCachedSocketOwner(uid, inode int, pids []int) (pid int, ok bool) { + socketOwners.lock.Lock() + defer socketOwners.lock.Unlock() + + rotateSocketOwners() + + owner, ok := socketOwners.cur[inode] + if !ok { + // Do not promote to the current generation, so that the owner is + // verified by a full scan at least every two generations. + owner, ok = socketOwners.prev[inode] + } + if !ok { + return socket.UndefinedProcessID, false + } + + // The owner exited, or the inode belongs to another user's socket now. + if owner.uid != uid || !slices.Contains(pids, owner.pid) { + delete(socketOwners.cur, inode) + delete(socketOwners.prev, inode) + return socket.UndefinedProcessID, false + } + + return owner.pid, true +} + +// cacheSocketOwner records the owner of the socket found by a scan. +func cacheSocketOwner(uid, inode, pid int) { + socketOwners.lock.Lock() + defer socketOwners.lock.Unlock() + + rotateSocketOwners() + if len(socketOwners.cur) >= socketOwnerMaxEntries { + socketOwners.prev = socketOwners.cur + socketOwners.cur = make(map[int]socketOwner) + socketOwners.rotatedAt = time.Now() + } + socketOwners.cur[inode] = socketOwner{uid: uid, pid: pid} +} + +// rotateSocketOwners drops generations that are due. +// The caller must hold socketOwners.lock. +func rotateSocketOwners() { + switch since := time.Since(socketOwners.rotatedAt); { + case since >= 2*socketOwnerGeneration: + // No access for two generations: both are too old. + socketOwners.prev = make(map[int]socketOwner) + socketOwners.cur = make(map[int]socketOwner) + case since >= socketOwnerGeneration: + socketOwners.prev = socketOwners.cur + socketOwners.cur = make(map[int]socketOwner) + default: + return + } + socketOwners.rotatedAt = time.Now() +} diff --git a/service/network/proc/socket_owners_test.go b/service/network/proc/socket_owners_test.go new file mode 100644 index 000000000..d22934333 --- /dev/null +++ b/service/network/proc/socket_owners_test.go @@ -0,0 +1,87 @@ +//go:build linux + +package proc + +import ( + "testing" + "time" +) + +// The tests share the package-level cache, so they must not run in parallel. + +func resetSocketOwners() { + socketOwners.lock.Lock() + defer socketOwners.lock.Unlock() + + socketOwners.cur = make(map[int]socketOwner) + socketOwners.prev = make(map[int]socketOwner) + socketOwners.rotatedAt = time.Now() +} + +func setSocketOwnersRotatedAt(t time.Time) { + socketOwners.lock.Lock() + defer socketOwners.lock.Unlock() + + socketOwners.rotatedAt = t +} + +func TestSocketOwnerCache(t *testing.T) { //nolint:paralleltest // Uses the package-level cache. + resetSocketOwners() + cacheSocketOwner(1000, 42, 500) + + if pid, ok := getCachedSocketOwner(1000, 42, []int{100, 500}); !ok || pid != 500 { + t.Fatalf("expected cached owner 500, got %d (ok=%v)", pid, ok) + } + if _, ok := getCachedSocketOwner(1001, 42, []int{500}); ok { + t.Fatal("owner of another user must not be returned") + } + + cacheSocketOwner(1000, 43, 600) + if _, ok := getCachedSocketOwner(1000, 43, []int{100}); ok { + t.Fatal("owner that is no longer running must not be returned") + } + if _, ok := getCachedSocketOwner(1000, 43, []int{100, 600}); ok { + t.Fatal("invalid owner must be removed from the cache") + } +} + +func TestSocketOwnerCacheExpiry(t *testing.T) { //nolint:paralleltest // Uses the package-level cache. + resetSocketOwners() + cacheSocketOwner(1000, 42, 500) + + setSocketOwnersRotatedAt(time.Now().Add(-socketOwnerGeneration)) + if _, ok := getCachedSocketOwner(1000, 42, []int{500}); !ok { + t.Fatal("owner must survive one rotation") + } + + setSocketOwnersRotatedAt(time.Now().Add(-socketOwnerGeneration)) + if _, ok := getCachedSocketOwner(1000, 42, []int{500}); ok { + t.Fatal("owner must expire after two rotations") + } +} + +func TestSocketOwnerCacheIdleExpiry(t *testing.T) { //nolint:paralleltest // Uses the package-level cache. + resetSocketOwners() + cacheSocketOwner(1000, 42, 500) + + setSocketOwnersRotatedAt(time.Now().Add(-2 * socketOwnerGeneration)) + if _, ok := getCachedSocketOwner(1000, 42, []int{500}); ok { + t.Fatal("owner must expire after an idle period of two generations") + } +} + +func TestSocketOwnerCacheMaxEntries(t *testing.T) { //nolint:paralleltest // Uses the package-level cache. + resetSocketOwners() + for inode := range socketOwnerMaxEntries { + cacheSocketOwner(1000, inode, 500) + } + // The current generation is full, so this forces an early rotation. + cacheSocketOwner(1000, socketOwnerMaxEntries, 500) + + socketOwners.lock.Lock() + curLen, prevLen := len(socketOwners.cur), len(socketOwners.prev) + socketOwners.lock.Unlock() + if curLen != 1 || prevLen != socketOwnerMaxEntries { + t.Fatalf("expected early rotation (cur=1, prev=%d), got cur=%d, prev=%d", socketOwnerMaxEntries, curLen, prevLen) + } +}