| 1 | //go:build linux |
| 2 | |
| 3 | // SPDX-License-Identifier: MPL-2.0 |
| 4 | /* |
| 5 | * libpathrs: safe path resolution on Linux |
| 6 | * Copyright (C) 2019-2025 SUSE LLC |
| 7 | * Copyright (C) 2026 Aleksa Sarai <[email protected]> |
| 8 | * |
| 9 | * This Source Code Form is subject to the terms of the Mozilla Public |
| 10 | * License, v. 2.0. If a copy of the MPL was not distributed with this |
| 11 | * file, You can obtain one at https://mozilla.org/MPL/2.0/. |
| 12 | */ |
| 13 | |
| 14 | // Package procfs provides a safe API for operating on /proc on Linux. |
| 15 | package procfs |
| 16 | |
| 17 | import ( |
| 18 | "os" |
| 19 | "runtime" |
| 20 | |
| 21 | "cyphar.com/go-pathrs/internal/fdutils" |
| 22 | "cyphar.com/go-pathrs/internal/libpathrs" |
| 23 | ) |
| 24 | |
| 25 | // ProcBase is used with [ProcReadlink] and related functions to indicate what |
| 26 | // /proc subpath path operations should be done relative to. |
| 27 | type ProcBase struct { |
| 28 | inner libpathrs.ProcBase |
| 29 | } |
| 30 | |
| 31 | var ( |
| 32 | // ProcRoot indicates to use /proc. Note that this mode may be more |
| 33 | // expensive because we have to take steps to try to avoid leaking unmasked |
| 34 | // procfs handles, so you should use [ProcBaseSelf] if you can. |
| 35 | ProcRoot = ProcBase{inner: libpathrs.ProcRoot} |
| 36 | // ProcSelf indicates to use /proc/self. For most programs, this is the |
| 37 | // standard choice. |
| 38 | ProcSelf = ProcBase{inner: libpathrs.ProcSelf} |
| 39 | // ProcThreadSelf indicates to use /proc/thread-self. In multi-threaded |
| 40 | // programs where one thread has a different CLONE_FS, it is possible for |
| 41 | // /proc/self to point the wrong thread and so /proc/thread-self may be |
| 42 | // necessary. |
| 43 | ProcThreadSelf = ProcBase{inner: libpathrs.ProcThreadSelf} |
| 44 | ) |
| 45 | |
| 46 | // ProcPid returns a ProcBase which indicates to use /proc/$pid for the given |
| 47 | // PID (or TID). Be aware that due to PID recycling, using this is generally |
| 48 | // not safe except in certain circumstances. Namely: |
| 49 | // |
| 50 | // - PID 1 (the init process), as that PID cannot ever get recycled. |
| 51 | // - Your current PID (though you should just use [ProcBaseSelf]). |
| 52 | // - Your current TID if you have used [runtime.LockOSThread] (though you |
| 53 | // should just use [ProcBaseThreadSelf]). |
| 54 | // - PIDs of child processes (as long as you are sure that no other part of |
| 55 | // your program incorrectly catches or ignores SIGCHLD, and that you do it |
| 56 | // *before* you call wait(2)or any equivalent method that could reap |
| 57 | // zombies). |
| 58 | func ProcPid(pid int) ProcBase { |
| 59 | if pid < 0 || uint64(pid) >= 1<<31 { |
| 60 | panic("invalid ProcBasePid value") // TODO: should this be an error? |
| 61 | } |
| 62 | pid32 := uint32(pid) //nolint:gosec // G115 false positive <https://github.com/securego/gosec/issues/1212> |
| 63 | return ProcBase{inner: libpathrs.ProcPid(pid32)} |
| 64 | } |
| 65 | |
| 66 | // ThreadCloser is a callback that needs to be called when you are done |
| 67 | // operating on an [os.File] fetched using [Handle.OpenThreadSelf]. |
| 68 | type ThreadCloser func() |
| 69 | |
| 70 | // Handle is a wrapper around an *os.File handle to "/proc", which can be |
| 71 | // used to do further procfs-related operations in a safe way. |
| 72 | type Handle struct { |
| 73 | inner *os.File |
| 74 | } |
| 75 | |
| 76 | // Close releases all internal resources for this [Handle]. |
| 77 | // |
| 78 | // Note that if the handle is actually the global cached handle, this operation |
| 79 | // is a no-op. |
| 80 | func (proc *Handle) Close() error { |
| 81 | var err error |
| 82 | if proc.inner != nil { |
| 83 | err = proc.inner.Close() |
| 84 | } |
| 85 | return err |
| 86 | } |
| 87 | |
| 88 | // OpenOption is a configuration function passed as an argument to [Open]. |
| 89 | type OpenOption func(*libpathrs.ProcfsOpenHow) error |
| 90 | |
| 91 | // UnmaskedProcRoot can be passed to [Open] to request an unmasked procfs |
| 92 | // handle be created. |
| 93 | // |
| 94 | // procfs, err := procfs.OpenRoot(procfs.UnmaskedProcRoot) |
| 95 | func UnmaskedProcRoot(how *libpathrs.ProcfsOpenHow) error { |
| 96 | *how.Flags() |= libpathrs.ProcfsNewUnmasked |
| 97 | return nil |
| 98 | } |
| 99 | |
| 100 | // Open creates a new [Handle] to a safe "/proc", based on the passed |
| 101 | // configuration options (in the form of a series of [OpenOption]s). |
| 102 | func Open(opts ...OpenOption) (*Handle, error) { |
| 103 | var how libpathrs.ProcfsOpenHow |
| 104 | for _, opt := range opts { |
| 105 | if err := opt(&how); err != nil { |
| 106 | return nil, err |
| 107 | } |
| 108 | } |
| 109 | fd, err := libpathrs.ProcfsOpen(&how) |
| 110 | if err != nil { |
| 111 | return nil, err |
| 112 | } |
| 113 | var procFile *os.File |
| 114 | if int(fd) >= 0 { |
| 115 | procFile = os.NewFile(fd, "/proc") |
| 116 | } |
| 117 | // TODO: Check that fd == PATHRS_PROC_DEFAULT_ROOTFD in the <0 case? |
| 118 | return &Handle{inner: procFile}, nil |
| 119 | } |
| 120 | |
| 121 | // TODO: Switch to something fdutils.WithFileFd-like. |
| 122 | func (proc *Handle) fd() int { |
| 123 | if proc.inner != nil { |
| 124 | return int(proc.inner.Fd()) |
| 125 | } |
| 126 | return libpathrs.ProcDefaultRootFd |
| 127 | } |
| 128 | |
| 129 | // TODO: Should we expose open? |
| 130 | func (proc *Handle) open(base ProcBase, path string, flags uint64) (_ *os.File, Closer ThreadCloser, Err error) { |
| 131 | var closer ThreadCloser |
| 132 | if base == ProcThreadSelf { |
| 133 | runtime.LockOSThread() |
| 134 | closer = runtime.UnlockOSThread |
| 135 | } |
| 136 | defer func() { |
| 137 | if closer != nil && Err != nil { |
| 138 | closer() |
| 139 | Closer = nil |
| 140 | } |
| 141 | }() |
| 142 | |
| 143 | fd, err := libpathrs.ProcOpenat(proc.fd(), base.inner, path, flags) |
| 144 | if err != nil { |
| 145 | return nil, nil, err |
| 146 | } |
| 147 | file, err := fdutils.MkFile(fd) |
| 148 | return file, closer, err |
| 149 | } |
| 150 | |
| 151 | // OpenRoot safely opens a given path from inside /proc/. |
| 152 | // |
| 153 | // This function must only be used for accessing global information from procfs |
| 154 | // (such as /proc/cpuinfo) or information about other processes (such as |
| 155 | // /proc/1). Accessing your own process information should be done using |
| 156 | // [Handle.OpenSelf] or [Handle.OpenThreadSelf]. |
| 157 | func (proc *Handle) OpenRoot(path string, flags uint64) (*os.File, error) { |
| 158 | file, closer, err := proc.open(ProcRoot, path, flags) |
| 159 | if closer != nil { |
| 160 | // should not happen |
| 161 | panic("non-zero closer returned from procOpen(ProcRoot)") |
| 162 | } |
| 163 | return file, err |
| 164 | } |
| 165 | |
| 166 | // OpenSelf safely opens a given path from inside /proc/self/. |
| 167 | // |
| 168 | // This method is recommend for getting process information about the current |
| 169 | // process for almost all Go processes *except* for cases where there are |
| 170 | // [runtime.LockOSThread] threads that have changed some aspect of their state |
| 171 | // (such as through unshare(CLONE_FS) or changing namespaces). |
| 172 | // |
| 173 | // For such non-heterogeneous processes, /proc/self may reference to a task |
| 174 | // that has different state from the current goroutine and so it may be |
| 175 | // preferable to use [Handle.OpenThreadSelf]. The same is true if a user |
| 176 | // really wants to inspect the current OS thread's information (such as |
| 177 | // /proc/thread-self/stack or /proc/thread-self/status which is always uniquely |
| 178 | // per-thread). |
| 179 | // |
| 180 | // Unlike [Handle.OpenThreadSelf], this method does not involve locking |
| 181 | // the goroutine to the current OS thread and so is simpler to use and |
| 182 | // theoretically has slightly less overhead. |
| 183 | func (proc *Handle) OpenSelf(path string, flags uint64) (*os.File, error) { |
| 184 | file, closer, err := proc.open(ProcSelf, path, flags) |
| 185 | if closer != nil { |
| 186 | // should not happen |
| 187 | panic("non-zero closer returned from procOpen(ProcSelf)") |
| 188 | } |
| 189 | return file, err |
| 190 | } |
| 191 | |
| 192 | // OpenPid safely opens a given path from inside /proc/$pid/, where pid can be |
| 193 | // either a PID or TID. |
| 194 | // |
| 195 | // This is effectively equivalent to calling [Handle.OpenRoot] with the |
| 196 | // pid prefixed to the subpath. |
| 197 | // |
| 198 | // Be aware that due to PID recycling, using this is generally not safe except |
| 199 | // in certain circumstances. See the documentation of [ProcPid] for more |
| 200 | // details. |
| 201 | func (proc *Handle) OpenPid(pid int, path string, flags uint64) (*os.File, error) { |
| 202 | file, closer, err := proc.open(ProcPid(pid), path, flags) |
| 203 | if closer != nil { |
| 204 | // should not happen |
| 205 | panic("non-zero closer returned from procOpen(ProcPidOpen)") |
| 206 | } |
| 207 | return file, err |
| 208 | } |
| 209 | |
| 210 | // OpenThreadSelf safely opens a given path from inside /proc/thread-self/. |
| 211 | // |
| 212 | // Most Go processes have heterogeneous threads (all threads have most of the |
| 213 | // same kernel state such as CLONE_FS) and so [Handle.OpenSelf] is |
| 214 | // preferable for most users. |
| 215 | // |
| 216 | // For non-heterogeneous threads, or users that actually want thread-specific |
| 217 | // information (such as /proc/thread-self/stack or /proc/thread-self/status), |
| 218 | // this method is necessary. |
| 219 | // |
| 220 | // Because Go can change the running OS thread of your goroutine without notice |
| 221 | // (and then subsequently kill the old thread), this method will lock the |
| 222 | // current goroutine to the OS thread (with [runtime.LockOSThread]) and the |
| 223 | // caller is responsible for unlocking the the OS thread with the |
| 224 | // [ThreadCloser] callback once they are done using the returned file. This |
| 225 | // callback MUST be called AFTER you have finished using the returned |
| 226 | // [os.File]. This callback is completely separate to [os.File.Close], so it |
| 227 | // must be called regardless of how you close the handle. |
| 228 | func (proc *Handle) OpenThreadSelf(path string, flags uint64) (*os.File, ThreadCloser, error) { |
| 229 | return proc.open(ProcThreadSelf, path, flags) |
| 230 | } |
| 231 | |
| 232 | // Readlink safely reads the contents of a symlink from the given procfs base. |
| 233 | // |
| 234 | // This is effectively equivalent to doing an Open*(O_PATH|O_NOFOLLOW) of the |
| 235 | // path and then doing unix.Readlinkat(fd, ""), but with the benefit that |
| 236 | // thread locking is not necessary for [ProcThreadSelf]. |
| 237 | func (proc *Handle) Readlink(base ProcBase, path string) (string, error) { |
| 238 | return libpathrs.ProcReadlinkat(proc.fd(), base.inner, path) |
| 239 | } |