Debian Codegraph @

pathrs-lite/internal/procfs/procfs_lookup_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 // This code is adapted to be a minimal version of the libpathrs proc resolver
13 // <https://github.com/opensuse/libpathrs/blob/v0.1.3/src/resolvers/procfs.rs>.
14 // As we only need O_PATH|O_NOFOLLOW support, this is not too much to port.
15
16 package procfs
17
18 import (
19 "fmt"
20 "os"
21 "path"
22 "path/filepath"
23 "strings"
24
25 "golang.org/x/sys/unix"
26
27 "github.com/cyphar/filepath-securejoin/internal/consts"
28 "github.com/cyphar/filepath-securejoin/pathrs-lite/internal"
29 "github.com/cyphar/filepath-securejoin/pathrs-lite/internal/fd"
30 "github.com/cyphar/filepath-securejoin/pathrs-lite/internal/gocompat"
31 "github.com/cyphar/filepath-securejoin/pathrs-lite/internal/linux"
32 )
33
34 // procfsLookupInRoot is a stripped down version of completeLookupInRoot,
35 // entirely designed to support the very small set of features necessary to
36 // make procfs handling work. Unlike completeLookupInRoot, we always have
37 // O_PATH|O_NOFOLLOW behaviour for trailing symlinks.
38 //
39 // The main restrictions are:
40 //
41 // - ".." is not supported (as it requires either os.Root-style replays,
42 // which is more bug-prone; or procfs verification, which is not possible
43 // due to re-entrancy issues).
44 // - Absolute symlinks for the same reason (and all absolute symlinks in
45 // procfs are magic-links, which we want to skip anyway).
46 // - If statx is supported (checkSymlinkOvermount), any mount-point crossings
47 // (which is the main attack of concern against /proc).
48 // - Partial lookups are not supported, so the symlink stack is not needed.
49 // - Trailing slash special handling is not necessary in most cases (if we
50 // operating on procfs, it's usually with programmer-controlled strings
51 // that will then be re-opened), so we skip it since whatever re-opens it
52 // can deal with it. It's a creature comfort anyway.
53 //
54 // If the system supports openat2(), this is implemented using equivalent flags
55 // (RESOLVE_BENEATH | RESOLVE_NO_XDEV | RESOLVE_NO_MAGICLINKS).
56 func procfsLookupInRoot(procRoot fd.Fd, unsafePath string) (Handle *os.File, _ error) {
57 unsafePath = filepath.ToSlash(unsafePath) // noop
58
59 // Make sure that an empty unsafe path still returns something sane, even
60 // with openat2 (which doesn't have AT_EMPTY_PATH semantics yet).
61 if unsafePath == "" {
62 unsafePath = "."
63 }
64
65 // This is already checked by getProcRoot, but make sure here since the
66 // core security of this lookup is based on this assumption.
67 if err := verifyProcRoot(procRoot); err != nil {
68 return nil, err
69 }
70
71 if linux.HasOpenat2() {
72 // We prefer being able to use RESOLVE_NO_XDEV if we can, to be
73 // absolutely sure we are operating on a clean /proc handle that
74 // doesn't have any cheeky overmounts that could trick us (including
75 // symlink mounts on top of /proc/thread-self). RESOLVE_BENEATH isn't
76 // strictly needed, but just use it since we have it.
77 //
78 // NOTE: /proc/self is technically a magic-link (the contents of the
79 // symlink are generated dynamically), but it doesn't use
80 // nd_jump_link() so RESOLVE_NO_MAGICLINKS allows it.
81 //
82 // TODO: It would be nice to have RESOLVE_NO_DOTDOT, purely for
83 // self-consistency with the backup O_PATH resolver.
84 handle, err := fd.Openat2(procRoot, unsafePath, &unix.OpenHow{
85 Flags: unix.O_PATH | unix.O_NOFOLLOW | unix.O_CLOEXEC,
86 Resolve: unix.RESOLVE_BENEATH | unix.RESOLVE_NO_XDEV | unix.RESOLVE_NO_MAGICLINKS,
87 })
88 if err != nil {
89 // TODO: Once we bump the minimum Go version to 1.20, we can use
90 // multiple %w verbs for this wrapping. For now we need to use a
91 // compatibility shim for older Go versions.
92 // err = fmt.Errorf("%w: %w", errUnsafeProcfs, err)
93 return nil, gocompat.WrapBaseError(err, errUnsafeProcfs)
94 }
95 return handle, nil
96 }
97
98 // To mirror openat2(RESOLVE_BENEATH), we need to return an error if the
99 // path is absolute.
100 if path.IsAbs(unsafePath) {
101 return nil, fmt.Errorf("%w: cannot resolve absolute paths in procfs resolver", internal.ErrPossibleBreakout)
102 }
103
104 currentDir, err := fd.Dup(procRoot)
105 if err != nil {
106 return nil, fmt.Errorf("clone root fd: %w", err)
107 }
108 defer func() {
109 // If a handle is not returned, close the internal handle.
110 if Handle == nil {
111 _ = currentDir.Close()
112 }
113 }()
114
115 var (
116 linksWalked int
117 currentPath string
118 remainingPath = unsafePath
119 )
120 for remainingPath != "" {
121 // Get the next path component.
122 var part string
123 if i := strings.IndexByte(remainingPath, '/'); i == -1 {
124 part, remainingPath = remainingPath, ""
125 } else {
126 part, remainingPath = remainingPath[:i], remainingPath[i+1:]
127 }
128 if part == "" {
129 // no-op component, but treat it the same as "."
130 part = "."
131 }
132 if part == ".." {
133 // not permitted
134 return nil, fmt.Errorf("%w: cannot walk into '..' in procfs resolver", internal.ErrPossibleBreakout)
135 }
136
137 // Apply the component lexically to the path we are building.
138 // currentPath does not contain any symlinks, and we are lexically
139 // dealing with a single component, so it's okay to do a filepath.Clean
140 // here. (Not to mention that ".." isn't allowed.)
141 nextPath := path.Join("/", currentPath, part)
142 // If we logically hit the root, just clone the root rather than
143 // opening the part and doing all of the other checks.
144 if nextPath == "/" {
145 // Jump to root.
146 rootClone, err := fd.Dup(procRoot)
147 if err != nil {
148 return nil, fmt.Errorf("clone root fd: %w", err)
149 }
150 _ = currentDir.Close()
151 currentDir = rootClone
152 currentPath = nextPath
153 continue
154 }
155
156 // Try to open the next component.
157 nextDir, err := fd.Openat(currentDir, part, unix.O_PATH|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0)
158 if err != nil {
159 return nil, err
160 }
161
162 // Make sure we are still on procfs and haven't crossed mounts.
163 if err := verifyProcHandle(nextDir); err != nil {
164 _ = nextDir.Close()
165 return nil, fmt.Errorf("check %q component is on procfs: %w", part, err)
166 }
167 if err := checkSubpathOvermount(procRoot, nextDir, ""); err != nil {
168 _ = nextDir.Close()
169 return nil, fmt.Errorf("check %q component is not overmounted: %w", part, err)
170 }
171
172 // We are emulating O_PATH|O_NOFOLLOW, so we only need to traverse into
173 // trailing symlinks if we are not the final component. Otherwise we
174 // can just return the currentDir.
175 if remainingPath != "" {
176 st, err := nextDir.Stat()
177 if err != nil {
178 _ = nextDir.Close()
179 return nil, fmt.Errorf("stat component %q: %w", part, err)
180 }
181
182 if st.Mode()&os.ModeType == os.ModeSymlink {
183 // readlinkat implies AT_EMPTY_PATH since Linux 2.6.39. See
184 // Linux commit 65cfc6722361 ("readlinkat(), fchownat() and
185 // fstatat() with empty relative pathnames").
186 linkDest, err := fd.Readlinkat(nextDir, "")
187 // We don't need the handle anymore.
188 _ = nextDir.Close()
189 if err != nil {
190 return nil, err
191 }
192
193 linksWalked++
194 if linksWalked > consts.MaxSymlinkLimit {
195 return nil, &os.PathError{Op: "securejoin.procfsLookupInRoot", Path: "/proc/" + unsafePath, Err: unix.ELOOP}
196 }
197
198 // Update our logical remaining path.
199 remainingPath = linkDest + "/" + remainingPath
200 // Absolute symlinks are probably magiclinks, we reject them.
201 if path.IsAbs(linkDest) {
202 return nil, fmt.Errorf("%w: cannot jump to / in procfs resolver -- possible magiclink", internal.ErrPossibleBreakout)
203 }
204 continue
205 }
206 }
207
208 // Walk into the next component.
209 _ = currentDir.Close()
210 currentDir = nextDir
211 currentPath = nextPath
212 }
213
214 // One final sanity-check.
215 if err := verifyProcHandle(currentDir); err != nil {
216 return nil, fmt.Errorf("check final handle is on procfs: %w", err)
217 }
218 if err := checkSubpathOvermount(procRoot, currentDir, ""); err != nil {
219 return nil, fmt.Errorf("check final handle is not overmounted: %w", err)
220 }
221 return currentDir, nil
222 }