crypto.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // SPDX-License-Identifier: GPL-2.0
  2. #include "ubifs.h"
  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. static int ubifs_crypt_set_context(struct inode *inode, const void *ctx,
  9. size_t len, void *fs_data)
  10. {
  11. /*
  12. * Creating an encryption context is done unlocked since we
  13. * operate on a new inode which is not visible to other users
  14. * at this point. So, no need to check whether inode is locked.
  15. */
  16. return ubifs_xattr_set(inode, UBIFS_XATTR_NAME_ENCRYPTION_CONTEXT,
  17. ctx, len, 0, false);
  18. }
  19. static bool ubifs_crypt_empty_dir(struct inode *inode)
  20. {
  21. return ubifs_check_dir_empty(inode) == 0;
  22. }
  23. int ubifs_encrypt(const struct inode *inode, struct ubifs_data_node *dn,
  24. unsigned int in_len, unsigned int *out_len, int block)
  25. {
  26. struct ubifs_info *c = inode->i_sb->s_fs_info;
  27. void *p = &dn->data;
  28. struct page *ret;
  29. unsigned int pad_len = round_up(in_len, UBIFS_CIPHER_BLOCK_SIZE);
  30. ubifs_assert(c, pad_len <= *out_len);
  31. dn->compr_size = cpu_to_le16(in_len);
  32. /* pad to full block cipher length */
  33. if (pad_len != in_len)
  34. memset(p + in_len, 0, pad_len - in_len);
  35. ret = fscrypt_encrypt_page(inode, virt_to_page(&dn->data), pad_len,
  36. offset_in_page(&dn->data), block, GFP_NOFS);
  37. if (IS_ERR(ret)) {
  38. ubifs_err(c, "fscrypt_encrypt_page failed: %ld", PTR_ERR(ret));
  39. return PTR_ERR(ret);
  40. }
  41. *out_len = pad_len;
  42. return 0;
  43. }
  44. int ubifs_decrypt(const struct inode *inode, struct ubifs_data_node *dn,
  45. unsigned int *out_len, int block)
  46. {
  47. struct ubifs_info *c = inode->i_sb->s_fs_info;
  48. int err;
  49. unsigned int clen = le16_to_cpu(dn->compr_size);
  50. unsigned int dlen = *out_len;
  51. if (clen <= 0 || clen > UBIFS_BLOCK_SIZE || clen > dlen) {
  52. ubifs_err(c, "bad compr_size: %i", clen);
  53. return -EINVAL;
  54. }
  55. ubifs_assert(c, dlen <= UBIFS_BLOCK_SIZE);
  56. err = fscrypt_decrypt_page(inode, virt_to_page(&dn->data), dlen,
  57. offset_in_page(&dn->data), block);
  58. if (err) {
  59. ubifs_err(c, "fscrypt_decrypt_page failed: %i", err);
  60. return err;
  61. }
  62. *out_len = clen;
  63. return 0;
  64. }
  65. const struct fscrypt_operations ubifs_crypt_operations = {
  66. .flags = FS_CFLG_OWN_PAGES,
  67. .key_prefix = "ubifs:",
  68. .get_context = ubifs_crypt_get_context,
  69. .set_context = ubifs_crypt_set_context,
  70. .empty_dir = ubifs_crypt_empty_dir,
  71. .max_namelen = UBIFS_MAX_NLEN,
  72. };