| 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 fd |
| 13 |
|
| 14 |
import ( |
| 15 |
"errors" |
| 16 |
"os" |
| 17 |
"runtime" |
| 18 |
|
| 19 |
"golang.org/x/sys/unix" |
| 20 |
) |
| 21 |
|
| 22 |
func scopedLookupShouldRetry(how *unix.OpenHow, err error) bool { |
| 23 |
// RESOLVE_IN_ROOT (and RESOLVE_BENEATH) can return -EAGAIN if we resolve |
| 24 |
// ".." while a mount or rename occurs anywhere on the system. This could |
| 25 |
// happen spuriously, or as the result of an attacker trying to mess with |
| 26 |
// us during lookup. |
| 27 |
// |
| 28 |
// In addition, scoped lookups have a "safety check" at the end of |
| 29 |
// complete_walk which will return -EXDEV if the final path is not in the |
| 30 |
// root. |
| 31 |
return how.Resolve&(unix.RESOLVE_IN_ROOT|unix.RESOLVE_BENEATH) != 0 && |
| 32 |
(errors.Is(err, unix.EAGAIN) || errors.Is(err, unix.EXDEV)) |
| 33 |
} |
| 34 |
|
| 35 |
// This is a fairly arbitrary limit we have just to avoid an attacker being |
| 36 |
// able to make us spin in an infinite retry loop -- callers can choose to |
| 37 |
// retry on EAGAIN if they prefer. |
| 38 |
const scopedLookupMaxRetries = 128 |
| 39 |
|
| 40 |
// Openat2 is an [Fd]-based wrapper around unix.Openat2, but with some retry |
| 41 |
// logic in case of EAGAIN errors. |
| 42 |
// |
| 43 |
// NOTE: This is a variable so that the lookup tests can force openat2 to fail. |
| 44 |
var Openat2 = func(dir Fd, path string, how *unix.OpenHow) (*os.File, error) { |
| 45 |
dirFd, fullPath := prepareAt(dir, path) |
| 46 |
// Make sure we always set O_CLOEXEC. |
| 47 |
how.Flags |= unix.O_CLOEXEC |
| 48 |
var tries int |
| 49 |
for { |
| 50 |
fd, err := unix.Openat2(dirFd, path, how) |
| 51 |
if err != nil { |
| 52 |
if scopedLookupShouldRetry(how, err) && tries < scopedLookupMaxRetries { |
| 53 |
// We retry a couple of times to avoid the spurious errors, and |
| 54 |
// if we are being attacked then returning -EAGAIN is the best |
| 55 |
// we can do. |
| 56 |
tries++ |
| 57 |
continue |
| 58 |
} |
| 59 |
return nil, &os.PathError{Op: "openat2", Path: fullPath, Err: err} |
| 60 |
} |
| 61 |
runtime.KeepAlive(dir) |
| 62 |
return os.NewFile(uintptr(fd), fullPath), nil |
| 63 |
} |
| 64 |
} |