Skip to content

Commit 50870e9

Browse files
committedSep 20, 2024
pkg/netns: ensure makeNetnsDir is race free
There are some rather bad problems when we bind mount over multiple times, this is a rather small race but can happen. In order to avoid this take an exclusive lock like ip netns add does because they create the same bind mount setup. As such we will not race against other podman process or ip netns add which is a good thing. Signed-off-by: Paul Holzinger <[email protected]>
1 parent 322f2c2 commit 50870e9

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed
 

Diff for: ‎pkg/netns/netns_linux.go

+19
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,25 @@ func makeNetnsDir(nsRunDir string) error {
105105
if err != nil {
106106
return err
107107
}
108+
// Important, the bind mount setup is racy if two process try to set it up in parallel.
109+
// This can have very bad consequences because we end up with two duplicated mounts
110+
// for the netns file that then might have a different parent mounts.
111+
// Also because as root netns dir is also created by ip netns we should not race against them.
112+
// Use a lock on the netns dir like they do, compare the iproute2 ip netns add code.
113+
// https://github.com/iproute2/iproute2/blob/8b9d9ea42759c91d950356ca43930a975d0c352b/ip/ipnetns.c#L806-L815
114+
115+
dirFD, err := unix.Open(nsRunDir, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_CLOEXEC, 0)
116+
if err != nil {
117+
return &os.PathError{Op: "open", Path: nsRunDir, Err: err}
118+
}
119+
// closing the fd will also unlock so we do not have to call flock(fd,LOCK_UN)
120+
defer unix.Close(dirFD)
121+
122+
err = unix.Flock(dirFD, unix.LOCK_EX)
123+
if err != nil {
124+
return fmt.Errorf("failed to lock %s dir: %w", nsRunDir, err)
125+
}
126+
108127
// Remount the namespace directory shared. This will fail with EINVAL
109128
// if it is not already a mountpoint, so bind-mount it on to itself
110129
// to "upgrade" it to a mountpoint.

0 commit comments

Comments
 (0)
Please sign in to comment.