Debian Codegraph @

filesystem/filesystem.go

raw
1 /*
2 * filesystem.go - Contains the functionality for a specific filesystem. This
3 * includes the commands to setup the filesystem, apply policies, and locate
4 * metadata.
5 *
6 * Copyright 2017 Google Inc.
7 * Author: Joe Richey ([email protected])
8 *
9 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
10 * use this file except in compliance with the License. You may obtain a copy of
11 * the License at
12 *
13 * http://www.apache.org/licenses/LICENSE-2.0
14 *
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
17 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
18 * License for the specific language governing permissions and limitations under
19 * the License.
20 */
21
22 // Package filesystem deals with the structure of the files on disk used to
23 // store the metadata for fscrypt. Specifically, this package includes:
24 // 1. mountpoint management (mountpoint.go)
25 // - querying existing mounted filesystems
26 // - getting filesystems from a UUID
27 // - finding the filesystem for a specific path
28 // 2. metadata organization (filesystem.go)
29 // - setting up a mounted filesystem for use with fscrypt
30 // - adding/querying/deleting metadata
31 // - making links to other filesystems' metadata
32 // - following links to get data from other filesystems
33 package filesystem
34
35 import (
36 "fmt"
37 "io"
38 "log"
39 "os"
40 "os/user"
41 "path/filepath"
42 "sort"
43 "strings"
44 "syscall"
45 "time"
46
47 "github.com/pkg/errors"
48 "golang.org/x/sys/unix"
49 "google.golang.org/protobuf/proto"
50
51 "github.com/google/fscrypt/metadata"
52 "github.com/google/fscrypt/util"
53 )
54
55 // ErrAlreadySetup indicates that a filesystem is already setup for fscrypt.
56 type ErrAlreadySetup struct {
57 Mount *Mount
58 }
59
60 func (err *ErrAlreadySetup) Error() string {
61 return fmt.Sprintf("filesystem %s is already setup for use with fscrypt",
62 err.Mount.Path)
63 }
64
65 // ErrCorruptMetadata indicates that an fscrypt metadata file is corrupt.
66 type ErrCorruptMetadata struct {
67 Path string
68 UnderlyingError error
69 }
70
71 func (err *ErrCorruptMetadata) Error() string {
72 return fmt.Sprintf("fscrypt metadata file at %q is corrupt: %s",
73 err.Path, err.UnderlyingError)
74 }
75
76 // ErrFollowLink indicates that a protector link can't be followed.
77 type ErrFollowLink struct {
78 Link string
79 UnderlyingError error
80 }
81
82 func (err *ErrFollowLink) Error() string {
83 return fmt.Sprintf("cannot follow filesystem link %q: %s",
84 err.Link, err.UnderlyingError)
85 }
86
87 // ErrInsecurePermissions indicates that a filesystem is not considered to be
88 // setup for fscrypt because a metadata directory has insecure permissions.
89 type ErrInsecurePermissions struct {
90 Path string
91 }
92
93 func (err *ErrInsecurePermissions) Error() string {
94 return fmt.Sprintf("%q has insecure permissions (world-writable without sticky bit)",
95 err.Path)
96 }
97
98 // ErrMakeLink indicates that a protector link can't be created.
99 type ErrMakeLink struct {
100 Target *Mount
101 UnderlyingError error
102 }
103
104 func (err *ErrMakeLink) Error() string {
105 return fmt.Sprintf("cannot create filesystem link to %q: %s",
106 err.Target.Path, err.UnderlyingError)
107 }
108
109 // ErrMountOwnedByAnotherUser indicates that the mountpoint root directory is
110 // owned by a user that isn't trusted in the current context, so we don't
111 // consider fscrypt to be properly setup on the filesystem.
112 type ErrMountOwnedByAnotherUser struct {
113 Mount *Mount
114 }
115
116 func (err *ErrMountOwnedByAnotherUser) Error() string {
117 return fmt.Sprintf("another non-root user owns the root directory of %s", err.Mount.Path)
118 }
119
120 // ErrNoCreatePermission indicates that the current user lacks permission to
121 // create fscrypt metadata on the given filesystem.
122 type ErrNoCreatePermission struct {
123 Mount *Mount
124 }
125
126 func (err *ErrNoCreatePermission) Error() string {
127 return fmt.Sprintf("user lacks permission to create fscrypt metadata on %s", err.Mount.Path)
128 }
129
130 // ErrNotAMountpoint indicates that a path is not a mountpoint.
131 type ErrNotAMountpoint struct {
132 Path string
133 }
134
135 func (err *ErrNotAMountpoint) Error() string {
136 return fmt.Sprintf("%q is not a mountpoint", err.Path)
137 }
138
139 // ErrNotSetup indicates that a filesystem is not setup for fscrypt.
140 type ErrNotSetup struct {
141 Mount *Mount
142 }
143
144 func (err *ErrNotSetup) Error() string {
145 return fmt.Sprintf("filesystem %s is not setup for use with fscrypt", err.Mount.Path)
146 }
147
148 // ErrSetupByAnotherUser indicates that one or more of the fscrypt metadata
149 // directories is owned by a user that isn't trusted in the current context, so
150 // we don't consider fscrypt to be properly setup on the filesystem.
151 type ErrSetupByAnotherUser struct {
152 Mount *Mount
153 }
154
155 func (err *ErrSetupByAnotherUser) Error() string {
156 return fmt.Sprintf("another non-root user owns fscrypt metadata directories on %s", err.Mount.Path)
157 }
158
159 // ErrSetupNotSupported indicates that the given filesystem type is not
160 // supported for fscrypt setup.
161 type ErrSetupNotSupported struct {
162 Mount *Mount
163 }
164
165 func (err *ErrSetupNotSupported) Error() string {
166 return fmt.Sprintf("filesystem type %s is not supported for fscrypt setup",
167 err.Mount.FilesystemType)
168 }
169
170 // ErrPolicyNotFound indicates that the policy metadata was not found.
171 type ErrPolicyNotFound struct {
172 Descriptor string
173 Mount *Mount
174 }
175
176 func (err *ErrPolicyNotFound) Error() string {
177 return fmt.Sprintf("policy metadata for %s not found on filesystem %s",
178 err.Descriptor, err.Mount.Path)
179 }
180
181 // ErrProtectorNotFound indicates that the protector metadata was not found.
182 type ErrProtectorNotFound struct {
183 Descriptor string
184 Mount *Mount
185 }
186
187 func (err *ErrProtectorNotFound) Error() string {
188 return fmt.Sprintf("protector metadata for %s not found on filesystem %s",
189 err.Descriptor, err.Mount.Path)
190 }
191
192 // SortDescriptorsByLastMtime indicates whether descriptors are sorted by last
193 // modification time when being listed. This can be set to true to get
194 // consistent output for testing.
195 var SortDescriptorsByLastMtime = false
196
197 // Mount contains information for a specific mounted filesystem.
198 //
199 // Path - Absolute path where the directory is mounted
200 // FilesystemType - Type of the mounted filesystem, e.g. "ext4"
201 // Device - Device for filesystem (empty string if we cannot find one)
202 // DeviceNumber - Device number of the filesystem. This is set even if
203 // Device isn't, since all filesystems have a device
204 // number assigned by the kernel, even pseudo-filesystems.
205 // Subtree - The mounted subtree of the filesystem. This is usually
206 // "/", meaning that the entire filesystem is mounted, but
207 // it can differ for bind mounts.
208 // ReadOnly - True if this is a read-only mount
209 //
210 // In order to use a Mount to store fscrypt metadata, some directories must be
211 // setup first. Specifically, the directories created look like:
212 // <mountpoint>
213 // └── .fscrypt
214 //
215 // ├── policies
216 // └── protectors
217 //
218 // These "policies" and "protectors" directories will contain files that are
219 // the corresponding metadata structures for policies and protectors. The public
220 // interface includes functions for setting up these directories and Adding,
221 // Getting, and Removing these files.
222 //
223 // There is also the ability to reference another filesystem's metadata. This is
224 // used when a Policy on filesystem A is protected with Protector on filesystem
225 // B. In this scenario, we store a "link file" in the protectors directory.
226 //
227 // We also allow ".fscrypt" to be a symlink which was previously created. This
228 // allows login protectors to be created when the root filesystem is read-only,
229 // provided that "/.fscrypt" is a symlink pointing to a writable location.
230 type Mount struct {
231 Path string
232 FilesystemType string
233 Device string
234 DeviceNumber DeviceNumber
235 Subtree string
236 ReadOnly bool
237 }
238
239 // PathSorter allows mounts to be sorted by Path.
240 type PathSorter []*Mount
241
242 func (p PathSorter) Len() int { return len(p) }
243 func (p PathSorter) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
244 func (p PathSorter) Less(i, j int) bool { return p[i].Path < p[j].Path }
245
246 const (
247 // Names of the various directories used in fscrypt
248 baseDirName = ".fscrypt"
249 policyDirName = "policies"
250 protectorDirName = "protectors"
251 tempPrefix = ".tmp"
252 linkFileExtension = ".link"
253
254 // The base directory should be read-only (except for the creator)
255 basePermissions = 0755
256
257 // The metadata files shouldn't be readable or writable by other users.
258 // Having them be world-readable wouldn't necessarily be a huge issue,
259 // but given that some of these files contain (strong) password hashes,
260 // we error on the side of caution -- similar to /etc/shadow.
261 // Note: existing files on-disk might have mode 0644, as that was the
262 // mode used by fscrypt v0.3.2 and earlier.
263 filePermissions = os.FileMode(0600)
264
265 // Maximum size of a metadata file. This value is arbitrary, and it can
266 // be changed. We just set a reasonable limit that shouldn't be reached
267 // in practice, except by users trying to cause havoc by creating
268 // extremely large files in the metadata directories.
269 maxMetadataFileSize = 16384
270 )
271
272 // SetupMode is a mode for creating the fscrypt metadata directories.
273 type SetupMode int
274
275 const (
276 // SingleUserWritable specifies to make the fscrypt metadata directories
277 // writable by a single user (usually root) only.
278 SingleUserWritable SetupMode = iota
279 // WorldWritable specifies to make the fscrypt metadata directories
280 // world-writable (with the sticky bit set).
281 WorldWritable
282 )
283
284 func (m *Mount) String() string {
285 return fmt.Sprintf(`%s
286 FilesystemType: %s
287 Device: %s`, m.Path, m.FilesystemType, m.Device)
288 }
289
290 // BaseDir returns the path to the base fscrypt directory for this filesystem.
291 func (m *Mount) BaseDir() string {
292 rawBaseDir := filepath.Join(m.Path, baseDirName)
293 // We allow the base directory to be a symlink, but some callers need
294 // the real path, so dereference the symlink here if needed. Since the
295 // directory the symlink points to may not exist yet, we have to read
296 // the symlink manually rather than use filepath.EvalSymlinks.
297 target, err := os.Readlink(rawBaseDir)
298 if err != nil {
299 return rawBaseDir // not a symlink
300 }
301 if filepath.IsAbs(target) {
302 return target
303 }
304 return filepath.Join(m.Path, target)
305 }
306
307 // ProtectorDir returns the directory containing the protector metadata.
308 func (m *Mount) ProtectorDir() string {
309 return filepath.Join(m.BaseDir(), protectorDirName)
310 }
311
312 // protectorPath returns the full path to a regular protector file with the
313 // specified descriptor.
314 func (m *Mount) protectorPath(descriptor string) string {
315 return filepath.Join(m.ProtectorDir(), descriptor)
316 }
317
318 // linkedProtectorPath returns the full path to a linked protector file with the
319 // specified descriptor.
320 func (m *Mount) linkedProtectorPath(descriptor string) string {
321 return m.protectorPath(descriptor) + linkFileExtension
322 }
323
324 // PolicyDir returns the directory containing the policy metadata.
325 func (m *Mount) PolicyDir() string {
326 return filepath.Join(m.BaseDir(), policyDirName)
327 }
328
329 // PolicyPath returns the full path to a regular policy file with the
330 // specified descriptor.
331 func (m *Mount) PolicyPath(descriptor string) string {
332 return filepath.Join(m.PolicyDir(), descriptor)
333 }
334
335 // tempMount creates a temporary directory alongside this Mount's base fscrypt
336 // directory and returns a temporary Mount which represents this temporary
337 // directory. The caller is responsible for removing this temporary directory.
338 func (m *Mount) tempMount() (*Mount, error) {
339 tempDir, err := os.MkdirTemp(filepath.Dir(m.BaseDir()), tempPrefix)
340 return &Mount{Path: tempDir}, err
341 }
342
343 // ErrEncryptionNotEnabled indicates that encryption is not enabled on the given
344 // filesystem.
345 type ErrEncryptionNotEnabled struct {
346 Mount *Mount
347 }
348
349 func (err *ErrEncryptionNotEnabled) Error() string {
350 return fmt.Sprintf("encryption not enabled on filesystem %s (%s).",
351 err.Mount.Path, err.Mount.Device)
352 }
353
354 // ErrEncryptionNotSupported indicates that encryption is not supported on the
355 // given filesystem.
356 type ErrEncryptionNotSupported struct {
357 Mount *Mount
358 }
359
360 func (err *ErrEncryptionNotSupported) Error() string {
361 return fmt.Sprintf("This kernel doesn't support encryption on %s filesystems.",
362 err.Mount.FilesystemType)
363 }
364
365 // EncryptionSupportError adds filesystem-specific context to the
366 // ErrEncryptionNotEnabled and ErrEncryptionNotSupported errors from the
367 // metadata package.
368 func (m *Mount) EncryptionSupportError(err error) error {
369 switch err {
370 case metadata.ErrEncryptionNotEnabled:
371 return &ErrEncryptionNotEnabled{m}
372 case metadata.ErrEncryptionNotSupported:
373 return &ErrEncryptionNotSupported{m}
374 }
375 return err
376 }
377
378 // isFscryptSetupAllowed decides whether the given filesystem is allowed to be
379 // set up for fscrypt, without actually accessing it. This basically checks
380 // whether the filesystem type is one of the types that supports encryption, or
381 // at least is in some stage of planning for encrption support in the future.
382 //
383 // We need this list so that we can skip filesystems that are irrelevant for
384 // fscrypt without having to look for the fscrypt metadata directories on them,
385 // which can trigger errors, long delays, or side effects on some filesystems.
386 //
387 // Unfortunately, this means that if a completely new filesystem adds encryption
388 // support, then it will need to be manually added to this list. But it seems
389 // to be a worthwhile tradeoff to avoid the above issues.
390 func (m *Mount) isFscryptSetupAllowed() bool {
391 if m.Path == "/" {
392 // The root filesystem is always allowed, since it's where login
393 // protectors are stored.
394 return true
395 }
396 switch m.FilesystemType {
397 case "ext4", "f2fs", "ubifs", "btrfs", "ceph", "xfs", "lustre":
398 return true
399 default:
400 return false
401 }
402 }
403
404 // CheckSupport returns an error if this filesystem does not support encryption.
405 func (m *Mount) CheckSupport() error {
406 if !m.isFscryptSetupAllowed() {
407 return &ErrEncryptionNotSupported{m}
408 }
409 return m.EncryptionSupportError(metadata.CheckSupport(m.Path))
410 }
411
412 func checkOwnership(path string, info os.FileInfo, trustedUser *user.User) bool {
413 if trustedUser == nil {
414 return true
415 }
416 trustedUID := uint32(util.AtoiOrPanic(trustedUser.Uid))
417 actualUID := info.Sys().(*syscall.Stat_t).Uid
418 if actualUID != 0 && actualUID != trustedUID {
419 log.Printf("WARNING: %q is owned by uid %d, but expected %d or 0",
420 path, actualUID, trustedUID)
421 return false
422 }
423 return true
424 }
425
426 // CheckSetup returns an error if any of the fscrypt metadata directories do not
427 // exist. Will log any unexpected errors or incorrect permissions.
428 func (m *Mount) CheckSetup(trustedUser *user.User) error {
429 if !m.isFscryptSetupAllowed() {
430 return &ErrNotSetup{m}
431 }
432 // Check that the mountpoint directory itself is not a symlink and has
433 // proper ownership, as otherwise we can't trust anything beneath it.
434 info, err := loggedLstat(m.Path)
435 if err != nil {
436 return &ErrNotSetup{m}
437 }
438 if (info.Mode() & os.ModeSymlink) != 0 {
439 log.Printf("mountpoint directory %q cannot be a symlink", m.Path)
440 return &ErrNotSetup{m}
441 }
442 if !info.IsDir() {
443 log.Printf("mountpoint %q is not a directory", m.Path)
444 return &ErrNotSetup{m}
445 }
446 if !checkOwnership(m.Path, info, trustedUser) {
447 return &ErrMountOwnedByAnotherUser{m}
448 }
449
450 // Check BaseDir similarly. However, unlike the other directories, we
451 // allow BaseDir to be a symlink, to support the use case of metadata
452 // for a read-only filesystem being redirected to a writable location.
453 info, err = loggedStat(m.BaseDir())
454 if err != nil {
455 return &ErrNotSetup{m}
456 }
457 if !info.IsDir() {
458 log.Printf("%q is not a directory", m.BaseDir())
459 return &ErrNotSetup{m}
460 }
461 if !checkOwnership(m.Path, info, trustedUser) {
462 return &ErrMountOwnedByAnotherUser{m}
463 }
464
465 // Check that the policies and protectors directories aren't symlinks and
466 // have proper ownership.
467 subdirs := []string{m.PolicyDir(), m.ProtectorDir()}
468 for _, path := range subdirs {
469 info, err := loggedLstat(path)
470 if err != nil {
471 return &ErrNotSetup{m}
472 }
473 if (info.Mode() & os.ModeSymlink) != 0 {
474 log.Printf("directory %q cannot be a symlink", path)
475 return &ErrNotSetup{m}
476 }
477 if !info.IsDir() {
478 log.Printf("%q is not a directory", path)
479 return &ErrNotSetup{m}
480 }
481 // We are no longer too picky about the mode, given that
482 // 'fscrypt setup' now offers a choice of two different modes,
483 // and system administrators could customize it further.
484 // However, we can at least verify that if the directory is
485 // world-writable, then the sticky bit is also set.
486 if info.Mode()&(os.ModeSticky|0002) == 0002 {
487 log.Printf("%q is world-writable but doesn't have sticky bit set", path)
488 return &ErrInsecurePermissions{path}
489 }
490 if !checkOwnership(path, info, trustedUser) {
491 return &ErrSetupByAnotherUser{m}
492 }
493 }
494 return nil
495 }
496
497 // makeDirectories creates the three metadata directories with the correct
498 // permissions. Note that this function overrides the umask.
499 func (m *Mount) makeDirectories(setupMode SetupMode) error {
500 // Zero the umask so we get the permissions we want
501 oldMask := unix.Umask(0)
502 defer func() {
503 unix.Umask(oldMask)
504 }()
505
506 if err := os.Mkdir(m.BaseDir(), basePermissions); err != nil {
507 return err
508 }
509
510 var dirMode os.FileMode
511 switch setupMode {
512 case SingleUserWritable:
513 dirMode = 0755
514 case WorldWritable:
515 dirMode = os.ModeSticky | 0777
516 }
517 if err := os.Mkdir(m.PolicyDir(), dirMode); err != nil {
518 return err
519 }
520 return os.Mkdir(m.ProtectorDir(), dirMode)
521 }
522
523 // GetSetupMode returns the current mode for fscrypt metadata creation on this
524 // filesystem.
525 func (m *Mount) GetSetupMode() (SetupMode, *user.User, error) {
526 info1, err1 := os.Stat(m.PolicyDir())
527 info2, err2 := os.Stat(m.ProtectorDir())
528
529 if err1 == nil && err2 == nil {
530 mask := os.ModeSticky | 0777
531 mode1 := info1.Mode() & mask
532 mode2 := info2.Mode() & mask
533 uid1 := info1.Sys().(*syscall.Stat_t).Uid
534 uid2 := info2.Sys().(*syscall.Stat_t).Uid
535 user, err := util.UserFromUID(int64(uid1))
536 if err == nil && mode1 == mode2 && uid1 == uid2 {
537 switch mode1 {
538 case mask:
539 return WorldWritable, nil, nil
540 case 0755:
541 return SingleUserWritable, user, nil
542 }
543 }
544 log.Printf("filesystem %s uses custom permissions on metadata directories", m.Path)
545 }
546 return -1, nil, errors.New("unable to determine setup mode")
547 }
548
549 // Setup sets up the filesystem for use with fscrypt. Note that this merely
550 // creates the appropriate files on the filesystem. It does not actually modify
551 // the filesystem's feature flags. This operation is atomic; it either succeeds
552 // or no files in the baseDir are created.
553 func (m *Mount) Setup(mode SetupMode) error {
554 if m.CheckSetup(nil) == nil {
555 return &ErrAlreadySetup{m}
556 }
557 if !m.isFscryptSetupAllowed() {
558 return &ErrSetupNotSupported{m}
559 }
560 // We build the directories under a temp Mount and then move into place.
561 temp, err := m.tempMount()
562 if err != nil {
563 return err
564 }
565 defer os.RemoveAll(temp.Path)
566
567 if err = temp.makeDirectories(mode); err != nil {
568 return err
569 }
570
571 // Atomically move directory into place.
572 return os.Rename(temp.BaseDir(), m.BaseDir())
573 }
574
575 // RemoveAllMetadata removes all the policy and protector metadata from the
576 // filesystem. This operation is atomic; it either succeeds or no files in the
577 // baseDir are removed.
578 // WARNING: Will cause data loss if the metadata is used to encrypt
579 // directories (this could include directories on other filesystems).
580 func (m *Mount) RemoveAllMetadata() error {
581 if err := m.CheckSetup(nil); err != nil {
582 return err
583 }
584 // temp will hold the old metadata temporarily
585 temp, err := m.tempMount()
586 if err != nil {
587 return err
588 }
589 defer os.RemoveAll(temp.Path)
590
591 // Move directory into temp (to be destroyed on defer)
592 return os.Rename(m.BaseDir(), temp.BaseDir())
593 }
594
595 func syncDirectory(dirPath string) error {
596 dirFile, err := os.Open(dirPath)
597 if err != nil {
598 return err
599 }
600 if err = dirFile.Sync(); err != nil {
601 dirFile.Close()
602 return err
603 }
604 return dirFile.Close()
605 }
606
607 func (m *Mount) overwriteDataNonAtomic(path string, data []byte) error {
608 file, err := os.OpenFile(path, os.O_WRONLY|os.O_TRUNC|unix.O_NOFOLLOW, 0)
609 if err != nil {
610 return err
611 }
612 if _, err = file.Write(data); err != nil {
613 log.Printf("WARNING: overwrite of %q failed; file will be corrupted!", path)
614 file.Close()
615 return err
616 }
617 if err = file.Sync(); err != nil {
618 file.Close()
619 return err
620 }
621 if err = file.Close(); err != nil {
622 return err
623 }
624 log.Printf("successfully overwrote %q non-atomically", path)
625 return nil
626 }
627
628 // writeData writes the given data to the given path such that, if possible, the
629 // data is either written to stable storage or an error is returned. If a file
630 // already exists at the path, it will be replaced.
631 //
632 // However, if the process doesn't have write permission to the directory but
633 // does have write permission to the file itself, then as a fallback the file is
634 // overwritten in-place rather than replaced. Note that this may be non-atomic.
635 func (m *Mount) writeData(path string, data []byte, owner *user.User, mode os.FileMode) error {
636 // Write the data to a temporary file, sync it, then rename into place
637 // so that the operation will be atomic.
638 dirPath := filepath.Dir(path)
639 tempFile, err := os.CreateTemp(dirPath, tempPrefix)
640 if err != nil {
641 log.Print(err)
642 if os.IsPermission(err) {
643 if _, err = os.Lstat(path); err == nil {
644 log.Printf("trying non-atomic overwrite of %q", path)
645 return m.overwriteDataNonAtomic(path, data)
646 }
647 return &ErrNoCreatePermission{m}
648 }
649 return err
650 }
651 defer os.Remove(tempFile.Name())
652
653 // Ensure the new file has the right permissions mask.
654 if err = tempFile.Chmod(mode); err != nil {
655 tempFile.Close()
656 return err
657 }
658 // Override the file owner if one was specified. This happens when root
659 // needs to create files owned by a particular user.
660 if owner != nil {
661 if err = util.Chown(tempFile, owner); err != nil {
662 log.Printf("could not set owner of %q to %v: %v",
663 path, owner.Username, err)
664 tempFile.Close()
665 return err
666 }
667 }
668 if _, err = tempFile.Write(data); err != nil {
669 tempFile.Close()
670 return err
671 }
672 if err = tempFile.Sync(); err != nil {
673 tempFile.Close()
674 return err
675 }
676 if err = tempFile.Close(); err != nil {
677 return err
678 }
679
680 if err = os.Rename(tempFile.Name(), path); err != nil {
681 return err
682 }
683 // Ensure the rename has been persisted before returning success.
684 return syncDirectory(dirPath)
685 }
686
687 // addMetadata writes the metadata structure to the file with the specified
688 // path. This will overwrite any existing data. The operation is atomic.
689 func (m *Mount) addMetadata(path string, md metadata.Metadata, owner *user.User) error {
690 if err := md.CheckValidity(); err != nil {
691 return errors.Wrap(err, "provided metadata is invalid")
692 }
693
694 data, err := proto.Marshal(md)
695 if err != nil {
696 return err
697 }
698
699 mode := filePermissions
700 // If the file already exists, then preserve its owner and mode if
701 // possible. This is necessary because by default, for atomicity
702 // reasons we'll replace the file rather than overwrite it.
703 info, err := os.Lstat(path)
704 if err == nil {
705 if owner == nil && util.IsUserRoot() {
706 uid := info.Sys().(*syscall.Stat_t).Uid
707 if owner, err = util.UserFromUID(int64(uid)); err != nil {
708 log.Print(err)
709 }
710 }
711 mode = info.Mode() & 0777
712 } else if !os.IsNotExist(err) {
713 log.Print(err)
714 }
715
716 if owner != nil {
717 log.Printf("writing metadata to %q and setting owner to %s", path, owner.Username)
718 } else {
719 log.Printf("writing metadata to %q", path)
720 }
721 return m.writeData(path, data, owner, mode)
722 }
723
724 // readMetadataFileSafe gets the contents of a metadata file extra-carefully,
725 // considering that it could be a malicious file created to cause a
726 // denial-of-service. Specifically, the following checks are done:
727 //
728 // - It must be a regular file, not another type of file like a symlink or FIFO.
729 // (Symlinks aren't bad by themselves, but given that a malicious user could
730 // point one to absolutely anywhere, and there is no known use case for the
731 // metadata files themselves being symlinks, it seems best to disallow them.)
732 // - It must have a reasonable size (<= maxMetadataFileSize).
733 // - If trustedUser is non-nil, then the file must be owned by the given user
734 // or by root.
735 //
736 // Take care to avoid TOCTOU (time-of-check-time-of-use) bugs when doing these
737 // tests. Notably, we must open the file before checking the file type, as the
738 // file type could change between any previous checks and the open. When doing
739 // this, O_NOFOLLOW is needed to avoid following a symlink (this applies to the
740 // last path component only), and O_NONBLOCK is needed to avoid blocking if the
741 // file is a FIFO.
742 //
743 // This function returns the data read as well as the UID of the user who owns
744 // the file. The returned UID is needed for login protectors, where the UID
745 // needs to be cross-checked with the UID stored in the file itself.
746 func readMetadataFileSafe(path string, trustedUser *user.User) ([]byte, int64, error) {
747 file, err := os.OpenFile(path, os.O_RDONLY|unix.O_NOFOLLOW|unix.O_NONBLOCK, 0)
748 if err != nil {
749 return nil, -1, err
750 }
751 defer file.Close()
752
753 info, err := file.Stat()
754 if err != nil {
755 return nil, -1, err
756 }
757 if !info.Mode().IsRegular() {
758 return nil, -1, &ErrCorruptMetadata{path, errors.New("not a regular file")}
759 }
760 if !checkOwnership(path, info, trustedUser) {
761 return nil, -1, &ErrCorruptMetadata{path, errors.New("metadata file belongs to another user")}
762 }
763 // Clear O_NONBLOCK, since it has served its purpose when opening the
764 // file, and the behavior of reading from a regular file with O_NONBLOCK
765 // is technically unspecified.
766 if _, err = unix.FcntlInt(file.Fd(), unix.F_SETFL, 0); err != nil {
767 return nil, -1, &os.PathError{Op: "clearing O_NONBLOCK", Path: path, Err: err}
768 }
769 // Read the file contents, allowing at most maxMetadataFileSize bytes.
770 reader := &io.LimitedReader{R: file, N: maxMetadataFileSize + 1}
771 data, err := io.ReadAll(reader)
772 if err != nil {
773 return nil, -1, err
774 }
775 if reader.N == 0 {
776 return nil, -1, &ErrCorruptMetadata{path, errors.New("metadata file size limit exceeded")}
777 }
778 return data, int64(info.Sys().(*syscall.Stat_t).Uid), nil
779 }
780
781 // getMetadata reads the metadata structure from the file with the specified
782 // path. Only reads normal metadata files, not linked metadata.
783 func (m *Mount) getMetadata(path string, trustedUser *user.User, md metadata.Metadata) (int64, error) {
784 data, owner, err := readMetadataFileSafe(path, trustedUser)
785 if err != nil {
786 log.Printf("could not read metadata from %q: %v", path, err)
787 return -1, err
788 }
789
790 if err := proto.Unmarshal(data, md); err != nil {
791 return -1, &ErrCorruptMetadata{path, err}
792 }
793
794 if err := md.CheckValidity(); err != nil {
795 return -1, &ErrCorruptMetadata{path, err}
796 }
797
798 log.Printf("successfully read metadata from %q", path)
799 return owner, nil
800 }
801
802 // removeMetadata deletes the metadata struct from the file with the specified
803 // path. Works with regular or linked metadata.
804 func (m *Mount) removeMetadata(path string) error {
805 if err := os.Remove(path); err != nil {
806 log.Printf("could not remove metadata file at %q: %v", path, err)
807 return err
808 }
809
810 log.Printf("successfully removed metadata file at %q", path)
811 return nil
812 }
813
814 // AddProtector adds the protector metadata to this filesystem's storage. This
815 // will overwrite the value of an existing protector with this descriptor. This
816 // will fail with ErrLinkedProtector if a linked protector with this descriptor
817 // already exists on the filesystem.
818 func (m *Mount) AddProtector(data *metadata.ProtectorData, owner *user.User) error {
819 var err error
820 if err = m.CheckSetup(nil); err != nil {
821 return err
822 }
823 if isRegularFile(m.linkedProtectorPath(data.ProtectorDescriptor)) {
824 return errors.Errorf("cannot modify linked protector %s on filesystem %s",
825 data.ProtectorDescriptor, m.Path)
826 }
827 path := m.protectorPath(data.ProtectorDescriptor)
828 return m.addMetadata(path, data, owner)
829 }
830
831 // AddLinkedProtector adds a link in this filesystem to the protector metadata
832 // in the dest filesystem, if one doesn't already exist. On success, the return
833 // value is a nil error and a bool that is true iff the link is newly created.
834 func (m *Mount) AddLinkedProtector(descriptor string, dest *Mount, trustedUser *user.User,
835 ownerIfCreating *user.User) (bool, error) {
836 if err := m.CheckSetup(trustedUser); err != nil {
837 return false, err
838 }
839 // Check that the link is good (descriptor exists, filesystem has UUID).
840 if _, err := dest.GetRegularProtector(descriptor, trustedUser); err != nil {
841 return false, err
842 }
843
844 linkPath := m.linkedProtectorPath(descriptor)
845
846 // Check whether the link already exists.
847 existingLink, _, err := readMetadataFileSafe(linkPath, trustedUser)
848 if err == nil {
849 existingLinkedMnt, err := getMountFromLink(string(existingLink))
850 if err != nil {
851 return false, errors.Wrap(err, linkPath)
852 }
853 if existingLinkedMnt != dest {
854 return false, errors.Errorf("link %q points to %q, but expected %q",
855 linkPath, existingLinkedMnt.Path, dest.Path)
856 }
857 return false, nil
858 }
859 if !os.IsNotExist(err) {
860 return false, err
861 }
862
863 var newLink string
864 newLink, err = makeLink(dest)
865 if err != nil {
866 return false, err
867 }
868 return true, m.writeData(linkPath, []byte(newLink), ownerIfCreating, filePermissions)
869 }
870
871 // GetRegularProtector looks up the protector metadata by descriptor. This will
872 // fail with ErrProtectorNotFound if the descriptor is a linked protector.
873 func (m *Mount) GetRegularProtector(descriptor string, trustedUser *user.User) (*metadata.ProtectorData, error) {
874 if err := m.CheckSetup(trustedUser); err != nil {
875 return nil, err
876 }
877 data := new(metadata.ProtectorData)
878 path := m.protectorPath(descriptor)
879 owner, err := m.getMetadata(path, trustedUser, data)
880 if os.IsNotExist(err) {
881 err = &ErrProtectorNotFound{descriptor, m}
882 }
883 if err != nil {
884 return nil, err
885 }
886 // Login protectors have their UID stored in the file. Since normally
887 // any user can create files in the fscrypt metadata directories, for a
888 // login protector to be considered valid it *must* be owned by the
889 // claimed user or by root. Note: fscrypt v0.3.2 and later always makes
890 // login protectors owned by the user, but previous versions could
891 // create them owned by root -- that is the main reason we allow root.
892 if data.Source == metadata.SourceType_pam_passphrase && owner != 0 && owner != data.Uid {
893 log.Printf("WARNING: %q claims to be the login protector for uid %d, but it is owned by uid %d. Needs to be %d or 0.",
894 path, data.Uid, owner, data.Uid)
895 return nil, &ErrCorruptMetadata{path, errors.New("login protector belongs to wrong user")}
896 }
897 return data, nil
898 }
899
900 // GetProtector returns the Mount of the filesystem containing the information
901 // and that protector's data. If the descriptor is a regular (not linked)
902 // protector, the mount will return itself.
903 func (m *Mount) GetProtector(descriptor string, trustedUser *user.User) (*Mount, *metadata.ProtectorData, error) {
904 if err := m.CheckSetup(trustedUser); err != nil {
905 return nil, nil, err
906 }
907 // Get the link data from the link file
908 path := m.linkedProtectorPath(descriptor)
909 link, _, err := readMetadataFileSafe(path, trustedUser)
910 if err != nil {
911 // If the link doesn't exist, try for a regular protector.
912 if os.IsNotExist(err) {
913 data, err := m.GetRegularProtector(descriptor, trustedUser)
914 return m, data, err
915 }
916 return nil, nil, err
917 }
918 log.Printf("following protector link %s", path)
919 linkedMnt, err := getMountFromLink(string(link))
920 if err != nil {
921 return nil, nil, errors.Wrap(err, path)
922 }
923 data, err := linkedMnt.GetRegularProtector(descriptor, trustedUser)
924 if err != nil {
925 return nil, nil, &ErrFollowLink{string(link), err}
926 }
927 return linkedMnt, data, nil
928 }
929
930 // RemoveProtector deletes the protector metadata (or a link to another
931 // filesystem's metadata) from the filesystem storage.
932 func (m *Mount) RemoveProtector(descriptor string) error {
933 if err := m.CheckSetup(nil); err != nil {
934 return err
935 }
936 // We first try to remove the linkedProtector. If that metadata does not
937 // exist, we try to remove the normal protector.
938 err := m.removeMetadata(m.linkedProtectorPath(descriptor))
939 if os.IsNotExist(err) {
940 err = m.removeMetadata(m.protectorPath(descriptor))
941 if os.IsNotExist(err) {
942 err = &ErrProtectorNotFound{descriptor, m}
943 }
944 }
945 return err
946 }
947
948 // ListProtectors lists the descriptors of all protectors on this filesystem.
949 // This does not include linked protectors. If trustedUser is non-nil, then
950 // the protectors are restricted to those owned by the given user or by root.
951 func (m *Mount) ListProtectors(trustedUser *user.User) ([]string, error) {
952 return m.listMetadata(m.ProtectorDir(), "protectors", trustedUser)
953 }
954
955 // AddPolicy adds the policy metadata to the filesystem storage.
956 func (m *Mount) AddPolicy(data *metadata.PolicyData, owner *user.User) error {
957 if err := m.CheckSetup(nil); err != nil {
958 return err
959 }
960
961 return m.addMetadata(m.PolicyPath(data.KeyDescriptor), data, owner)
962 }
963
964 // GetPolicy looks up the policy metadata by descriptor.
965 func (m *Mount) GetPolicy(descriptor string, trustedUser *user.User) (*metadata.PolicyData, error) {
966 if err := m.CheckSetup(trustedUser); err != nil {
967 return nil, err
968 }
969 data := new(metadata.PolicyData)
970 _, err := m.getMetadata(m.PolicyPath(descriptor), trustedUser, data)
971 if os.IsNotExist(err) {
972 err = &ErrPolicyNotFound{descriptor, m}
973 }
974 return data, err
975 }
976
977 // RemovePolicy deletes the policy metadata from the filesystem storage.
978 func (m *Mount) RemovePolicy(descriptor string) error {
979 if err := m.CheckSetup(nil); err != nil {
980 return err
981 }
982 err := m.removeMetadata(m.PolicyPath(descriptor))
983 if os.IsNotExist(err) {
984 err = &ErrPolicyNotFound{descriptor, m}
985 }
986 return err
987 }
988
989 // ListPolicies lists the descriptors of all policies on this filesystem. If
990 // trustedUser is non-nil, then the policies are restricted to those owned by
991 // the given user or by root.
992 func (m *Mount) ListPolicies(trustedUser *user.User) ([]string, error) {
993 return m.listMetadata(m.PolicyDir(), "policies", trustedUser)
994 }
995
996 type namesAndTimes struct {
997 names []string
998 times []time.Time
999 }
1000
1001 func (c namesAndTimes) Len() int {
1002 return len(c.names)
1003 }
1004
1005 func (c namesAndTimes) Less(i, j int) bool {
1006 return c.times[i].Before(c.times[j])
1007 }
1008
1009 func (c namesAndTimes) Swap(i, j int) {
1010 c.names[i], c.names[j] = c.names[j], c.names[i]
1011 c.times[i], c.times[j] = c.times[j], c.times[i]
1012 }
1013
1014 func sortFileListByLastMtime(directoryPath string, names []string) error {
1015 c := namesAndTimes{names: names, times: make([]time.Time, len(names))}
1016 for i, name := range names {
1017 fi, err := os.Lstat(filepath.Join(directoryPath, name))
1018 if err != nil {
1019 return err
1020 }
1021 c.times[i] = fi.ModTime()
1022 }
1023 sort.Sort(c)
1024 return nil
1025 }
1026
1027 // listDirectory returns a list of descriptors for a metadata directory,
1028 // including files which are links to other filesystem's metadata.
1029 func (m *Mount) listDirectory(directoryPath string) ([]string, error) {
1030 dir, err := os.Open(directoryPath)
1031 if err != nil {
1032 return nil, err
1033 }
1034 defer dir.Close()
1035
1036 names, err := dir.Readdirnames(-1)
1037 if err != nil {
1038 return nil, err
1039 }
1040
1041 if SortDescriptorsByLastMtime {
1042 if err := sortFileListByLastMtime(directoryPath, names); err != nil {
1043 return nil, err
1044 }
1045 }
1046
1047 descriptors := make([]string, 0, len(names))
1048 for _, name := range names {
1049 // Be sure to include links as well
1050 descriptors = append(descriptors, strings.TrimSuffix(name, linkFileExtension))
1051 }
1052 return descriptors, nil
1053 }
1054
1055 func (m *Mount) listMetadata(dirPath string, metadataType string, owner *user.User) ([]string, error) {
1056 log.Printf("listing %s in %q", metadataType, dirPath)
1057 if err := m.CheckSetup(owner); err != nil {
1058 return nil, err
1059 }
1060 names, err := m.listDirectory(dirPath)
1061 if err != nil {
1062 return nil, err
1063 }
1064 filesIgnoredDescription := ""
1065 if owner != nil {
1066 filteredNames := make([]string, 0, len(names))
1067 uid := uint32(util.AtoiOrPanic(owner.Uid))
1068 for _, name := range names {
1069 info, err := os.Lstat(filepath.Join(dirPath, name))
1070 if err != nil {
1071 continue
1072 }
1073 fileUID := info.Sys().(*syscall.Stat_t).Uid
1074 if fileUID != uid && fileUID != 0 {
1075 continue
1076 }
1077 filteredNames = append(filteredNames, name)
1078 }
1079 numIgnored := len(names) - len(filteredNames)
1080 if numIgnored != 0 {
1081 filesIgnoredDescription =
1082 fmt.Sprintf(" (ignored %d %s not owned by %s or root)",
1083 numIgnored, metadataType, owner.Username)
1084 }
1085 names = filteredNames
1086 }
1087 log.Printf("found %d %s%s", len(names), metadataType, filesIgnoredDescription)
1088 return names, nil
1089 }