| 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 linux |
| 13 |
|
| 14 |
import ( |
| 15 |
"golang.org/x/sys/unix" |
| 16 |
|
| 17 |
"github.com/cyphar/filepath-securejoin/pathrs-lite/internal/gocompat" |
| 18 |
) |
| 19 |
|
| 20 |
// sawOpenat2Error stores whether we have seen an error from HasOpenat2. This |
| 21 |
// is a one-way toggle, so as soon as we see an error we "lock" into that mode. |
| 22 |
// We cannot use sync.OnceValue to store the success/fail state once because it |
| 23 |
// is possible for the program we are running in to apply a seccomp-bpf filter |
| 24 |
// and thus disable openat2 during execution. |
| 25 |
var sawOpenat2Error gocompat.Bool |
| 26 |
|
| 27 |
// HasOpenat2 returns whether openat2(2) is supported on the running kernel. |
| 28 |
var HasOpenat2 = func() bool { |
| 29 |
if sawOpenat2Error.Load() { |
| 30 |
return false |
| 31 |
} |
| 32 |
|
| 33 |
fd, err := unix.Openat2(unix.AT_FDCWD, ".", &unix.OpenHow{ |
| 34 |
Flags: unix.O_PATH | unix.O_CLOEXEC, |
| 35 |
Resolve: unix.RESOLVE_NO_SYMLINKS | unix.RESOLVE_IN_ROOT, |
| 36 |
}) |
| 37 |
if err != nil { |
| 38 |
sawOpenat2Error.Store(true) // doesn't matter if we race here |
| 39 |
return false |
| 40 |
} |
| 41 |
_ = unix.Close(fd) |
| 42 |
return true |
| 43 |
} |