Debian Codegraph @

pathrs-lite/internal/procfs/procfs_linux.go

raw
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 provides a safe API for operating on /proc on Linux. Note
13 // that this is the *internal* procfs API, mainy needed due to Go's
14 // restrictions on cyclic dependencies and its incredibly minimal visibility
15 // system without making a separate internal/ package.
16 package procfs
17
18 import (
19 "errors"
20 "fmt"
21 "io"
22 "os"
23 "runtime"
24 "strconv"
25
26 "golang.org/x/sys/unix"
27
28 "github.com/cyphar/filepath-securejoin/pathrs-lite/internal"
29 "github.com/cyphar/filepath-securejoin/pathrs-lite/internal/assert"
30 "github.com/cyphar/filepath-securejoin/pathrs-lite/internal/fd"
31 "github.com/cyphar/filepath-securejoin/pathrs-lite/internal/gocompat"
32 "github.com/cyphar/filepath-securejoin/pathrs-lite/internal/linux"
33 )
34
35 // The kernel guarantees that the root inode of a procfs mount has an
36 // f_type of PROC_SUPER_MAGIC and st_ino of PROC_ROOT_INO.
37 const (
38 procSuperMagic = 0x9fa0 // PROC_SUPER_MAGIC
39 procRootIno = 1 // PROC_ROOT_INO
40 )
41
42 // verifyProcHandle checks that the handle is from a procfs filesystem.
43 // Contrast this to [verifyProcRoot], which also verifies that the handle is
44 // the root of a procfs mount.
45 func verifyProcHandle(procHandle fd.Fd) error {
46 if statfs, err := fd.Fstatfs(procHandle); err != nil {
47 return err
48 } else if statfs.Type != procSuperMagic {
49 return fmt.Errorf("%w: incorrect procfs root filesystem type 0x%x", errUnsafeProcfs, statfs.Type)
50 }
51 return nil
52 }
53
54 // verifyProcRoot verifies that the handle is the root of a procfs filesystem.
55 // Contrast this to [verifyProcHandle], which only verifies if the handle is
56 // some file on procfs (regardless of what file it is).
57 func verifyProcRoot(procRoot fd.Fd) error {
58 if err := verifyProcHandle(procRoot); err != nil {
59 return err
60 }
61 if stat, err := fd.Fstat(procRoot); err != nil {
62 return err
63 } else if stat.Ino != procRootIno {
64 return fmt.Errorf("%w: incorrect procfs root inode number %d", errUnsafeProcfs, stat.Ino)
65 }
66 return nil
67 }
68
69 type procfsFeatures struct {
70 // hasSubsetPid was added in Linux 5.8, along with hidepid=ptraceable (and
71 // string-based hidepid= values). Before this patchset, it was not really
72 // safe to try to modify procfs superblock flags because the superblock was
73 // shared -- so if this feature is not available, **you should not set any
74 // superblock flags**.
75 //
76 // 6814ef2d992a ("proc: add option to mount only a pids subset")
77 // fa10fed30f25 ("proc: allow to mount many instances of proc in one pid namespace")
78 // 24a71ce5c47f ("proc: instantiate only pids that we can ptrace on 'hidepid=4' mount option")
79 // 1c6c4d112e81 ("proc: use human-readable values for hidepid")
80 // 9ff7258575d5 ("Merge branch 'proc-linus' of git://git.kernel.org/pub/scm/linux/kernel/git/ebiederm/user-namespace")
81 hasSubsetPid bool
82 }
83
84 var getProcfsFeatures = gocompat.SyncOnceValue(func() procfsFeatures {
85 if !linux.HasNewMountAPI() {
86 return procfsFeatures{}
87 }
88 procfsCtx, err := fd.Fsopen("proc", unix.FSOPEN_CLOEXEC)
89 if err != nil {
90 return procfsFeatures{}
91 }
92 defer procfsCtx.Close() //nolint:errcheck // close failures aren't critical here
93
94 return procfsFeatures{
95 hasSubsetPid: unix.FsconfigSetString(int(procfsCtx.Fd()), "subset", "pid") == nil,
96 }
97 })
98
99 func newPrivateProcMount(subset bool) (_ *Handle, Err error) {
100 procfsCtx, err := fd.Fsopen("proc", unix.FSOPEN_CLOEXEC)
101 if err != nil {
102 return nil, err
103 }
104 defer procfsCtx.Close() //nolint:errcheck // close failures aren't critical here
105
106 if subset && getProcfsFeatures().hasSubsetPid {
107 // Try to configure hidepid=ptraceable,subset=pid if possible, but
108 // ignore errors.
109 _ = unix.FsconfigSetString(int(procfsCtx.Fd()), "hidepid", "ptraceable")
110 _ = unix.FsconfigSetString(int(procfsCtx.Fd()), "subset", "pid")
111 }
112
113 // Get an actual handle.
114 if err := unix.FsconfigCreate(int(procfsCtx.Fd())); err != nil {
115 return nil, os.NewSyscallError("fsconfig create procfs", err)
116 }
117 // TODO: Output any information from the fscontext log to debug logs.
118 procRoot, err := fd.Fsmount(procfsCtx, unix.FSMOUNT_CLOEXEC, unix.MS_NODEV|unix.MS_NOEXEC|unix.MS_NOSUID)
119 if err != nil {
120 return nil, err
121 }
122 defer func() {
123 if Err != nil {
124 _ = procRoot.Close()
125 }
126 }()
127 return newHandle(procRoot)
128 }
129
130 func clonePrivateProcMount() (_ *Handle, Err error) {
131 // Try to make a clone without using AT_RECURSIVE if we can. If this works,
132 // we can be sure there are no over-mounts and so if the root is valid then
133 // we're golden. Otherwise, we have to deal with over-mounts.
134 procRoot, err := fd.OpenTree(nil, "/proc", unix.OPEN_TREE_CLONE)
135 if err != nil || hookForcePrivateProcRootOpenTreeAtRecursive(procRoot) {
136 procRoot, err = fd.OpenTree(nil, "/proc", unix.OPEN_TREE_CLONE|unix.AT_RECURSIVE)
137 }
138 if err != nil {
139 return nil, fmt.Errorf("creating a detached procfs clone: %w", err)
140 }
141 defer func() {
142 if Err != nil {
143 _ = procRoot.Close()
144 }
145 }()
146 return newHandle(procRoot)
147 }
148
149 func privateProcRoot(subset bool) (*Handle, error) {
150 if !linux.HasNewMountAPI() || hookForceGetProcRootUnsafe() {
151 return nil, fmt.Errorf("new mount api: %w", unix.ENOTSUP)
152 }
153 // Try to create a new procfs mount from scratch if we can. This ensures we
154 // can get a procfs mount even if /proc is fake (for whatever reason).
155 procRoot, err := newPrivateProcMount(subset)
156 if err != nil || hookForcePrivateProcRootOpenTree(procRoot) {
157 // Try to clone /proc then...
158 procRoot, err = clonePrivateProcMount()
159 }
160 return procRoot, err
161 }
162
163 func unsafeHostProcRoot() (_ *Handle, Err error) {
164 procRoot, err := os.OpenFile("/proc", unix.O_PATH|unix.O_NOFOLLOW|unix.O_DIRECTORY|unix.O_CLOEXEC, 0)
165 if err != nil {
166 return nil, err
167 }
168 defer func() {
169 if Err != nil {
170 _ = procRoot.Close()
171 }
172 }()
173 return newHandle(procRoot)
174 }
175
176 // Handle is a wrapper around an *os.File handle to "/proc", which can be used
177 // to do further procfs-related operations in a safe way.
178 type Handle struct {
179 Inner fd.Fd
180 // Does this handle have subset=pid set?
181 isSubset bool
182 }
183
184 func newHandle(procRoot fd.Fd) (*Handle, error) {
185 if err := verifyProcRoot(procRoot); err != nil {
186 // This is only used in methods that
187 _ = procRoot.Close()
188 return nil, err
189 }
190 proc := &Handle{Inner: procRoot}
191 // With subset=pid we can be sure that /proc/uptime will not exist.
192 if err := fd.Faccessat(proc.Inner, "uptime", unix.F_OK, unix.AT_SYMLINK_NOFOLLOW); err != nil {
193 proc.isSubset = errors.Is(err, os.ErrNotExist)
194 }
195 return proc, nil
196 }
197
198 // Close closes the underlying file for the Handle.
199 func (proc *Handle) Close() error { return proc.Inner.Close() }
200
201 var getCachedProcRoot = gocompat.SyncOnceValue(func() *Handle {
202 procRoot, err := getProcRoot(true)
203 if err != nil {
204 return nil // just don't cache if we see an error
205 }
206 if !procRoot.isSubset {
207 return nil // we only cache verified subset=pid handles
208 }
209
210 // Disarm (*Handle).Close() to stop someone from accidentally closing
211 // the global handle.
212 procRoot.Inner = fd.NopCloser(procRoot.Inner)
213 return procRoot
214 })
215
216 // OpenProcRoot tries to open a "safer" handle to "/proc".
217 func OpenProcRoot() (*Handle, error) {
218 if proc := getCachedProcRoot(); proc != nil {
219 return proc, nil
220 }
221 return getProcRoot(true)
222 }
223
224 // OpenUnsafeProcRoot opens a handle to "/proc" without any overmounts or
225 // masked paths (but also without "subset=pid").
226 func OpenUnsafeProcRoot() (*Handle, error) { return getProcRoot(false) }
227
228 func getProcRoot(subset bool) (*Handle, error) {
229 proc, err := privateProcRoot(subset)
230 if err != nil {
231 // Fall back to using a /proc handle if making a private mount failed.
232 // If we have openat2, at least we can avoid some kinds of over-mount
233 // attacks, but without openat2 there's not much we can do.
234 proc, err = unsafeHostProcRoot()
235 }
236 return proc, err
237 }
238
239 var hasProcThreadSelf = gocompat.SyncOnceValue(func() bool {
240 return unix.Access("/proc/thread-self/", unix.F_OK) == nil
241 })
242
243 var errUnsafeProcfs = errors.New("unsafe procfs detected")
244
245 // lookup is a very minimal wrapper around [procfsLookupInRoot] which is
246 // intended to be called from the external API.
247 func (proc *Handle) lookup(subpath string) (*os.File, error) {
248 handle, err := procfsLookupInRoot(proc.Inner, subpath)
249 if err != nil {
250 return nil, err
251 }
252 return handle, nil
253 }
254
255 // procfsBase is an enum indicating the prefix of a subpath in operations
256 // involving [Handle]s.
257 type procfsBase string
258
259 const (
260 // ProcRoot refers to the root of the procfs (i.e., "/proc/<subpath>").
261 ProcRoot procfsBase = "/proc"
262 // ProcSelf refers to the current process' subdirectory (i.e.,
263 // "/proc/self/<subpath>").
264 ProcSelf procfsBase = "/proc/self"
265 // ProcThreadSelf refers to the current thread's subdirectory (i.e.,
266 // "/proc/thread-self/<subpath>"). In multi-threaded programs (i.e., all Go
267 // programs) where one thread has a different CLONE_FS, it is possible for
268 // "/proc/self" to point the wrong thread and so "/proc/thread-self" may be
269 // necessary. Note that on pre-3.17 kernels, "/proc/thread-self" doesn't
270 // exist and so a fallback will be used in that case.
271 ProcThreadSelf procfsBase = "/proc/thread-self"
272 // TODO: Switch to an interface setup so we can have a more type-safe
273 // version of ProcPid and remove the need to worry about invalid string
274 // values.
275 )
276
277 // prefix returns a prefix that can be used with the given [Handle].
278 func (base procfsBase) prefix(proc *Handle) (string, error) {
279 switch base {
280 case ProcRoot:
281 return ".", nil
282 case ProcSelf:
283 return "self", nil
284 case ProcThreadSelf:
285 threadSelf := "thread-self"
286 if !hasProcThreadSelf() || hookForceProcSelfTask() {
287 // Pre-3.17 kernels don't have /proc/thread-self, so do it
288 // manually.
289 threadSelf = "self/task/" + strconv.Itoa(unix.Gettid())
290 if err := fd.Faccessat(proc.Inner, threadSelf, unix.F_OK, unix.AT_SYMLINK_NOFOLLOW); err != nil || hookForceProcSelf() {
291 // In this case, we running in a pid namespace that doesn't
292 // match the /proc mount we have. This can happen inside runc.
293 //
294 // Unfortunately, there is no nice way to get the correct TID
295 // to use here because of the age of the kernel, so we have to
296 // just use /proc/self and hope that it works.
297 threadSelf = "self"
298 }
299 }
300 return threadSelf, nil
301 }
302 return "", fmt.Errorf("invalid procfs base %q", base)
303 }
304
305 // ProcThreadSelfCloser is a callback that needs to be called when you are done
306 // operating on an [os.File] fetched using [ProcThreadSelf].
307 //
308 // [os.File]: https://pkg.go.dev/os#File
309 type ProcThreadSelfCloser func()
310
311 // open is the core lookup operation for [Handle]. It returns a handle to
312 // "/proc/<base>/<subpath>". If the returned [ProcThreadSelfCloser] is non-nil,
313 // you should call it after you are done interacting with the returned handle.
314 //
315 // In general you should use prefer to use the other helpers, as they remove
316 // the need to interact with [procfsBase] and do not return a nil
317 // [ProcThreadSelfCloser] for [procfsBase] values other than [ProcThreadSelf]
318 // where it is necessary.
319 func (proc *Handle) open(base procfsBase, subpath string) (_ *os.File, closer ProcThreadSelfCloser, Err error) {
320 prefix, err := base.prefix(proc)
321 if err != nil {
322 return nil, nil, err
323 }
324 subpath = prefix + "/" + subpath
325
326 switch base {
327 case ProcRoot:
328 file, err := proc.lookup(subpath)
329 if errors.Is(err, os.ErrNotExist) {
330 // The Handle handle in use might be a subset=pid one, which will
331 // result in spurious errors. In this case, just open a temporary
332 // unmasked procfs handle for this operation.
333 proc, err2 := OpenUnsafeProcRoot() // !subset=pid
334 if err2 != nil {
335 return nil, nil, err
336 }
337 defer proc.Close() //nolint:errcheck // close failures aren't critical here
338
339 file, err = proc.lookup(subpath)
340 }
341 return file, nil, err
342
343 case ProcSelf:
344 file, err := proc.lookup(subpath)
345 return file, nil, err
346
347 case ProcThreadSelf:
348 // We need to lock our thread until the caller is done with the handle
349 // because between getting the handle and using it we could get
350 // interrupted by the Go runtime and hit the case where the underlying
351 // thread is swapped out and the original thread is killed, resulting
352 // in pull-your-hair-out-hard-to-debug issues in the caller.
353 runtime.LockOSThread()
354 defer func() {
355 if Err != nil {
356 runtime.UnlockOSThread()
357 closer = nil
358 }
359 }()
360
361 file, err := proc.lookup(subpath)
362 return file, runtime.UnlockOSThread, err
363 }
364 // should never be reached
365 return nil, nil, fmt.Errorf("[internal error] invalid procfs base %q", base)
366 }
367
368 // OpenThreadSelf returns a handle to "/proc/thread-self/<subpath>" (or an
369 // equivalent handle on older kernels where "/proc/thread-self" doesn't exist).
370 // Once finished with the handle, you must call the returned closer function
371 // (runtime.UnlockOSThread). You must not pass the returned *os.File to other
372 // Go threads or use the handle after calling the closer.
373 func (proc *Handle) OpenThreadSelf(subpath string) (_ *os.File, _ ProcThreadSelfCloser, Err error) {
374 return proc.open(ProcThreadSelf, subpath)
375 }
376
377 // OpenSelf returns a handle to /proc/self/<subpath>.
378 func (proc *Handle) OpenSelf(subpath string) (*os.File, error) {
379 file, closer, err := proc.open(ProcSelf, subpath)
380 assert.Assert(closer == nil, "closer for ProcSelf must be nil")
381 return file, err
382 }
383
384 // OpenRoot returns a handle to /proc/<subpath>.
385 func (proc *Handle) OpenRoot(subpath string) (*os.File, error) {
386 file, closer, err := proc.open(ProcRoot, subpath)
387 assert.Assert(closer == nil, "closer for ProcRoot must be nil")
388 return file, err
389 }
390
391 // OpenPid returns a handle to /proc/$pid/<subpath> (pid can be a pid or tid).
392 // This is mainly intended for usage when operating on other processes.
393 func (proc *Handle) OpenPid(pid int, subpath string) (*os.File, error) {
394 return proc.OpenRoot(strconv.Itoa(pid) + "/" + subpath)
395 }
396
397 // checkSubpathOvermount checks if the dirfd and path combination is on the
398 // same mount as the given root.
399 func checkSubpathOvermount(root, dir fd.Fd, path string) error {
400 // Get the mntID of our procfs handle.
401 expectedMountID, err := fd.GetMountID(root, "")
402 if err != nil {
403 return fmt.Errorf("get root mount id: %w", err)
404 }
405 // Get the mntID of the target magic-link.
406 gotMountID, err := fd.GetMountID(dir, path)
407 if err != nil {
408 return fmt.Errorf("get subpath mount id: %w", err)
409 }
410 // As long as the directory mount is alive, even with wrapping mount IDs,
411 // we would expect to see a different mount ID here. (Of course, if we're
412 // using unsafeHostProcRoot() then an attaker could change this after we
413 // did this check.)
414 if expectedMountID != gotMountID {
415 return fmt.Errorf("%w: subpath %s/%s has an overmount obscuring the real path (mount ids do not match %d != %d)",
416 errUnsafeProcfs, dir.Name(), path, expectedMountID, gotMountID)
417 }
418 return nil
419 }
420
421 // Readlink performs a readlink operation on "/proc/<base>/<subpath>" in a way
422 // that should be free from race attacks. This is most commonly used to get the
423 // real path of a file by looking at "/proc/self/fd/$n", with the same safety
424 // protections as [Open] (as well as some additional checks against
425 // overmounts).
426 func (proc *Handle) Readlink(base procfsBase, subpath string) (string, error) {
427 link, closer, err := proc.open(base, subpath)
428 if closer != nil {
429 defer closer()
430 }
431 if err != nil {
432 return "", fmt.Errorf("get safe %s/%s handle: %w", base, subpath, err)
433 }
434 defer link.Close() //nolint:errcheck // close failures aren't critical here
435
436 // Try to detect if there is a mount on top of the magic-link. This should
437 // be safe in general (a mount on top of the path afterwards would not
438 // affect the handle itself) and will definitely be safe if we are using
439 // privateProcRoot() (at least since Linux 5.12[1], when anonymous mount
440 // namespaces were completely isolated from external mounts including mount
441 // propagation events).
442 //
443 // [1]: Linux commit ee2e3f50629f ("mount: fix mounting of detached mounts
444 // onto targets that reside on shared mounts").
445 if err := checkSubpathOvermount(proc.Inner, link, ""); err != nil {
446 return "", fmt.Errorf("check safety of %s/%s magiclink: %w", base, subpath, err)
447 }
448
449 // readlinkat implies AT_EMPTY_PATH since Linux 2.6.39. See Linux commit
450 // 65cfc6722361 ("readlinkat(), fchownat() and fstatat() with empty
451 // relative pathnames").
452 return fd.Readlinkat(link, "")
453 }
454
455 // ProcSelfFdReadlink gets the real path of the given file by looking at
456 // readlink(/proc/thread-self/fd/$n).
457 //
458 // This is just a wrapper around [Handle.Readlink].
459 func ProcSelfFdReadlink(fd fd.Fd) (string, error) {
460 procRoot, err := OpenProcRoot() // subset=pid
461 if err != nil {
462 return "", err
463 }
464 defer procRoot.Close() //nolint:errcheck // close failures aren't critical here
465
466 fdPath := "fd/" + strconv.Itoa(int(fd.Fd()))
467 return procRoot.Readlink(ProcThreadSelf, fdPath)
468 }
469
470 // CheckProcSelfFdPath returns whether the given file handle matches the
471 // expected path. (This is inherently racy.)
472 func CheckProcSelfFdPath(path string, file fd.Fd) error {
473 if err := fd.IsDeadInode(file); err != nil {
474 return err
475 }
476 actualPath, err := ProcSelfFdReadlink(file)
477 if err != nil {
478 return fmt.Errorf("get path of handle: %w", err)
479 }
480 if actualPath != path {
481 return fmt.Errorf("%w: handle path %q doesn't match expected path %q", internal.ErrPossibleBreakout, actualPath, path)
482 }
483 return nil
484 }
485
486 // ReopenFd takes an existing file descriptor and "re-opens" it through
487 // /proc/thread-self/fd/<fd>. This allows for O_PATH file descriptors to be
488 // upgraded to regular file descriptors, as well as changing the open mode of a
489 // regular file descriptor. Some filesystems have unique handling of open(2)
490 // which make this incredibly useful (such as /dev/ptmx).
491 func ReopenFd(handle fd.Fd, flags int) (*os.File, error) {
492 procRoot, err := OpenProcRoot() // subset=pid
493 if err != nil {
494 return nil, err
495 }
496 defer procRoot.Close() //nolint:errcheck // close failures aren't critical here
497
498 // We can't operate on /proc/thread-self/fd/$n directly when doing a
499 // re-open, so we need to open /proc/thread-self/fd and then open a single
500 // final component.
501 procFdDir, closer, err := procRoot.OpenThreadSelf("fd/")
502 if err != nil {
503 return nil, fmt.Errorf("get safe /proc/thread-self/fd handle: %w", err)
504 }
505 defer procFdDir.Close() //nolint:errcheck // close failures aren't critical here
506 defer closer()
507
508 // Try to detect if there is a mount on top of the magic-link we are about
509 // to open. If we are using unsafeHostProcRoot(), this could change after
510 // we check it (and there's nothing we can do about that) but for
511 // privateProcRoot() this should be guaranteed to be safe (at least since
512 // Linux 5.12[1], when anonymous mount namespaces were completely isolated
513 // from external mounts including mount propagation events).
514 //
515 // [1]: Linux commit ee2e3f50629f ("mount: fix mounting of detached mounts
516 // onto targets that reside on shared mounts").
517 fdStr := strconv.Itoa(int(handle.Fd()))
518 if err := checkSubpathOvermount(procRoot.Inner, procFdDir, fdStr); err != nil {
519 return nil, fmt.Errorf("check safety of /proc/thread-self/fd/%s magiclink: %w", fdStr, err)
520 }
521
522 flags |= unix.O_CLOEXEC
523 // Rather than just wrapping fd.Openat, open-code it so we can copy
524 // handle.Name().
525 reopenFd, err := unix.Openat(int(procFdDir.Fd()), fdStr, flags, 0)
526 if err != nil {
527 return nil, fmt.Errorf("reopen fd %d: %w", handle.Fd(), err)
528 }
529 return os.NewFile(uintptr(reopenFd), handle.Name()), nil
530 }
531
532 // Test hooks used in the procfs tests to verify that the fallback logic works.
533 // See testing_mocks_linux_test.go and procfs_linux_test.go for more details.
534 var (
535 hookForcePrivateProcRootOpenTree = hookDummyFile
536 hookForcePrivateProcRootOpenTreeAtRecursive = hookDummyFile
537 hookForceGetProcRootUnsafe = hookDummy
538
539 hookForceProcSelfTask = hookDummy
540 hookForceProcSelf = hookDummy
541 )
542
543 func hookDummy() bool { return false }
544 func hookDummyFile(_ io.Closer) bool { return false }