| 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 pathrs |
| 13 |
|
| 14 |
import ( |
| 15 |
"errors" |
| 16 |
"fmt" |
| 17 |
"os" |
| 18 |
"path" |
| 19 |
"path/filepath" |
| 20 |
"strings" |
| 21 |
|
| 22 |
"golang.org/x/sys/unix" |
| 23 |
|
| 24 |
"github.com/cyphar/filepath-securejoin/internal/consts" |
| 25 |
"github.com/cyphar/filepath-securejoin/pathrs-lite/internal/fd" |
| 26 |
"github.com/cyphar/filepath-securejoin/pathrs-lite/internal/gocompat" |
| 27 |
"github.com/cyphar/filepath-securejoin/pathrs-lite/internal/linux" |
| 28 |
"github.com/cyphar/filepath-securejoin/pathrs-lite/internal/procfs" |
| 29 |
) |
| 30 |
|
| 31 |
type symlinkStackEntry struct { |
| 32 |
// (dir, remainingPath) is what we would've returned if the link didn't |
| 33 |
// exist. This matches what openat2(RESOLVE_IN_ROOT) would return in |
| 34 |
// this case. |
| 35 |
dir *os.File |
| 36 |
remainingPath string |
| 37 |
// linkUnwalked is the remaining path components from the original |
| 38 |
// Readlink which we have yet to walk. When this slice is empty, we |
| 39 |
// drop the link from the stack. |
| 40 |
linkUnwalked []string |
| 41 |
} |
| 42 |
|
| 43 |
func (se symlinkStackEntry) String() string { |
| 44 |
return fmt.Sprintf("<%s>/%s [->%s]", se.dir.Name(), se.remainingPath, strings.Join(se.linkUnwalked, "/")) |
| 45 |
} |
| 46 |
|
| 47 |
func (se symlinkStackEntry) Close() { |
| 48 |
_ = se.dir.Close() |
| 49 |
} |
| 50 |
|
| 51 |
type symlinkStack []*symlinkStackEntry |
| 52 |
|
| 53 |
func (s *symlinkStack) IsEmpty() bool { |
| 54 |
return s == nil || len(*s) == 0 |
| 55 |
} |
| 56 |
|
| 57 |
func (s *symlinkStack) Close() { |
| 58 |
if s != nil { |
| 59 |
for _, link := range *s { |
| 60 |
link.Close() |
| 61 |
} |
| 62 |
// TODO: Switch to clear once we switch to Go 1.21. |
| 63 |
*s = nil |
| 64 |
} |
| 65 |
} |
| 66 |
|
| 67 |
var ( |
| 68 |
errEmptyStack = errors.New("[internal] stack is empty") |
| 69 |
errBrokenSymlinkStack = errors.New("[internal error] broken symlink stack") |
| 70 |
) |
| 71 |
|
| 72 |
func (s *symlinkStack) popPart(part string) error { |
| 73 |
if s == nil || s.IsEmpty() { |
| 74 |
// If there is nothing in the symlink stack, then the part was from the |
| 75 |
// real path provided by the user, and this is a no-op. |
| 76 |
return errEmptyStack |
| 77 |
} |
| 78 |
if part == "." { |
| 79 |
// "." components are no-ops -- we drop them when doing SwapLink. |
| 80 |
return nil |
| 81 |
} |
| 82 |
|
| 83 |
tailEntry := (*s)[len(*s)-1] |
| 84 |
|
| 85 |
// Double-check that we are popping the component we expect. |
| 86 |
if len(tailEntry.linkUnwalked) == 0 { |
| 87 |
return fmt.Errorf("%w: trying to pop component %q of empty stack entry %s", errBrokenSymlinkStack, part, tailEntry) |
| 88 |
} |
| 89 |
headPart := tailEntry.linkUnwalked[0] |
| 90 |
if headPart != part { |
| 91 |
return fmt.Errorf("%w: trying to pop component %q but the last stack entry is %s (%q)", errBrokenSymlinkStack, part, tailEntry, headPart) |
| 92 |
} |
| 93 |
|
| 94 |
// Drop the component, but keep the entry around in case we are dealing |
| 95 |
// with a "tail-chained" symlink. |
| 96 |
tailEntry.linkUnwalked = tailEntry.linkUnwalked[1:] |
| 97 |
return nil |
| 98 |
} |
| 99 |
|
| 100 |
func (s *symlinkStack) PopPart(part string) error { |
| 101 |
if err := s.popPart(part); err != nil { |
| 102 |
if errors.Is(err, errEmptyStack) { |
| 103 |
// Skip empty stacks. |
| 104 |
err = nil |
| 105 |
} |
| 106 |
return err |
| 107 |
} |
| 108 |
|
| 109 |
// Clean up any of the trailing stack entries that are empty. |
| 110 |
for lastGood := len(*s) - 1; lastGood >= 0; lastGood-- { |
| 111 |
entry := (*s)[lastGood] |
| 112 |
if len(entry.linkUnwalked) > 0 { |
| 113 |
break |
| 114 |
} |
| 115 |
entry.Close() |
| 116 |
(*s) = (*s)[:lastGood] |
| 117 |
} |
| 118 |
return nil |
| 119 |
} |
| 120 |
|
| 121 |
func (s *symlinkStack) push(dir *os.File, remainingPath, linkTarget string) error { |
| 122 |
if s == nil { |
| 123 |
return nil |
| 124 |
} |
| 125 |
// Split the link target and clean up any "" parts. |
| 126 |
linkTargetParts := gocompat.SlicesDeleteFunc( |
| 127 |
strings.Split(linkTarget, "/"), |
| 128 |
func(part string) bool { return part == "" || part == "." }) |
| 129 |
|
| 130 |
// Copy the directory so the caller doesn't close our copy. |
| 131 |
dirCopy, err := fd.Dup(dir) |
| 132 |
if err != nil { |
| 133 |
return err |
| 134 |
} |
| 135 |
|
| 136 |
// Add to the stack. |
| 137 |
*s = append(*s, &symlinkStackEntry{ |
| 138 |
dir: dirCopy, |
| 139 |
remainingPath: remainingPath, |
| 140 |
linkUnwalked: linkTargetParts, |
| 141 |
}) |
| 142 |
return nil |
| 143 |
} |
| 144 |
|
| 145 |
func (s *symlinkStack) SwapLink(linkPart string, dir *os.File, remainingPath, linkTarget string) error { |
| 146 |
// If we are currently inside a symlink resolution, remove the symlink |
| 147 |
// component from the last symlink entry, but don't remove the entry even |
| 148 |
// if it's empty. If we are a "tail-chained" symlink (a trailing symlink we |
| 149 |
// hit during a symlink resolution) we need to keep the old symlink until |
| 150 |
// we finish the resolution. |
| 151 |
if err := s.popPart(linkPart); err != nil { |
| 152 |
if !errors.Is(err, errEmptyStack) { |
| 153 |
return err |
| 154 |
} |
| 155 |
// Push the component regardless of whether the stack was empty. |
| 156 |
} |
| 157 |
return s.push(dir, remainingPath, linkTarget) |
| 158 |
} |
| 159 |
|
| 160 |
func (s *symlinkStack) PopTopSymlink() (*os.File, string, bool) { |
| 161 |
if s == nil || s.IsEmpty() { |
| 162 |
return nil, "", false |
| 163 |
} |
| 164 |
tailEntry := (*s)[0] |
| 165 |
*s = (*s)[1:] |
| 166 |
return tailEntry.dir, tailEntry.remainingPath, true |
| 167 |
} |
| 168 |
|
| 169 |
// partialLookupInRoot tries to lookup as much of the request path as possible |
| 170 |
// within the provided root (a-la RESOLVE_IN_ROOT) and opens the final existing |
| 171 |
// component of the requested path, returning a file handle to the final |
| 172 |
// existing component and a string containing the remaining path components. |
| 173 |
func partialLookupInRoot(root fd.Fd, unsafePath string) (*os.File, string, error) { |
| 174 |
return lookupInRoot(root, unsafePath, true) |
| 175 |
} |
| 176 |
|
| 177 |
func completeLookupInRoot(root fd.Fd, unsafePath string) (*os.File, error) { |
| 178 |
handle, remainingPath, err := lookupInRoot(root, unsafePath, false) |
| 179 |
if remainingPath != "" && err == nil { |
| 180 |
// should never happen |
| 181 |
err = fmt.Errorf("[bug] non-empty remaining path when doing a non-partial lookup: %q", remainingPath) |
| 182 |
} |
| 183 |
// lookupInRoot(partial=false) will always close the handle if an error is |
| 184 |
// returned, so no need to double-check here. |
| 185 |
return handle, err |
| 186 |
} |
| 187 |
|
| 188 |
func lookupInRoot(root fd.Fd, unsafePath string, partial bool) (Handle *os.File, _ string, _ error) { |
| 189 |
unsafePath = filepath.ToSlash(unsafePath) // noop |
| 190 |
|
| 191 |
// This is very similar to SecureJoin, except that we operate on the |
| 192 |
// components using file descriptors. We then return the last component we |
| 193 |
// managed open, along with the remaining path components not opened. |
| 194 |
|
| 195 |
// Try to use openat2 if possible. |
| 196 |
// |
| 197 |
// NOTE: If openat2(2) works normally but fails for this lookup, it is |
| 198 |
// probably not a good idea to fall-back to the O_PATH resolver. An |
| 199 |
// attacker could find a bug in the O_PATH resolver and uncontionally |
| 200 |
// falling back to the O_PATH resolver would form a downgrade attack. |
| 201 |
if handle, remainingPath, err := lookupOpenat2(root, unsafePath, partial); err == nil || linux.HasOpenat2() { |
| 202 |
return handle, remainingPath, err |
| 203 |
} |
| 204 |
|
| 205 |
// Get the "actual" root path from /proc/self/fd. This is necessary if the |
| 206 |
// root is some magic-link like /proc/$pid/root, in which case we want to |
| 207 |
// make sure when we do procfs.CheckProcSelfFdPath that we are using the |
| 208 |
// correct root path. |
| 209 |
logicalRootPath, err := procfs.ProcSelfFdReadlink(root) |
| 210 |
if err != nil { |
| 211 |
return nil, "", fmt.Errorf("get real root path: %w", err) |
| 212 |
} |
| 213 |
|
| 214 |
currentDir, err := fd.Dup(root) |
| 215 |
if err != nil { |
| 216 |
return nil, "", fmt.Errorf("clone root fd: %w", err) |
| 217 |
} |
| 218 |
defer func() { |
| 219 |
// If a handle is not returned, close the internal handle. |
| 220 |
if Handle == nil { |
| 221 |
_ = currentDir.Close() |
| 222 |
} |
| 223 |
}() |
| 224 |
|
| 225 |
// symlinkStack is used to emulate how openat2(RESOLVE_IN_ROOT) treats |
| 226 |
// dangling symlinks. If we hit a non-existent path while resolving a |
| 227 |
// symlink, we need to return the (dir, remainingPath) that we had when we |
| 228 |
// hit the symlink (treating the symlink as though it were a regular file). |
| 229 |
// The set of (dir, remainingPath) sets is stored within the symlinkStack |
| 230 |
// and we add and remove parts when we hit symlink and non-symlink |
| 231 |
// components respectively. We need a stack because of recursive symlinks |
| 232 |
// (symlinks that contain symlink components in their target). |
| 233 |
// |
| 234 |
// Note that the stack is ONLY used for book-keeping. All of the actual |
| 235 |
// path walking logic is still based on currentPath/remainingPath and |
| 236 |
// currentDir (as in SecureJoin). |
| 237 |
var symStack *symlinkStack |
| 238 |
if partial { |
| 239 |
symStack = new(symlinkStack) |
| 240 |
defer symStack.Close() |
| 241 |
} |
| 242 |
|
| 243 |
var ( |
| 244 |
linksWalked int |
| 245 |
currentPath string |
| 246 |
remainingPath = unsafePath |
| 247 |
) |
| 248 |
for remainingPath != "" { |
| 249 |
// Save the current remaining path so if the part is not real we can |
| 250 |
// return the path including the component. |
| 251 |
oldRemainingPath := remainingPath |
| 252 |
|
| 253 |
// Get the next path component. |
| 254 |
var part string |
| 255 |
if i := strings.IndexByte(remainingPath, '/'); i == -1 { |
| 256 |
part, remainingPath = remainingPath, "" |
| 257 |
} else { |
| 258 |
part, remainingPath = remainingPath[:i], remainingPath[i+1:] |
| 259 |
} |
| 260 |
// If we hit an empty component, we need to treat it as though it is |
| 261 |
// "." so that trailing "/" and "//" components on a non-directory |
| 262 |
// correctly return the right error code. |
| 263 |
if part == "" { |
| 264 |
part = "." |
| 265 |
} |
| 266 |
|
| 267 |
// Apply the component lexically to the path we are building. |
| 268 |
// currentPath does not contain any symlinks, and we are lexically |
| 269 |
// dealing with a single component, so it's okay to do a filepath.Clean |
| 270 |
// here. |
| 271 |
nextPath := path.Join("/", currentPath, part) |
| 272 |
// If we logically hit the root, just clone the root rather than |
| 273 |
// opening the part and doing all of the other checks. |
| 274 |
if nextPath == "/" { |
| 275 |
if err := symStack.PopPart(part); err != nil { |
| 276 |
return nil, "", fmt.Errorf("walking into root with part %q failed: %w", part, err) |
| 277 |
} |
| 278 |
// Jump to root. |
| 279 |
rootClone, err := fd.Dup(root) |
| 280 |
if err != nil { |
| 281 |
return nil, "", fmt.Errorf("clone root fd: %w", err) |
| 282 |
} |
| 283 |
_ = currentDir.Close() |
| 284 |
currentDir = rootClone |
| 285 |
currentPath = nextPath |
| 286 |
continue |
| 287 |
} |
| 288 |
|
| 289 |
// Try to open the next component. |
| 290 |
nextDir, err := fd.Openat(currentDir, part, unix.O_PATH|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0) |
| 291 |
switch err { |
| 292 |
case nil: |
| 293 |
st, err := nextDir.Stat() |
| 294 |
if err != nil { |
| 295 |
_ = nextDir.Close() |
| 296 |
return nil, "", fmt.Errorf("stat component %q: %w", part, err) |
| 297 |
} |
| 298 |
|
| 299 |
switch st.Mode() & os.ModeType { //nolint:exhaustive // just a glorified if statement |
| 300 |
case os.ModeSymlink: |
| 301 |
// readlinkat implies AT_EMPTY_PATH since Linux 2.6.39. See |
| 302 |
// Linux commit 65cfc6722361 ("readlinkat(), fchownat() and |
| 303 |
// fstatat() with empty relative pathnames"). |
| 304 |
linkDest, err := fd.Readlinkat(nextDir, "") |
| 305 |
// We don't need the handle anymore. |
| 306 |
_ = nextDir.Close() |
| 307 |
if err != nil { |
| 308 |
return nil, "", err |
| 309 |
} |
| 310 |
|
| 311 |
linksWalked++ |
| 312 |
if linksWalked > consts.MaxSymlinkLimit { |
| 313 |
return nil, "", &os.PathError{Op: "securejoin.lookupInRoot", Path: logicalRootPath + "/" + unsafePath, Err: unix.ELOOP} |
| 314 |
} |
| 315 |
|
| 316 |
// Swap out the symlink's component for the link entry itself. |
| 317 |
if err := symStack.SwapLink(part, currentDir, oldRemainingPath, linkDest); err != nil { |
| 318 |
return nil, "", fmt.Errorf("walking into symlink %q failed: push symlink: %w", part, err) |
| 319 |
} |
| 320 |
|
| 321 |
// Update our logical remaining path. |
| 322 |
remainingPath = linkDest + "/" + remainingPath |
| 323 |
// Absolute symlinks reset any work we've already done. |
| 324 |
if path.IsAbs(linkDest) { |
| 325 |
// Jump to root. |
| 326 |
rootClone, err := fd.Dup(root) |
| 327 |
if err != nil { |
| 328 |
return nil, "", fmt.Errorf("clone root fd: %w", err) |
| 329 |
} |
| 330 |
_ = currentDir.Close() |
| 331 |
currentDir = rootClone |
| 332 |
currentPath = "/" |
| 333 |
} |
| 334 |
|
| 335 |
default: |
| 336 |
// If we are dealing with a directory, simply walk into it. |
| 337 |
_ = currentDir.Close() |
| 338 |
currentDir = nextDir |
| 339 |
currentPath = nextPath |
| 340 |
|
| 341 |
// The part was real, so drop it from the symlink stack. |
| 342 |
if err := symStack.PopPart(part); err != nil { |
| 343 |
return nil, "", fmt.Errorf("walking into directory %q failed: %w", part, err) |
| 344 |
} |
| 345 |
|
| 346 |
// If we are operating on a .., make sure we haven't escaped. |
| 347 |
// We only have to check for ".." here because walking down |
| 348 |
// into a regular component component cannot cause you to |
| 349 |
// escape. This mirrors the logic in RESOLVE_IN_ROOT, except we |
| 350 |
// have to check every ".." rather than only checking after a |
| 351 |
// rename or mount on the system. |
| 352 |
if part == ".." { |
| 353 |
// Make sure the root hasn't moved. |
| 354 |
if err := procfs.CheckProcSelfFdPath(logicalRootPath, root); err != nil { |
| 355 |
return nil, "", fmt.Errorf("root path moved during lookup: %w", err) |
| 356 |
} |
| 357 |
// Make sure the path is what we expect. |
| 358 |
fullPath := logicalRootPath + nextPath |
| 359 |
if err := procfs.CheckProcSelfFdPath(fullPath, currentDir); err != nil { |
| 360 |
return nil, "", fmt.Errorf("walking into %q had unexpected result: %w", part, err) |
| 361 |
} |
| 362 |
} |
| 363 |
} |
| 364 |
|
| 365 |
default: |
| 366 |
if !partial { |
| 367 |
return nil, "", err |
| 368 |
} |
| 369 |
// If there are any remaining components in the symlink stack, we |
| 370 |
// are still within a symlink resolution and thus we hit a dangling |
| 371 |
// symlink. So pretend that the first symlink in the stack we hit |
| 372 |
// was an ENOENT (to match openat2). |
| 373 |
if oldDir, remainingPath, ok := symStack.PopTopSymlink(); ok { |
| 374 |
_ = currentDir.Close() |
| 375 |
return oldDir, remainingPath, err |
| 376 |
} |
| 377 |
// We have hit a final component that doesn't exist, so we have our |
| 378 |
// partial open result. Note that we have to use the OLD remaining |
| 379 |
// path, since the lookup failed. |
| 380 |
return currentDir, oldRemainingPath, err |
| 381 |
} |
| 382 |
} |
| 383 |
|
| 384 |
// If the unsafePath had a trailing slash, we need to make sure we try to |
| 385 |
// do a relative "." open so that we will correctly return an error when |
| 386 |
// the final component is a non-directory (to match openat2). In the |
| 387 |
// context of openat2, a trailing slash and a trailing "/." are completely |
| 388 |
// equivalent. |
| 389 |
if strings.HasSuffix(unsafePath, "/") { |
| 390 |
nextDir, err := fd.Openat(currentDir, ".", unix.O_PATH|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0) |
| 391 |
if err != nil { |
| 392 |
if !partial { |
| 393 |
_ = currentDir.Close() |
| 394 |
currentDir = nil |
| 395 |
} |
| 396 |
return currentDir, "", err |
| 397 |
} |
| 398 |
_ = currentDir.Close() |
| 399 |
currentDir = nextDir |
| 400 |
} |
| 401 |
|
| 402 |
// All of the components existed! |
| 403 |
return currentDir, "", nil |
| 404 |
} |