blob: 382ed428cfd2167cc8c57c934e06ab29a92ceb6c [file] [log] [blame]
Richard Weinbergerd475a502016-10-20 16:47:56 +02001#include "ubifs.h"
2
3static int ubifs_crypt_get_context(struct inode *inode, void *ctx, size_t len)
4{
5 return ubifs_xattr_get(inode, UBIFS_XATTR_NAME_ENCRYPTION_CONTEXT,
6 ctx, len);
7}
8
9static int ubifs_crypt_set_context(struct inode *inode, const void *ctx,
10 size_t len, void *fs_data)
11{
12 return ubifs_xattr_set(inode, UBIFS_XATTR_NAME_ENCRYPTION_CONTEXT,
13 ctx, len, 0);
14}
15
16static bool ubifs_crypt_empty_dir(struct inode *inode)
17{
18 return ubifs_check_dir_empty(inode) == 0;
19}
20
21static unsigned int ubifs_crypt_max_namelen(struct inode *inode)
22{
23 if (S_ISLNK(inode->i_mode))
24 return UBIFS_MAX_INO_DATA;
25 else
26 return UBIFS_MAX_NLEN;
27}
28
Richard Weinberger77999532016-09-29 22:20:19 +020029int ubifs_encrypt(const struct inode *inode, struct ubifs_data_node *dn,
30 unsigned int in_len, unsigned int *out_len, int block)
31{
32 struct ubifs_info *c = inode->i_sb->s_fs_info;
33 void *p = &dn->data;
34 struct page *ret;
35 unsigned int pad_len = round_up(in_len, UBIFS_CIPHER_BLOCK_SIZE);
36
37 ubifs_assert(pad_len <= *out_len);
38 dn->compr_size = cpu_to_le16(in_len);
39
40 /* pad to full block cipher length */
41 if (pad_len != in_len)
42 memset(p + in_len, 0, pad_len - in_len);
43
44 ret = fscrypt_encrypt_page(inode, virt_to_page(&dn->data), pad_len,
45 offset_in_page(&dn->data), block, GFP_NOFS);
46 if (IS_ERR(ret)) {
47 ubifs_err(c, "fscrypt_encrypt_page failed: %ld", PTR_ERR(ret));
48 return PTR_ERR(ret);
49 }
50 *out_len = pad_len;
51
52 return 0;
53}
54
55int ubifs_decrypt(const struct inode *inode, struct ubifs_data_node *dn,
56 unsigned int *out_len, int block)
57{
58 struct ubifs_info *c = inode->i_sb->s_fs_info;
59 int err;
60 unsigned int clen = le16_to_cpu(dn->compr_size);
61 unsigned int dlen = *out_len;
62
63 if (clen <= 0 || clen > UBIFS_BLOCK_SIZE || clen > dlen) {
64 ubifs_err(c, "bad compr_size: %i", clen);
65 return -EINVAL;
66 }
67
68 ubifs_assert(dlen <= UBIFS_BLOCK_SIZE);
69 err = fscrypt_decrypt_page(inode, virt_to_page(&dn->data), dlen,
70 offset_in_page(&dn->data), block);
71 if (err) {
72 ubifs_err(c, "fscrypt_decrypt_page failed: %i", err);
73 return err;
74 }
75 *out_len = clen;
76
77 return 0;
78}
79
Eric Biggers6f69f0e2017-02-07 12:42:10 -080080const struct fscrypt_operations ubifs_crypt_operations = {
Richard Weinberger38588662016-12-13 00:27:58 +010081 .flags = FS_CFLG_OWN_PAGES,
Eric Biggersa5d431e2017-01-05 13:51:18 -080082 .key_prefix = "ubifs:",
Richard Weinbergerd475a502016-10-20 16:47:56 +020083 .get_context = ubifs_crypt_get_context,
84 .set_context = ubifs_crypt_set_context,
Richard Weinberger1ee77872016-10-21 14:03:19 +020085 .is_encrypted = __ubifs_crypt_is_encrypted,
Richard Weinbergerd475a502016-10-20 16:47:56 +020086 .empty_dir = ubifs_crypt_empty_dir,
87 .max_namelen = ubifs_crypt_max_namelen,
Richard Weinbergerd475a502016-10-20 16:47:56 +020088};