Debian Codegraph @

pathrs-lite/internal/procfs/procfs_linux_test.go

raw ◀ ▶
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 if (err != nil) {
513 t.Skipf("Test setup failed: %v", err)
514 }
515 require.NoError(t, err, "ProcRoot(sys/kernel/version)")
516 require.NotNil(t, handle, "ProcPid(sys/kernel/version) handle")
517
518 realPath, err := ProcSelfFdReadlink(handle)
519 require.NoError(t, err)
520 wantPath := "/sys/kernel/version"
521 if !isFsopenRoot(t) {
522 // The /proc prefix is only present when not using fsopen.
523 wantPath = "/proc" + wantPath
524 }
525 assert.Equal(t, wantPath, realPath, "final handle path")
526 })
527 })
528 })
529 }
530 }
531
532 func canFsOpen() bool {
533 f, err := fd.Fsopen("tmpfs", 0)
534 if f != nil {
535 _ = f.Close()
536 }
537 return err == nil
538 }
539
540 func testProcOvermount(t *testing.T, procRootFn procRootFunc, privateProcMount bool) {
541 testForceProcThreadSelf(t, func(t *testing.T) {
542 for _, mount := range []struct {
543 source, fsType string
544 flags uintptr
545 }{
546 // Try a non-procfs filesystem overmount.
547 {"", "tmpfs", 0},
548 // Try a procfs subdir overmount.
549 {"/proc/tty", "bind", unix.MS_BIND},
550 } {
551 mount := mount // copy iterator
552 t.Run("procmount="+mount.fsType, func(t *testing.T) {
553 setupMountNamespace(t)
554 doMount(t, mount.source, "/proc", mount.fsType, mount.flags)
555
556 procRoot, err := procRootFn()
557 if procRoot != nil {
558 defer procRoot.Close() //nolint:errcheck // test code
559 }
560 if privateProcMount {
561 assert.NoError(t, err, "get proc handle should succeed") //nolint:testifylint
562 assert.NoError(t, verifyProcRoot(procRoot.Inner), "verify private proc mount should succeed") //nolint:testifylint
563 } else {
564 if !assert.ErrorIs(t, err, errUnsafeProcfs, "get proc handle should fail") { //nolint:testifylint
565 t.Logf("procRootFn() = %v, %v", procRoot, err)
566 }
567 }
568 })
569 }
570 })
571 }
572
573 func TestProcOvermount_unsafeHostProcRoot(t *testing.T) {
574 testProcOvermount(t, unsafeHostProcRoot, false)
575 }
576
577 func TestProcOvermount_clonePrivateProcMount(t *testing.T) {
578 if !linux.HasNewMountAPI() {
579 t.Skip("test requires open_tree support")
580 }
581 testProcOvermount(t, clonePrivateProcMount, false)
582 }
583
584 func TestProcOvermount_newPrivateProcMountSubset(t *testing.T) {
585 if !linux.HasNewMountAPI() || !canFsOpen() {
586 t.Skip("test requires fsopen support")
587 }
588 testProcOvermount(t, newPrivateProcMountSubset, true)
589 }
590
591 func TestProcOvermount_newPrivateProcMountUnmasked(t *testing.T) {
592 if !linux.HasNewMountAPI() || !canFsOpen() {
593 t.Skip("test requires fsopen support")
594 }
595 testProcOvermount(t, newPrivateProcMountUnmasked, true)
596 }
597
598 func TestProcOvermount_OpenProcRoot(t *testing.T) {
599 privateProcMount := canFsOpen() && !testingForcePrivateProcRootOpenTree(nil)
600 procRootFn := func() (*Handle, error) { return getProcRoot(true) }
601 testProcOvermount(t, procRootFn, privateProcMount)
602 }
603
604 func TestProcOvermount_OpenProcRoot_Mocked(t *testing.T) {
605 if !linux.HasNewMountAPI() {
606 t.Skip("test requires fsopen/open_tree support")
607 }
608 testForceGetProcRoot(t, func(t *testing.T, _ bool) {
609 privateProcMount := canFsOpen() && !testingForcePrivateProcRootOpenTree(nil)
610 procRootFn := func() (*Handle, error) { return getProcRoot(true) }
611 testProcOvermount(t, procRootFn, privateProcMount)
612 })
613 }
614
615 func TestProcSelfFdPath(t *testing.T) {
616 testForceProcThreadSelf(t, func(t *testing.T) {
617 root := t.TempDir()
618
619 filePath := path.Join(root, "file")
620 err := unix.Mknod(filePath, unix.S_IFREG|0o644, 0)
621 require.NoError(t, err)
622
623 symPath := path.Join(root, "sym")
624 err = unix.Symlink(filePath, symPath)
625 require.NoError(t, err)
626
627 // Open through the symlink.
628 handle, err := os.Open(symPath)
629 require.NoError(t, err)
630 defer handle.Close() //nolint:errcheck // test code
631
632 // The check should fail if we expect the symlink path.
633 err = CheckProcSelfFdPath(symPath, handle)
634 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
635
636 // The check should fail if we expect the symlink path.
637 err = CheckProcSelfFdPath(filePath, handle)
638 assert.NoError(t, err) //nolint:testifylint // this is an isolated operation so we can continue despite an error
639 })
640 }
641
642 func TestProcSelfFdPath_DeadFile(t *testing.T) {
643 testForceProcThreadSelf(t, func(t *testing.T) {
644 root := t.TempDir()
645
646 fullPath := path.Join(root, "file")
647 handle, err := os.Create(fullPath)
648 require.NoError(t, err)
649 defer handle.Close() //nolint:errcheck // test code
650
651 // The path still exists.
652 err = CheckProcSelfFdPath(fullPath, handle)
653 assert.NoError(t, err, "CheckProcSelfFdPath should succeed with regular file") //nolint:testifylint // this is an isolated operation so we can continue despite an error
654
655 // Delete the path.
656 err = os.Remove(fullPath)
657 require.NoError(t, err)
658
659 // The check should fail now.
660 err = CheckProcSelfFdPath(fullPath, handle)
661 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
662
663 // The check should fail even if the expected path ends with " (deleted)".
664 err = CheckProcSelfFdPath(fullPath+" (deleted)", handle)
665 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
666 })
667 }
668
669 func TestProcSelfFdPath_DeadDir(t *testing.T) {
670 testForceProcThreadSelf(t, func(t *testing.T) {
671 root := t.TempDir()
672
673 fullPath := path.Join(root, "dir")
674 err := os.Mkdir(fullPath, 0o755)
675 require.NoError(t, err)
676
677 handle, err := os.OpenFile(fullPath, unix.O_DIRECTORY|unix.O_CLOEXEC, 0)
678 require.NoError(t, err)
679 defer handle.Close() //nolint:errcheck // test code
680
681 // The path still exists.
682 err = CheckProcSelfFdPath(fullPath, handle)
683 assert.NoError(t, err, "CheckProcSelfFdPath should succeed with regular directory") //nolint:testifylint // this is an isolated operation so we can continue despite an error
684
685 // Delete the path.
686 err = os.Remove(fullPath)
687 require.NoError(t, err)
688
689 // The check should fail now.
690 err = CheckProcSelfFdPath(fullPath, handle)
691 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
692
693 // The check should fail even if the expected path ends with " (deleted)".
694 err = CheckProcSelfFdPath(fullPath+" (deleted)", handle)
695 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
696 })
697 }
698
699 func testVerifyProcRoot(t *testing.T, procRoot string, expectedHandleErr, expectedRootErr error, errString string) {
700 fakeProcRoot, err := os.OpenFile(procRoot, unix.O_PATH|unix.O_CLOEXEC, 0)
701 require.NoError(t, err)
702 defer fakeProcRoot.Close() //nolint:errcheck // test code
703
704 err = verifyProcRoot(fakeProcRoot)
705 require.ErrorIsf(t, err, expectedRootErr, "verifyProcRoot(%s)", procRoot)
706 if expectedRootErr != nil {
•707 t.Skipf("Test setup failed: %v", err)
708 require.ErrorContainsf(t, err, errString, "verifyProcRoot(%s)", procRoot)
709 }
710
711 err = verifyProcHandle(fakeProcRoot)
712 require.ErrorIsf(t, err, expectedHandleErr, "verifyProcHandle(%s)", procRoot)
713 if expectedHandleErr != nil {
714 require.ErrorContainsf(t, err, errString, "verifyProcHandle(%s)", procRoot)
715 }
716 }
717
718 func TestVerifyProcRoot_Regular(t *testing.T) {
719 testForceProcThreadSelf(t, func(t *testing.T) {
720 testVerifyProcRoot(t, "/proc", nil, nil, "")
721 })
722 }
723
724 func TestVerifyProcRoot_ProcNonRoot(t *testing.T) {
725 testForceProcThreadSelf(t, func(t *testing.T) {
•726 testVerifyProcRoot(t, "/proc/self", nil, errUnsafeProcfs, "incorrect procfs root")
727 testVerifyProcRoot(t, "/proc/mounts", nil, errUnsafeProcfs, "incorrect procfs root")
728 testVerifyProcRoot(t, "/proc/stat", nil, errUnsafeProcfs, "incorrect procfs root")
729 })
730 }
731
732 func TestVerifyProcRoot_NotProc(t *testing.T) {
733 testForceProcThreadSelf(t, func(t *testing.T) {
734 testVerifyProcRoot(t, "/", errUnsafeProcfs, errUnsafeProcfs, "incorrect procfs root filesystem type")
735 testVerifyProcRoot(t, ".", errUnsafeProcfs, errUnsafeProcfs, "incorrect procfs root filesystem type")
736 testVerifyProcRoot(t, t.TempDir(), errUnsafeProcfs, errUnsafeProcfs, "incorrect procfs root filesystem type")
737 })
738 }
739
740 func TestProcfsDummyHooks(t *testing.T) {
741 assert.False(t, hookDummy(), "hookDummy should always return false")
742 assert.False(t, hookDummyFile(nil), "hookDummyFile should always return false")
743 }
744
745 func TestCachedProcRoot_Close(t *testing.T) {
746 proc := getCachedProcRoot()
747 if proc == nil {
748 t.Skip("cannot get proc handle")
749 }
750
751 f, err := proc.OpenSelf(".")
752 require.NoError(t, err)
753 _ = f.Close()
754
755 for i := 0; i < 4; i++ {
756 require.NoError(t, proc.Close(), "closing cached Handle")
757 }
758
759 f2, err := proc.OpenSelf(".")
760 require.NoError(t, err)
761 _ = f2.Close()
762 }