keysetup.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Key setup facility for FS encryption support.
  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. #include <crypto/skcipher.h>
  11. #include <linux/random.h>
  12. #include "fscrypt_private.h"
  13. struct fscrypt_mode fscrypt_modes[] = {
  14. [FSCRYPT_MODE_AES_256_XTS] = {
  15. .friendly_name = "AES-256-XTS",
  16. .cipher_str = "xts(aes)",
  17. .keysize = 64,
  18. .security_strength = 32,
  19. .ivsize = 16,
  20. .blk_crypto_mode = BLK_ENCRYPTION_MODE_AES_256_XTS,
  21. },
  22. [FSCRYPT_MODE_AES_256_CTS] = {
  23. .friendly_name = "AES-256-CBC-CTS",
  24. .cipher_str = "cts(cbc(aes))",
  25. .keysize = 32,
  26. .security_strength = 32,
  27. .ivsize = 16,
  28. },
  29. [FSCRYPT_MODE_AES_128_CBC] = {
  30. .friendly_name = "AES-128-CBC-ESSIV",
  31. .cipher_str = "essiv(cbc(aes),sha256)",
  32. .keysize = 16,
  33. .security_strength = 16,
  34. .ivsize = 16,
  35. .blk_crypto_mode = BLK_ENCRYPTION_MODE_AES_128_CBC_ESSIV,
  36. },
  37. [FSCRYPT_MODE_AES_128_CTS] = {
  38. .friendly_name = "AES-128-CBC-CTS",
  39. .cipher_str = "cts(cbc(aes))",
  40. .keysize = 16,
  41. .security_strength = 16,
  42. .ivsize = 16,
  43. },
  44. [FSCRYPT_MODE_SM4_XTS] = {
  45. .friendly_name = "SM4-XTS",
  46. .cipher_str = "xts(sm4)",
  47. .keysize = 32,
  48. .security_strength = 16,
  49. .ivsize = 16,
  50. .blk_crypto_mode = BLK_ENCRYPTION_MODE_SM4_XTS,
  51. },
  52. [FSCRYPT_MODE_SM4_CTS] = {
  53. .friendly_name = "SM4-CBC-CTS",
  54. .cipher_str = "cts(cbc(sm4))",
  55. .keysize = 16,
  56. .security_strength = 16,
  57. .ivsize = 16,
  58. },
  59. [FSCRYPT_MODE_ADIANTUM] = {
  60. .friendly_name = "Adiantum",
  61. .cipher_str = "adiantum(xchacha12,aes)",
  62. .keysize = 32,
  63. .security_strength = 32,
  64. .ivsize = 32,
  65. .blk_crypto_mode = BLK_ENCRYPTION_MODE_ADIANTUM,
  66. },
  67. [FSCRYPT_MODE_AES_256_HCTR2] = {
  68. .friendly_name = "AES-256-HCTR2",
  69. .cipher_str = "hctr2(aes)",
  70. .keysize = 32,
  71. .security_strength = 32,
  72. .ivsize = 32,
  73. },
  74. };
  75. static DEFINE_MUTEX(fscrypt_mode_key_setup_mutex);
  76. static struct fscrypt_mode *
  77. select_encryption_mode(const union fscrypt_policy *policy,
  78. const struct inode *inode)
  79. {
  80. BUILD_BUG_ON(ARRAY_SIZE(fscrypt_modes) != FSCRYPT_MODE_MAX + 1);
  81. if (S_ISREG(inode->i_mode))
  82. return &fscrypt_modes[fscrypt_policy_contents_mode(policy)];
  83. if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))
  84. return &fscrypt_modes[fscrypt_policy_fnames_mode(policy)];
  85. WARN_ONCE(1, "fscrypt: filesystem tried to load encryption info for inode %lu, which is not encryptable (file type %d)\n",
  86. inode->i_ino, (inode->i_mode & S_IFMT));
  87. return ERR_PTR(-EINVAL);
  88. }
  89. /* Create a symmetric cipher object for the given encryption mode and key */
  90. static struct crypto_skcipher *
  91. fscrypt_allocate_skcipher(struct fscrypt_mode *mode, const u8 *raw_key,
  92. const struct inode *inode)
  93. {
  94. struct crypto_skcipher *tfm;
  95. int err;
  96. tfm = crypto_alloc_skcipher(mode->cipher_str, 0,
  97. FSCRYPT_CRYPTOAPI_MASK);
  98. if (IS_ERR(tfm)) {
  99. if (PTR_ERR(tfm) == -ENOENT) {
  100. fscrypt_warn(inode,
  101. "Missing crypto API support for %s (API name: \"%s\")",
  102. mode->friendly_name, mode->cipher_str);
  103. return ERR_PTR(-ENOPKG);
  104. }
  105. fscrypt_err(inode, "Error allocating '%s' transform: %ld",
  106. mode->cipher_str, PTR_ERR(tfm));
  107. return tfm;
  108. }
  109. if (!xchg(&mode->logged_cryptoapi_impl, 1)) {
  110. /*
  111. * fscrypt performance can vary greatly depending on which
  112. * crypto algorithm implementation is used. Help people debug
  113. * performance problems by logging the ->cra_driver_name the
  114. * first time a mode is used.
  115. */
  116. pr_info("fscrypt: %s using implementation \"%s\"\n",
  117. mode->friendly_name, crypto_skcipher_driver_name(tfm));
  118. }
  119. if (WARN_ON_ONCE(crypto_skcipher_ivsize(tfm) != mode->ivsize)) {
  120. err = -EINVAL;
  121. goto err_free_tfm;
  122. }
  123. crypto_skcipher_set_flags(tfm, CRYPTO_TFM_REQ_FORBID_WEAK_KEYS);
  124. err = crypto_skcipher_setkey(tfm, raw_key, mode->keysize);
  125. if (err)
  126. goto err_free_tfm;
  127. return tfm;
  128. err_free_tfm:
  129. crypto_free_skcipher(tfm);
  130. return ERR_PTR(err);
  131. }
  132. /*
  133. * Prepare the crypto transform object or blk-crypto key in @prep_key, given the
  134. * raw key, encryption mode (@ci->ci_mode), flag indicating which encryption
  135. * implementation (fs-layer or blk-crypto) will be used (@ci->ci_inlinecrypt),
  136. * and IV generation method (@ci->ci_policy.flags).
  137. */
  138. int fscrypt_prepare_key(struct fscrypt_prepared_key *prep_key,
  139. const u8 *raw_key, const struct fscrypt_inode_info *ci)
  140. {
  141. struct crypto_skcipher *tfm;
  142. if (fscrypt_using_inline_encryption(ci))
  143. return fscrypt_prepare_inline_crypt_key(prep_key, raw_key, ci);
  144. tfm = fscrypt_allocate_skcipher(ci->ci_mode, raw_key, ci->ci_inode);
  145. if (IS_ERR(tfm))
  146. return PTR_ERR(tfm);
  147. /*
  148. * Pairs with the smp_load_acquire() in fscrypt_is_key_prepared().
  149. * I.e., here we publish ->tfm with a RELEASE barrier so that
  150. * concurrent tasks can ACQUIRE it. Note that this concurrency is only
  151. * possible for per-mode keys, not for per-file keys.
  152. */
  153. smp_store_release(&prep_key->tfm, tfm);
  154. return 0;
  155. }
  156. /* Destroy a crypto transform object and/or blk-crypto key. */
  157. void fscrypt_destroy_prepared_key(struct super_block *sb,
  158. struct fscrypt_prepared_key *prep_key)
  159. {
  160. crypto_free_skcipher(prep_key->tfm);
  161. fscrypt_destroy_inline_crypt_key(sb, prep_key);
  162. memzero_explicit(prep_key, sizeof(*prep_key));
  163. }
  164. /* Given a per-file encryption key, set up the file's crypto transform object */
  165. int fscrypt_set_per_file_enc_key(struct fscrypt_inode_info *ci,
  166. const u8 *raw_key)
  167. {
  168. ci->ci_owns_key = true;
  169. return fscrypt_prepare_key(&ci->ci_enc_key, raw_key, ci);
  170. }
  171. static int setup_per_mode_enc_key(struct fscrypt_inode_info *ci,
  172. struct fscrypt_master_key *mk,
  173. struct fscrypt_prepared_key *keys,
  174. u8 hkdf_context, bool include_fs_uuid)
  175. {
  176. const struct inode *inode = ci->ci_inode;
  177. const struct super_block *sb = inode->i_sb;
  178. struct fscrypt_mode *mode = ci->ci_mode;
  179. const u8 mode_num = mode - fscrypt_modes;
  180. struct fscrypt_prepared_key *prep_key;
  181. u8 mode_key[FSCRYPT_MAX_KEY_SIZE];
  182. u8 hkdf_info[sizeof(mode_num) + sizeof(sb->s_uuid)];
  183. unsigned int hkdf_infolen = 0;
  184. int err;
  185. if (WARN_ON_ONCE(mode_num > FSCRYPT_MODE_MAX))
  186. return -EINVAL;
  187. prep_key = &keys[mode_num];
  188. if (fscrypt_is_key_prepared(prep_key, ci)) {
  189. ci->ci_enc_key = *prep_key;
  190. return 0;
  191. }
  192. mutex_lock(&fscrypt_mode_key_setup_mutex);
  193. if (fscrypt_is_key_prepared(prep_key, ci))
  194. goto done_unlock;
  195. BUILD_BUG_ON(sizeof(mode_num) != 1);
  196. BUILD_BUG_ON(sizeof(sb->s_uuid) != 16);
  197. BUILD_BUG_ON(sizeof(hkdf_info) != 17);
  198. hkdf_info[hkdf_infolen++] = mode_num;
  199. if (include_fs_uuid) {
  200. memcpy(&hkdf_info[hkdf_infolen], &sb->s_uuid,
  201. sizeof(sb->s_uuid));
  202. hkdf_infolen += sizeof(sb->s_uuid);
  203. }
  204. err = fscrypt_hkdf_expand(&mk->mk_secret.hkdf,
  205. hkdf_context, hkdf_info, hkdf_infolen,
  206. mode_key, mode->keysize);
  207. if (err)
  208. goto out_unlock;
  209. err = fscrypt_prepare_key(prep_key, mode_key, ci);
  210. memzero_explicit(mode_key, mode->keysize);
  211. if (err)
  212. goto out_unlock;
  213. done_unlock:
  214. ci->ci_enc_key = *prep_key;
  215. err = 0;
  216. out_unlock:
  217. mutex_unlock(&fscrypt_mode_key_setup_mutex);
  218. return err;
  219. }
  220. /*
  221. * Derive a SipHash key from the given fscrypt master key and the given
  222. * application-specific information string.
  223. *
  224. * Note that the KDF produces a byte array, but the SipHash APIs expect the key
  225. * as a pair of 64-bit words. Therefore, on big endian CPUs we have to do an
  226. * endianness swap in order to get the same results as on little endian CPUs.
  227. */
  228. static int fscrypt_derive_siphash_key(const struct fscrypt_master_key *mk,
  229. u8 context, const u8 *info,
  230. unsigned int infolen, siphash_key_t *key)
  231. {
  232. int err;
  233. err = fscrypt_hkdf_expand(&mk->mk_secret.hkdf, context, info, infolen,
  234. (u8 *)key, sizeof(*key));
  235. if (err)
  236. return err;
  237. BUILD_BUG_ON(sizeof(*key) != 16);
  238. BUILD_BUG_ON(ARRAY_SIZE(key->key) != 2);
  239. le64_to_cpus(&key->key[0]);
  240. le64_to_cpus(&key->key[1]);
  241. return 0;
  242. }
  243. int fscrypt_derive_dirhash_key(struct fscrypt_inode_info *ci,
  244. const struct fscrypt_master_key *mk)
  245. {
  246. int err;
  247. err = fscrypt_derive_siphash_key(mk, HKDF_CONTEXT_DIRHASH_KEY,
  248. ci->ci_nonce, FSCRYPT_FILE_NONCE_SIZE,
  249. &ci->ci_dirhash_key);
  250. if (err)
  251. return err;
  252. ci->ci_dirhash_key_initialized = true;
  253. return 0;
  254. }
  255. void fscrypt_hash_inode_number(struct fscrypt_inode_info *ci,
  256. const struct fscrypt_master_key *mk)
  257. {
  258. WARN_ON_ONCE(ci->ci_inode->i_ino == 0);
  259. WARN_ON_ONCE(!mk->mk_ino_hash_key_initialized);
  260. ci->ci_hashed_ino = (u32)siphash_1u64(ci->ci_inode->i_ino,
  261. &mk->mk_ino_hash_key);
  262. }
  263. static int fscrypt_setup_iv_ino_lblk_32_key(struct fscrypt_inode_info *ci,
  264. struct fscrypt_master_key *mk)
  265. {
  266. int err;
  267. err = setup_per_mode_enc_key(ci, mk, mk->mk_iv_ino_lblk_32_keys,
  268. HKDF_CONTEXT_IV_INO_LBLK_32_KEY, true);
  269. if (err)
  270. return err;
  271. /* pairs with smp_store_release() below */
  272. if (!smp_load_acquire(&mk->mk_ino_hash_key_initialized)) {
  273. mutex_lock(&fscrypt_mode_key_setup_mutex);
  274. if (mk->mk_ino_hash_key_initialized)
  275. goto unlock;
  276. err = fscrypt_derive_siphash_key(mk,
  277. HKDF_CONTEXT_INODE_HASH_KEY,
  278. NULL, 0, &mk->mk_ino_hash_key);
  279. if (err)
  280. goto unlock;
  281. /* pairs with smp_load_acquire() above */
  282. smp_store_release(&mk->mk_ino_hash_key_initialized, true);
  283. unlock:
  284. mutex_unlock(&fscrypt_mode_key_setup_mutex);
  285. if (err)
  286. return err;
  287. }
  288. /*
  289. * New inodes may not have an inode number assigned yet.
  290. * Hashing their inode number is delayed until later.
  291. */
  292. if (ci->ci_inode->i_ino)
  293. fscrypt_hash_inode_number(ci, mk);
  294. return 0;
  295. }
  296. static int fscrypt_setup_v2_file_key(struct fscrypt_inode_info *ci,
  297. struct fscrypt_master_key *mk,
  298. bool need_dirhash_key)
  299. {
  300. int err;
  301. if (ci->ci_policy.v2.flags & FSCRYPT_POLICY_FLAG_DIRECT_KEY) {
  302. /*
  303. * DIRECT_KEY: instead of deriving per-file encryption keys, the
  304. * per-file nonce will be included in all the IVs. But unlike
  305. * v1 policies, for v2 policies in this case we don't encrypt
  306. * with the master key directly but rather derive a per-mode
  307. * encryption key. This ensures that the master key is
  308. * consistently used only for HKDF, avoiding key reuse issues.
  309. */
  310. err = setup_per_mode_enc_key(ci, mk, mk->mk_direct_keys,
  311. HKDF_CONTEXT_DIRECT_KEY, false);
  312. } else if (ci->ci_policy.v2.flags &
  313. FSCRYPT_POLICY_FLAG_IV_INO_LBLK_64) {
  314. /*
  315. * IV_INO_LBLK_64: encryption keys are derived from (master_key,
  316. * mode_num, filesystem_uuid), and inode number is included in
  317. * the IVs. This format is optimized for use with inline
  318. * encryption hardware compliant with the UFS standard.
  319. */
  320. err = setup_per_mode_enc_key(ci, mk, mk->mk_iv_ino_lblk_64_keys,
  321. HKDF_CONTEXT_IV_INO_LBLK_64_KEY,
  322. true);
  323. } else if (ci->ci_policy.v2.flags &
  324. FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32) {
  325. err = fscrypt_setup_iv_ino_lblk_32_key(ci, mk);
  326. } else {
  327. u8 derived_key[FSCRYPT_MAX_KEY_SIZE];
  328. err = fscrypt_hkdf_expand(&mk->mk_secret.hkdf,
  329. HKDF_CONTEXT_PER_FILE_ENC_KEY,
  330. ci->ci_nonce, FSCRYPT_FILE_NONCE_SIZE,
  331. derived_key, ci->ci_mode->keysize);
  332. if (err)
  333. return err;
  334. err = fscrypt_set_per_file_enc_key(ci, derived_key);
  335. memzero_explicit(derived_key, ci->ci_mode->keysize);
  336. }
  337. if (err)
  338. return err;
  339. /* Derive a secret dirhash key for directories that need it. */
  340. if (need_dirhash_key) {
  341. err = fscrypt_derive_dirhash_key(ci, mk);
  342. if (err)
  343. return err;
  344. }
  345. return 0;
  346. }
  347. /*
  348. * Check whether the size of the given master key (@mk) is appropriate for the
  349. * encryption settings which a particular file will use (@ci).
  350. *
  351. * If the file uses a v1 encryption policy, then the master key must be at least
  352. * as long as the derived key, as this is a requirement of the v1 KDF.
  353. *
  354. * Otherwise, the KDF can accept any size key, so we enforce a slightly looser
  355. * requirement: we require that the size of the master key be at least the
  356. * maximum security strength of any algorithm whose key will be derived from it
  357. * (but in practice we only need to consider @ci->ci_mode, since any other
  358. * possible subkeys such as DIRHASH and INODE_HASH will never increase the
  359. * required key size over @ci->ci_mode). This allows AES-256-XTS keys to be
  360. * derived from a 256-bit master key, which is cryptographically sufficient,
  361. * rather than requiring a 512-bit master key which is unnecessarily long. (We
  362. * still allow 512-bit master keys if the user chooses to use them, though.)
  363. */
  364. static bool fscrypt_valid_master_key_size(const struct fscrypt_master_key *mk,
  365. const struct fscrypt_inode_info *ci)
  366. {
  367. unsigned int min_keysize;
  368. if (ci->ci_policy.version == FSCRYPT_POLICY_V1)
  369. min_keysize = ci->ci_mode->keysize;
  370. else
  371. min_keysize = ci->ci_mode->security_strength;
  372. if (mk->mk_secret.size < min_keysize) {
  373. fscrypt_warn(NULL,
  374. "key with %s %*phN is too short (got %u bytes, need %u+ bytes)",
  375. master_key_spec_type(&mk->mk_spec),
  376. master_key_spec_len(&mk->mk_spec),
  377. (u8 *)&mk->mk_spec.u,
  378. mk->mk_secret.size, min_keysize);
  379. return false;
  380. }
  381. return true;
  382. }
  383. /*
  384. * Find the master key, then set up the inode's actual encryption key.
  385. *
  386. * If the master key is found in the filesystem-level keyring, then it is
  387. * returned in *mk_ret with its semaphore read-locked. This is needed to ensure
  388. * that only one task links the fscrypt_inode_info into ->mk_decrypted_inodes
  389. * (as multiple tasks may race to create an fscrypt_inode_info for the same
  390. * inode), and to synchronize the master key being removed with a new inode
  391. * starting to use it.
  392. */
  393. static int setup_file_encryption_key(struct fscrypt_inode_info *ci,
  394. bool need_dirhash_key,
  395. struct fscrypt_master_key **mk_ret)
  396. {
  397. struct super_block *sb = ci->ci_inode->i_sb;
  398. struct fscrypt_key_specifier mk_spec;
  399. struct fscrypt_master_key *mk;
  400. int err;
  401. err = fscrypt_select_encryption_impl(ci);
  402. if (err)
  403. return err;
  404. err = fscrypt_policy_to_key_spec(&ci->ci_policy, &mk_spec);
  405. if (err)
  406. return err;
  407. mk = fscrypt_find_master_key(sb, &mk_spec);
  408. if (unlikely(!mk)) {
  409. const union fscrypt_policy *dummy_policy =
  410. fscrypt_get_dummy_policy(sb);
  411. /*
  412. * Add the test_dummy_encryption key on-demand. In principle,
  413. * it should be added at mount time. Do it here instead so that
  414. * the individual filesystems don't need to worry about adding
  415. * this key at mount time and cleaning up on mount failure.
  416. */
  417. if (dummy_policy &&
  418. fscrypt_policies_equal(dummy_policy, &ci->ci_policy)) {
  419. err = fscrypt_add_test_dummy_key(sb, &mk_spec);
  420. if (err)
  421. return err;
  422. mk = fscrypt_find_master_key(sb, &mk_spec);
  423. }
  424. }
  425. if (unlikely(!mk)) {
  426. if (ci->ci_policy.version != FSCRYPT_POLICY_V1)
  427. return -ENOKEY;
  428. /*
  429. * As a legacy fallback for v1 policies, search for the key in
  430. * the current task's subscribed keyrings too. Don't move this
  431. * to before the search of ->s_master_keys, since users
  432. * shouldn't be able to override filesystem-level keys.
  433. */
  434. return fscrypt_setup_v1_file_key_via_subscribed_keyrings(ci);
  435. }
  436. down_read(&mk->mk_sem);
  437. if (!mk->mk_present) {
  438. /* FS_IOC_REMOVE_ENCRYPTION_KEY has been executed on this key */
  439. err = -ENOKEY;
  440. goto out_release_key;
  441. }
  442. if (!fscrypt_valid_master_key_size(mk, ci)) {
  443. err = -ENOKEY;
  444. goto out_release_key;
  445. }
  446. switch (ci->ci_policy.version) {
  447. case FSCRYPT_POLICY_V1:
  448. err = fscrypt_setup_v1_file_key(ci, mk->mk_secret.raw);
  449. break;
  450. case FSCRYPT_POLICY_V2:
  451. err = fscrypt_setup_v2_file_key(ci, mk, need_dirhash_key);
  452. break;
  453. default:
  454. WARN_ON_ONCE(1);
  455. err = -EINVAL;
  456. break;
  457. }
  458. if (err)
  459. goto out_release_key;
  460. *mk_ret = mk;
  461. return 0;
  462. out_release_key:
  463. up_read(&mk->mk_sem);
  464. fscrypt_put_master_key(mk);
  465. return err;
  466. }
  467. static void put_crypt_info(struct fscrypt_inode_info *ci)
  468. {
  469. struct fscrypt_master_key *mk;
  470. if (!ci)
  471. return;
  472. if (ci->ci_direct_key)
  473. fscrypt_put_direct_key(ci->ci_direct_key);
  474. else if (ci->ci_owns_key)
  475. fscrypt_destroy_prepared_key(ci->ci_inode->i_sb,
  476. &ci->ci_enc_key);
  477. mk = ci->ci_master_key;
  478. if (mk) {
  479. /*
  480. * Remove this inode from the list of inodes that were unlocked
  481. * with the master key. In addition, if we're removing the last
  482. * inode from an incompletely removed key, then complete the
  483. * full removal of the key.
  484. */
  485. spin_lock(&mk->mk_decrypted_inodes_lock);
  486. list_del(&ci->ci_master_key_link);
  487. spin_unlock(&mk->mk_decrypted_inodes_lock);
  488. fscrypt_put_master_key_activeref(ci->ci_inode->i_sb, mk);
  489. }
  490. memzero_explicit(ci, sizeof(*ci));
  491. kmem_cache_free(fscrypt_inode_info_cachep, ci);
  492. }
  493. static int
  494. fscrypt_setup_encryption_info(struct inode *inode,
  495. const union fscrypt_policy *policy,
  496. const u8 nonce[FSCRYPT_FILE_NONCE_SIZE],
  497. bool need_dirhash_key)
  498. {
  499. struct fscrypt_inode_info *crypt_info;
  500. struct fscrypt_mode *mode;
  501. struct fscrypt_master_key *mk = NULL;
  502. int res;
  503. res = fscrypt_initialize(inode->i_sb);
  504. if (res)
  505. return res;
  506. crypt_info = kmem_cache_zalloc(fscrypt_inode_info_cachep, GFP_KERNEL);
  507. if (!crypt_info)
  508. return -ENOMEM;
  509. crypt_info->ci_inode = inode;
  510. crypt_info->ci_policy = *policy;
  511. memcpy(crypt_info->ci_nonce, nonce, FSCRYPT_FILE_NONCE_SIZE);
  512. mode = select_encryption_mode(&crypt_info->ci_policy, inode);
  513. if (IS_ERR(mode)) {
  514. res = PTR_ERR(mode);
  515. goto out;
  516. }
  517. WARN_ON_ONCE(mode->ivsize > FSCRYPT_MAX_IV_SIZE);
  518. crypt_info->ci_mode = mode;
  519. crypt_info->ci_data_unit_bits =
  520. fscrypt_policy_du_bits(&crypt_info->ci_policy, inode);
  521. crypt_info->ci_data_units_per_block_bits =
  522. inode->i_blkbits - crypt_info->ci_data_unit_bits;
  523. res = setup_file_encryption_key(crypt_info, need_dirhash_key, &mk);
  524. if (res)
  525. goto out;
  526. /*
  527. * For existing inodes, multiple tasks may race to set ->i_crypt_info.
  528. * So use cmpxchg_release(). This pairs with the smp_load_acquire() in
  529. * fscrypt_get_inode_info(). I.e., here we publish ->i_crypt_info with
  530. * a RELEASE barrier so that other tasks can ACQUIRE it.
  531. */
  532. if (cmpxchg_release(&inode->i_crypt_info, NULL, crypt_info) == NULL) {
  533. /*
  534. * We won the race and set ->i_crypt_info to our crypt_info.
  535. * Now link it into the master key's inode list.
  536. */
  537. if (mk) {
  538. crypt_info->ci_master_key = mk;
  539. refcount_inc(&mk->mk_active_refs);
  540. spin_lock(&mk->mk_decrypted_inodes_lock);
  541. list_add(&crypt_info->ci_master_key_link,
  542. &mk->mk_decrypted_inodes);
  543. spin_unlock(&mk->mk_decrypted_inodes_lock);
  544. }
  545. crypt_info = NULL;
  546. }
  547. res = 0;
  548. out:
  549. if (mk) {
  550. up_read(&mk->mk_sem);
  551. fscrypt_put_master_key(mk);
  552. }
  553. put_crypt_info(crypt_info);
  554. return res;
  555. }
  556. /**
  557. * fscrypt_get_encryption_info() - set up an inode's encryption key
  558. * @inode: the inode to set up the key for. Must be encrypted.
  559. * @allow_unsupported: if %true, treat an unsupported encryption policy (or
  560. * unrecognized encryption context) the same way as the key
  561. * being unavailable, instead of returning an error. Use
  562. * %false unless the operation being performed is needed in
  563. * order for files (or directories) to be deleted.
  564. *
  565. * Set up ->i_crypt_info, if it hasn't already been done.
  566. *
  567. * Note: unless ->i_crypt_info is already set, this isn't %GFP_NOFS-safe. So
  568. * generally this shouldn't be called from within a filesystem transaction.
  569. *
  570. * Return: 0 if ->i_crypt_info was set or was already set, *or* if the
  571. * encryption key is unavailable. (Use fscrypt_has_encryption_key() to
  572. * distinguish these cases.) Also can return another -errno code.
  573. */
  574. int fscrypt_get_encryption_info(struct inode *inode, bool allow_unsupported)
  575. {
  576. int res;
  577. union fscrypt_context ctx;
  578. union fscrypt_policy policy;
  579. if (fscrypt_has_encryption_key(inode))
  580. return 0;
  581. res = inode->i_sb->s_cop->get_context(inode, &ctx, sizeof(ctx));
  582. if (res < 0) {
  583. if (res == -ERANGE && allow_unsupported)
  584. return 0;
  585. fscrypt_warn(inode, "Error %d getting encryption context", res);
  586. return res;
  587. }
  588. res = fscrypt_policy_from_context(&policy, &ctx, res);
  589. if (res) {
  590. if (allow_unsupported)
  591. return 0;
  592. fscrypt_warn(inode,
  593. "Unrecognized or corrupt encryption context");
  594. return res;
  595. }
  596. if (!fscrypt_supported_policy(&policy, inode)) {
  597. if (allow_unsupported)
  598. return 0;
  599. return -EINVAL;
  600. }
  601. res = fscrypt_setup_encryption_info(inode, &policy,
  602. fscrypt_context_nonce(&ctx),
  603. IS_CASEFOLDED(inode) &&
  604. S_ISDIR(inode->i_mode));
  605. if (res == -ENOPKG && allow_unsupported) /* Algorithm unavailable? */
  606. res = 0;
  607. if (res == -ENOKEY)
  608. res = 0;
  609. return res;
  610. }
  611. /**
  612. * fscrypt_prepare_new_inode() - prepare to create a new inode in a directory
  613. * @dir: a possibly-encrypted directory
  614. * @inode: the new inode. ->i_mode and ->i_blkbits must be set already.
  615. * ->i_ino doesn't need to be set yet.
  616. * @encrypt_ret: (output) set to %true if the new inode will be encrypted
  617. *
  618. * If the directory is encrypted, set up its ->i_crypt_info in preparation for
  619. * encrypting the name of the new file. Also, if the new inode will be
  620. * encrypted, set up its ->i_crypt_info and set *encrypt_ret=true.
  621. *
  622. * This isn't %GFP_NOFS-safe, and therefore it should be called before starting
  623. * any filesystem transaction to create the inode. For this reason, ->i_ino
  624. * isn't required to be set yet, as the filesystem may not have set it yet.
  625. *
  626. * This doesn't persist the new inode's encryption context. That still needs to
  627. * be done later by calling fscrypt_set_context().
  628. *
  629. * Return: 0 on success, -ENOKEY if the encryption key is missing, or another
  630. * -errno code
  631. */
  632. int fscrypt_prepare_new_inode(struct inode *dir, struct inode *inode,
  633. bool *encrypt_ret)
  634. {
  635. const union fscrypt_policy *policy;
  636. u8 nonce[FSCRYPT_FILE_NONCE_SIZE];
  637. policy = fscrypt_policy_to_inherit(dir);
  638. if (policy == NULL)
  639. return 0;
  640. if (IS_ERR(policy))
  641. return PTR_ERR(policy);
  642. if (WARN_ON_ONCE(inode->i_blkbits == 0))
  643. return -EINVAL;
  644. if (WARN_ON_ONCE(inode->i_mode == 0))
  645. return -EINVAL;
  646. /*
  647. * Only regular files, directories, and symlinks are encrypted.
  648. * Special files like device nodes and named pipes aren't.
  649. */
  650. if (!S_ISREG(inode->i_mode) &&
  651. !S_ISDIR(inode->i_mode) &&
  652. !S_ISLNK(inode->i_mode))
  653. return 0;
  654. *encrypt_ret = true;
  655. get_random_bytes(nonce, FSCRYPT_FILE_NONCE_SIZE);
  656. return fscrypt_setup_encryption_info(inode, policy, nonce,
  657. IS_CASEFOLDED(dir) &&
  658. S_ISDIR(inode->i_mode));
  659. }
  660. EXPORT_SYMBOL_GPL(fscrypt_prepare_new_inode);
  661. /**
  662. * fscrypt_put_encryption_info() - free most of an inode's fscrypt data
  663. * @inode: an inode being evicted
  664. *
  665. * Free the inode's fscrypt_inode_info. Filesystems must call this when the
  666. * inode is being evicted. An RCU grace period need not have elapsed yet.
  667. */
  668. void fscrypt_put_encryption_info(struct inode *inode)
  669. {
  670. put_crypt_info(inode->i_crypt_info);
  671. inode->i_crypt_info = NULL;
  672. }
  673. EXPORT_SYMBOL(fscrypt_put_encryption_info);
  674. /**
  675. * fscrypt_free_inode() - free an inode's fscrypt data requiring RCU delay
  676. * @inode: an inode being freed
  677. *
  678. * Free the inode's cached decrypted symlink target, if any. Filesystems must
  679. * call this after an RCU grace period, just before they free the inode.
  680. */
  681. void fscrypt_free_inode(struct inode *inode)
  682. {
  683. if (IS_ENCRYPTED(inode) && S_ISLNK(inode->i_mode)) {
  684. kfree(inode->i_link);
  685. inode->i_link = NULL;
  686. }
  687. }
  688. EXPORT_SYMBOL(fscrypt_free_inode);
  689. /**
  690. * fscrypt_drop_inode() - check whether the inode's master key has been removed
  691. * @inode: an inode being considered for eviction
  692. *
  693. * Filesystems supporting fscrypt must call this from their ->drop_inode()
  694. * method so that encrypted inodes are evicted as soon as they're no longer in
  695. * use and their master key has been removed.
  696. *
  697. * Return: 1 if fscrypt wants the inode to be evicted now, otherwise 0
  698. */
  699. int fscrypt_drop_inode(struct inode *inode)
  700. {
  701. const struct fscrypt_inode_info *ci = fscrypt_get_inode_info(inode);
  702. /*
  703. * If ci is NULL, then the inode doesn't have an encryption key set up
  704. * so it's irrelevant. If ci_master_key is NULL, then the master key
  705. * was provided via the legacy mechanism of the process-subscribed
  706. * keyrings, so we don't know whether it's been removed or not.
  707. */
  708. if (!ci || !ci->ci_master_key)
  709. return 0;
  710. /*
  711. * With proper, non-racy use of FS_IOC_REMOVE_ENCRYPTION_KEY, all inodes
  712. * protected by the key were cleaned by sync_filesystem(). But if
  713. * userspace is still using the files, inodes can be dirtied between
  714. * then and now. We mustn't lose any writes, so skip dirty inodes here.
  715. */
  716. if (inode->i_state & I_DIRTY_ALL)
  717. return 0;
  718. /*
  719. * We can't take ->mk_sem here, since this runs in atomic context.
  720. * Therefore, ->mk_present can change concurrently, and our result may
  721. * immediately become outdated. But there's no correctness problem with
  722. * unnecessarily evicting. Nor is there a correctness problem with not
  723. * evicting while iput() is racing with the key being removed, since
  724. * then the thread removing the key will either evict the inode itself
  725. * or will correctly detect that it wasn't evicted due to the race.
  726. */
  727. return !READ_ONCE(ci->ci_master_key->mk_present);
  728. }
  729. EXPORT_SYMBOL_GPL(fscrypt_drop_inode);