Debian Codegraph @

metadata/policy.go

raw
1 /*
2 * policy.go - Functions for getting and setting policies on a specified
3 * directory or file.
4 *
5 * Copyright 2017 Google Inc.
6 * Author: Joe Richey ([email protected])
7 *
8 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
9 * use this file except in compliance with the License. You may obtain a copy of
10 * the License at
11 *
12 * http://www.apache.org/licenses/LICENSE-2.0
13 *
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
17 * License for the specific language governing permissions and limitations under
18 * the License.
19 */
20
21 package metadata
22
23 import (
24 "encoding/hex"
25 "fmt"
26 "log"
27 "math"
28 "os"
29 "os/user"
30 "strconv"
31 "syscall"
32 "unsafe"
33
34 "github.com/pkg/errors"
35 "golang.org/x/sys/unix"
36
37 "github.com/google/fscrypt/util"
38 )
39
40 var (
41 // ErrEncryptionNotSupported indicates that encryption is not supported
42 // on the given filesystem, and there is no way to enable it.
43 ErrEncryptionNotSupported = errors.New("encryption not supported")
44
45 // ErrEncryptionNotEnabled indicates that encryption is not supported on
46 // the given filesystem, but there is a way to enable it.
47 ErrEncryptionNotEnabled = errors.New("encryption not enabled")
48 )
49
50 // ErrAlreadyEncrypted indicates that the path is already encrypted.
51 type ErrAlreadyEncrypted struct {
52 Path string
53 }
54
55 func (err *ErrAlreadyEncrypted) Error() string {
56 return fmt.Sprintf("file or directory %q is already encrypted", err.Path)
57 }
58
59 // ErrBadEncryptionOptions indicates that unsupported encryption options were given.
60 type ErrBadEncryptionOptions struct {
61 Path string
62 Options *EncryptionOptions
63 }
64
65 func (err *ErrBadEncryptionOptions) Error() string {
66 return fmt.Sprintf(`cannot encrypt %q because the kernel doesn't support the requested encryption options.
67
68 The options are %s`, err.Path, err.Options)
69 }
70
71 // ErrDirectoryNotOwned indicates a directory can't be encrypted because it's
72 // owned by another user.
73 type ErrDirectoryNotOwned struct {
74 Path string
75 Owner uint32
76 }
77
78 func (err *ErrDirectoryNotOwned) Error() string {
79 owner := strconv.Itoa(int(err.Owner))
80 if u, e := user.LookupId(owner); e == nil && u.Username != "" {
81 owner = u.Username
82 }
83 return fmt.Sprintf(`cannot encrypt %q because it's owned by another user (%s).
84
85 Encryption can only be enabled on a directory you own, even if you have
86 write access to the directory.`, err.Path, owner)
87 }
88
89 // ErrLockedRegularFile indicates that the path is a locked regular file.
90 type ErrLockedRegularFile struct {
91 Path string
92 }
93
94 func (err *ErrLockedRegularFile) Error() string {
95 return fmt.Sprintf("cannot operate on locked regular file %q", err.Path)
96 }
97
98 // ErrNotEncrypted indicates that the path is not encrypted.
99 type ErrNotEncrypted struct {
100 Path string
101 }
102
103 func (err *ErrNotEncrypted) Error() string {
104 return fmt.Sprintf("file or directory %q is not encrypted", err.Path)
105 }
106
107 func getPolicyIoctl(file *os.File, request uintptr, arg unsafe.Pointer) error {
108 _, _, errno := unix.Syscall(unix.SYS_IOCTL, file.Fd(), request, uintptr(arg))
109 if errno == 0 {
110 return nil
111 }
112 return errno
113 }
114
115 func setPolicy(file *os.File, arg unsafe.Pointer) error {
116 _, _, errno := unix.Syscall(unix.SYS_IOCTL, file.Fd(), unix.FS_IOC_SET_ENCRYPTION_POLICY, uintptr(arg))
117 if errno != 0 {
118 return errno
119 }
120
121 if err := file.Sync(); err != nil {
122 return err
123 }
124
125 return nil
126 }
127
128 // Maps EncryptionOptions.Padding <-> FSCRYPT_POLICY_FLAGS
129 var (
130 paddingArray = []int64{4, 8, 16, 32}
131 flagsArray = []int64{unix.FSCRYPT_POLICY_FLAGS_PAD_4, unix.FSCRYPT_POLICY_FLAGS_PAD_8,
132 unix.FSCRYPT_POLICY_FLAGS_PAD_16, unix.FSCRYPT_POLICY_FLAGS_PAD_32}
133 )
134
135 // flagsToPadding returns the amount of padding specified in the policy flags.
136 func flagsToPadding(flags uint8) int64 {
137 paddingFlag := int64(flags & unix.FS_POLICY_FLAGS_PAD_MASK)
138
139 // This lookup should always succeed
140 padding, ok := util.Lookup(paddingFlag, flagsArray, paddingArray)
141 if !ok {
142 log.Panicf("padding flag of %x not found", paddingFlag)
143 }
144 return padding
145 }
146
147 func buildV1PolicyData(policy *unix.FscryptPolicyV1) *PolicyData {
148 return &PolicyData{
149 KeyDescriptor: hex.EncodeToString(policy.Master_key_descriptor[:]),
150 Options: &EncryptionOptions{
151 Padding: flagsToPadding(policy.Flags),
152 Contents: EncryptionOptions_Mode(policy.Contents_encryption_mode),
153 Filenames: EncryptionOptions_Mode(policy.Filenames_encryption_mode),
154 PolicyVersion: 1,
155 },
156 }
157 }
158
159 func buildV2PolicyData(policy *unix.FscryptPolicyV2) *PolicyData {
160 return &PolicyData{
161 KeyDescriptor: hex.EncodeToString(policy.Master_key_identifier[:]),
162 Options: &EncryptionOptions{
163 Padding: flagsToPadding(policy.Flags),
164 Contents: EncryptionOptions_Mode(policy.Contents_encryption_mode),
165 Filenames: EncryptionOptions_Mode(policy.Filenames_encryption_mode),
166 PolicyVersion: 2,
167 },
168 }
169 }
170
171 // GetPolicy returns the Policy data for the given directory or file (includes
172 // the KeyDescriptor and the encryption options). Returns an error if the
173 // path is not encrypted or the policy couldn't be retrieved.
174 func GetPolicy(path string) (*PolicyData, error) {
175 file, err := os.Open(path)
176 if err != nil {
177 if err.(*os.PathError).Err == syscall.ENOKEY {
178 return nil, &ErrLockedRegularFile{path}
179 }
180 return nil, err
181 }
182 defer file.Close()
183
184 // First try the new version of the ioctl. This works for both v1 and v2 policies.
185 var arg unix.FscryptGetPolicyExArg
186 arg.Size = uint64(unsafe.Sizeof(arg.Policy))
187 policyPtr := util.Ptr(arg.Policy[:])
188 err = getPolicyIoctl(file, unix.FS_IOC_GET_ENCRYPTION_POLICY_EX, unsafe.Pointer(&arg))
189 if err == unix.ENOTTY {
190 // Fall back to the old version of the ioctl. This works for v1 policies only.
191 err = getPolicyIoctl(file, unix.FS_IOC_GET_ENCRYPTION_POLICY, policyPtr)
192 arg.Size = uint64(unsafe.Sizeof(unix.FscryptPolicyV1{}))
193 }
194 switch err {
195 case nil:
196 break
197 case unix.ENOTTY:
198 return nil, ErrEncryptionNotSupported
199 case unix.EOPNOTSUPP:
200 return nil, ErrEncryptionNotEnabled
201 case unix.ENODATA, unix.ENOENT:
202 // ENOENT was returned instead of ENODATA on some filesystems before v4.11.
203 return nil, &ErrNotEncrypted{path}
204 default:
205 return nil, errors.Wrapf(err, "failed to get encryption policy of %q", path)
206 }
207 switch arg.Policy[0] { // arg.policy.version
208 case unix.FSCRYPT_POLICY_V1:
209 if arg.Size != uint64(unsafe.Sizeof(unix.FscryptPolicyV1{})) {
210 // should never happen
211 return nil, errors.New("unexpected size for v1 policy")
212 }
213 return buildV1PolicyData((*unix.FscryptPolicyV1)(policyPtr)), nil
214 case unix.FSCRYPT_POLICY_V2:
215 if arg.Size != uint64(unsafe.Sizeof(unix.FscryptPolicyV2{})) {
216 // should never happen
217 return nil, errors.New("unexpected size for v2 policy")
218 }
219 return buildV2PolicyData((*unix.FscryptPolicyV2)(policyPtr)), nil
220 default:
221 return nil, errors.Errorf("unsupported encryption policy version [%d]",
222 arg.Policy[0])
223 }
224 }
225
226 // For improved performance, use the DIRECT_KEY flag when using ciphers that
227 // support it, e.g. Adiantum. It is safe because fscrypt won't reuse the key
228 // for any other policy. (Multiple directories with same policy are okay.)
229 func shouldUseDirectKeyFlag(options *EncryptionOptions) bool {
230 // Contents and filenames encryption modes must be the same
231 if options.Contents != options.Filenames {
232 return false
233 }
234 // Currently only Adiantum supports DIRECT_KEY.
235 return options.Contents == EncryptionOptions_Adiantum
236 }
237
238 func buildPolicyFlags(options *EncryptionOptions) uint8 {
239 // This lookup should always succeed (as policy is valid)
240 flags, ok := util.Lookup(options.Padding, paddingArray, flagsArray)
241 if !ok {
242 log.Panicf("padding of %d was not found", options.Padding)
243 }
244 if shouldUseDirectKeyFlag(options) {
245 flags |= unix.FSCRYPT_POLICY_FLAG_DIRECT_KEY
246 }
247 return uint8(flags)
248 }
249
250 func setV1Policy(file *os.File, options *EncryptionOptions, descriptorBytes []byte) error {
251 policy := unix.FscryptPolicyV1{
252 Version: unix.FSCRYPT_POLICY_V1,
253 Contents_encryption_mode: uint8(options.Contents),
254 Filenames_encryption_mode: uint8(options.Filenames),
255 Flags: uint8(buildPolicyFlags(options)),
256 }
257
258 // The descriptor should always be the correct length (as policy is valid)
259 if len(descriptorBytes) != unix.FSCRYPT_KEY_DESCRIPTOR_SIZE {
260 log.Panic("wrong descriptor size for v1 policy")
261 }
262 copy(policy.Master_key_descriptor[:], descriptorBytes)
263
264 return setPolicy(file, unsafe.Pointer(&policy))
265 }
266
267 func setV2Policy(file *os.File, options *EncryptionOptions, descriptorBytes []byte) error {
268 policy := unix.FscryptPolicyV2{
269 Version: unix.FSCRYPT_POLICY_V2,
270 Contents_encryption_mode: uint8(options.Contents),
271 Filenames_encryption_mode: uint8(options.Filenames),
272 Flags: uint8(buildPolicyFlags(options)),
273 }
274
275 // The descriptor should always be the correct length (as policy is valid)
276 if len(descriptorBytes) != unix.FSCRYPT_KEY_IDENTIFIER_SIZE {
277 log.Panic("wrong descriptor size for v2 policy")
278 }
279 copy(policy.Master_key_identifier[:], descriptorBytes)
280
281 return setPolicy(file, unsafe.Pointer(&policy))
282 }
283
284 // SetPolicy sets up the specified directory to be encrypted with the specified
285 // policy. Returns an error if we cannot set the policy for any reason (not a
286 // directory, invalid options or KeyDescriptor, etc).
287 func SetPolicy(path string, data *PolicyData) error {
288 file, err := os.Open(path)
289 if err != nil {
290 return err
291 }
292 defer file.Close()
293
294 if err = data.CheckValidity(); err != nil {
295 return errors.Wrap(err, "invalid policy")
296 }
297
298 descriptorBytes, err := hex.DecodeString(data.KeyDescriptor)
299 if err != nil {
300 return errors.New("invalid key descriptor: " + data.KeyDescriptor)
301 }
302
303 switch data.Options.PolicyVersion {
304 case 1:
305 err = setV1Policy(file, data.Options, descriptorBytes)
306 case 2:
307 err = setV2Policy(file, data.Options, descriptorBytes)
308 default:
309 err = errors.Errorf("policy version of %d is invalid", data.Options.PolicyVersion)
310 }
311 if err == unix.EINVAL {
312 // Before kernel v4.11, many different errors all caused unix.EINVAL to be returned.
313 // We try to disambiguate this error here. This disambiguation will not always give
314 // the correct error due to a potential race condition on path.
315 if info, statErr := os.Stat(path); statErr != nil || !info.IsDir() {
316 // Checking if the path is not a directory
317 err = unix.ENOTDIR
318 } else if _, policyErr := GetPolicy(path); policyErr == nil {
319 // Checking if a policy is already set on this directory
320 err = unix.EEXIST
321 }
322 }
323 switch err {
324 case nil:
325 return nil
326 case unix.EACCES:
327 var stat unix.Stat_t
328 if statErr := unix.Stat(path, &stat); statErr == nil && stat.Uid != uint32(os.Geteuid()) {
329 return &ErrDirectoryNotOwned{path, stat.Uid}
330 }
331 case unix.EEXIST:
332 return &ErrAlreadyEncrypted{path}
333 case unix.EINVAL:
334 return &ErrBadEncryptionOptions{path, data.Options}
335 case unix.ENOTTY:
336 return ErrEncryptionNotSupported
337 case unix.EOPNOTSUPP:
338 return ErrEncryptionNotEnabled
339 }
340 return errors.Wrapf(err, "failed to set encryption policy on %q", path)
341 }
342
343 // CheckSupport returns an error if the filesystem containing path does not
344 // support filesystem encryption. This can be for many reasons including an
345 // incompatible kernel or filesystem or not enabling the right feature flags.
346 func CheckSupport(path string) error {
347 file, err := os.Open(path)
348 if err != nil {
349 return err
350 }
351 defer file.Close()
352
353 // On supported directories, giving a bad policy will return EINVAL
354 badPolicy := unix.FscryptPolicyV1{
355 Version: math.MaxUint8,
356 Contents_encryption_mode: math.MaxUint8,
357 Filenames_encryption_mode: math.MaxUint8,
358 Flags: math.MaxUint8,
359 }
360
361 err = setPolicy(file, unsafe.Pointer(&badPolicy))
362 switch err {
363 case nil:
364 log.Panicf(`FS_IOC_SET_ENCRYPTION_POLICY succeeded when it should have failed.
365 Please open an issue, filesystem %q may be corrupted.`, path)
366 case unix.EINVAL, unix.EACCES:
367 return nil
368 case unix.ENOTTY:
369 return ErrEncryptionNotSupported
370 case unix.EOPNOTSUPP:
371 return ErrEncryptionNotEnabled
372 }
373 return errors.Wrapf(err, "unexpected error checking for encryption support on filesystem %q", path)
374 }