keysetup.c 26 KB

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