Debian Codegraph @

actions/policy.go

raw
1 /*
2 * policy.go - functions for dealing with policies
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 actions
21
22 import (
23 "fmt"
24 "log"
25 "os"
26 "os/user"
27 "reflect"
28
29 "github.com/pkg/errors"
30 "google.golang.org/protobuf/proto"
31
32 "github.com/google/fscrypt/crypto"
33 "github.com/google/fscrypt/filesystem"
34 "github.com/google/fscrypt/keyring"
35 "github.com/google/fscrypt/metadata"
36 "github.com/google/fscrypt/util"
37 )
38
39 // ErrAccessDeniedPossiblyV2 indicates that a directory's encryption policy
40 // couldn't be retrieved due to "permission denied", but it looks like it's due
41 // to the directory using a v2 policy but the kernel not supporting it.
42 type ErrAccessDeniedPossiblyV2 struct {
43 DirPath string
44 }
45
46 func (err *ErrAccessDeniedPossiblyV2) Error() string {
47 return fmt.Sprintf(`
48 failed to get encryption policy of %s: permission denied
49
50 This may be caused by the directory using a v2 encryption policy and the
51 current kernel not supporting it. If indeed the case, then this
52 directory can only be used on kernel v5.4 and later. You can create
53 directories accessible on older kernels by changing policy_version to 1
54 in %s.`,
55 err.DirPath, ConfigFileLocation)
56 }
57
58 // ErrAlreadyProtected indicates that a policy is already protected by the given
59 // protector.
60 type ErrAlreadyProtected struct {
61 Policy *Policy
62 Protector *Protector
63 }
64
65 func (err *ErrAlreadyProtected) Error() string {
66 return fmt.Sprintf("policy %s is already protected by protector %s",
67 err.Policy.Descriptor(), err.Protector.Descriptor())
68 }
69
70 // ErrDifferentFilesystem indicates that a policy can't be applied to a
71 // directory on a different filesystem.
72 type ErrDifferentFilesystem struct {
73 PolicyMount *filesystem.Mount
74 PathMount *filesystem.Mount
75 }
76
77 func (err *ErrDifferentFilesystem) Error() string {
78 return fmt.Sprintf(`cannot apply policy from filesystem %q to a
79 directory on filesystem %q. Policies may only protect files on the same
80 filesystem.`, err.PolicyMount.Path, err.PathMount.Path)
81 }
82
83 // ErrMissingPolicyMetadata indicates that a directory is encrypted but its
84 // policy metadata cannot be found.
85 type ErrMissingPolicyMetadata struct {
86 Mount *filesystem.Mount
87 DirPath string
88 Descriptor string
89 }
90
91 func (err *ErrMissingPolicyMetadata) Error() string {
92 return fmt.Sprintf(`filesystem %q does not contain the policy metadata
93 for %q. This directory has either been encrypted with another tool (such
94 as e4crypt), or the file %q has been deleted.`,
95 err.Mount.Path, err.DirPath,
96 err.Mount.PolicyPath(err.Descriptor))
97 }
98
99 // ErrNotProtected indicates that the given policy is not protected by the given
100 // protector.
101 type ErrNotProtected struct {
102 PolicyDescriptor string
103 ProtectorDescriptor string
104 }
105
106 func (err *ErrNotProtected) Error() string {
107 return fmt.Sprintf(`policy %s is not protected by protector %s`,
108 err.PolicyDescriptor, err.ProtectorDescriptor)
109 }
110
111 // ErrOnlyProtector indicates that the last protector can't be removed from a
112 // policy.
113 type ErrOnlyProtector struct {
114 Policy *Policy
115 }
116
117 func (err *ErrOnlyProtector) Error() string {
118 return fmt.Sprintf(`cannot remove the only protector from policy %s. A
119 policy must have at least one protector.`, err.Policy.Descriptor())
120 }
121
122 // ErrPolicyMetadataMismatch indicates that the policy metadata for an encrypted
123 // directory is inconsistent with that directory.
124 type ErrPolicyMetadataMismatch struct {
125 DirPath string
126 Mount *filesystem.Mount
127 PathData *metadata.PolicyData
128 MountData *metadata.PolicyData
129 }
130
131 func (err *ErrPolicyMetadataMismatch) Error() string {
132 return fmt.Sprintf(`inconsistent metadata between encrypted directory %q
133 and its corresponding metadata file %q.
134
135 Directory has descriptor:%s %s
136
137 Metadata file has descriptor:%s %s`,
138 err.DirPath, err.Mount.PolicyPath(err.PathData.KeyDescriptor),
139 err.PathData.KeyDescriptor, err.PathData.Options,
140 err.MountData.KeyDescriptor, err.MountData.Options)
141 }
142
143 // PurgeAllPolicies removes all policy keys on the filesystem from the kernel
144 // keyring. In order for this to fully take effect, the filesystem may also need
145 // to be unmounted or caches dropped.
146 func PurgeAllPolicies(ctx *Context) error {
147 if err := ctx.checkContext(); err != nil {
148 return err
149 }
150 policies, err := ctx.Mount.ListPolicies(nil)
151 if err != nil {
152 return err
153 }
154
155 for _, policyDescriptor := range policies {
156 err = keyring.RemoveEncryptionKey(policyDescriptor, ctx.getKeyringOptions(), false)
157 switch errors.Cause(err) {
158 case nil, keyring.ErrKeyNotPresent:
159 // We don't care if the key has already been removed
160 case keyring.ErrKeyFilesOpen:
161 log.Printf("Key for policy %s couldn't be fully removed because some files are still in-use",
162 policyDescriptor)
163 case keyring.ErrKeyAddedByOtherUsers:
164 log.Printf("Key for policy %s couldn't be fully removed because other user(s) have added it too",
165 policyDescriptor)
166 default:
167 return err
168 }
169 }
170 return nil
171 }
172
173 // Policy represents an unlocked policy, so it contains the PolicyData as well
174 // as the actual protector key. These unlocked Polices can then be applied to a
175 // directory, or have their key material inserted into the keyring (which will
176 // allow encrypted files to be accessed). As with the key struct, a Policy
177 // should be wiped after use.
178 type Policy struct {
179 Context *Context
180 data *metadata.PolicyData
181 key *crypto.Key
182 created bool
183 ownerIfCreating *user.User
184 newLinkedProtectors []string
185 }
186
187 // CreatePolicy creates a Policy protected by given Protector and stores the
188 // appropriate data on the filesystem. On error, no data is changed on the
189 // filesystem.
190 func CreatePolicy(ctx *Context, protector *Protector) (*Policy, error) {
191 if err := ctx.checkContext(); err != nil {
192 return nil, err
193 }
194 // Randomly create the underlying policy key (and wipe if we fail)
195 key, err := crypto.NewRandomKey(metadata.PolicyKeyLen)
196 if err != nil {
197 return nil, err
198 }
199
200 keyDescriptor, err := crypto.ComputeKeyDescriptor(key, ctx.Config.Options.PolicyVersion)
201 if err != nil {
202 key.Wipe()
203 return nil, err
204 }
205
206 policy := &Policy{
207 Context: ctx,
208 data: &metadata.PolicyData{
209 Options: ctx.Config.Options,
210 KeyDescriptor: keyDescriptor,
211 },
212 key: key,
213 created: true,
214 }
215
216 policy.ownerIfCreating, err = getOwnerOfMetadataForProtector(protector)
217 if err != nil {
218 policy.Lock()
219 return nil, err
220 }
221
222 if err = policy.AddProtector(protector); err != nil {
223 policy.Lock()
224 return nil, err
225 }
226
227 return policy, nil
228 }
229
230 // GetPolicy retrieves a locked policy with a specific descriptor. The Policy is
231 // still locked in this case, so it must be unlocked before using certain
232 // methods.
233 func GetPolicy(ctx *Context, descriptor string) (*Policy, error) {
234 if err := ctx.checkContext(); err != nil {
235 return nil, err
236 }
237 data, err := ctx.Mount.GetPolicy(descriptor, ctx.TrustedUser)
238 if err != nil {
239 return nil, err
240 }
241 log.Printf("got data for %s from %q", descriptor, ctx.Mount.Path)
242
243 return &Policy{Context: ctx, data: data}, nil
244 }
245
246 // GetPolicyFromPath returns the locked policy descriptor for a file on the
247 // filesystem. The Policy is still locked in this case, so it must be unlocked
248 // before using certain methods. An error is returned if the metadata is
249 // inconsistent or the path is not encrypted.
250 func GetPolicyFromPath(ctx *Context, path string) (*Policy, error) {
251 if err := ctx.checkContext(); err != nil {
252 return nil, err
253 }
254
255 // We double check that the options agree for both the data we get from
256 // the path, and the data we get from the mountpoint.
257 pathData, err := metadata.GetPolicy(path)
258 err = ctx.Mount.EncryptionSupportError(err)
259 if err != nil {
260 // On kernels that don't support v2 encryption policies, trying
261 // to open a directory with a v2 policy simply gave EACCES. This
262 // is ambiguous with other errors, but try to detect this case
263 // and show a better error message.
264 if os.IsPermission(err) &&
265 filesystem.HaveReadAccessTo(path) &&
266 !keyring.IsFsKeyringSupported(ctx.Mount) {
267 return nil, &ErrAccessDeniedPossiblyV2{path}
268 }
269 return nil, err
270 }
271 descriptor := pathData.KeyDescriptor
272 log.Printf("found policy %s for %q", descriptor, path)
273
274 mountData, err := ctx.Mount.GetPolicy(descriptor, ctx.TrustedUser)
275 if err != nil {
276 log.Printf("getting policy metadata: %v", err)
277 if _, ok := err.(*filesystem.ErrPolicyNotFound); ok {
278 return nil, &ErrMissingPolicyMetadata{ctx.Mount, path, descriptor}
279 }
280 return nil, err
281 }
282 log.Printf("found data for policy %s on %q", descriptor, ctx.Mount.Path)
283
284 if !proto.Equal(pathData.Options, mountData.Options) ||
285 pathData.KeyDescriptor != mountData.KeyDescriptor {
286 return nil, &ErrPolicyMetadataMismatch{path, ctx.Mount, pathData, mountData}
287 }
288 log.Print("data from filesystem and path agree")
289
290 return &Policy{Context: ctx, data: mountData}, nil
291 }
292
293 // ProtectorOptions creates a slice of ProtectorOptions for the protectors
294 // protecting this policy.
295 func (policy *Policy) ProtectorOptions() []*ProtectorOption {
296 options := make([]*ProtectorOption, len(policy.data.WrappedPolicyKeys))
297 for i, wrappedPolicyKey := range policy.data.WrappedPolicyKeys {
298 options[i] = policy.Context.getProtectorOption(wrappedPolicyKey.ProtectorDescriptor)
299 }
300 return options
301 }
302
303 // ProtectorDescriptors creates a slice of the Protector descriptors for the
304 // protectors protecting this policy.
305 func (policy *Policy) ProtectorDescriptors() []string {
306 descriptors := make([]string, len(policy.data.WrappedPolicyKeys))
307 for i, wrappedPolicyKey := range policy.data.WrappedPolicyKeys {
308 descriptors[i] = wrappedPolicyKey.ProtectorDescriptor
309 }
310 return descriptors
311 }
312
313 // Descriptor returns the key descriptor for this policy.
314 func (policy *Policy) Descriptor() string {
315 return policy.data.KeyDescriptor
316 }
317
318 // Options returns the encryption options of this policy.
319 func (policy *Policy) Options() *metadata.EncryptionOptions {
320 return policy.data.Options
321 }
322
323 // Version returns the version of this policy.
324 func (policy *Policy) Version() int64 {
325 return policy.data.Options.PolicyVersion
326 }
327
328 // Destroy removes a policy from the filesystem. It also removes any new
329 // protector links that were created for the policy. This does *not* wipe the
330 // policy's internal key from memory; use Lock() to do that.
331 func (policy *Policy) Destroy() error {
332 for _, protectorDescriptor := range policy.newLinkedProtectors {
333 policy.Context.Mount.RemoveProtector(protectorDescriptor)
334 }
335 return policy.Context.Mount.RemovePolicy(policy.Descriptor())
336 }
337
338 // Revert destroys a policy if it was created, but does nothing if it was just
339 // queried from the filesystem.
340 func (policy *Policy) Revert() error {
341 if !policy.created {
342 return nil
343 }
344 return policy.Destroy()
345 }
346
347 func (policy *Policy) String() string {
348 return fmt.Sprintf("Policy: %s\nMountpoint: %s\nOptions: %v\nProtectors:%+v",
349 policy.Descriptor(), policy.Context.Mount, policy.data.Options,
350 policy.ProtectorDescriptors())
351 }
352
353 // Unlock unwraps the Policy's internal key. As a Protector is needed to unlock
354 // the Policy, callbacks to select the Policy and get the key are needed. This
355 // method will retry the keyFn as necessary to get the correct key for the
356 // selected protector. Does nothing if policy is already unlocked.
357 func (policy *Policy) Unlock(optionFn OptionFunc, keyFn KeyFunc) error {
358 if policy.key != nil {
359 return nil
360 }
361 options := policy.ProtectorOptions()
362
363 // The OptionFunc indicates which option and wrapped key we should use.
364 idx, err := optionFn(policy.Descriptor(), options)
365 if err != nil {
366 return err
367 }
368 option := options[idx]
369 if option.LoadError != nil {
370 return option.LoadError
371 }
372
373 log.Printf("protector %s selected in callback", option.Descriptor())
374 protectorKey, err := unwrapProtectorKey(option.ProtectorInfo, keyFn)
375 if err != nil {
376 return err
377 }
378 defer protectorKey.Wipe()
379
380 log.Printf("unwrapping policy %s with protector", policy.Descriptor())
381 wrappedPolicyKey := policy.data.WrappedPolicyKeys[idx].WrappedKey
382 policy.key, err = crypto.Unwrap(protectorKey, wrappedPolicyKey)
383 return err
384 }
385
386 // UnlockWithProtector uses an unlocked Protector to unlock a policy. An error
387 // is returned if the Protector is not yet unlocked or does not protect the
388 // policy. Does nothing if policy is already unlocked.
389 func (policy *Policy) UnlockWithProtector(protector *Protector) error {
390 if policy.key != nil {
391 return nil
392 }
393 if protector.key == nil {
394 return ErrLocked
395 }
396 idx, ok := policy.findWrappedKeyIndex(protector.Descriptor())
397 if !ok {
398 return &ErrNotProtected{policy.Descriptor(), protector.Descriptor()}
399 }
400
401 var err error
402 wrappedPolicyKey := policy.data.WrappedPolicyKeys[idx].WrappedKey
403 policy.key, err = crypto.Unwrap(protector.key, wrappedPolicyKey)
404 return err
405 }
406
407 // Lock wipes a Policy's internal Key. It should always be called after using a
408 // Policy. This is often done with a defer statement. There is no effect if
409 // called multiple times.
410 func (policy *Policy) Lock() error {
411 err := policy.key.Wipe()
412 policy.key = nil
413 return err
414 }
415
416 // UsesProtector returns if the policy is protected with the protector
417 func (policy *Policy) UsesProtector(protector *Protector) bool {
418 _, ok := policy.findWrappedKeyIndex(protector.Descriptor())
419 return ok
420 }
421
422 // getOwnerOfMetadataForProtector returns the User to whom the owner of any new
423 // policies or protector links for the given protector should be set.
424 //
425 // This will return a non-nil value only when the protector is a login protector
426 // and the process is running as root. In this scenario, root is setting up
427 // encryption on the user's behalf, so we need to make new policies and
428 // protector links owned by the user (rather than root) to allow them to be read
429 // by the user, just like the login protector itself which is handled elsewhere.
430 func getOwnerOfMetadataForProtector(protector *Protector) (*user.User, error) {
431 if protector.data.Source == metadata.SourceType_pam_passphrase && util.IsUserRoot() {
432 owner, err := util.UserFromUID(protector.data.Uid)
433 if err != nil {
434 return nil, err
435 }
436 return owner, nil
437 }
438 return nil, nil
439 }
440
441 // AddProtector updates the data that is wrapping the Policy Key so that the
442 // provided Protector is now protecting the specified Policy. If an error is
443 // returned, no data has been changed. If the policy and protector are on
444 // different filesystems, a link will be created between them. The policy and
445 // protector must both be unlocked.
446 func (policy *Policy) AddProtector(protector *Protector) error {
447 if policy.UsesProtector(protector) {
448 return &ErrAlreadyProtected{policy, protector}
449 }
450 if policy.key == nil || protector.key == nil {
451 return ErrLocked
452 }
453
454 // If the protector is on a different filesystem, we need to add a link
455 // to it on the policy's filesystem.
456 if !reflect.DeepEqual(policy.Context.Mount, protector.Context.Mount) {
457 log.Printf("policy on %s\n protector on %s\n", policy.Context.Mount, protector.Context.Mount)
458 ownerIfCreating, err := getOwnerOfMetadataForProtector(protector)
459 if err != nil {
460 return err
461 }
462 isNewLink, err := policy.Context.Mount.AddLinkedProtector(
463 protector.Descriptor(), protector.Context.Mount,
464 protector.Context.TrustedUser, ownerIfCreating)
465 if err != nil {
466 return err
467 }
468 if isNewLink {
469 policy.newLinkedProtectors = append(policy.newLinkedProtectors,
470 protector.Descriptor())
471 }
472 } else {
473 log.Printf("policy and protector both on %q", policy.Context.Mount)
474 }
475
476 // Create the wrapped policy key
477 wrappedKey, err := crypto.Wrap(protector.key, policy.key)
478 if err != nil {
479 return err
480 }
481
482 // Append the wrapped key to the data
483 policy.addKey(&metadata.WrappedPolicyKey{
484 ProtectorDescriptor: protector.Descriptor(),
485 WrappedKey: wrappedKey,
486 })
487
488 if err := policy.commitData(); err != nil {
489 // revert the addition on failure
490 policy.removeKey(len(policy.data.WrappedPolicyKeys) - 1)
491 return err
492 }
493 return nil
494 }
495
496 // RemoveProtector updates the data that is wrapping the Policy Key so that the
497 // protector with the given descriptor is no longer protecting the specified
498 // Policy. If an error is returned, no data has been changed. Note that the
499 // protector itself won't be removed, nor will a link to the protector be
500 // removed (in the case where the protector and policy are on different
501 // filesystems). The policy can be locked or unlocked.
502 func (policy *Policy) RemoveProtector(protectorDescriptor string) error {
503 idx, ok := policy.findWrappedKeyIndex(protectorDescriptor)
504 if !ok {
505 return &ErrNotProtected{policy.Descriptor(), protectorDescriptor}
506 }
507
508 if len(policy.data.WrappedPolicyKeys) == 1 {
509 return &ErrOnlyProtector{policy}
510 }
511
512 // Remove the wrapped key from the data
513 toRemove := policy.removeKey(idx)
514
515 if err := policy.commitData(); err != nil {
516 // revert the removal on failure (order is irrelevant)
517 policy.addKey(toRemove)
518 return err
519 }
520 return nil
521 }
522
523 // Apply sets the Policy on a specified directory. Currently we impose the
524 // additional constraint that policies and the directories they are applied to
525 // must reside on the same filesystem.
526 func (policy *Policy) Apply(path string) error {
527 if pathMount, err := filesystem.FindMount(path); err != nil {
528 return err
529 } else if !reflect.DeepEqual(pathMount, policy.Context.Mount) {
530 return &ErrDifferentFilesystem{policy.Context.Mount, pathMount}
531 }
532
533 err := metadata.SetPolicy(path, policy.data)
534 return policy.Context.Mount.EncryptionSupportError(err)
535 }
536
537 // GetProvisioningStatus returns the status of this policy's key in the keyring.
538 func (policy *Policy) GetProvisioningStatus() keyring.KeyStatus {
539 status, _ := keyring.GetEncryptionKeyStatus(policy.Descriptor(),
540 policy.Context.getKeyringOptions())
541 return status
542 }
543
544 // IsProvisionedByTargetUser returns true if the policy's key is present in the
545 // target kernel keyring, but not if that keyring is a filesystem keyring and
546 // the key only been added by users other than Context.TargetUser.
547 func (policy *Policy) IsProvisionedByTargetUser() bool {
548 return policy.GetProvisioningStatus() == keyring.KeyPresent
549 }
550
551 // Provision inserts the Policy key into the kernel keyring. This allows reading
552 // and writing of files encrypted with this directory. Requires unlocked Policy.
553 func (policy *Policy) Provision() error {
554 if policy.key == nil {
555 return ErrLocked
556 }
557 return keyring.AddEncryptionKey(policy.key, policy.Descriptor(),
558 policy.Context.getKeyringOptions())
559 }
560
561 // Deprovision removes the Policy key from the kernel keyring. This prevents
562 // reading and writing to the directory --- unless the target keyring is a user
563 // keyring, in which case caches must be dropped too. If the Policy key was
564 // already removed, returns keyring.ErrKeyNotPresent.
565 func (policy *Policy) Deprovision(allUsers bool) error {
566 return keyring.RemoveEncryptionKey(policy.Descriptor(),
567 policy.Context.getKeyringOptions(), allUsers)
568 }
569
570 // NeedsUserKeyring returns true if Provision and Deprovision for this policy
571 // will use a user keyring (deprecated), not a filesystem keyring.
572 func (policy *Policy) NeedsUserKeyring() bool {
573 return policy.Version() == 1 && !policy.Context.Config.GetUseFsKeyringForV1Policies()
574 }
575
576 // NeedsRootToProvision returns true if Provision and Deprovision will require
577 // root for this policy in the current configuration.
578 func (policy *Policy) NeedsRootToProvision() bool {
579 return policy.Version() == 1 && policy.Context.Config.GetUseFsKeyringForV1Policies()
580 }
581
582 // CanBeAppliedWithoutProvisioning returns true if this process can apply this
583 // policy to a directory without first calling Provision.
584 func (policy *Policy) CanBeAppliedWithoutProvisioning() bool {
585 return policy.Version() == 1 || util.IsUserRoot()
586 }
587
588 // commitData writes the Policy's current data to the filesystem.
589 func (policy *Policy) commitData() error {
590 return policy.Context.Mount.AddPolicy(policy.data, policy.ownerIfCreating)
591 }
592
593 // findWrappedPolicyKey returns the index of the wrapped policy key
594 // corresponding to this policy and protector. The returned bool is false if no
595 // wrapped policy key corresponds to the specified protector, true otherwise.
596 func (policy *Policy) findWrappedKeyIndex(protectorDescriptor string) (int, bool) {
597 for idx, wrappedPolicyKey := range policy.data.WrappedPolicyKeys {
598 if wrappedPolicyKey.ProtectorDescriptor == protectorDescriptor {
599 return idx, true
600 }
601 }
602 return 0, false
603 }
604
605 // addKey adds the wrapped policy key to end of the wrapped key data.
606 func (policy *Policy) addKey(toAdd *metadata.WrappedPolicyKey) {
607 policy.data.WrappedPolicyKeys = append(policy.data.WrappedPolicyKeys, toAdd)
608 }
609
610 // removeKey removes the wrapped policy key at the specified index. This
611 // does not preserve the order of the wrapped policy key array. If no index is
612 // specified the last key is removed.
613 func (policy *Policy) removeKey(index int) *metadata.WrappedPolicyKey {
614 lastIdx := len(policy.data.WrappedPolicyKeys) - 1
615 toRemove := policy.data.WrappedPolicyKeys[index]
616
617 // See https://github.com/golang/go/wiki/SliceTricks
618 policy.data.WrappedPolicyKeys[index] = policy.data.WrappedPolicyKeys[lastIdx]
619 policy.data.WrappedPolicyKeys[lastIdx] = nil
620 policy.data.WrappedPolicyKeys = policy.data.WrappedPolicyKeys[:lastIdx]
621
622 return toRemove
623 }