Debian Codegraph @

filesystem/filesystem_test.go

raw
1 /*
2 * filesystem_test.go - Tests for reading/writing metadata to disk.
3 *
4 * Copyright 2017 Google Inc.
5 * Author: Joe Richey ([email protected])
6 *
7 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
8 * use this file except in compliance with the License. You may obtain a copy of
9 * the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16 * License for the specific language governing permissions and limitations under
17 * the License.
18 */
19
20 package filesystem
21
22 import (
23 "os"
24 "os/user"
25 "path/filepath"
26 "syscall"
27 "testing"
28
29 "golang.org/x/sys/unix"
30 "google.golang.org/protobuf/proto"
31
32 "github.com/google/fscrypt/crypto"
33 "github.com/google/fscrypt/metadata"
34 "github.com/google/fscrypt/util"
35 )
36
37 var (
38 fakeProtectorKey, _ = crypto.NewRandomKey(metadata.InternalKeyLen)
39 fakePolicyKey, _ = crypto.NewRandomKey(metadata.PolicyKeyLen)
40 wrappedProtectorKey, _ = crypto.Wrap(fakeProtectorKey, fakeProtectorKey)
41 wrappedPolicyKey, _ = crypto.Wrap(fakeProtectorKey, fakePolicyKey)
42 )
43
44 // Gets the mount corresponding to the integration test path.
45 func getTestMount(t *testing.T) (*Mount, error) {
46 mountpoint, err := util.TestRoot()
47 if err != nil {
48 t.Skip(err)
49 }
50 return GetMount(mountpoint)
51 }
52
53 func getFakeProtector() *metadata.ProtectorData {
54 return &metadata.ProtectorData{
55 ProtectorDescriptor: "fedcba9876543210",
56 Name: "goodProtector",
57 Source: metadata.SourceType_raw_key,
58 WrappedKey: wrappedProtectorKey,
59 }
60 }
61
62 func getFakeLoginProtector(uid int64) *metadata.ProtectorData {
63 protector := getFakeProtector()
64 protector.Source = metadata.SourceType_pam_passphrase
65 protector.Uid = uid
66 protector.Costs = &metadata.HashingCosts{
67 Time: 1,
68 Memory: 1 << 8,
69 Parallelism: 1,
70 }
71 protector.Salt = make([]byte, 16)
72 return protector
73 }
74
75 func getFakePolicy() *metadata.PolicyData {
76 return &metadata.PolicyData{
77 KeyDescriptor: "0123456789abcdef",
78 Options: metadata.DefaultOptions,
79 WrappedPolicyKeys: []*metadata.WrappedPolicyKey{
80 {
81 ProtectorDescriptor: "fedcba9876543210",
82 WrappedKey: wrappedPolicyKey,
83 },
84 },
85 }
86 }
87
88 // Gets the mount and sets it up
89 func getSetupMount(t *testing.T) (*Mount, error) {
90 mnt, err := getTestMount(t)
91 if err != nil {
92 return nil, err
93 }
94 return mnt, mnt.Setup(WorldWritable)
95 }
96
97 // Tests that the setup works and creates the correct files
98 func TestSetup(t *testing.T) {
99 mnt, err := getSetupMount(t)
100 if err != nil {
101 t.Fatal(err)
102 }
103
104 if err := mnt.CheckSetup(nil); err != nil {
105 t.Error(err)
106 }
107
108 os.RemoveAll(mnt.BaseDir())
109 }
110
111 // Tests that we can remove all of the metadata
112 func TestRemoveAllMetadata(t *testing.T) {
113 mnt, err := getSetupMount(t)
114 if err != nil {
115 t.Fatal(err)
116 }
117
118 if err = mnt.RemoveAllMetadata(); err != nil {
119 t.Fatal(err)
120 }
121
122 if isDir(mnt.BaseDir()) {
123 t.Error("metadata was not removed")
124 }
125 }
126
127 // isSymlink returns true if the path exists and is that of a symlink.
128 func isSymlink(path string) bool {
129 info, err := loggedLstat(path)
130 return err == nil && info.Mode()&os.ModeSymlink != 0
131 }
132
133 // Test that when MOUNTPOINT/.fscrypt is a pre-created symlink, fscrypt will
134 // create/delete the metadata at the location pointed to by the symlink.
135 //
136 // This is a helper function that is called twice: once to test an absolute
137 // symlink and once to test a relative symlink.
138 func testSetupWithSymlink(t *testing.T, mnt *Mount, symlinkTarget string, realDir string) {
139 rawBaseDir := filepath.Join(mnt.Path, baseDirName)
140 if err := os.Symlink(symlinkTarget, rawBaseDir); err != nil {
141 t.Fatal(err)
142 }
143 defer os.Remove(rawBaseDir)
144
145 if err := mnt.Setup(WorldWritable); err != nil {
146 t.Fatal(err)
147 }
148 defer mnt.RemoveAllMetadata()
149 if err := mnt.CheckSetup(nil); err != nil {
150 t.Fatal(err)
151 }
152 if !isSymlink(rawBaseDir) {
153 t.Fatal("base dir should still be a symlink")
154 }
155 if !isDir(realDir) {
156 t.Fatal("real base dir should exist")
157 }
158 if err := mnt.RemoveAllMetadata(); err != nil {
159 t.Fatal(err)
160 }
161 if !isSymlink(rawBaseDir) {
162 t.Fatal("base dir should still be a symlink")
163 }
164 if isDir(realDir) {
165 t.Fatal("real base dir should no longer exist")
166 }
167 }
168
169 func TestSetupWithAbsoluteSymlink(t *testing.T) {
170 mnt, err := getTestMount(t)
171 if err != nil {
172 t.Fatal(err)
173 }
174 tempDir, err := os.MkdirTemp("", "fscrypt")
175 if err != nil {
176 t.Fatal(err)
177 }
178 defer os.RemoveAll(tempDir)
179 realDir := filepath.Join(tempDir, "realDir")
180 if realDir, err = filepath.Abs(realDir); err != nil {
181 t.Fatal(err)
182 }
183 testSetupWithSymlink(t, mnt, realDir, realDir)
184 }
185
186 func TestSetupWithRelativeSymlink(t *testing.T) {
187 mnt, err := getTestMount(t)
188 if err != nil {
189 t.Fatal(err)
190 }
191 realDir := filepath.Join(mnt.Path, ".fscrypt-real")
192 testSetupWithSymlink(t, mnt, ".fscrypt-real", realDir)
193 }
194
195 func testSetupMode(t *testing.T, mnt *Mount, setupMode SetupMode, expectedPerms os.FileMode) {
196 mnt.RemoveAllMetadata()
197 if err := mnt.Setup(setupMode); err != nil {
198 t.Fatal(err)
199 }
200 dirNames := []string{"policies", "protectors"}
201 for _, dirName := range dirNames {
202 fi, err := os.Stat(filepath.Join(mnt.Path, ".fscrypt", dirName))
203 if err != nil {
204 t.Fatal(err)
205 }
206 if fi.Mode()&(os.ModeSticky|0777) != expectedPerms {
207 t.Errorf("directory %s doesn't have permissions %o", dirName, expectedPerms)
208 }
209 }
210 }
211
212 // Tests that the supported setup modes (WorldWritable and SingleUserWritable)
213 // work as intended.
214 func TestSetupModes(t *testing.T) {
215 mnt, err := getTestMount(t)
216 if err != nil {
217 t.Fatal(err)
218 }
219 defer mnt.RemoveAllMetadata()
220 testSetupMode(t, mnt, WorldWritable, os.ModeSticky|0777)
221 testSetupMode(t, mnt, SingleUserWritable, 0755)
222 }
223
224 // Tests that fscrypt refuses to use metadata directories that are
225 // world-writable but don't have the sticky bit set.
226 func TestInsecurePermissions(t *testing.T) {
227 mnt, err := getTestMount(t)
228 if err != nil {
229 t.Fatal(err)
230 }
231 defer mnt.RemoveAllMetadata()
232
233 if err = mnt.Setup(WorldWritable); err != nil {
234 t.Fatal(err)
235 }
236 if err = os.Chmod(mnt.PolicyDir(), 0777); err != nil {
237 t.Fatal(err)
238 }
239 defer os.Chmod(mnt.PolicyDir(), os.ModeSticky|0777)
240 err = mnt.CheckSetup(nil)
241 if _, ok := err.(*ErrInsecurePermissions); !ok {
242 t.Fatal("expected ErrInsecurePermissions")
243 }
244 }
245
246 // Adding a good Protector should succeed, adding a bad one should fail
247 func TestAddProtector(t *testing.T) {
248 mnt, err := getSetupMount(t)
249 if err != nil {
250 t.Fatal(err)
251 }
252 defer mnt.RemoveAllMetadata()
253
254 protector := getFakeProtector()
255 if err = mnt.AddProtector(protector, nil); err != nil {
256 t.Error(err)
257 }
258
259 // Change the source to bad one, or one that requires hashing costs
260 protector.Source = metadata.SourceType_default
261 if mnt.AddProtector(protector, nil) == nil {
262 t.Error("bad source for a descriptor should make metadata invalid")
263 }
264 protector.Source = metadata.SourceType_custom_passphrase
265 if mnt.AddProtector(protector, nil) == nil {
266 t.Error("protectors using passphrases should require hashing costs")
267 }
268 protector.Source = metadata.SourceType_raw_key
269
270 // Use a bad wrapped key
271 protector.WrappedKey = wrappedPolicyKey
272 if mnt.AddProtector(protector, nil) == nil {
273 t.Error("bad length for protector keys should make metadata invalid")
274 }
275 protector.WrappedKey = wrappedProtectorKey
276
277 // Change the descriptor (to a bad length)
278 protector.ProtectorDescriptor = "abcde"
279 if mnt.AddProtector(protector, nil) == nil {
280 t.Error("bad descriptor length should make metadata invalid")
281 }
282
283 }
284
285 // Adding a good Policy should succeed, adding a bad one should fail
286 func TestAddPolicy(t *testing.T) {
287 mnt, err := getSetupMount(t)
288 if err != nil {
289 t.Fatal(err)
290 }
291 defer mnt.RemoveAllMetadata()
292
293 policy := getFakePolicy()
294 if err = mnt.AddPolicy(policy, nil); err != nil {
295 t.Error(err)
296 }
297
298 // Bad encryption options should make policy invalid
299 policy.Options.Padding = 7
300 if mnt.AddPolicy(policy, nil) == nil {
301 t.Error("padding not a power of 2 should make metadata invalid")
302 }
303 policy.Options.Padding = 16
304 policy.Options.Filenames = metadata.EncryptionOptions_default
305 if mnt.AddPolicy(policy, nil) == nil {
306 t.Error("encryption mode not set should make metadata invalid")
307 }
308 policy.Options.Filenames = metadata.EncryptionOptions_AES_256_CTS
309
310 // Use a bad wrapped key
311 policy.WrappedPolicyKeys[0].WrappedKey = wrappedProtectorKey
312 if mnt.AddPolicy(policy, nil) == nil {
313 t.Error("bad length for policy keys should make metadata invalid")
314 }
315 policy.WrappedPolicyKeys[0].WrappedKey = wrappedPolicyKey
316
317 // Change the descriptor (to a bad length)
318 policy.KeyDescriptor = "abcde"
319 if mnt.AddPolicy(policy, nil) == nil {
320 t.Error("bad descriptor length should make metadata invalid")
321 }
322 }
323
324 // Tests that we can set a policy and get it back
325 func TestSetPolicy(t *testing.T) {
326 mnt, err := getSetupMount(t)
327 if err != nil {
328 t.Fatal(err)
329 }
330 defer mnt.RemoveAllMetadata()
331
332 policy := getFakePolicy()
333 if err = mnt.AddPolicy(policy, nil); err != nil {
334 t.Fatal(err)
335 }
336
337 realPolicy, err := mnt.GetPolicy(policy.KeyDescriptor, nil)
338 if err != nil {
339 t.Fatal(err)
340 }
341
342 if !proto.Equal(realPolicy, policy) {
343 t.Errorf("policy %+v does not equal expected policy %+v", realPolicy, policy)
344 }
345
346 }
347
348 // Tests that we can set a normal protector and get it back
349 func TestSetProtector(t *testing.T) {
350 mnt, err := getSetupMount(t)
351 if err != nil {
352 t.Fatal(err)
353 }
354 defer mnt.RemoveAllMetadata()
355
356 protector := getFakeProtector()
357 if err = mnt.AddProtector(protector, nil); err != nil {
358 t.Fatal(err)
359 }
360
361 realProtector, err := mnt.GetRegularProtector(protector.ProtectorDescriptor, nil)
362 if err != nil {
363 t.Fatal(err)
364 }
365
366 if !proto.Equal(realProtector, protector) {
367 t.Errorf("protector %+v does not equal expected protector %+v", realProtector, protector)
368 }
369 }
370
371 // Tests that a login protector whose embedded UID doesn't match the file owner
372 // is considered invalid. (Such a file could be created by a malicious user to
373 // try to confuse fscrypt into processing the wrong file.)
374 func TestSpoofedLoginProtector(t *testing.T) {
375 myUID := int64(os.Geteuid())
376 badUID := myUID + 1 // anything different from myUID
377 mnt, err := getSetupMount(t)
378 if err != nil {
379 t.Fatal(err)
380 }
381 defer mnt.RemoveAllMetadata()
382
383 // Control case: protector with matching UID should be accepted.
384 protector := getFakeLoginProtector(myUID)
385 if err = mnt.AddProtector(protector, nil); err != nil {
386 t.Fatal(err)
387 }
388 _, err = mnt.GetRegularProtector(protector.ProtectorDescriptor, nil)
389 if err != nil {
390 t.Fatal(err)
391 }
392 if err = mnt.RemoveProtector(protector.ProtectorDescriptor); err != nil {
393 t.Fatal(err)
394 }
395
396 // The real test: protector with mismatching UID should rejected,
397 // *unless* the process running the tests (and hence the file owner) is
398 // root in which case it should be accepted.
399 protector = getFakeLoginProtector(badUID)
400 if err = mnt.AddProtector(protector, nil); err != nil {
401 t.Fatal(err)
402 }
403 _, err = mnt.GetRegularProtector(protector.ProtectorDescriptor, nil)
404 if myUID == 0 {
405 if err != nil {
406 t.Fatal(err)
407 }
408 } else {
409 if err == nil {
410 t.Fatal("reading protector with bad UID unexpectedly succeeded")
411 }
412 }
413 }
414
415 // Tests that the fscrypt metadata files are given mode 0600.
416 func TestMetadataFileMode(t *testing.T) {
417 mnt, err := getSetupMount(t)
418 if err != nil {
419 t.Fatal(err)
420 }
421 defer mnt.RemoveAllMetadata()
422
423 // Policy
424 policy := getFakePolicy()
425 if err = mnt.AddPolicy(policy, nil); err != nil {
426 t.Fatal(err)
427 }
428 fi, err := os.Stat(filepath.Join(mnt.Path, ".fscrypt/policies/", policy.KeyDescriptor))
429 if err != nil {
430 t.Fatal(err)
431 }
432 if fi.Mode()&0777 != 0600 {
433 t.Error("Policy file has wrong mode")
434 }
435
436 // Protector
437 protector := getFakeProtector()
438 if err = mnt.AddProtector(protector, nil); err != nil {
439 t.Fatal(err)
440 }
441 fi, err = os.Stat(filepath.Join(mnt.Path, ".fscrypt/protectors", protector.ProtectorDescriptor))
442 if err != nil {
443 t.Fatal(err)
444 }
445 if fi.Mode()&0777 != 0600 {
446 t.Error("Protector file has wrong mode")
447 }
448 }
449
450 // Gets a setup mount and a fake second mount
451 func getTwoSetupMounts(t *testing.T) (realMnt, fakeMnt *Mount, err error) {
452 if realMnt, err = getSetupMount(t); err != nil {
453 return
454 }
455
456 // Create and setup a fake filesystem
457 fakeMountpoint := filepath.Join(realMnt.Path, "fake")
458 if err = os.MkdirAll(fakeMountpoint, basePermissions); err != nil {
459 return
460 }
461 fakeMnt = &Mount{Path: fakeMountpoint, FilesystemType: realMnt.FilesystemType}
462 err = fakeMnt.Setup(WorldWritable)
463 return
464 }
465
466 // Removes all the data from the fake and real filesystems
467 func cleanupTwoMounts(realMnt, fakeMnt *Mount) {
468 realMnt.RemoveAllMetadata()
469 os.RemoveAll(fakeMnt.Path)
470 }
471
472 // Tests that we can set a linked protector and get it back
473 func TestLinkedProtector(t *testing.T) {
474 realMnt, fakeMnt, err := getTwoSetupMounts(t)
475 if err != nil {
476 t.Fatal(err)
477 }
478 defer cleanupTwoMounts(realMnt, fakeMnt)
479
480 // Add the protector to the first filesystem
481 protector := getFakeProtector()
482 if err = realMnt.AddProtector(protector, nil); err != nil {
483 t.Fatal(err)
484 }
485
486 // Add the link to the second filesystem
487 var isNewLink bool
488 if isNewLink, err = fakeMnt.AddLinkedProtector(protector.ProtectorDescriptor, realMnt, nil, nil); err != nil {
489 t.Fatal(err)
490 }
491 if !isNewLink {
492 t.Fatal("Link was not new")
493 }
494 if isNewLink, err = fakeMnt.AddLinkedProtector(protector.ProtectorDescriptor, realMnt, nil, nil); err != nil {
495 t.Fatal(err)
496 }
497 if isNewLink {
498 t.Fatal("Link was new")
499 }
500
501 // Get the protector though the second system
502 _, err = fakeMnt.GetRegularProtector(protector.ProtectorDescriptor, nil)
503 if _, ok := err.(*ErrProtectorNotFound); !ok {
504 t.Fatal(err)
505 }
506
507 retMnt, retProtector, err := fakeMnt.GetProtector(protector.ProtectorDescriptor, nil)
508 if err != nil {
509 t.Fatal(err)
510 }
511 if retMnt != realMnt {
512 t.Error("mount returned was incorrect")
513 }
514
515 if !proto.Equal(retProtector, protector) {
516 t.Errorf("protector %+v does not equal expected protector %+v", retProtector, protector)
517 }
518 }
519
520 func createFile(path string, size int64) error {
521 if err := os.WriteFile(path, []byte{}, 0600); err != nil {
522 return err
523 }
524 return os.Truncate(path, size)
525 }
526
527 // Tests the readMetadataFileSafe() function.
528 func TestReadMetadataFileSafe(t *testing.T) {
529 currentUser, err := util.EffectiveUser()
530 otherUser := &user.User{Uid: "-1"}
531 if err != nil {
532 t.Fatal(err)
533 }
534 tempDir, err := os.MkdirTemp("", "fscrypt")
535 if err != nil {
536 t.Fatal(err)
537 }
538 filePath := filepath.Join(tempDir, "file")
539 defer os.RemoveAll(tempDir)
540
541 // Good file (control case)
542 if err = createFile(filePath, 1000); err != nil {
543 t.Fatal(err)
544 }
545 _, owner, err := readMetadataFileSafe(filePath, nil)
546 if err != nil {
547 t.Fatal("failed to read file")
548 }
549 if owner != int64(os.Geteuid()) {
550 t.Fatal("got wrong owner")
551 }
552 // Also try it with the trustedUser argument set to the current user.
553 if _, _, err = readMetadataFileSafe(filePath, currentUser); err != nil {
554 t.Fatal("failed to read file")
555 }
556 os.Remove(filePath)
557
558 // File owned by another user. We might not have permission to actually
559 // change the file's ownership, so we simulate this by passing in a bad
560 // value for the trustedUser argument.
561 if err = createFile(filePath, 1000); err != nil {
562 t.Fatal(err)
563 }
564 _, _, err = readMetadataFileSafe(filePath, otherUser)
565 if util.IsUserRoot() {
566 if err != nil {
567 t.Fatal("root-owned file didn't pass owner validation")
568 }
569 } else {
570 if err == nil {
571 t.Fatal("unexpectedly could read file owned by another user")
572 }
573 }
574 os.Remove(filePath)
575
576 // Nonexistent file
577 _, _, err = readMetadataFileSafe(filePath, nil)
578 if !os.IsNotExist(err) {
579 t.Fatal("trying to read nonexistent file didn't fail with expected error")
580 }
581
582 // Symlink
583 if err = os.Symlink("target", filePath); err != nil {
584 t.Fatal(err)
585 }
586 _, _, err = readMetadataFileSafe(filePath, nil)
587 if err.(*os.PathError).Err != syscall.ELOOP {
588 t.Fatal("trying to read symlink didn't fail with ELOOP")
589 }
590 os.Remove(filePath)
591
592 // FIFO
593 if err = unix.Mkfifo(filePath, 0600); err != nil {
594 t.Fatal(err)
595 }
596 _, _, err = readMetadataFileSafe(filePath, nil)
597 if _, ok := err.(*ErrCorruptMetadata); !ok {
598 t.Fatal("trying to read FIFO didn't fail with expected error")
599 }
600 os.Remove(filePath)
601
602 // Very large file
603 if err = createFile(filePath, 1000000); err != nil {
604 t.Fatal(err)
605 }
606 _, _, err = readMetadataFileSafe(filePath, nil)
607 if _, ok := err.(*ErrCorruptMetadata); !ok {
608 t.Fatal("trying to read very large file didn't fail with expected error")
609 }
610 }