| 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 |
"path/filepath" |
| 25 |
"strings" |
| 26 |
"time" |
| 27 |
|
| 28 |
utilexec "k8s.io/utils/exec" |
| 29 |
) |
| 30 |
|
| 31 |
const ( |
| 32 |
// Default mount command if mounter path is not specified. |
| 33 |
defaultMountCommand = "mount" |
| 34 |
// Log message where sensitive mount options were removed |
| 35 |
sensitiveOptionsRemoved = "<masked>" |
| 36 |
) |
| 37 |
|
| 38 |
// Interface defines the set of methods to allow for mount operations on a system. |
| 39 |
type Interface interface { |
| 40 |
// Mount mounts source to target as fstype with given options. |
| 41 |
// options MUST not contain sensitive material (like passwords). |
| 42 |
Mount(source string, target string, fstype string, options []string) error |
| 43 |
// MountSensitive is the same as Mount() but this method allows |
| 44 |
// sensitiveOptions to be passed in a separate parameter from the normal |
| 45 |
// mount options and ensures the sensitiveOptions are never logged. This |
| 46 |
// method should be used by callers that pass sensitive material (like |
| 47 |
// passwords) as mount options. |
| 48 |
MountSensitive(source string, target string, fstype string, options []string, sensitiveOptions []string) error |
| 49 |
// MountSensitiveWithoutSystemd is the same as MountSensitive() but this method disable using systemd mount. |
| 50 |
MountSensitiveWithoutSystemd(source string, target string, fstype string, options []string, sensitiveOptions []string) error |
| 51 |
// MountSensitiveWithoutSystemdWithMountFlags is the same as MountSensitiveWithoutSystemd() with additional mount flags |
| 52 |
MountSensitiveWithoutSystemdWithMountFlags(source string, target string, fstype string, options []string, sensitiveOptions []string, mountFlags []string) error |
| 53 |
// Unmount unmounts given target. |
| 54 |
Unmount(target string) error |
| 55 |
// List returns a list of all mounted filesystems. This can be large. |
| 56 |
// On some platforms, reading mounts directly from the OS is not guaranteed |
| 57 |
// consistent (i.e. it could change between chunked reads). This is guaranteed |
| 58 |
// to be consistent. |
| 59 |
List() ([]MountPoint, error) |
| 60 |
// IsLikelyNotMountPoint uses heuristics to determine if a directory |
| 61 |
// is not a mountpoint. |
| 62 |
// It should return ErrNotExist when the directory does not exist. |
| 63 |
// IsLikelyNotMountPoint does NOT properly detect all mountpoint types |
| 64 |
// most notably linux bind mounts and symbolic link. For callers that do not |
| 65 |
// care about such situations, this is a faster alternative to calling List() |
| 66 |
// and scanning that output. |
| 67 |
IsLikelyNotMountPoint(file string) (bool, error) |
| 68 |
// CanSafelySkipMountPointCheck indicates whether this mounter returns errors on |
| 69 |
// operations for targets that are not mount points. If this returns true, no such |
| 70 |
// errors will be returned. |
| 71 |
CanSafelySkipMountPointCheck() bool |
| 72 |
// IsMountPoint determines if a directory is a mountpoint. |
| 73 |
// It should return ErrNotExist when the directory does not exist. |
| 74 |
// IsMountPoint is more expensive than IsLikelyNotMountPoint. |
| 75 |
// IsMountPoint detects bind mounts in linux. |
| 76 |
// IsMountPoint may enumerate all the mountpoints using List() and |
| 77 |
// the list of mountpoints may be large, then it uses |
| 78 |
// isMountPointMatch to evaluate whether the directory is a mountpoint. |
| 79 |
IsMountPoint(file string) (bool, error) |
| 80 |
// GetMountRefs finds all mount references to pathname, returning a slice of |
| 81 |
// paths. Pathname can be a mountpoint path or a normal directory |
| 82 |
// (for bind mount). On Linux, pathname is excluded from the slice. |
| 83 |
// For example, if /dev/sdc was mounted at /path/a and /path/b, |
| 84 |
// GetMountRefs("/path/a") would return ["/path/b"] |
| 85 |
// GetMountRefs("/path/b") would return ["/path/a"] |
| 86 |
// On Windows there is no way to query all mount points; as long as pathname is |
| 87 |
// a valid mount, it will be returned. |
| 88 |
GetMountRefs(pathname string) ([]string, error) |
| 89 |
} |
| 90 |
|
| 91 |
// Compile-time check to ensure all Mounter implementations satisfy |
| 92 |
// the mount interface. |
| 93 |
var _ Interface = &Mounter{} |
| 94 |
|
| 95 |
type MounterForceUnmounter interface { |
| 96 |
Interface |
| 97 |
// UnmountWithForce unmounts given target but will retry unmounting with force option |
| 98 |
// after given timeout. |
| 99 |
UnmountWithForce(target string, umountTimeout time.Duration) error |
| 100 |
} |
| 101 |
|
| 102 |
// MountPoint represents a single line in /proc/mounts or /etc/fstab. |
| 103 |
type MountPoint struct { |
| 104 |
Device string |
| 105 |
Path string |
| 106 |
Type string |
| 107 |
Opts []string // Opts may contain sensitive mount options (like passwords) and MUST be treated as such (e.g. not logged). |
| 108 |
Freq int |
| 109 |
Pass int |
| 110 |
} |
| 111 |
|
| 112 |
type MountErrorType string |
| 113 |
|
| 114 |
const ( |
| 115 |
FilesystemMismatch MountErrorType = "FilesystemMismatch" |
| 116 |
HasFilesystemErrors MountErrorType = "HasFilesystemErrors" |
| 117 |
UnformattedReadOnly MountErrorType = "UnformattedReadOnly" |
| 118 |
FormatFailed MountErrorType = "FormatFailed" |
| 119 |
GetDiskFormatFailed MountErrorType = "GetDiskFormatFailed" |
| 120 |
UnknownMountError MountErrorType = "UnknownMountError" |
| 121 |
) |
| 122 |
|
| 123 |
type MountError struct { |
| 124 |
Type MountErrorType |
| 125 |
Message string |
| 126 |
} |
| 127 |
|
| 128 |
func (mountError MountError) String() string { |
| 129 |
return mountError.Message |
| 130 |
} |
| 131 |
|
| 132 |
func (mountError MountError) Error() string { |
| 133 |
return mountError.Message |
| 134 |
} |
| 135 |
|
| 136 |
func NewMountError(mountErrorValue MountErrorType, format string, args ...interface{}) error { |
| 137 |
mountError := MountError{ |
| 138 |
Type: mountErrorValue, |
| 139 |
Message: fmt.Sprintf(format, args...), |
| 140 |
} |
| 141 |
return mountError |
| 142 |
} |
| 143 |
|
| 144 |
// SafeFormatAndMount probes a device to see if it is formatted. |
| 145 |
// Namely it checks to see if a file system is present. If so it |
| 146 |
// mounts it otherwise the device is formatted first then mounted. |
| 147 |
type SafeFormatAndMount struct { |
| 148 |
Interface |
| 149 |
Exec utilexec.Interface |
| 150 |
|
| 151 |
formatSem chan any |
| 152 |
formatTimeout time.Duration |
| 153 |
} |
| 154 |
|
| 155 |
func NewSafeFormatAndMount(mounter Interface, exec utilexec.Interface, opts ...Option) *SafeFormatAndMount { |
| 156 |
res := &SafeFormatAndMount{ |
| 157 |
Interface: mounter, |
| 158 |
Exec: exec, |
| 159 |
} |
| 160 |
for _, opt := range opts { |
| 161 |
opt(res) |
| 162 |
} |
| 163 |
return res |
| 164 |
} |
| 165 |
|
| 166 |
type Option func(*SafeFormatAndMount) |
| 167 |
|
| 168 |
// WithMaxConcurrentFormat sets the maximum number of concurrent format |
| 169 |
// operations executed by the mounter. The timeout controls the maximum |
| 170 |
// duration of a format operation before its concurrency token is released. |
| 171 |
// Once a token is released, it can be acquired by another concurrent format |
| 172 |
// operation. The original operation is allowed to complete. |
| 173 |
// If n < 1, concurrency is set to unlimited. |
| 174 |
func WithMaxConcurrentFormat(n int, timeout time.Duration) Option { |
| 175 |
return func(mounter *SafeFormatAndMount) { |
| 176 |
if n > 0 { |
| 177 |
mounter.formatSem = make(chan any, n) |
| 178 |
mounter.formatTimeout = timeout |
| 179 |
} |
| 180 |
} |
| 181 |
} |
| 182 |
|
| 183 |
// FormatAndMount formats the given disk, if needed, and mounts it. |
| 184 |
// That is if the disk is not formatted and it is not being mounted as |
| 185 |
// read-only it will format it first then mount it. Otherwise, if the |
| 186 |
// disk is already formatted or it is being mounted as read-only, it |
| 187 |
// will be mounted without formatting. |
| 188 |
// options MUST not contain sensitive material (like passwords). |
| 189 |
func (mounter *SafeFormatAndMount) FormatAndMount(source string, target string, fstype string, options []string) error { |
| 190 |
return mounter.FormatAndMountSensitive(source, target, fstype, options, nil /* sensitiveOptions */) |
| 191 |
} |
| 192 |
|
| 193 |
// FormatAndMountSensitive is the same as FormatAndMount but this method allows |
| 194 |
// sensitiveOptions to be passed in a separate parameter from the normal mount |
| 195 |
// options and ensures the sensitiveOptions are never logged. This method should |
| 196 |
// be used by callers that pass sensitive material (like passwords) as mount |
| 197 |
// options. |
| 198 |
func (mounter *SafeFormatAndMount) FormatAndMountSensitive(source string, target string, fstype string, options []string, sensitiveOptions []string) error { |
| 199 |
return mounter.FormatAndMountSensitiveWithFormatOptions(source, target, fstype, options, sensitiveOptions, nil /* formatOptions */) |
| 200 |
} |
| 201 |
|
| 202 |
// FormatAndMountSensitiveWithFormatOptions behaves exactly the same as |
| 203 |
// FormatAndMountSensitive, but allows for options to be passed when the disk |
| 204 |
// is formatted. These options are NOT validated in any way and should never |
| 205 |
// come directly from untrusted user input as that would be an injection risk. |
| 206 |
func (mounter *SafeFormatAndMount) FormatAndMountSensitiveWithFormatOptions(source string, target string, fstype string, options []string, sensitiveOptions []string, formatOptions []string) error { |
| 207 |
return mounter.formatAndMountSensitive(source, target, fstype, options, sensitiveOptions, formatOptions) |
| 208 |
} |
| 209 |
|
| 210 |
// getMountRefsByDev finds all references to the device provided |
| 211 |
// by mountPath; returns a list of paths. |
| 212 |
// Note that mountPath should be path after the evaluation of any symblolic links. |
| 213 |
func getMountRefsByDev(mounter Interface, mountPath string) ([]string, error) { |
| 214 |
mps, err := mounter.List() |
| 215 |
if err != nil { |
| 216 |
return nil, err |
| 217 |
} |
| 218 |
|
| 219 |
// Finding the device mounted to mountPath. |
| 220 |
diskDev := "" |
| 221 |
for i := range mps { |
| 222 |
if mountPath == mps[i].Path { |
| 223 |
diskDev = mps[i].Device |
| 224 |
break |
| 225 |
} |
| 226 |
} |
| 227 |
|
| 228 |
// Find all references to the device. |
| 229 |
var refs []string |
| 230 |
for i := range mps { |
| 231 |
if mps[i].Device == diskDev || mps[i].Device == mountPath { |
| 232 |
if mps[i].Path != mountPath { |
| 233 |
refs = append(refs, mps[i].Path) |
| 234 |
} |
| 235 |
} |
| 236 |
} |
| 237 |
return refs, nil |
| 238 |
} |
| 239 |
|
| 240 |
// IsNotMountPoint determines if a directory is a mountpoint. |
| 241 |
// It should return ErrNotExist when the directory does not exist. |
| 242 |
// IsNotMountPoint is more expensive than IsLikelyNotMountPoint |
| 243 |
// and depends on IsMountPoint. |
| 244 |
// |
| 245 |
// If an error occurs, it returns true (assuming it is not a mountpoint) |
| 246 |
// when ErrNotExist is returned for callers similar to IsLikelyNotMountPoint. |
| 247 |
// |
| 248 |
// Deprecated: This function is kept to keep changes backward compatible with |
| 249 |
// previous library version. Callers should prefer mounter.IsMountPoint. |
| 250 |
func IsNotMountPoint(mounter Interface, file string) (bool, error) { |
| 251 |
isMnt, err := mounter.IsMountPoint(file) |
| 252 |
if err != nil { |
| 253 |
return true, err |
| 254 |
} |
| 255 |
return !isMnt, nil |
| 256 |
} |
| 257 |
|
| 258 |
// GetDeviceNameFromMount given a mnt point, find the device from /proc/mounts |
| 259 |
// returns the device name, reference count, and error code. |
| 260 |
func GetDeviceNameFromMount(mounter Interface, mountPath string) (string, int, error) { |
| 261 |
mps, err := mounter.List() |
| 262 |
if err != nil { |
| 263 |
return "", 0, err |
| 264 |
} |
| 265 |
|
| 266 |
// Find the device name. |
| 267 |
// FIXME if multiple devices mounted on the same mount path, only the first one is returned. |
| 268 |
device := "" |
| 269 |
// If mountPath is symlink, need get its target path. |
| 270 |
slTarget, err := filepath.EvalSymlinks(mountPath) |
| 271 |
if err != nil { |
| 272 |
slTarget = mountPath |
| 273 |
} |
| 274 |
for i := range mps { |
| 275 |
if mps[i].Path == slTarget { |
| 276 |
device = mps[i].Device |
| 277 |
break |
| 278 |
} |
| 279 |
} |
| 280 |
|
| 281 |
// Find all references to the device. |
| 282 |
refCount := 0 |
| 283 |
for i := range mps { |
| 284 |
if mps[i].Device == device { |
| 285 |
refCount++ |
| 286 |
} |
| 287 |
} |
| 288 |
return device, refCount, nil |
| 289 |
} |
| 290 |
|
| 291 |
// MakeBindOpts detects whether a bind mount is being requested and makes the remount options to |
| 292 |
// use in case of bind mount, due to the fact that bind mount doesn't respect mount options. |
| 293 |
// The list equals: |
| 294 |
// |
| 295 |
// options - 'bind' + 'remount' (no duplicate) |
| 296 |
func MakeBindOpts(options []string) (bool, []string, []string) { |
| 297 |
bind, bindOpts, bindRemountOpts, _ := MakeBindOptsSensitive(options, nil /* sensitiveOptions */) |
| 298 |
return bind, bindOpts, bindRemountOpts |
| 299 |
} |
| 300 |
|
| 301 |
// MakeBindOptsSensitive is the same as MakeBindOpts but this method allows |
| 302 |
// sensitiveOptions to be passed in a separate parameter from the normal mount |
| 303 |
// options and ensures the sensitiveOptions are never logged. This method should |
| 304 |
// be used by callers that pass sensitive material (like passwords) as mount |
| 305 |
// options. |
| 306 |
func MakeBindOptsSensitive(options []string, sensitiveOptions []string) (bool, []string, []string, []string) { |
| 307 |
// Because we have an FD opened on the subpath bind mount, the "bind" option |
| 308 |
// needs to be included, otherwise the mount target will error as busy if you |
| 309 |
// remount as readonly. |
| 310 |
// |
| 311 |
// As a consequence, all read only bind mounts will no longer change the underlying |
| 312 |
// volume mount to be read only. |
| 313 |
bindRemountOpts := []string{"bind", "remount"} |
| 314 |
bindRemountSensitiveOpts := []string{} |
| 315 |
bind := false |
| 316 |
bindOpts := []string{"bind"} |
| 317 |
|
| 318 |
// _netdev is a userspace mount option and does not automatically get added when |
| 319 |
// bind mount is created and hence we must carry it over. |
| 320 |
if checkForNetDev(options, sensitiveOptions) { |
| 321 |
bindOpts = append(bindOpts, "_netdev") |
| 322 |
} |
| 323 |
|
| 324 |
for _, option := range options { |
| 325 |
switch option { |
| 326 |
case "bind": |
| 327 |
bind = true |
| 328 |
case "remount": |
| 329 |
default: |
| 330 |
bindRemountOpts = append(bindRemountOpts, option) |
| 331 |
} |
| 332 |
} |
| 333 |
|
| 334 |
for _, sensitiveOption := range sensitiveOptions { |
| 335 |
switch sensitiveOption { |
| 336 |
case "bind": |
| 337 |
bind = true |
| 338 |
case "remount": |
| 339 |
default: |
| 340 |
bindRemountSensitiveOpts = append(bindRemountSensitiveOpts, sensitiveOption) |
| 341 |
} |
| 342 |
} |
| 343 |
|
| 344 |
return bind, bindOpts, bindRemountOpts, bindRemountSensitiveOpts |
| 345 |
} |
| 346 |
|
| 347 |
func checkForNetDev(options []string, sensitiveOptions []string) bool { |
| 348 |
for _, option := range options { |
| 349 |
if option == "_netdev" { |
| 350 |
return true |
| 351 |
} |
| 352 |
} |
| 353 |
for _, sensitiveOption := range sensitiveOptions { |
| 354 |
if sensitiveOption == "_netdev" { |
| 355 |
return true |
| 356 |
} |
| 357 |
} |
| 358 |
return false |
| 359 |
} |
| 360 |
|
| 361 |
// PathWithinBase checks if give path is within given base directory. |
| 362 |
func PathWithinBase(fullPath, basePath string) bool { |
| 363 |
rel, err := filepath.Rel(basePath, fullPath) |
| 364 |
if err != nil { |
| 365 |
return false |
| 366 |
} |
| 367 |
if StartsWithBackstep(rel) { |
| 368 |
// Needed to escape the base path. |
| 369 |
return false |
| 370 |
} |
| 371 |
return true |
| 372 |
} |
| 373 |
|
| 374 |
// StartsWithBackstep checks if the given path starts with a backstep segment. |
| 375 |
func StartsWithBackstep(rel string) bool { |
| 376 |
// normalize to / and check for ../ |
| 377 |
return rel == ".." || strings.HasPrefix(filepath.ToSlash(rel), "../") |
| 378 |
} |
| 379 |
|
| 380 |
// sanitizedOptionsForLogging will return a comma separated string containing |
| 381 |
// options and sensitiveOptions. Each entry in sensitiveOptions will be |
| 382 |
// replaced with the string sensitiveOptionsRemoved |
| 383 |
// e.g. o1,o2,<masked>,<masked> |
| 384 |
func sanitizedOptionsForLogging(options []string, sensitiveOptions []string) string { |
| 385 |
separator := "" |
| 386 |
if len(options) > 0 && len(sensitiveOptions) > 0 { |
| 387 |
separator = "," |
| 388 |
} |
| 389 |
|
| 390 |
sensitiveOptionsStart := "" |
| 391 |
sensitiveOptionsEnd := "" |
| 392 |
if len(sensitiveOptions) > 0 { |
| 393 |
sensitiveOptionsStart = strings.Repeat(sensitiveOptionsRemoved+",", len(sensitiveOptions)-1) |
| 394 |
sensitiveOptionsEnd = sensitiveOptionsRemoved |
| 395 |
} |
| 396 |
|
| 397 |
return strings.Join(options, ",") + |
| 398 |
separator + |
| 399 |
sensitiveOptionsStart + |
| 400 |
sensitiveOptionsEnd |
| 401 |
} |