Debian Codegraph @

pathrs-lite/internal/procfs/procfs_linux_test.go

raw ◀ ▶
Source reconstructed at patch state 0 of 2 — not the installed (fully patched) source.
2 Debian patches touch this file
1 // SPDX-License-Identifier: MPL-2.0
2
3 //go:build linux
4
5 // Copyright (C) 2024-2025 Aleksa Sarai <[email protected]>
6 // Copyright (C) 2024-2025 SUSE LLC
7 //
8 // This Source Code Form is subject to the terms of the Mozilla Public
9 // License, v. 2.0. If a copy of the MPL was not distributed with this
10 // file, You can obtain one at https://mozilla.org/MPL/2.0/.
11
12 package procfs
13
14 import (
15 "errors"
16 "fmt"
17 "os"
18 "path"
19 "runtime"
20 "testing"
21
22 "github.com/stretchr/testify/assert"
23 "github.com/stretchr/testify/require"
24 "golang.org/x/sys/unix"
25
26 "github.com/cyphar/filepath-securejoin/pathrs-lite/internal"
27 "github.com/cyphar/filepath-securejoin/pathrs-lite/internal/fd"
28 "github.com/cyphar/filepath-securejoin/pathrs-lite/internal/linux"
29 "github.com/cyphar/filepath-securejoin/pathrs-lite/internal/testutils"
30 )
31
32 func newPrivateProcMountSubset() (*Handle, error) { return newPrivateProcMount(true) }
33 func newPrivateProcMountUnmasked() (*Handle, error) { return newPrivateProcMount(false) }
34
35 func doMount(t *testing.T, source, target, fsType string, flags uintptr) {
36 var sourcePath string
37 if source != "" {
38 // In order to be able to bind-mount a symlink source we need to
39 // bind-mount using an O_PATH|O_NOFOLLOW of the source.
40 file, err := os.OpenFile(source, unix.O_PATH|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0)
41 require.NoError(t, err)
42 defer runtime.KeepAlive(file)
43 defer file.Close() //nolint:errcheck // test code
44 sourcePath = fmt.Sprintf("/proc/self/fd/%d", file.Fd())
45 }
46
47 var targetPath string
48 if target != "" {
49 // In order to be able to mount on top of symlinks we need to
50 // bind-mount through an O_PATH|O_NOFOLLOW of the target.
51 file, err := os.OpenFile(target, unix.O_PATH|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0)
52 require.NoError(t, err)
53 defer runtime.KeepAlive(file)
54 defer file.Close() //nolint:errcheck // test code
55 targetPath = fmt.Sprintf("/proc/self/fd/%d", file.Fd())
56 }
57
58 err := unix.Mount(sourcePath, targetPath, fsType, flags, "")
59 if errors.Is(err, unix.ENOENT) {
60 // Future kernels will block these kinds of mounts by marking all of
61 // these dentries with dont_mount(), which returns -ENOENT from mount.
62 // See <https://lore.kernel.org/all/[email protected]/>,
63 // which should make it into Linux 6.12. So ignore those errors.
64 t.Skipf("current kernel does not allow /proc overmounts -- all proc operations are implicitly safe")
65 }
66 require.NoErrorf(t, err, "mount(%s<%s>, %s<%s>, %s, 0x%x)", sourcePath, source, targetPath, target, fsType, flags)
67 }
68
69 func setupMountNamespace(t *testing.T) {
70 testutils.RequireRoot(t)
71
72 // Lock our thread because we need to create a custom mount namespace. Each
73 // test run is run in its own goroutine (this is not _explicitly_
74 // guaranteed by Go but t.FailNow() uses Goexit, which means it has to be
75 // true in practice) so locking the test to this thread means the other
76 // tests will run on different goroutines.
77 //
78 // There is no UnlockOSThread() here, to ensure that the Go runtime will
79 // kill this thread once this goroutine returns (ensuring no other
80 // goroutines run in this context).
81 runtime.LockOSThread()
82
83 // New mount namespace (we are multi-threaded with a shared fs so we need
84 // CLONE_FS to split us from the other threads in the Go process).
85 err := unix.Unshare(unix.CLONE_FS | unix.CLONE_NEWNS)
86 require.NoError(t, err, "new mount namespace")
87
88 // Private /.
89 err = unix.Mount("", "/", "", unix.MS_PRIVATE|unix.MS_REC, "")
90 require.NoError(t, err)
91 }
92
93 func testProcThreadSelf(t *testing.T, procRoot *Handle, subpath string, expectErr bool) {
94 handle, closer, err := procRoot.OpenThreadSelf(subpath)
95 if expectErr {
96 assert.ErrorIsf(t, err, errUnsafeProcfs, "should have detected /proc/thread-self/%s overmount", subpath)
97 } else if assert.NoErrorf(t, err, "/proc/thread-self/%s open should succeed", subpath) {
98 _ = handle.Close()
99 closer() // LockOSThread stacks, so we can call this safely.
100 }
101 }
102
103 type procRootFunc func() (*Handle, error)
104
105 func testProcOvermountSubdir(t *testing.T, procRootFn procRootFunc, expectOvermounts bool) {
106 testForceProcThreadSelf(t, func(t *testing.T) {
107 setupMountNamespace(t)
108
109 // Create some overmounts on /proc/{thread-self/,self/}.
110 for _, procThreadSelfPath := range []string{
111 fmt.Sprintf("/proc/self/task/%d", unix.Gettid()),
112 "/proc/self",
113 } {
114 for _, mount := range []struct {
115 source, targetSubPath, fsType string
116 flags uintptr
117 }{
118 // A tmpfs on top of /proc/thread-self/fdinfo to check whether
119 // verifyProcRoot() works on old kernels.
120 {"", "fdinfo", "tmpfs", 0},
121 // A bind-mount of noop-write real procfs file on top of
122 // /proc/thread-self/attr/current so we can test whether
123 // verifyProcRoot() works for the file case.
124 //
125 // We don't use procThreadSelf for files in filepath-securejoin, but
126 // this is to test the runc-equivalent behaviour for when this logic is
127 // moved to libpathrs.
128 {"/proc/self/sched", "attr/current", "", unix.MS_BIND},
129 // Bind-mounts on top of symlinks should be detected by
130 // checkSubpathOvermount.
131 {"/proc/1/fd/0", "exe", "", unix.MS_BIND},
132 {"/proc/1/exe", "fd/0", "", unix.MS_BIND},
133 // TODO: Add a test for mounting on top of /proc/self or
134 // /proc/thread-self. This should be detected with openat2.
135 } {
136 target := path.Join(procThreadSelfPath, mount.targetSubPath)
137 doMount(t, mount.source, target, mount.fsType, mount.flags)
138 }
139 }
140
141 procRoot, err := procRootFn()
142 require.NoError(t, err)
143 defer procRoot.Close() //nolint:errcheck // test code
144
145 // For both tmpfs and procfs overmounts, we should catch them (with or
146 // without openat2, thanks to procfsLookupInRoot).
147 testProcThreadSelf(t, procRoot, "fdinfo", expectOvermounts)
148 testProcThreadSelf(t, procRoot, "attr/current", expectOvermounts)
149
150 // For magic-links we expect to detect overmounts if there are any.
151 symlinkOvermountErr := errUnsafeProcfs
152 if !expectOvermounts {
153 symlinkOvermountErr = nil
154 }
155
156 procSelf, closer, err := procRoot.OpenThreadSelf(".")
157 require.NoError(t, err)
158 defer procSelf.Close() //nolint:errcheck // test code
159 defer closer()
160
161 // Open these paths directly to emulate a non-openat2 handle that
162 // didn't detect a bind-mount to check that checkSubpathOvermount works
163 // properly for AT_EMPTY_PATH checks as well.
164 procCwd, err := fd.Openat(procSelf, "cwd", unix.O_PATH|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0)
165 require.NoError(t, err)
166 defer procCwd.Close() //nolint:errcheck // test code
167 procExe, err := fd.Openat(procSelf, "exe", unix.O_PATH|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0)
168 require.NoError(t, err)
169 defer procExe.Close() //nolint:errcheck // test code
170
171 // no overmount
172 err = checkSubpathOvermount(procRoot.Inner, procCwd, "")
173 assert.NoError(t, err, "checking /proc/self/cwd with no overmount should succeed") //nolint:testifylint // this is an isolated operation so we can continue despite an error
174 err = checkSubpathOvermount(procRoot.Inner, procSelf, "cwd")
175 assert.NoError(t, err, "checking /proc/self/cwd with no overmount should succeed") //nolint:testifylint // this is an isolated operation so we can continue despite an error
176 // basic overmount
177 err = checkSubpathOvermount(procRoot.Inner, procExe, "")
178 assert.ErrorIs(t, err, symlinkOvermountErr, "unexpected /proc/self/exe overmount result") //nolint:testifylint // this is an isolated operation so we can continue despite an error
179 err = checkSubpathOvermount(procRoot.Inner, procSelf, "exe")
180 assert.ErrorIs(t, err, symlinkOvermountErr, "unexpected /proc/self/exe overmount result") //nolint:testifylint // this is an isolated operation so we can continue despite an error
181
182 // fd no overmount
183 _, err = procRoot.Readlink(ProcThreadSelf, "fd/1")
184 assert.NoError(t, err, "checking /proc/self/fd/1 with no overmount should succeed") //nolint:testifylint // this is an isolated operation so we can continue despite an error
185 // fd overmount
186 link, err := procRoot.Readlink(ProcThreadSelf, "fd/0")
187 assert.ErrorIs(t, err, symlinkOvermountErr, "unexpected /proc/self/fd/0 overmount result: got link %q", link) //nolint:testifylint // this is an isolated operation so we can continue despite an error
188 })
189 }
190
191 func tRunWrapper(t *testing.T) testutils.TRunFunc {
192 return func(name string, doFn testutils.TDoFunc) {
193 t.Run(name, func(t *testing.T) {
194 doFn(t)
195 })
196 }
197 }
198
199 func TestProcOvermountSubdir_unsafeHostProcRoot(t *testing.T) {
200 testutils.WithWithoutOpenat2(true, tRunWrapper(t), func(ti testutils.TestingT) {
201 t := ti.(*testing.T) //nolint:forcetypeassert // guaranteed to be true and in test code
202 // If we use the host /proc directly, we should see overmounts.
203 testProcOvermountSubdir(t, unsafeHostProcRoot, true)
204 })
205 }
206
207 func TestProcOvermountSubdir_newPrivateProcMountSubset(t *testing.T) {
208 if !linux.HasNewMountAPI() {
209 t.Skip("test requires fsopen/open_tree support")
210 }
211 testutils.WithWithoutOpenat2(true, tRunWrapper(t), func(ti testutils.TestingT) {
212 t := ti.(*testing.T) //nolint:forcetypeassert // guaranteed to be true and in test code
213 // If we create our own procfs, the overmounts shouldn't appear.
214 testProcOvermountSubdir(t, newPrivateProcMountSubset, false)
215 })
216 }
217
218 func TestProcOvermountSubdir_newPrivateProcMountUnmasked(t *testing.T) {
219 if !linux.HasNewMountAPI() {
220 t.Skip("test requires fsopen/open_tree support")
221 }
222 testutils.WithWithoutOpenat2(true, tRunWrapper(t), func(ti testutils.TestingT) {
223 t := ti.(*testing.T) //nolint:forcetypeassert // guaranteed to be true and in test code
224 // If we create our own procfs, the overmounts shouldn't appear.
225 testProcOvermountSubdir(t, newPrivateProcMountUnmasked, false)
226 })
227 }
228
229 func TestProcOvermountSubdir_clonePrivateProcMount(t *testing.T) {
230 if !linux.HasNewMountAPI() {
231 t.Skip("test requires fsopen/open_tree support")
232 }
233 testutils.WithWithoutOpenat2(true, tRunWrapper(t), func(ti testutils.TestingT) {
234 t := ti.(*testing.T) //nolint:forcetypeassert // guaranteed to be true and in test code
235 // If we use open_tree(2), we don't use AT_RECURSIVE when running in
236 // this test (because the overmounts are not locked mounts) and so we
237 // don't expect to see overmounts.
238 testProcOvermountSubdir(t, clonePrivateProcMount, false)
239 })
240 }
241
242 func TestProcOvermountSubdir_OpenProcRoot(t *testing.T) {
243 testutils.WithWithoutOpenat2(true, tRunWrapper(t), func(ti testutils.TestingT) {
244 t := ti.(*testing.T) //nolint:forcetypeassert // guaranteed to be true and in test code
245 // We expect to not get overmounts if we have the new mount API.
246 // FIXME: It's possible to hit overmounts if there are locked mounts
247 // and we hit the AT_RECURSIVE case...
248 procRootFn := func() (*Handle, error) { return getProcRoot(true) }
249 testProcOvermountSubdir(t, procRootFn, !linux.HasNewMountAPI())
250 })
251 }
252
253 func TestProcOvermountSubdir_OpenUnsafeProcRoot(t *testing.T) {
254 testutils.WithWithoutOpenat2(true, tRunWrapper(t), func(ti testutils.TestingT) {
255 t := ti.(*testing.T) //nolint:forcetypeassert // guaranteed to be true and in test code
256 // We expect to not get overmounts if we have the new mount API.
257 // FIXME: It's possible to hit overmounts if there are locked mounts
258 // and we hit the AT_RECURSIVE case...
259 testProcOvermountSubdir(t, OpenUnsafeProcRoot, !linux.HasNewMountAPI())
260 })
261 }
262
263 func TestProcOvermountSubdir_getProcRootSubset_Mocked(t *testing.T) {
264 if !linux.HasNewMountAPI() {
265 t.Skip("test requires fsopen/open_tree support")
266 }
267 testutils.WithWithoutOpenat2(true, tRunWrapper(t), func(ti testutils.TestingT) {
268 t := ti.(*testing.T) //nolint:forcetypeassert // guaranteed to be true and in test code
269 testForceGetProcRoot(t, func(t *testing.T, expectOvermounts bool) {
270 procRootFn := func() (*Handle, error) { return getProcRoot(true) }
271 testProcOvermountSubdir(t, procRootFn, expectOvermounts)
272 })
273 })
274 }
275
276 // isFsopenRoot returns whether the internal procfs handle is an fsopen root.
277 func isFsopenRoot(t *testing.T) bool {
278 procRoot, err := OpenUnsafeProcRoot() // !subset=pid
279 require.NoError(t, err)
280 return procRoot.Inner.Name() == "fsmount:fscontext:proc"
281 }
282
283 // Because of the introduction of protections against /proc overmounts,
284 // ProcThreadSelf will not be called in actual tests unless we have a basic
285 // test here.
286 func TestProcThreadSelf(t *testing.T) {
287 proc, err := OpenProcRoot()
288 require.NoError(t, err)
289
290 testutils.WithWithoutOpenat2(true, tRunWrapper(t), func(ti testutils.TestingT) {
291 t := ti.(*testing.T) //nolint:forcetypeassert // guaranteed to be true and in test code
292 t.Run("stat", func(t *testing.T) {
293 handle, closer, err := proc.OpenThreadSelf("stat")
294 require.NoError(t, err, "ProcThreadSelf(stat)")
295 require.NotNil(t, handle, "ProcThreadSelf(stat) handle")
296 require.NotNil(t, closer, "ProcThreadSelf(stat) closer")
297 defer closer()
298 defer handle.Close() //nolint:errcheck // test code
299
300 realPath, err := ProcSelfFdReadlink(handle)
301 require.NoError(t, err)
302 wantPath := fmt.Sprintf("/%d/task/%d/stat", os.Getpid(), unix.Gettid())
303 if !isFsopenRoot(t) {
304 // The /proc prefix is only present when not using fsopen.
305 wantPath = "/proc" + wantPath
306 }
307 assert.Equal(t, wantPath, realPath, "final handle path")
308 })
309
310 t.Run("abspath", func(t *testing.T) {
311 handle, closer, err := proc.OpenThreadSelf("/stat")
312 require.NoError(t, err, "ProcThreadSelf(/stat)")
313 require.NotNil(t, handle, "ProcThreadSelf(/stat) handle")
314 require.NotNil(t, closer, "ProcThreadSelf(/stat) closer")
315 defer closer()
316 defer handle.Close() //nolint:errcheck // test code
317
318 realPath, err := ProcSelfFdReadlink(handle)
319 require.NoError(t, err)
320 wantPath := fmt.Sprintf("/%d/task/%d/stat", os.Getpid(), unix.Gettid())
321 if !isFsopenRoot(t) {
322 // The /proc prefix is only present when not using fsopen.
323 wantPath = "/proc" + wantPath
324 }
325 assert.Equal(t, wantPath, realPath, "final handle path")
326 })
327
328 t.Run("wacky-abspath", func(t *testing.T) {
329 handle, closer, err := proc.OpenThreadSelf("////./////stat")
330 require.NoError(t, err, "ProcThreadSelf(////./////stat)")
331 require.NotNil(t, handle, "ProcThreadSelf(////./////stat) handle")
332 require.NotNil(t, closer, "ProcThreadSelf(////./////stat) closer")
333 defer closer()
334 defer handle.Close() //nolint:errcheck // test code
335
336 realPath, err := ProcSelfFdReadlink(handle)
337 require.NoError(t, err)
338 wantPath := fmt.Sprintf("/%d/task/%d/stat", os.Getpid(), unix.Gettid())
339 if !isFsopenRoot(t) {
340 // The /proc prefix is only present when not using fsopen.
341 wantPath = "/proc" + wantPath
342 }
343 assert.Equal(t, wantPath, realPath, "final handle path")
344 })
345
346 t.Run("dotdot", func(t *testing.T) {
347 handle, closer, err := proc.OpenThreadSelf("../../../../../../../../..")
348 require.Error(t, err, "ProcThreadSelf(../...)")
349 require.Nil(t, handle, "ProcThreadSelf(../...) handle")
350 require.Nil(t, closer, "ProcThreadSelf(../...) closer")
351 })
352
353 t.Run("wacky-dotdot", func(t *testing.T) {
354 handle, closer, err := proc.OpenThreadSelf("/../../../../../../../../..")
355 require.Error(t, err, "ProcThreadSelf(/../...)")
356 require.Nil(t, handle, "ProcThreadSelf(/../...) handle")
357 require.Nil(t, closer, "ProcThreadSelf(/../...) closer")
358 })
359 })
360 }
361
362 func TestProcSelf(t *testing.T) {
363 proc, err := OpenProcRoot()
364 require.NoError(t, err)
365
366 testutils.WithWithoutOpenat2(true, tRunWrapper(t), func(ti testutils.TestingT) {
367 t := ti.(*testing.T) //nolint:forcetypeassert // guaranteed to be true and in test code
368 t.Run("stat", func(t *testing.T) {
369 handle, err := proc.OpenSelf("stat")
370 require.NoError(t, err, "ProcSelf(stat)")
371 require.NotNil(t, handle, "ProcSelf(stat) handle")
372 defer handle.Close() //nolint:errcheck // test code
373
374 realPath, err := ProcSelfFdReadlink(handle)
375 require.NoError(t, err)
376 wantPath := fmt.Sprintf("/%d/stat", os.Getpid())
377 if !isFsopenRoot(t) {
378 // The /proc prefix is only present when not using fsopen.
379 wantPath = "/proc" + wantPath
380 }
381 assert.Equal(t, wantPath, realPath, "final handle path")
382 })
383
384 t.Run("abspath", func(t *testing.T) {
385 handle, err := proc.OpenSelf("/stat")
386 require.NoError(t, err, "ProcSelf(/stat)")
387 require.NotNil(t, handle, "ProcSelf(/stat) handle")
388 defer handle.Close() //nolint:errcheck // test code
389
390 realPath, err := ProcSelfFdReadlink(handle)
391 require.NoError(t, err)
392 wantPath := fmt.Sprintf("/%d/stat", os.Getpid())
393 if !isFsopenRoot(t) {
394 // The /proc prefix is only present when not using fsopen.
395 wantPath = "/proc" + wantPath
396 }
397 assert.Equal(t, wantPath, realPath, "final handle path")
398 })
399
400 t.Run("wacky-abspath", func(t *testing.T) {
401 handle, err := proc.OpenSelf("////./////stat")
402 require.NoError(t, err, "ProcSelf(////./////stat)")
403 require.NotNil(t, handle, "ProcSelf(////./////stat) handle")
404 defer handle.Close() //nolint:errcheck // test code
405
406 realPath, err := ProcSelfFdReadlink(handle)
407 require.NoError(t, err)
408 wantPath := fmt.Sprintf("/%d/stat", os.Getpid())
409 if !isFsopenRoot(t) {
410 // The /proc prefix is only present when not using fsopen.
411 wantPath = "/proc" + wantPath
412 }
413 assert.Equal(t, wantPath, realPath, "final handle path")
414 })
415
416 t.Run("dotdot", func(t *testing.T) {
417 handle, err := proc.OpenSelf("../../../../../../../../..")
418 require.Error(t, err, "ProcSelf(../...)")
419 require.Nil(t, handle, "ProcSelf(../...) handle")
420 })
421
422 t.Run("wacky-dotdot", func(t *testing.T) {
423 handle, err := proc.OpenSelf("/../../../../../../../../..")
424 require.Error(t, err, "ProcSelf(/../...)")
425 require.Nil(t, handle, "ProcSelf(/../...) handle")
426 })
427 })
428 }
429
430 func TestProcPid(t *testing.T) {
431 proc, err := OpenProcRoot()
432 require.NoError(t, err)
433
434 testutils.WithWithoutOpenat2(true, tRunWrapper(t), func(ti testutils.TestingT) {
435 t := ti.(*testing.T) //nolint:forcetypeassert // guaranteed to be true and in test code
436 t.Run("pid1-stat", func(t *testing.T) {
437 handle, err := proc.OpenPid(1, "stat")
438 require.NoError(t, err, "ProcPid(1, stat)")
439 require.NotNil(t, handle, "ProcPid(1, stat) handle")
440
441 realPath, err := ProcSelfFdReadlink(handle)
442 require.NoError(t, err)
443 wantPath := "/1/stat"
444 if !isFsopenRoot(t) {
445 // The /proc prefix is only present when not using fsopen.
446 wantPath = "/proc" + wantPath
447 }
448 assert.Equal(t, wantPath, realPath, "final handle path")
449 })
450
451 t.Run("pid1-stat-abspath", func(t *testing.T) {
452 handle, err := proc.OpenPid(1, "/stat")
453 require.NoError(t, err, "ProcPid(1, /stat)")
454 require.NotNil(t, handle, "ProcPid(1, /stat) handle")
455
456 realPath, err := ProcSelfFdReadlink(handle)
457 require.NoError(t, err)
458 wantPath := "/1/stat"
459 if !isFsopenRoot(t) {
460 // The /proc prefix is only present when not using fsopen.
461 wantPath = "/proc" + wantPath
462 }
463 assert.Equal(t, wantPath, realPath, "final handle path")
464 })
465
466 t.Run("pid1-stat-wacky-abspath", func(t *testing.T) {
467 handle, err := proc.OpenPid(1, "////.////stat")
468 require.NoError(t, err, "ProcPid(1, ////.////stat)")
469 require.NotNil(t, handle, "ProcPid(1, ////.////stat) handle")
470
471 realPath, err := ProcSelfFdReadlink(handle)
472 require.NoError(t, err)
473 wantPath := "/1/stat"
474 if !isFsopenRoot(t) {
475 // The /proc prefix is only present when not using fsopen.
476 wantPath = "/proc" + wantPath
477 }
478 assert.Equal(t, wantPath, realPath, "final handle path")
479 })
480
481 t.Run("dotdot", func(t *testing.T) {
482 handle, err := proc.OpenPid(1, "../../../../../../../../..")
483 require.Error(t, err, "ProcPid(1, ../...)")
484 require.Nil(t, handle, "ProcPid(1, ../...) handle")
485 })
486
487 t.Run("wacky-dotdot", func(t *testing.T) {
488 handle, err := proc.OpenPid(1, "/../../../../../../../../..")
489 require.Error(t, err, "ProcPid(1, /../...)")
490 require.Nil(t, handle, "ProcPid(1, /../...) handle")
491 })
492 })
493 }
494
495 func TestProcRoot(t *testing.T) {
496 for _, test := range []struct {
497 name string
498 procRootFn procRootFunc
499 }{
500 {"OpenProcRoot", OpenProcRoot},
501 {"OpenUnsafeProcRoot", OpenUnsafeProcRoot},
502 } {
503 test := test // copy iterator
504 t.Run(test.name, func(t *testing.T) {
505 proc, err := test.procRootFn()
506 require.NoError(t, err)
507
508 testutils.WithWithoutOpenat2(true, tRunWrapper(t), func(ti testutils.TestingT) {
509 t := ti.(*testing.T) //nolint:forcetypeassert // guaranteed to be true and in test code
510 t.Run("sysctl", func(t *testing.T) {
511 handle, err := proc.OpenRoot("sys/kernel/version")
512 require.NoError(t, err, "ProcRoot(sys/kernel/version)")
513 require.NotNil(t, handle, "ProcPid(sys/kernel/version) handle")
514
515 realPath, err := ProcSelfFdReadlink(handle)
516 require.NoError(t, err)
517 wantPath := "/sys/kernel/version"
518 if !isFsopenRoot(t) {
519 // The /proc prefix is only present when not using fsopen.
520 wantPath = "/proc" + wantPath
521 }
522 assert.Equal(t, wantPath, realPath, "final handle path")
523 })
524 })
525 })
526 }
527 }
528
529 func canFsOpen() bool {
530 f, err := fd.Fsopen("tmpfs", 0)
531 if f != nil {
532 _ = f.Close()
533 }
534 return err == nil
535 }
536
537 func testProcOvermount(t *testing.T, procRootFn procRootFunc, privateProcMount bool) {
538 testForceProcThreadSelf(t, func(t *testing.T) {
539 for _, mount := range []struct {
540 source, fsType string
541 flags uintptr
542 }{
543 // Try a non-procfs filesystem overmount.
544 {"", "tmpfs", 0},
545 // Try a procfs subdir overmount.
546 {"/proc/tty", "bind", unix.MS_BIND},
547 } {
548 mount := mount // copy iterator
549 t.Run("procmount="+mount.fsType, func(t *testing.T) {
550 setupMountNamespace(t)
551 doMount(t, mount.source, "/proc", mount.fsType, mount.flags)
552
553 procRoot, err := procRootFn()
554 if procRoot != nil {
555 defer procRoot.Close() //nolint:errcheck // test code
556 }
557 if privateProcMount {
558 assert.NoError(t, err, "get proc handle should succeed") //nolint:testifylint
559 assert.NoError(t, verifyProcRoot(procRoot.Inner), "verify private proc mount should succeed") //nolint:testifylint
560 } else {
561 if !assert.ErrorIs(t, err, errUnsafeProcfs, "get proc handle should fail") { //nolint:testifylint
562 t.Logf("procRootFn() = %v, %v", procRoot, err)
563 }
564 }
565 })
566 }
567 })
568 }
569
570 func TestProcOvermount_unsafeHostProcRoot(t *testing.T) {
571 testProcOvermount(t, unsafeHostProcRoot, false)
572 }
573
574 func TestProcOvermount_clonePrivateProcMount(t *testing.T) {
575 if !linux.HasNewMountAPI() {
576 t.Skip("test requires open_tree support")
577 }
578 testProcOvermount(t, clonePrivateProcMount, false)
579 }
580
581 func TestProcOvermount_newPrivateProcMountSubset(t *testing.T) {
582 if !linux.HasNewMountAPI() || !canFsOpen() {
583 t.Skip("test requires fsopen support")
584 }
585 testProcOvermount(t, newPrivateProcMountSubset, true)
586 }
587
588 func TestProcOvermount_newPrivateProcMountUnmasked(t *testing.T) {
589 if !linux.HasNewMountAPI() || !canFsOpen() {
590 t.Skip("test requires fsopen support")
591 }
592 testProcOvermount(t, newPrivateProcMountUnmasked, true)
593 }
594
595 func TestProcOvermount_OpenProcRoot(t *testing.T) {
596 privateProcMount := canFsOpen() && !testingForcePrivateProcRootOpenTree(nil)
597 procRootFn := func() (*Handle, error) { return getProcRoot(true) }
598 testProcOvermount(t, procRootFn, privateProcMount)
599 }
600
601 func TestProcOvermount_OpenProcRoot_Mocked(t *testing.T) {
602 if !linux.HasNewMountAPI() {
603 t.Skip("test requires fsopen/open_tree support")
604 }
605 testForceGetProcRoot(t, func(t *testing.T, _ bool) {
606 privateProcMount := canFsOpen() && !testingForcePrivateProcRootOpenTree(nil)
607 procRootFn := func() (*Handle, error) { return getProcRoot(true) }
608 testProcOvermount(t, procRootFn, privateProcMount)
609 })
610 }
611
612 func TestProcSelfFdPath(t *testing.T) {
613 testForceProcThreadSelf(t, func(t *testing.T) {
614 root := t.TempDir()
615
616 filePath := path.Join(root, "file")
617 err := unix.Mknod(filePath, unix.S_IFREG|0o644, 0)
618 require.NoError(t, err)
619
620 symPath := path.Join(root, "sym")
621 err = unix.Symlink(filePath, symPath)
622 require.NoError(t, err)
623
624 // Open through the symlink.
625 handle, err := os.Open(symPath)
626 require.NoError(t, err)
627 defer handle.Close() //nolint:errcheck // test code
628
629 // The check should fail if we expect the symlink path.
630 err = CheckProcSelfFdPath(symPath, handle)
631 assert.ErrorIs(t, err, internal.ErrPossibleBreakout, "CheckProcSelfFdPath should fail for wrong path") //nolint:testifylint // this is an isolated operation so we can continue despite an error
632
633 // The check should fail if we expect the symlink path.
634 err = CheckProcSelfFdPath(filePath, handle)
635 assert.NoError(t, err) //nolint:testifylint // this is an isolated operation so we can continue despite an error
636 })
637 }
638
639 func TestProcSelfFdPath_DeadFile(t *testing.T) {
640 testForceProcThreadSelf(t, func(t *testing.T) {
641 root := t.TempDir()
642
643 fullPath := path.Join(root, "file")
644 handle, err := os.Create(fullPath)
645 require.NoError(t, err)
646 defer handle.Close() //nolint:errcheck // test code
647
648 // The path still exists.
649 err = CheckProcSelfFdPath(fullPath, handle)
650 assert.NoError(t, err, "CheckProcSelfFdPath should succeed with regular file") //nolint:testifylint // this is an isolated operation so we can continue despite an error
651
652 // Delete the path.
653 err = os.Remove(fullPath)
654 require.NoError(t, err)
655
656 // The check should fail now.
657 err = CheckProcSelfFdPath(fullPath, handle)
658 assert.ErrorIs(t, err, internal.ErrDeletedInode, "CheckProcSelfFdPath should fail after deletion") //nolint:testifylint // this is an isolated operation so we can continue despite an error
659
660 // The check should fail even if the expected path ends with " (deleted)".
661 err = CheckProcSelfFdPath(fullPath+" (deleted)", handle)
662 assert.ErrorIs(t, err, internal.ErrDeletedInode, "CheckProcSelfFdPath should fail after deletion even with (deleted) suffix") //nolint:testifylint // this is an isolated operation so we can continue despite an error
663 })
664 }
665
666 func TestProcSelfFdPath_DeadDir(t *testing.T) {
667 testForceProcThreadSelf(t, func(t *testing.T) {
668 root := t.TempDir()
669
670 fullPath := path.Join(root, "dir")
671 err := os.Mkdir(fullPath, 0o755)
672 require.NoError(t, err)
673
674 handle, err := os.OpenFile(fullPath, unix.O_DIRECTORY|unix.O_CLOEXEC, 0)
675 require.NoError(t, err)
676 defer handle.Close() //nolint:errcheck // test code
677
678 // The path still exists.
679 err = CheckProcSelfFdPath(fullPath, handle)
680 assert.NoError(t, err, "CheckProcSelfFdPath should succeed with regular directory") //nolint:testifylint // this is an isolated operation so we can continue despite an error
681
682 // Delete the path.
683 err = os.Remove(fullPath)
684 require.NoError(t, err)
685
686 // The check should fail now.
687 err = CheckProcSelfFdPath(fullPath, handle)
688 assert.ErrorIs(t, err, internal.ErrInvalidDirectory, "CheckProcSelfFdPath should fail after deletion") //nolint:testifylint // this is an isolated operation so we can continue despite an error
689
690 // The check should fail even if the expected path ends with " (deleted)".
691 err = CheckProcSelfFdPath(fullPath+" (deleted)", handle)
692 assert.ErrorIs(t, err, internal.ErrInvalidDirectory, "CheckProcSelfFdPath should fail after deletion even with (deleted) suffix") //nolint:testifylint // this is an isolated operation so we can continue despite an error
693 })
694 }
695
696 func testVerifyProcRoot(t *testing.T, procRoot string, expectedHandleErr, expectedRootErr error, errString string) {
697 fakeProcRoot, err := os.OpenFile(procRoot, unix.O_PATH|unix.O_CLOEXEC, 0)
698 require.NoError(t, err)
699 defer fakeProcRoot.Close() //nolint:errcheck // test code
700
701 err = verifyProcRoot(fakeProcRoot)
702 require.ErrorIsf(t, err, expectedRootErr, "verifyProcRoot(%s)", procRoot)
703 if expectedRootErr != nil {
704 require.ErrorContainsf(t, err, errString, "verifyProcRoot(%s)", procRoot)
705 }
706
707 err = verifyProcHandle(fakeProcRoot)
708 require.ErrorIsf(t, err, expectedHandleErr, "verifyProcHandle(%s)", procRoot)
709 if expectedHandleErr != nil {
710 require.ErrorContainsf(t, err, errString, "verifyProcHandle(%s)", procRoot)
711 }
712 }
713
714 func TestVerifyProcRoot_Regular(t *testing.T) {
715 testForceProcThreadSelf(t, func(t *testing.T) {
716 testVerifyProcRoot(t, "/proc", nil, nil, "")
717 })
718 }
719
720 func TestVerifyProcRoot_ProcNonRoot(t *testing.T) {
721 testForceProcThreadSelf(t, func(t *testing.T) {
722 testVerifyProcRoot(t, "/proc/self", nil, errUnsafeProcfs, "incorrect procfs root inode number")
723 testVerifyProcRoot(t, "/proc/mounts", nil, errUnsafeProcfs, "incorrect procfs root inode number")
724 testVerifyProcRoot(t, "/proc/stat", nil, errUnsafeProcfs, "incorrect procfs root inode number")
725 })
726 }
727
728 func TestVerifyProcRoot_NotProc(t *testing.T) {
729 testForceProcThreadSelf(t, func(t *testing.T) {
730 testVerifyProcRoot(t, "/", errUnsafeProcfs, errUnsafeProcfs, "incorrect procfs root filesystem type")
731 testVerifyProcRoot(t, ".", errUnsafeProcfs, errUnsafeProcfs, "incorrect procfs root filesystem type")
732 testVerifyProcRoot(t, t.TempDir(), errUnsafeProcfs, errUnsafeProcfs, "incorrect procfs root filesystem type")
733 })
734 }
735
736 func TestProcfsDummyHooks(t *testing.T) {
737 assert.False(t, hookDummy(), "hookDummy should always return false")
738 assert.False(t, hookDummyFile(nil), "hookDummyFile should always return false")
739 }
740
741 func TestCachedProcRoot_Close(t *testing.T) {
742 proc := getCachedProcRoot()
743 if proc == nil {
744 t.Skip("cannot get proc handle")
745 }
746
747 f, err := proc.OpenSelf(".")
748 require.NoError(t, err)
749 _ = f.Close()
750
751 for i := 0; i < 4; i++ {
752 require.NoError(t, proc.Close(), "closing cached Handle")
753 }
754
755 f2, err := proc.OpenSelf(".")
756 require.NoError(t, err)
757 _ = f2.Close()
758 }