Repository navigation
Linux: fix memory growth and verdict timeouts under many connections per socket #2293
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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) | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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() | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
Repository: safing/portmaster
Length of output: 5721
🏁 Script executed:
Repository: safing/portmaster
Length of output: 10497
🏁 Script executed:
Repository: safing/portmaster
Length of output: 18374
🏁 Script executed:
Repository: safing/portmaster
Length of output: 21480
🏁 Script executed:
Repository: safing/portmaster
Length of output: 10542
🏁 Script executed:
Repository: safing/portmaster
Length of output: 6951
Key in-flight scans by UID and validate the shared PID.
When a socket inode is reused by another UID while the previous lookup is still scanning, two
state.Lookupcalls can reachsocketScans.Dowith the samesocketName. The callback uses the first caller's PID list, and the second caller accepts its PID without validation. The second socket can therefore receive the first process's PID. This violatesGetPidOfConnection's valid-owner contract.Suggested fix
🤖 Prompt for AI Agents