1// SPDX-License-Identifier: GPL-2.0-only
2/*
3 * fs/crypto/hooks.c
4 *
5 * Encryption hooks for higher-level filesystem operations.
6 */
7
8#include "fscrypt_private.h"
9
10/**
11 * fscrypt_file_open() - prepare to open a possibly-encrypted regular file
12 * @inode: the inode being opened
13 * @filp: the struct file being set up
14 *
15 * Currently, an encrypted regular file can only be opened if its encryption key
16 * is available; access to the raw encrypted contents is not supported.
17 * Therefore, we first set up the inode's encryption key (if not already done)
18 * and return an error if it's unavailable.
19 *
20 * We also verify that if the parent directory (from the path via which the file
21 * is being opened) is encrypted, then the inode being opened uses the same
22 * encryption policy. This is needed as part of the enforcement that all files
23 * in an encrypted directory tree use the same encryption policy, as a
24 * protection against certain types of offline attacks. Note that this check is
25 * needed even when opening an *unencrypted* file, since it's forbidden to have
26 * an unencrypted file in an encrypted directory.
27 *
28 * Return: 0 on success, -ENOKEY if the key is missing, or another -errno code
29 */
30int fscrypt_file_open(struct inode *inode, struct file *filp)
31{
32 int err;
33 struct dentry *dir;
34
35 err = fscrypt_require_key(inode);
36 if (err)
37 return err;
38
39 dir = dget_parent(dentry: file_dentry(file: filp));
40 if (IS_ENCRYPTED(d_inode(dir)) &&
41 !fscrypt_has_permitted_context(parent: d_inode(dentry: dir), child: inode)) {
42 fscrypt_warn(inode,
43 "Inconsistent encryption context (parent directory: %lu)",
44 d_inode(dir)->i_ino);
45 err = -EPERM;
46 }
47 dput(dir);
48 return err;
49}
50EXPORT_SYMBOL_GPL(fscrypt_file_open);
51
52int __fscrypt_prepare_link(struct inode *inode, struct inode *dir,
53 struct dentry *dentry)
54{
55 if (fscrypt_is_nokey_name(dentry))
56 return -ENOKEY;
57 /*
58 * We don't need to separately check that the directory inode's key is
59 * available, as it's implied by the dentry not being a no-key name.
60 */
61
62 if (!fscrypt_has_permitted_context(parent: dir, child: inode))
63 return -EXDEV;
64
65 return 0;
66}
67EXPORT_SYMBOL_GPL(__fscrypt_prepare_link);
68
69int __fscrypt_prepare_rename(struct inode *old_dir, struct dentry *old_dentry,
70 struct inode *new_dir, struct dentry *new_dentry,
71 unsigned int flags)
72{
73 if (fscrypt_is_nokey_name(dentry: old_dentry) ||
74 fscrypt_is_nokey_name(dentry: new_dentry))
75 return -ENOKEY;
76 /*
77 * We don't need to separately check that the directory inodes' keys are
78 * available, as it's implied by the dentries not being no-key names.
79 */
80
81 if (old_dir != new_dir) {
82 if (IS_ENCRYPTED(new_dir) &&
83 !fscrypt_has_permitted_context(parent: new_dir,
84 child: d_inode(dentry: old_dentry)))
85 return -EXDEV;
86
87 if ((flags & RENAME_EXCHANGE) &&
88 IS_ENCRYPTED(old_dir) &&
89 !fscrypt_has_permitted_context(parent: old_dir,
90 child: d_inode(dentry: new_dentry)))
91 return -EXDEV;
92 }
93 return 0;
94}
95EXPORT_SYMBOL_GPL(__fscrypt_prepare_rename);
96
97int __fscrypt_prepare_lookup(struct inode *dir, struct dentry *dentry,
98 struct fscrypt_name *fname)
99{
100 int err = fscrypt_setup_filename(inode: dir, iname: &dentry->d_name, lookup: 1, fname);
101
102 if (err && err != -ENOENT)
103 return err;
104
105 if (fname->is_nokey_name) {
106 spin_lock(lock: &dentry->d_lock);
107 dentry->d_flags |= DCACHE_NOKEY_NAME;
108 spin_unlock(lock: &dentry->d_lock);
109 }
110 return err;
111}
112EXPORT_SYMBOL_GPL(__fscrypt_prepare_lookup);
113
114/**
115 * fscrypt_prepare_lookup_partial() - prepare lookup without filename setup
116 * @dir: the encrypted directory being searched
117 * @dentry: the dentry being looked up in @dir
118 *
119 * This function should be used by the ->lookup and ->atomic_open methods of
120 * filesystems that handle filename encryption and no-key name encoding
121 * themselves and thus can't use fscrypt_prepare_lookup(). Like
122 * fscrypt_prepare_lookup(), this will try to set up the directory's encryption
123 * key and will set DCACHE_NOKEY_NAME on the dentry if the key is unavailable.
124 * However, this function doesn't set up a struct fscrypt_name for the filename.
125 *
126 * Return: 0 on success; -errno on error. Note that the encryption key being
127 * unavailable is not considered an error. It is also not an error if
128 * the encryption policy is unsupported by this kernel; that is treated
129 * like the key being unavailable, so that files can still be deleted.
130 */
131int fscrypt_prepare_lookup_partial(struct inode *dir, struct dentry *dentry)
132{
133 int err = fscrypt_get_encryption_info(inode: dir, allow_unsupported: true);
134
135 if (!err && !fscrypt_has_encryption_key(inode: dir)) {
136 spin_lock(lock: &dentry->d_lock);
137 dentry->d_flags |= DCACHE_NOKEY_NAME;
138 spin_unlock(lock: &dentry->d_lock);
139 }
140 return err;
141}
142EXPORT_SYMBOL_GPL(fscrypt_prepare_lookup_partial);
143
144int __fscrypt_prepare_readdir(struct inode *dir)
145{
146 return fscrypt_get_encryption_info(inode: dir, allow_unsupported: true);
147}
148EXPORT_SYMBOL_GPL(__fscrypt_prepare_readdir);
149
150int __fscrypt_prepare_setattr(struct dentry *dentry, struct iattr *attr)
151{
152 if (attr->ia_valid & ATTR_SIZE)
153 return fscrypt_require_key(inode: d_inode(dentry));
154 return 0;
155}
156EXPORT_SYMBOL_GPL(__fscrypt_prepare_setattr);
157
158/**
159 * fscrypt_prepare_setflags() - prepare to change flags with FS_IOC_SETFLAGS
160 * @inode: the inode on which flags are being changed
161 * @oldflags: the old flags
162 * @flags: the new flags
163 *
164 * The caller should be holding i_rwsem for write.
165 *
166 * Return: 0 on success; -errno if the flags change isn't allowed or if
167 * another error occurs.
168 */
169int fscrypt_prepare_setflags(struct inode *inode,
170 unsigned int oldflags, unsigned int flags)
171{
172 struct fscrypt_inode_info *ci;
173 struct fscrypt_master_key *mk;
174 int err;
175
176 /*
177 * When the CASEFOLD flag is set on an encrypted directory, we must
178 * derive the secret key needed for the dirhash. This is only possible
179 * if the directory uses a v2 encryption policy.
180 */
181 if (IS_ENCRYPTED(inode) && (flags & ~oldflags & FS_CASEFOLD_FL)) {
182 err = fscrypt_require_key(inode);
183 if (err)
184 return err;
185 ci = inode->i_crypt_info;
186 if (ci->ci_policy.version != FSCRYPT_POLICY_V2)
187 return -EINVAL;
188 mk = ci->ci_master_key;
189 down_read(sem: &mk->mk_sem);
190 if (mk->mk_present)
191 err = fscrypt_derive_dirhash_key(ci, mk);
192 else
193 err = -ENOKEY;
194 up_read(sem: &mk->mk_sem);
195 return err;
196 }
197 return 0;
198}
199
200/**
201 * fscrypt_prepare_symlink() - prepare to create a possibly-encrypted symlink
202 * @dir: directory in which the symlink is being created
203 * @target: plaintext symlink target
204 * @len: length of @target excluding null terminator
205 * @max_len: space the filesystem has available to store the symlink target
206 * @disk_link: (out) the on-disk symlink target being prepared
207 *
208 * This function computes the size the symlink target will require on-disk,
209 * stores it in @disk_link->len, and validates it against @max_len. An
210 * encrypted symlink may be longer than the original.
211 *
212 * Additionally, @disk_link->name is set to @target if the symlink will be
213 * unencrypted, but left NULL if the symlink will be encrypted. For encrypted
214 * symlinks, the filesystem must call fscrypt_encrypt_symlink() to create the
215 * on-disk target later. (The reason for the two-step process is that some
216 * filesystems need to know the size of the symlink target before creating the
217 * inode, e.g. to determine whether it will be a "fast" or "slow" symlink.)
218 *
219 * Return: 0 on success, -ENAMETOOLONG if the symlink target is too long,
220 * -ENOKEY if the encryption key is missing, or another -errno code if a problem
221 * occurred while setting up the encryption key.
222 */
223int fscrypt_prepare_symlink(struct inode *dir, const char *target,
224 unsigned int len, unsigned int max_len,
225 struct fscrypt_str *disk_link)
226{
227 const union fscrypt_policy *policy;
228
229 /*
230 * To calculate the size of the encrypted symlink target we need to know
231 * the amount of NUL padding, which is determined by the flags set in
232 * the encryption policy which will be inherited from the directory.
233 */
234 policy = fscrypt_policy_to_inherit(dir);
235 if (policy == NULL) {
236 /* Not encrypted */
237 disk_link->name = (unsigned char *)target;
238 disk_link->len = len + 1;
239 if (disk_link->len > max_len)
240 return -ENAMETOOLONG;
241 return 0;
242 }
243 if (IS_ERR(ptr: policy))
244 return PTR_ERR(ptr: policy);
245
246 /*
247 * Calculate the size of the encrypted symlink and verify it won't
248 * exceed max_len. Note that for historical reasons, encrypted symlink
249 * targets are prefixed with the ciphertext length, despite this
250 * actually being redundant with i_size. This decreases by 2 bytes the
251 * longest symlink target we can accept.
252 *
253 * We could recover 1 byte by not counting a null terminator, but
254 * counting it (even though it is meaningless for ciphertext) is simpler
255 * for now since filesystems will assume it is there and subtract it.
256 */
257 if (!__fscrypt_fname_encrypted_size(policy, orig_len: len,
258 max_len: max_len - sizeof(struct fscrypt_symlink_data) - 1,
259 encrypted_len_ret: &disk_link->len))
260 return -ENAMETOOLONG;
261 disk_link->len += sizeof(struct fscrypt_symlink_data) + 1;
262
263 disk_link->name = NULL;
264 return 0;
265}
266EXPORT_SYMBOL_GPL(fscrypt_prepare_symlink);
267
268int __fscrypt_encrypt_symlink(struct inode *inode, const char *target,
269 unsigned int len, struct fscrypt_str *disk_link)
270{
271 int err;
272 struct qstr iname = QSTR_INIT(target, len);
273 struct fscrypt_symlink_data *sd;
274 unsigned int ciphertext_len;
275
276 /*
277 * fscrypt_prepare_new_inode() should have already set up the new
278 * symlink inode's encryption key. We don't wait until now to do it,
279 * since we may be in a filesystem transaction now.
280 */
281 if (WARN_ON_ONCE(!fscrypt_has_encryption_key(inode)))
282 return -ENOKEY;
283
284 if (disk_link->name) {
285 /* filesystem-provided buffer */
286 sd = (struct fscrypt_symlink_data *)disk_link->name;
287 } else {
288 sd = kmalloc(size: disk_link->len, GFP_NOFS);
289 if (!sd)
290 return -ENOMEM;
291 }
292 ciphertext_len = disk_link->len - sizeof(*sd) - 1;
293 sd->len = cpu_to_le16(ciphertext_len);
294
295 err = fscrypt_fname_encrypt(inode, iname: &iname, out: sd->encrypted_path,
296 olen: ciphertext_len);
297 if (err)
298 goto err_free_sd;
299
300 /*
301 * Null-terminating the ciphertext doesn't make sense, but we still
302 * count the null terminator in the length, so we might as well
303 * initialize it just in case the filesystem writes it out.
304 */
305 sd->encrypted_path[ciphertext_len] = '\0';
306
307 /* Cache the plaintext symlink target for later use by get_link() */
308 err = -ENOMEM;
309 inode->i_link = kmemdup(p: target, size: len + 1, GFP_NOFS);
310 if (!inode->i_link)
311 goto err_free_sd;
312
313 if (!disk_link->name)
314 disk_link->name = (unsigned char *)sd;
315 return 0;
316
317err_free_sd:
318 if (!disk_link->name)
319 kfree(objp: sd);
320 return err;
321}
322EXPORT_SYMBOL_GPL(__fscrypt_encrypt_symlink);
323
324/**
325 * fscrypt_get_symlink() - get the target of an encrypted symlink
326 * @inode: the symlink inode
327 * @caddr: the on-disk contents of the symlink
328 * @max_size: size of @caddr buffer
329 * @done: if successful, will be set up to free the returned target if needed
330 *
331 * If the symlink's encryption key is available, we decrypt its target.
332 * Otherwise, we encode its target for presentation.
333 *
334 * This may sleep, so the filesystem must have dropped out of RCU mode already.
335 *
336 * Return: the presentable symlink target or an ERR_PTR()
337 */
338const char *fscrypt_get_symlink(struct inode *inode, const void *caddr,
339 unsigned int max_size,
340 struct delayed_call *done)
341{
342 const struct fscrypt_symlink_data *sd;
343 struct fscrypt_str cstr, pstr;
344 bool has_key;
345 int err;
346
347 /* This is for encrypted symlinks only */
348 if (WARN_ON_ONCE(!IS_ENCRYPTED(inode)))
349 return ERR_PTR(error: -EINVAL);
350
351 /* If the decrypted target is already cached, just return it. */
352 pstr.name = READ_ONCE(inode->i_link);
353 if (pstr.name)
354 return pstr.name;
355
356 /*
357 * Try to set up the symlink's encryption key, but we can continue
358 * regardless of whether the key is available or not.
359 */
360 err = fscrypt_get_encryption_info(inode, allow_unsupported: false);
361 if (err)
362 return ERR_PTR(error: err);
363 has_key = fscrypt_has_encryption_key(inode);
364
365 /*
366 * For historical reasons, encrypted symlink targets are prefixed with
367 * the ciphertext length, even though this is redundant with i_size.
368 */
369
370 if (max_size < sizeof(*sd) + 1)
371 return ERR_PTR(error: -EUCLEAN);
372 sd = caddr;
373 cstr.name = (unsigned char *)sd->encrypted_path;
374 cstr.len = le16_to_cpu(sd->len);
375
376 if (cstr.len == 0)
377 return ERR_PTR(error: -EUCLEAN);
378
379 if (cstr.len + sizeof(*sd) > max_size)
380 return ERR_PTR(error: -EUCLEAN);
381
382 err = fscrypt_fname_alloc_buffer(max_encrypted_len: cstr.len, crypto_str: &pstr);
383 if (err)
384 return ERR_PTR(error: err);
385
386 err = fscrypt_fname_disk_to_usr(inode, hash: 0, minor_hash: 0, iname: &cstr, oname: &pstr);
387 if (err)
388 goto err_kfree;
389
390 err = -EUCLEAN;
391 if (pstr.name[0] == '\0')
392 goto err_kfree;
393
394 pstr.name[pstr.len] = '\0';
395
396 /*
397 * Cache decrypted symlink targets in i_link for later use. Don't cache
398 * symlink targets encoded without the key, since those become outdated
399 * once the key is added. This pairs with the READ_ONCE() above and in
400 * the VFS path lookup code.
401 */
402 if (!has_key ||
403 cmpxchg_release(&inode->i_link, NULL, pstr.name) != NULL)
404 set_delayed_call(call: done, fn: kfree_link, arg: pstr.name);
405
406 return pstr.name;
407
408err_kfree:
409 kfree(objp: pstr.name);
410 return ERR_PTR(error: err);
411}
412EXPORT_SYMBOL_GPL(fscrypt_get_symlink);
413
414/**
415 * fscrypt_symlink_getattr() - set the correct st_size for encrypted symlinks
416 * @path: the path for the encrypted symlink being queried
417 * @stat: the struct being filled with the symlink's attributes
418 *
419 * Override st_size of encrypted symlinks to be the length of the decrypted
420 * symlink target (or the no-key encoded symlink target, if the key is
421 * unavailable) rather than the length of the encrypted symlink target. This is
422 * necessary for st_size to match the symlink target that userspace actually
423 * sees. POSIX requires this, and some userspace programs depend on it.
424 *
425 * This requires reading the symlink target from disk if needed, setting up the
426 * inode's encryption key if possible, and then decrypting or encoding the
427 * symlink target. This makes lstat() more heavyweight than is normally the
428 * case. However, decrypted symlink targets will be cached in ->i_link, so
429 * usually the symlink won't have to be read and decrypted again later if/when
430 * it is actually followed, readlink() is called, or lstat() is called again.
431 *
432 * Return: 0 on success, -errno on failure
433 */
434int fscrypt_symlink_getattr(const struct path *path, struct kstat *stat)
435{
436 struct dentry *dentry = path->dentry;
437 struct inode *inode = d_inode(dentry);
438 const char *link;
439 DEFINE_DELAYED_CALL(done);
440
441 /*
442 * To get the symlink target that userspace will see (whether it's the
443 * decrypted target or the no-key encoded target), we can just get it in
444 * the same way the VFS does during path resolution and readlink().
445 */
446 link = READ_ONCE(inode->i_link);
447 if (!link) {
448 link = inode->i_op->get_link(dentry, inode, &done);
449 if (IS_ERR(ptr: link))
450 return PTR_ERR(ptr: link);
451 }
452 stat->size = strlen(link);
453 do_delayed_call(call: &done);
454 return 0;
455}
456EXPORT_SYMBOL_GPL(fscrypt_symlink_getattr);
457

source code of linux/fs/crypto/hooks.c