fscrypt: avoid data race on fscrypt_mode::logged_impl_name
[linux-block.git] / fs / crypto / fscrypt_private.h
1 /* SPDX-License-Identifier: GPL-2.0 */
2 /*
3  * fscrypt_private.h
4  *
5  * Copyright (C) 2015, Google, Inc.
6  *
7  * Originally written by Michael Halcrow, Ildar Muslukhov, and Uday Savagaonkar.
8  * Heavily modified since then.
9  */
10
11 #ifndef _FSCRYPT_PRIVATE_H
12 #define _FSCRYPT_PRIVATE_H
13
14 #include <linux/fscrypt.h>
15 #include <crypto/hash.h>
16
17 #define CONST_STRLEN(str)       (sizeof(str) - 1)
18
19 #define FS_KEY_DERIVATION_NONCE_SIZE    16
20
21 #define FSCRYPT_MIN_KEY_SIZE            16
22
23 #define FSCRYPT_CONTEXT_V1      1
24 #define FSCRYPT_CONTEXT_V2      2
25
26 struct fscrypt_context_v1 {
27         u8 version; /* FSCRYPT_CONTEXT_V1 */
28         u8 contents_encryption_mode;
29         u8 filenames_encryption_mode;
30         u8 flags;
31         u8 master_key_descriptor[FSCRYPT_KEY_DESCRIPTOR_SIZE];
32         u8 nonce[FS_KEY_DERIVATION_NONCE_SIZE];
33 };
34
35 struct fscrypt_context_v2 {
36         u8 version; /* FSCRYPT_CONTEXT_V2 */
37         u8 contents_encryption_mode;
38         u8 filenames_encryption_mode;
39         u8 flags;
40         u8 __reserved[4];
41         u8 master_key_identifier[FSCRYPT_KEY_IDENTIFIER_SIZE];
42         u8 nonce[FS_KEY_DERIVATION_NONCE_SIZE];
43 };
44
45 /**
46  * fscrypt_context - the encryption context of an inode
47  *
48  * This is the on-disk equivalent of an fscrypt_policy, stored alongside each
49  * encrypted file usually in a hidden extended attribute.  It contains the
50  * fields from the fscrypt_policy, in order to identify the encryption algorithm
51  * and key with which the file is encrypted.  It also contains a nonce that was
52  * randomly generated by fscrypt itself; this is used as KDF input or as a tweak
53  * to cause different files to be encrypted differently.
54  */
55 union fscrypt_context {
56         u8 version;
57         struct fscrypt_context_v1 v1;
58         struct fscrypt_context_v2 v2;
59 };
60
61 /*
62  * Return the size expected for the given fscrypt_context based on its version
63  * number, or 0 if the context version is unrecognized.
64  */
65 static inline int fscrypt_context_size(const union fscrypt_context *ctx)
66 {
67         switch (ctx->version) {
68         case FSCRYPT_CONTEXT_V1:
69                 BUILD_BUG_ON(sizeof(ctx->v1) != 28);
70                 return sizeof(ctx->v1);
71         case FSCRYPT_CONTEXT_V2:
72                 BUILD_BUG_ON(sizeof(ctx->v2) != 40);
73                 return sizeof(ctx->v2);
74         }
75         return 0;
76 }
77
78 #undef fscrypt_policy
79 union fscrypt_policy {
80         u8 version;
81         struct fscrypt_policy_v1 v1;
82         struct fscrypt_policy_v2 v2;
83 };
84
85 /*
86  * Return the size expected for the given fscrypt_policy based on its version
87  * number, or 0 if the policy version is unrecognized.
88  */
89 static inline int fscrypt_policy_size(const union fscrypt_policy *policy)
90 {
91         switch (policy->version) {
92         case FSCRYPT_POLICY_V1:
93                 return sizeof(policy->v1);
94         case FSCRYPT_POLICY_V2:
95                 return sizeof(policy->v2);
96         }
97         return 0;
98 }
99
100 /* Return the contents encryption mode of a valid encryption policy */
101 static inline u8
102 fscrypt_policy_contents_mode(const union fscrypt_policy *policy)
103 {
104         switch (policy->version) {
105         case FSCRYPT_POLICY_V1:
106                 return policy->v1.contents_encryption_mode;
107         case FSCRYPT_POLICY_V2:
108                 return policy->v2.contents_encryption_mode;
109         }
110         BUG();
111 }
112
113 /* Return the filenames encryption mode of a valid encryption policy */
114 static inline u8
115 fscrypt_policy_fnames_mode(const union fscrypt_policy *policy)
116 {
117         switch (policy->version) {
118         case FSCRYPT_POLICY_V1:
119                 return policy->v1.filenames_encryption_mode;
120         case FSCRYPT_POLICY_V2:
121                 return policy->v2.filenames_encryption_mode;
122         }
123         BUG();
124 }
125
126 /* Return the flags (FSCRYPT_POLICY_FLAG*) of a valid encryption policy */
127 static inline u8
128 fscrypt_policy_flags(const union fscrypt_policy *policy)
129 {
130         switch (policy->version) {
131         case FSCRYPT_POLICY_V1:
132                 return policy->v1.flags;
133         case FSCRYPT_POLICY_V2:
134                 return policy->v2.flags;
135         }
136         BUG();
137 }
138
139 static inline bool
140 fscrypt_is_direct_key_policy(const union fscrypt_policy *policy)
141 {
142         return fscrypt_policy_flags(policy) & FSCRYPT_POLICY_FLAG_DIRECT_KEY;
143 }
144
145 /**
146  * For encrypted symlinks, the ciphertext length is stored at the beginning
147  * of the string in little-endian format.
148  */
149 struct fscrypt_symlink_data {
150         __le16 len;
151         char encrypted_path[1];
152 } __packed;
153
154 /*
155  * fscrypt_info - the "encryption key" for an inode
156  *
157  * When an encrypted file's key is made available, an instance of this struct is
158  * allocated and stored in ->i_crypt_info.  Once created, it remains until the
159  * inode is evicted.
160  */
161 struct fscrypt_info {
162
163         /* The actual crypto transform used for encryption and decryption */
164         struct crypto_skcipher *ci_ctfm;
165
166         /*
167          * Encryption mode used for this inode.  It corresponds to either the
168          * contents or filenames encryption mode, depending on the inode type.
169          */
170         struct fscrypt_mode *ci_mode;
171
172         /* Back-pointer to the inode */
173         struct inode *ci_inode;
174
175         /*
176          * The master key with which this inode was unlocked (decrypted).  This
177          * will be NULL if the master key was found in a process-subscribed
178          * keyring rather than in the filesystem-level keyring.
179          */
180         struct key *ci_master_key;
181
182         /*
183          * Link in list of inodes that were unlocked with the master key.
184          * Only used when ->ci_master_key is set.
185          */
186         struct list_head ci_master_key_link;
187
188         /*
189          * If non-NULL, then encryption is done using the master key directly
190          * and ci_ctfm will equal ci_direct_key->dk_ctfm.
191          */
192         struct fscrypt_direct_key *ci_direct_key;
193
194         /* The encryption policy used by this inode */
195         union fscrypt_policy ci_policy;
196
197         /* This inode's nonce, copied from the fscrypt_context */
198         u8 ci_nonce[FS_KEY_DERIVATION_NONCE_SIZE];
199 };
200
201 typedef enum {
202         FS_DECRYPT = 0,
203         FS_ENCRYPT,
204 } fscrypt_direction_t;
205
206 static inline bool fscrypt_valid_enc_modes(u32 contents_mode,
207                                            u32 filenames_mode)
208 {
209         if (contents_mode == FSCRYPT_MODE_AES_128_CBC &&
210             filenames_mode == FSCRYPT_MODE_AES_128_CTS)
211                 return true;
212
213         if (contents_mode == FSCRYPT_MODE_AES_256_XTS &&
214             filenames_mode == FSCRYPT_MODE_AES_256_CTS)
215                 return true;
216
217         if (contents_mode == FSCRYPT_MODE_ADIANTUM &&
218             filenames_mode == FSCRYPT_MODE_ADIANTUM)
219                 return true;
220
221         return false;
222 }
223
224 /* crypto.c */
225 extern struct kmem_cache *fscrypt_info_cachep;
226 extern int fscrypt_initialize(unsigned int cop_flags);
227 extern int fscrypt_crypt_block(const struct inode *inode,
228                                fscrypt_direction_t rw, u64 lblk_num,
229                                struct page *src_page, struct page *dest_page,
230                                unsigned int len, unsigned int offs,
231                                gfp_t gfp_flags);
232 extern struct page *fscrypt_alloc_bounce_page(gfp_t gfp_flags);
233 extern const struct dentry_operations fscrypt_d_ops;
234
235 extern void __printf(3, 4) __cold
236 fscrypt_msg(const struct inode *inode, const char *level, const char *fmt, ...);
237
238 #define fscrypt_warn(inode, fmt, ...)           \
239         fscrypt_msg((inode), KERN_WARNING, fmt, ##__VA_ARGS__)
240 #define fscrypt_err(inode, fmt, ...)            \
241         fscrypt_msg((inode), KERN_ERR, fmt, ##__VA_ARGS__)
242
243 #define FSCRYPT_MAX_IV_SIZE     32
244
245 union fscrypt_iv {
246         struct {
247                 /* logical block number within the file */
248                 __le64 lblk_num;
249
250                 /* per-file nonce; only set in DIRECT_KEY mode */
251                 u8 nonce[FS_KEY_DERIVATION_NONCE_SIZE];
252         };
253         u8 raw[FSCRYPT_MAX_IV_SIZE];
254 };
255
256 void fscrypt_generate_iv(union fscrypt_iv *iv, u64 lblk_num,
257                          const struct fscrypt_info *ci);
258
259 /* fname.c */
260 extern int fname_encrypt(struct inode *inode, const struct qstr *iname,
261                          u8 *out, unsigned int olen);
262 extern bool fscrypt_fname_encrypted_size(const struct inode *inode,
263                                          u32 orig_len, u32 max_len,
264                                          u32 *encrypted_len_ret);
265
266 /* hkdf.c */
267
268 struct fscrypt_hkdf {
269         struct crypto_shash *hmac_tfm;
270 };
271
272 extern int fscrypt_init_hkdf(struct fscrypt_hkdf *hkdf, const u8 *master_key,
273                              unsigned int master_key_size);
274
275 /*
276  * The list of contexts in which fscrypt uses HKDF.  These values are used as
277  * the first byte of the HKDF application-specific info string to guarantee that
278  * info strings are never repeated between contexts.  This ensures that all HKDF
279  * outputs are unique and cryptographically isolated, i.e. knowledge of one
280  * output doesn't reveal another.
281  */
282 #define HKDF_CONTEXT_KEY_IDENTIFIER     1
283 #define HKDF_CONTEXT_PER_FILE_KEY       2
284 #define HKDF_CONTEXT_PER_MODE_KEY       3
285
286 extern int fscrypt_hkdf_expand(struct fscrypt_hkdf *hkdf, u8 context,
287                                const u8 *info, unsigned int infolen,
288                                u8 *okm, unsigned int okmlen);
289
290 extern void fscrypt_destroy_hkdf(struct fscrypt_hkdf *hkdf);
291
292 /* keyring.c */
293
294 /*
295  * fscrypt_master_key_secret - secret key material of an in-use master key
296  */
297 struct fscrypt_master_key_secret {
298
299         /*
300          * For v2 policy keys: HKDF context keyed by this master key.
301          * For v1 policy keys: not set (hkdf.hmac_tfm == NULL).
302          */
303         struct fscrypt_hkdf     hkdf;
304
305         /* Size of the raw key in bytes.  Set even if ->raw isn't set. */
306         u32                     size;
307
308         /* For v1 policy keys: the raw key.  Wiped for v2 policy keys. */
309         u8                      raw[FSCRYPT_MAX_KEY_SIZE];
310
311 } __randomize_layout;
312
313 /*
314  * fscrypt_master_key - an in-use master key
315  *
316  * This represents a master encryption key which has been added to the
317  * filesystem and can be used to "unlock" the encrypted files which were
318  * encrypted with it.
319  */
320 struct fscrypt_master_key {
321
322         /*
323          * The secret key material.  After FS_IOC_REMOVE_ENCRYPTION_KEY is
324          * executed, this is wiped and no new inodes can be unlocked with this
325          * key; however, there may still be inodes in ->mk_decrypted_inodes
326          * which could not be evicted.  As long as some inodes still remain,
327          * FS_IOC_REMOVE_ENCRYPTION_KEY can be retried, or
328          * FS_IOC_ADD_ENCRYPTION_KEY can add the secret again.
329          *
330          * Locking: protected by key->sem (outer) and mk_secret_sem (inner).
331          * The reason for two locks is that key->sem also protects modifying
332          * mk_users, which ranks it above the semaphore for the keyring key
333          * type, which is in turn above page faults (via keyring_read).  But
334          * sometimes filesystems call fscrypt_get_encryption_info() from within
335          * a transaction, which ranks it below page faults.  So we need a
336          * separate lock which protects mk_secret but not also mk_users.
337          */
338         struct fscrypt_master_key_secret        mk_secret;
339         struct rw_semaphore                     mk_secret_sem;
340
341         /*
342          * For v1 policy keys: an arbitrary key descriptor which was assigned by
343          * userspace (->descriptor).
344          *
345          * For v2 policy keys: a cryptographic hash of this key (->identifier).
346          */
347         struct fscrypt_key_specifier            mk_spec;
348
349         /*
350          * Keyring which contains a key of type 'key_type_fscrypt_user' for each
351          * user who has added this key.  Normally each key will be added by just
352          * one user, but it's possible that multiple users share a key, and in
353          * that case we need to keep track of those users so that one user can't
354          * remove the key before the others want it removed too.
355          *
356          * This is NULL for v1 policy keys; those can only be added by root.
357          *
358          * Locking: in addition to this keyrings own semaphore, this is
359          * protected by the master key's key->sem, so we can do atomic
360          * search+insert.  It can also be searched without taking any locks, but
361          * in that case the returned key may have already been removed.
362          */
363         struct key              *mk_users;
364
365         /*
366          * Length of ->mk_decrypted_inodes, plus one if mk_secret is present.
367          * Once this goes to 0, the master key is removed from ->s_master_keys.
368          * The 'struct fscrypt_master_key' will continue to live as long as the
369          * 'struct key' whose payload it is, but we won't let this reference
370          * count rise again.
371          */
372         refcount_t              mk_refcount;
373
374         /*
375          * List of inodes that were unlocked using this key.  This allows the
376          * inodes to be evicted efficiently if the key is removed.
377          */
378         struct list_head        mk_decrypted_inodes;
379         spinlock_t              mk_decrypted_inodes_lock;
380
381         /* Per-mode tfms for DIRECT_KEY policies, allocated on-demand */
382         struct crypto_skcipher  *mk_mode_keys[__FSCRYPT_MODE_MAX + 1];
383
384 } __randomize_layout;
385
386 static inline bool
387 is_master_key_secret_present(const struct fscrypt_master_key_secret *secret)
388 {
389         /*
390          * The READ_ONCE() is only necessary for fscrypt_drop_inode() and
391          * fscrypt_key_describe().  These run in atomic context, so they can't
392          * take ->mk_secret_sem and thus 'secret' can change concurrently which
393          * would be a data race.  But they only need to know whether the secret
394          * *was* present at the time of check, so READ_ONCE() suffices.
395          */
396         return READ_ONCE(secret->size) != 0;
397 }
398
399 static inline const char *master_key_spec_type(
400                                 const struct fscrypt_key_specifier *spec)
401 {
402         switch (spec->type) {
403         case FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR:
404                 return "descriptor";
405         case FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER:
406                 return "identifier";
407         }
408         return "[unknown]";
409 }
410
411 static inline int master_key_spec_len(const struct fscrypt_key_specifier *spec)
412 {
413         switch (spec->type) {
414         case FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR:
415                 return FSCRYPT_KEY_DESCRIPTOR_SIZE;
416         case FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER:
417                 return FSCRYPT_KEY_IDENTIFIER_SIZE;
418         }
419         return 0;
420 }
421
422 extern struct key *
423 fscrypt_find_master_key(struct super_block *sb,
424                         const struct fscrypt_key_specifier *mk_spec);
425
426 extern int fscrypt_verify_key_added(struct super_block *sb,
427                                     const u8 identifier[FSCRYPT_KEY_IDENTIFIER_SIZE]);
428
429 extern int __init fscrypt_init_keyring(void);
430
431 /* keysetup.c */
432
433 struct fscrypt_mode {
434         const char *friendly_name;
435         const char *cipher_str;
436         int keysize;
437         int ivsize;
438         int logged_impl_name;
439 };
440
441 static inline bool
442 fscrypt_mode_supports_direct_key(const struct fscrypt_mode *mode)
443 {
444         return mode->ivsize >= offsetofend(union fscrypt_iv, nonce);
445 }
446
447 extern struct crypto_skcipher *
448 fscrypt_allocate_skcipher(struct fscrypt_mode *mode, const u8 *raw_key,
449                           const struct inode *inode);
450
451 extern int fscrypt_set_derived_key(struct fscrypt_info *ci,
452                                    const u8 *derived_key);
453
454 /* keysetup_v1.c */
455
456 extern void fscrypt_put_direct_key(struct fscrypt_direct_key *dk);
457
458 extern int fscrypt_setup_v1_file_key(struct fscrypt_info *ci,
459                                      const u8 *raw_master_key);
460
461 extern int fscrypt_setup_v1_file_key_via_subscribed_keyrings(
462                                         struct fscrypt_info *ci);
463 /* policy.c */
464
465 extern bool fscrypt_policies_equal(const union fscrypt_policy *policy1,
466                                    const union fscrypt_policy *policy2);
467 extern bool fscrypt_supported_policy(const union fscrypt_policy *policy_u,
468                                      const struct inode *inode);
469 extern int fscrypt_policy_from_context(union fscrypt_policy *policy_u,
470                                        const union fscrypt_context *ctx_u,
471                                        int ctx_size);
472
473 #endif /* _FSCRYPT_PRIVATE_H */