| 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/filepath" |
| 19 |
"strings" |
| 20 |
|
| 21 |
"golang.org/x/sys/unix" |
| 22 |
|
| 23 |
"github.com/cyphar/filepath-securejoin/pathrs-lite/internal/fd" |
| 24 |
"github.com/cyphar/filepath-securejoin/pathrs-lite/internal/gocompat" |
| 25 |
"github.com/cyphar/filepath-securejoin/pathrs-lite/internal/linux" |
| 26 |
) |
| 27 |
|
| 28 |
var errInvalidMode = errors.New("invalid permission mode") |
| 29 |
|
| 30 |
// modePermExt is like os.ModePerm except that it also includes the set[ug]id |
| 31 |
// and sticky bits. |
| 32 |
const modePermExt = os.ModePerm | os.ModeSetuid | os.ModeSetgid | os.ModeSticky |
| 33 |
|
| 34 |
//nolint:cyclop // this function needs to handle a lot of cases |
| 35 |
func toUnixMode(mode os.FileMode) (uint32, error) { |
| 36 |
sysMode := uint32(mode.Perm()) |
| 37 |
if mode&os.ModeSetuid != 0 { |
| 38 |
sysMode |= unix.S_ISUID |
| 39 |
} |
| 40 |
if mode&os.ModeSetgid != 0 { |
| 41 |
sysMode |= unix.S_ISGID |
| 42 |
} |
| 43 |
if mode&os.ModeSticky != 0 { |
| 44 |
sysMode |= unix.S_ISVTX |
| 45 |
} |
| 46 |
// We don't allow file type bits. |
| 47 |
if mode&os.ModeType != 0 { |
| 48 |
return 0, fmt.Errorf("%w %+.3o (%s): type bits not permitted", errInvalidMode, mode, mode) |
| 49 |
} |
| 50 |
// We don't allow other unknown modes. |
| 51 |
if mode&^modePermExt != 0 || sysMode&unix.S_IFMT != 0 { |
| 52 |
return 0, fmt.Errorf("%w %+.3o (%s): unknown mode bits", errInvalidMode, mode, mode) |
| 53 |
} |
| 54 |
return sysMode, nil |
| 55 |
} |
| 56 |
|
| 57 |
// MkdirAllHandle is equivalent to [MkdirAll], except that it is safer to use |
| 58 |
// in two respects: |
| 59 |
// |
| 60 |
// - The caller provides the root directory as an *[os.File] (preferably O_PATH) |
| 61 |
// handle. This means that the caller can be sure which root directory is |
| 62 |
// being used. Note that this can be emulated by using /proc/self/fd/... as |
| 63 |
// the root path with [os.MkdirAll]. |
| 64 |
// |
| 65 |
// - Once all of the directories have been created, an *[os.File] O_PATH handle |
| 66 |
// to the directory at unsafePath is returned to the caller. This is done in |
| 67 |
// an effectively-race-free way (an attacker would only be able to swap the |
| 68 |
// final directory component), which is not possible to emulate with |
| 69 |
// [MkdirAll]. |
| 70 |
// |
| 71 |
// In addition, the returned handle is obtained far more efficiently than doing |
| 72 |
// a brand new lookup of unsafePath (such as with [SecureJoin] or openat2) after |
| 73 |
// doing [MkdirAll]. If you intend to open the directory after creating it, you |
| 74 |
// should use MkdirAllHandle. |
| 75 |
// |
| 76 |
// [SecureJoin]: https://pkg.go.dev/github.com/cyphar/filepath-securejoin#SecureJoin |
| 77 |
func MkdirAllHandle(root *os.File, unsafePath string, mode os.FileMode) (_ *os.File, Err error) { |
| 78 |
unixMode, err := toUnixMode(mode) |
| 79 |
if err != nil { |
| 80 |
return nil, err |
| 81 |
} |
| 82 |
// On Linux, mkdirat(2) (and os.Mkdir) silently ignore the suid and sgid |
| 83 |
// bits. We could also silently ignore them but since we have very few |
| 84 |
// users it seems more prudent to return an error so users notice that |
| 85 |
// these bits will not be set. |
| 86 |
if unixMode&^0o1777 != 0 { |
| 87 |
return nil, fmt.Errorf("%w for mkdir %+.3o: suid and sgid are ignored by mkdir", errInvalidMode, mode) |
| 88 |
} |
| 89 |
|
| 90 |
// Try to open as much of the path as possible. |
| 91 |
currentDir, remainingPath, err := partialLookupInRoot(root, unsafePath) |
| 92 |
defer func() { |
| 93 |
if Err != nil { |
| 94 |
_ = currentDir.Close() |
| 95 |
} |
| 96 |
}() |
| 97 |
if err != nil && !errors.Is(err, unix.ENOENT) { |
| 98 |
return nil, fmt.Errorf("find existing subpath of %q: %w", unsafePath, err) |
| 99 |
} |
| 100 |
|
| 101 |
// If there is an attacker deleting directories as we walk into them, |
| 102 |
// detect this proactively. Note this is guaranteed to detect if the |
| 103 |
// attacker deleted any part of the tree up to currentDir. |
| 104 |
// |
| 105 |
// Once we walk into a dead directory, partialLookupInRoot would not be |
| 106 |
// able to walk further down the tree (directories must be empty before |
| 107 |
// they are deleted), and if the attacker has removed the entire tree we |
| 108 |
// can be sure that anything that was originally inside a dead directory |
| 109 |
// must also be deleted and thus is a dead directory in its own right. |
| 110 |
// |
| 111 |
// This is mostly a quality-of-life check, because mkdir will simply fail |
| 112 |
// later if the attacker deletes the tree after this check. |
| 113 |
if err := fd.IsDeadInode(currentDir); err != nil { |
| 114 |
return nil, fmt.Errorf("finding existing subpath of %q: %w", unsafePath, err) |
| 115 |
} |
| 116 |
|
| 117 |
// Re-open the path to match the O_DIRECTORY reopen loop later (so that we |
| 118 |
// always return a non-O_PATH handle). We also check that we actually got a |
| 119 |
// directory. |
| 120 |
if reopenDir, err := Reopen(currentDir, unix.O_DIRECTORY|unix.O_CLOEXEC); errors.Is(err, unix.ENOTDIR) { |
| 121 |
return nil, fmt.Errorf("cannot create subdirectories in %q: %w", currentDir.Name(), unix.ENOTDIR) |
| 122 |
} else if err != nil { |
| 123 |
return nil, fmt.Errorf("re-opening handle to %q: %w", currentDir.Name(), err) |
| 124 |
} else { //nolint:revive // indent-error-flow lint doesn't make sense here |
| 125 |
_ = currentDir.Close() |
| 126 |
currentDir = reopenDir |
| 127 |
} |
| 128 |
|
| 129 |
remainingParts := strings.Split(remainingPath, string(filepath.Separator)) |
| 130 |
if gocompat.SlicesContains(remainingParts, "..") { |
| 131 |
// The path contained ".." components after the end of the "real" |
| 132 |
// components. We could try to safely resolve ".." here but that would |
| 133 |
// add a bunch of extra logic for something that it's not clear even |
| 134 |
// needs to be supported. So just return an error. |
| 135 |
// |
| 136 |
// If we do filepath.Clean(remainingPath) then we end up with the |
| 137 |
// problem that ".." can erase a trailing dangling symlink and produce |
| 138 |
// a path that doesn't quite match what the user asked for. |
| 139 |
return nil, fmt.Errorf("%w: yet-to-be-created path %q contains '..' components", unix.ENOENT, remainingPath) |
| 140 |
} |
| 141 |
|
| 142 |
// Create the remaining components. |
| 143 |
for _, part := range remainingParts { |
| 144 |
switch part { |
| 145 |
case "", ".": |
| 146 |
// Skip over no-op paths. |
| 147 |
continue |
| 148 |
} |
| 149 |
|
| 150 |
// NOTE: mkdir(2) will not follow trailing symlinks, so we can safely |
| 151 |
// create the final component without worrying about symlink-exchange |
| 152 |
// attacks. |
| 153 |
// |
| 154 |
// If we get -EEXIST, it's possible that another program created the |
| 155 |
// directory at the same time as us. In that case, just continue on as |
| 156 |
// if we created it (if the created inode is not a directory, the |
| 157 |
// following open call will fail). |
| 158 |
if err := unix.Mkdirat(int(currentDir.Fd()), part, unixMode); err != nil && !errors.Is(err, unix.EEXIST) { |
| 159 |
err = &os.PathError{Op: "mkdirat", Path: currentDir.Name() + "/" + part, Err: err} |
| 160 |
// Make the error a bit nicer if the directory is dead. |
| 161 |
if deadErr := fd.IsDeadInode(currentDir); deadErr != nil { |
| 162 |
// TODO: Once we bump the minimum Go version to 1.20, we can use |
| 163 |
// multiple %w verbs for this wrapping. For now we need to use a |
| 164 |
// compatibility shim for older Go versions. |
| 165 |
// err = fmt.Errorf("%w (%w)", err, deadErr) |
| 166 |
err = gocompat.WrapBaseError(err, deadErr) |
| 167 |
} |
| 168 |
return nil, err |
| 169 |
} |
| 170 |
|
| 171 |
// Get a handle to the next component. O_DIRECTORY means we don't need |
| 172 |
// to use O_PATH. |
| 173 |
var nextDir *os.File |
| 174 |
if linux.HasOpenat2() { |
| 175 |
nextDir, err = openat2(currentDir, part, &unix.OpenHow{ |
| 176 |
Flags: unix.O_NOFOLLOW | unix.O_DIRECTORY | unix.O_CLOEXEC, |
| 177 |
Resolve: unix.RESOLVE_BENEATH | unix.RESOLVE_NO_SYMLINKS | unix.RESOLVE_NO_XDEV, |
| 178 |
}) |
| 179 |
} else { |
| 180 |
nextDir, err = fd.Openat(currentDir, part, unix.O_NOFOLLOW|unix.O_DIRECTORY|unix.O_CLOEXEC, 0) |
| 181 |
} |
| 182 |
if err != nil { |
| 183 |
return nil, err |
| 184 |
} |
| 185 |
_ = currentDir.Close() |
| 186 |
currentDir = nextDir |
| 187 |
|
| 188 |
// It's possible that the directory we just opened was swapped by an |
| 189 |
// attacker. Unfortunately there isn't much we can do to protect |
| 190 |
// against this, and MkdirAll's behaviour is that we will reuse |
| 191 |
// existing directories anyway so the need to protect against this is |
| 192 |
// incredibly limited (and arguably doesn't even deserve mention here). |
| 193 |
// |
| 194 |
// Ideally we might want to check that the owner and mode match what we |
| 195 |
// would've created -- unfortunately, it is non-trivial to verify that |
| 196 |
// the owner and mode of the created directory match. While plain Unix |
| 197 |
// DAC rules seem simple enough to emulate, there are a bunch of other |
| 198 |
// factors that can change the mode or owner of created directories |
| 199 |
// (default POSIX ACLs, mount options like uid=1,gid=2,umask=0 on |
| 200 |
// filesystems like vfat, etc etc). We used to try to verify this but |
| 201 |
// it just lead to a series of spurious errors. |
| 202 |
// |
| 203 |
// We could also check that the directory is non-empty, but |
| 204 |
// unfortunately some pseduofilesystems (like cgroupfs) create |
| 205 |
// non-empty directories, which would result in different spurious |
| 206 |
// errors. |
| 207 |
} |
| 208 |
return currentDir, nil |
| 209 |
} |
| 210 |
|
| 211 |
// MkdirAll is a race-safe alternative to the [os.MkdirAll] function, |
| 212 |
// where the new directory is guaranteed to be within the root directory (if an |
| 213 |
// attacker can move directories from inside the root to outside the root, the |
| 214 |
// created directory tree might be outside of the root but the key constraint |
| 215 |
// is that at no point will we walk outside of the directory tree we are |
| 216 |
// creating). |
| 217 |
// |
| 218 |
// Effectively, MkdirAll(root, unsafePath, mode) is equivalent to |
| 219 |
// |
| 220 |
// path, _ := securejoin.SecureJoin(root, unsafePath) |
| 221 |
// err := os.MkdirAll(path, mode) |
| 222 |
// |
| 223 |
// But is much safer. The above implementation is unsafe because if an attacker |
| 224 |
// can modify the filesystem tree between [SecureJoin] and [os.MkdirAll], it is |
| 225 |
// possible for MkdirAll to resolve unsafe symlink components and create |
| 226 |
// directories outside of the root. |
| 227 |
// |
| 228 |
// If you plan to open the directory after you have created it or want to use |
| 229 |
// an open directory handle as the root, you should use [MkdirAllHandle] instead. |
| 230 |
// This function is a wrapper around [MkdirAllHandle]. |
| 231 |
// |
| 232 |
// [SecureJoin]: https://pkg.go.dev/github.com/cyphar/filepath-securejoin#SecureJoin |
| 233 |
func MkdirAll(root, unsafePath string, mode os.FileMode) error { |
| 234 |
rootDir, err := os.OpenFile(root, unix.O_PATH|unix.O_DIRECTORY|unix.O_CLOEXEC, 0) |
| 235 |
if err != nil { |
| 236 |
return err |
| 237 |
} |
| 238 |
defer rootDir.Close() //nolint:errcheck // close failures aren't critical here |
| 239 |
|
| 240 |
f, err := MkdirAllHandle(rootDir, unsafePath, mode) |
| 241 |
if err != nil { |
| 242 |
return err |
| 243 |
} |
| 244 |
_ = f.Close() |
| 245 |
return nil |
| 246 |
} |