xref: /openbmc/linux/fs/ubifs/crypto.c (revision 1c2dd16a)
1 #include "ubifs.h"
2 
3 static 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 
9 static 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 
16 static bool ubifs_crypt_empty_dir(struct inode *inode)
17 {
18 	return ubifs_check_dir_empty(inode) == 0;
19 }
20 
21 static 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 
29 int 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 
55 int 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 
80 const struct fscrypt_operations ubifs_crypt_operations = {
81 	.flags			= FS_CFLG_OWN_PAGES,
82 	.key_prefix		= "ubifs:",
83 	.get_context		= ubifs_crypt_get_context,
84 	.set_context		= ubifs_crypt_set_context,
85 	.is_encrypted		= __ubifs_crypt_is_encrypted,
86 	.empty_dir		= ubifs_crypt_empty_dir,
87 	.max_namelen		= ubifs_crypt_max_namelen,
88 };
89