| 1 |
/* |
| 2 |
Copyright 2014 The Kubernetes Authors. |
| 3 |
|
| 4 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 |
you may not use this file except in compliance with the License. |
| 6 |
You may obtain a copy of the License at |
| 7 |
|
| 8 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
|
| 10 |
Unless required by applicable law or agreed to in writing, software |
| 11 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 12 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 |
See the License for the specific language governing permissions and |
| 14 |
limitations under the License. |
| 15 |
*/ |
| 16 |
|
| 17 |
// TODO(thockin): This whole pkg is pretty linux-centric. As soon as we have |
| 18 |
// an alternate platform, we will need to abstract further. |
| 19 |
|
| 20 |
package mount |
| 21 |
|
| 22 |
import ( |
| 23 |
"fmt" |
| 24 |
"os" |
| 25 |
"path/filepath" |
| 26 |
"slices" |
| 27 |
"strings" |
| 28 |
|
| 29 |
utilexec "k8s.io/utils/exec" |
| 30 |
) |
| 31 |
|
| 32 |
const ( |
| 33 |
// Default mount command if mounter path is not specified. |
| 34 |
defaultMountCommand = "mount" |
| 35 |
// Log message where sensitive mount options were removed |
| 36 |
sensitiveOptionsRemoved = "<masked>" |
| 37 |
) |
| 38 |
|
| 39 |
// Interface defines the set of methods to allow for mount operations on a system. |
| 40 |
type Interface interface { |
| 41 |
// Mount mounts source to target as fstype with given options. |
| 42 |
// options MUST not contain sensitive material (like passwords). |
| 43 |
Mount(source string, target string, fstype string, options []string) error |
| 44 |
// MountSensitive is the same as Mount() but this method allows |
| 45 |
// sensitiveOptions to be passed in a separate parameter from the normal |
| 46 |
// mount options and ensures the sensitiveOptions are never logged. This |
| 47 |
// method should be used by callers that pass sensitive material (like |
| 48 |
// passwords) as mount options. |
| 49 |
MountSensitive(source string, target string, fstype string, options []string, sensitiveOptions []string) error |
| 50 |
// Unmount unmounts given target. |
| 51 |
Unmount(target string) error |
| 52 |
// List returns a list of all mounted filesystems. This can be large. |
| 53 |
// On some platforms, reading mounts directly from the OS is not guaranteed |
| 54 |
// consistent (i.e. it could change between chunked reads). This is guaranteed |
| 55 |
// to be consistent. |
| 56 |
List() ([]MountPoint, error) |
| 57 |
// IsLikelyNotMountPoint uses heuristics to determine if a directory |
| 58 |
// is not a mountpoint. |
| 59 |
// It should return ErrNotExist when the directory does not exist. |
| 60 |
// IsLikelyNotMountPoint does NOT properly detect all mountpoint types |
| 61 |
// most notably linux bind mounts and symbolic link. For callers that do not |
| 62 |
// care about such situations, this is a faster alternative to calling List() |
| 63 |
// and scanning that output. |
| 64 |
IsLikelyNotMountPoint(file string) (bool, error) |
| 65 |
// GetMountRefs finds all mount references to pathname, returning a slice of |
| 66 |
// paths. Pathname can be a mountpoint path or a normal directory |
| 67 |
// (for bind mount). On Linux, pathname is excluded from the slice. |
| 68 |
// For example, if /dev/sdc was mounted at /path/a and /path/b, |
| 69 |
// GetMountRefs("/path/a") would return ["/path/b"] |
| 70 |
// GetMountRefs("/path/b") would return ["/path/a"] |
| 71 |
// On Windows there is no way to query all mount points; as long as pathname is |
| 72 |
// a valid mount, it will be returned. |
| 73 |
GetMountRefs(pathname string) ([]string, error) |
| 74 |
} |
| 75 |
|
| 76 |
// Compile-time check to ensure all Mounter implementations satisfy |
| 77 |
// the mount interface. |
| 78 |
var _ Interface = &Mounter{} |
| 79 |
|
| 80 |
// MountPoint represents a single line in /proc/mounts or /etc/fstab. |
| 81 |
type MountPoint struct { // nolint: revive |
| 82 |
Device string |
| 83 |
Path string |
| 84 |
Type string |
| 85 |
Opts []string // Opts may contain sensitive mount options (like passwords) and MUST be treated as such (e.g. not logged). |
| 86 |
Freq int |
| 87 |
Pass int |
| 88 |
} |
| 89 |
|
| 90 |
type MountErrorType string // nolint: revive |
| 91 |
|
| 92 |
const ( |
| 93 |
FilesystemMismatch MountErrorType = "FilesystemMismatch" |
| 94 |
HasFilesystemErrors MountErrorType = "HasFilesystemErrors" |
| 95 |
UnformattedReadOnly MountErrorType = "UnformattedReadOnly" |
| 96 |
FormatFailed MountErrorType = "FormatFailed" |
| 97 |
GetDiskFormatFailed MountErrorType = "GetDiskFormatFailed" |
| 98 |
UnknownMountError MountErrorType = "UnknownMountError" |
| 99 |
) |
| 100 |
|
| 101 |
type MountError struct { // nolint: revive |
| 102 |
Type MountErrorType |
| 103 |
Message string |
| 104 |
} |
| 105 |
|
| 106 |
func (mountError MountError) String() string { |
| 107 |
return mountError.Message |
| 108 |
} |
| 109 |
|
| 110 |
func (mountError MountError) Error() string { |
| 111 |
return mountError.Message |
| 112 |
} |
| 113 |
|
| 114 |
func NewMountError(mountErrorValue MountErrorType, format string, args ...any) error { |
| 115 |
mountError := MountError{ |
| 116 |
Type: mountErrorValue, |
| 117 |
Message: fmt.Sprintf(format, args...), |
| 118 |
} |
| 119 |
return mountError |
| 120 |
} |
| 121 |
|
| 122 |
// SafeFormatAndMount probes a device to see if it is formatted. |
| 123 |
// Namely it checks to see if a file system is present. If so it |
| 124 |
// mounts it otherwise the device is formatted first then mounted. |
| 125 |
type SafeFormatAndMount struct { |
| 126 |
Interface |
| 127 |
Exec utilexec.Interface |
| 128 |
} |
| 129 |
|
| 130 |
// FormatAndMount formats the given disk, if needed, and mounts it. |
| 131 |
// That is if the disk is not formatted and it is not being mounted as |
| 132 |
// read-only it will format it first then mount it. Otherwise, if the |
| 133 |
// disk is already formatted or it is being mounted as read-only, it |
| 134 |
// will be mounted without formatting. |
| 135 |
// options MUST not contain sensitive material (like passwords). |
| 136 |
func (mounter *SafeFormatAndMount) FormatAndMount(source string, target string, fstype string, options []string) error { |
| 137 |
return mounter.FormatAndMountSensitive(source, target, fstype, options, nil /* sensitiveOptions */) |
| 138 |
} |
| 139 |
|
| 140 |
// FormatAndMountSensitive is the same as FormatAndMount but this method allows |
| 141 |
// sensitiveOptions to be passed in a separate parameter from the normal mount |
| 142 |
// options and ensures the sensitiveOptions are never logged. This method should |
| 143 |
// be used by callers that pass sensitive material (like passwords) as mount |
| 144 |
// options. |
| 145 |
func (mounter *SafeFormatAndMount) FormatAndMountSensitive(source string, target string, fstype string, options []string, sensitiveOptions []string) error { |
| 146 |
return mounter.formatAndMountSensitive(source, target, fstype, options, sensitiveOptions) |
| 147 |
} |
| 148 |
|
| 149 |
// getMountRefsByDev finds all references to the device provided |
| 150 |
// by mountPath; returns a list of paths. |
| 151 |
// Note that mountPath should be path after the evaluation of any symblolic links. |
| 152 |
func getMountRefsByDev(mounter Interface, mountPath string) ([]string, error) { |
| 153 |
mps, err := mounter.List() |
| 154 |
if err != nil { |
| 155 |
return nil, err |
| 156 |
} |
| 157 |
|
| 158 |
// Finding the device mounted to mountPath. |
| 159 |
diskDev := "" |
| 160 |
for i := range mps { |
| 161 |
if mountPath == mps[i].Path { |
| 162 |
diskDev = mps[i].Device |
| 163 |
break |
| 164 |
} |
| 165 |
} |
| 166 |
|
| 167 |
// Find all references to the device. |
| 168 |
var refs []string |
| 169 |
for i := range mps { |
| 170 |
if mps[i].Device == diskDev || mps[i].Device == mountPath { |
| 171 |
if mps[i].Path != mountPath { |
| 172 |
refs = append(refs, mps[i].Path) |
| 173 |
} |
| 174 |
} |
| 175 |
} |
| 176 |
return refs, nil |
| 177 |
} |
| 178 |
|
| 179 |
// GetDeviceNameFromMount given a mnt point, find the device from /proc/mounts |
| 180 |
// returns the device name, reference count, and error code. |
| 181 |
func GetDeviceNameFromMount(mounter Interface, mountPath string) (string, int, error) { |
| 182 |
mps, err := mounter.List() |
| 183 |
if err != nil { |
| 184 |
return "", 0, err |
| 185 |
} |
| 186 |
|
| 187 |
// Find the device name. |
| 188 |
// FIXME if multiple devices mounted on the same mount path, only the first one is returned. |
| 189 |
device := "" |
| 190 |
// If mountPath is symlink, need get its target path. |
| 191 |
slTarget, err := filepath.EvalSymlinks(mountPath) |
| 192 |
if err != nil { |
| 193 |
slTarget = mountPath |
| 194 |
} |
| 195 |
for i := range mps { |
| 196 |
if mps[i].Path == slTarget { |
| 197 |
device = mps[i].Device |
| 198 |
break |
| 199 |
} |
| 200 |
} |
| 201 |
|
| 202 |
// Find all references to the device. |
| 203 |
refCount := 0 |
| 204 |
for i := range mps { |
| 205 |
if mps[i].Device == device { |
| 206 |
refCount++ |
| 207 |
} |
| 208 |
} |
| 209 |
return device, refCount, nil |
| 210 |
} |
| 211 |
|
| 212 |
// IsNotMountPoint determines if a directory is a mountpoint. |
| 213 |
// It should return ErrNotExist when the directory does not exist. |
| 214 |
// IsNotMountPoint is more expensive than IsLikelyNotMountPoint. |
| 215 |
// IsNotMountPoint detects bind mounts in linux. |
| 216 |
// IsNotMountPoint enumerates all the mountpoints using List() and |
| 217 |
// the list of mountpoints may be large, then it uses |
| 218 |
// isMountPointMatch to evaluate whether the directory is a mountpoint. |
| 219 |
func IsNotMountPoint(mounter Interface, file string) (bool, error) { |
| 220 |
// IsLikelyNotMountPoint provides a quick check |
| 221 |
// to determine whether file IS A mountpoint. |
| 222 |
notMnt, notMntErr := mounter.IsLikelyNotMountPoint(file) |
| 223 |
if notMntErr != nil && os.IsPermission(notMntErr) { |
| 224 |
// We were not allowed to do the simple stat() check, e.g. on NFS with |
| 225 |
// root_squash. Fall back to /proc/mounts check below. |
| 226 |
notMnt = true |
| 227 |
notMntErr = nil |
| 228 |
} |
| 229 |
if notMntErr != nil { |
| 230 |
return notMnt, notMntErr |
| 231 |
} |
| 232 |
// identified as mountpoint, so return this fact. |
| 233 |
if notMnt == false { |
| 234 |
return notMnt, nil |
| 235 |
} |
| 236 |
|
| 237 |
// Resolve any symlinks in file, kernel would do the same and use the resolved path in /proc/mounts. |
| 238 |
resolvedFile, err := filepath.EvalSymlinks(file) |
| 239 |
if err != nil { |
| 240 |
return true, err |
| 241 |
} |
| 242 |
|
| 243 |
// check all mountpoints since IsLikelyNotMountPoint |
| 244 |
// is not reliable for some mountpoint types. |
| 245 |
mountPoints, mountPointsErr := mounter.List() |
| 246 |
if mountPointsErr != nil { |
| 247 |
return notMnt, mountPointsErr |
| 248 |
} |
| 249 |
for _, mp := range mountPoints { |
| 250 |
if isMountPointMatch(mp, resolvedFile) { |
| 251 |
notMnt = false |
| 252 |
break |
| 253 |
} |
| 254 |
} |
| 255 |
return notMnt, nil |
| 256 |
} |
| 257 |
|
| 258 |
// MakeBindOpts detects whether a bind mount is being requested and makes the remount options to |
| 259 |
// use in case of bind mount, due to the fact that bind mount doesn't respect mount options. |
| 260 |
// The list equals: |
| 261 |
// |
| 262 |
// options - 'bind' + 'remount' (no duplicate) |
| 263 |
func MakeBindOpts(options []string) (bool, []string, []string) { |
| 264 |
bind, bindOpts, bindRemountOpts, _ := MakeBindOptsSensitive(options, nil /* sensitiveOptions */) |
| 265 |
return bind, bindOpts, bindRemountOpts |
| 266 |
} |
| 267 |
|
| 268 |
// MakeBindOptsSensitive is the same as MakeBindOpts but this method allows |
| 269 |
// sensitiveOptions to be passed in a separate parameter from the normal mount |
| 270 |
// options and ensures the sensitiveOptions are never logged. This method should |
| 271 |
// be used by callers that pass sensitive material (like passwords) as mount |
| 272 |
// options. |
| 273 |
func MakeBindOptsSensitive(options []string, sensitiveOptions []string) (bool, []string, []string, []string) { |
| 274 |
// Because we have an FD opened on the subpath bind mount, the "bind" option |
| 275 |
// needs to be included, otherwise the mount target will error as busy if you |
| 276 |
// remount as readonly. |
| 277 |
// |
| 278 |
// As a consequence, all read only bind mounts will no longer change the underlying |
| 279 |
// volume mount to be read only. |
| 280 |
bindRemountOpts := []string{"bind", "remount"} |
| 281 |
bindRemountSensitiveOpts := []string{} |
| 282 |
bind := false |
| 283 |
bindOpts := []string{"bind"} |
| 284 |
|
| 285 |
// _netdev is a userspace mount option and does not automatically get added when |
| 286 |
// bind mount is created and hence we must carry it over. |
| 287 |
if checkForNetDev(options, sensitiveOptions) { |
| 288 |
bindOpts = append(bindOpts, "_netdev") |
| 289 |
} |
| 290 |
|
| 291 |
for _, option := range options { |
| 292 |
switch option { |
| 293 |
case "bind": |
| 294 |
bind = true |
| 295 |
case "remount": // Do nothing. |
| 296 |
default: |
| 297 |
bindRemountOpts = append(bindRemountOpts, option) |
| 298 |
} |
| 299 |
} |
| 300 |
|
| 301 |
for _, sensitiveOption := range sensitiveOptions { |
| 302 |
switch sensitiveOption { |
| 303 |
case "bind": |
| 304 |
bind = true |
| 305 |
case "remount": // Do nothing. |
| 306 |
default: |
| 307 |
bindRemountSensitiveOpts = append(bindRemountSensitiveOpts, sensitiveOption) |
| 308 |
} |
| 309 |
} |
| 310 |
|
| 311 |
return bind, bindOpts, bindRemountOpts, bindRemountSensitiveOpts |
| 312 |
} |
| 313 |
|
| 314 |
func checkForNetDev(options []string, sensitiveOptions []string) bool { |
| 315 |
return slices.Contains(options, "_netdev") || slices.Contains(sensitiveOptions, "_netdev") |
| 316 |
} |
| 317 |
|
| 318 |
// PathWithinBase checks if give path is within given base directory. |
| 319 |
func PathWithinBase(fullPath, basePath string) bool { |
| 320 |
rel, err := filepath.Rel(basePath, fullPath) |
| 321 |
if err != nil { |
| 322 |
return false |
| 323 |
} |
| 324 |
if StartsWithBackstep(rel) { |
| 325 |
// Needed to escape the base path. |
| 326 |
return false |
| 327 |
} |
| 328 |
return true |
| 329 |
} |
| 330 |
|
| 331 |
// StartsWithBackstep checks if the given path starts with a backstep segment. |
| 332 |
func StartsWithBackstep(rel string) bool { |
| 333 |
// normalize to / and check for ../ |
| 334 |
return rel == ".." || strings.HasPrefix(filepath.ToSlash(rel), "../") |
| 335 |
} |
| 336 |
|
| 337 |
// sanitizedOptionsForLogging will return a comma separated string containing |
| 338 |
// options and sensitiveOptions. Each entry in sensitiveOptions will be |
| 339 |
// replaced with the string sensitiveOptionsRemoved |
| 340 |
// e.g. o1,o2,<masked>,<masked> |
| 341 |
func sanitizedOptionsForLogging(options []string, sensitiveOptions []string) string { |
| 342 |
separator := "" |
| 343 |
if len(options) > 0 && len(sensitiveOptions) > 0 { |
| 344 |
separator = "," |
| 345 |
} |
| 346 |
|
| 347 |
sensitiveOptionsStart := "" |
| 348 |
sensitiveOptionsEnd := "" |
| 349 |
if len(sensitiveOptions) > 0 { |
| 350 |
sensitiveOptionsStart = strings.Repeat(sensitiveOptionsRemoved+",", len(sensitiveOptions)-1) |
| 351 |
sensitiveOptionsEnd = sensitiveOptionsRemoved |
| 352 |
} |
| 353 |
|
| 354 |
return strings.Join(options, ",") + |
| 355 |
separator + |
| 356 |
sensitiveOptionsStart + |
| 357 |
sensitiveOptionsEnd |
| 358 |
} |