fname.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * This contains functions for filename crypto management
  4. *
  5. * Copyright (C) 2015, Google, Inc.
  6. * Copyright (C) 2015, Motorola Mobility
  7. *
  8. * Written by Uday Savagaonkar, 2014.
  9. * Modified by Jaegeuk Kim, 2015.
  10. *
  11. * This has not yet undergone a rigorous security audit.
  12. */
  13. #include <crypto/sha2.h>
  14. #include <crypto/skcipher.h>
  15. #include <linux/export.h>
  16. #include <linux/namei.h>
  17. #include <linux/scatterlist.h>
  18. #include <linux/base64.h>
  19. #include "fscrypt_private.h"
  20. /*
  21. * The minimum message length (input and output length), in bytes, for all
  22. * filenames encryption modes. Filenames shorter than this will be zero-padded
  23. * before being encrypted.
  24. */
  25. #define FSCRYPT_FNAME_MIN_MSG_LEN 16
  26. /*
  27. * struct fscrypt_nokey_name - identifier for directory entry when key is absent
  28. *
  29. * When userspace lists an encrypted directory without access to the key, the
  30. * filesystem must present a unique "no-key name" for each filename that allows
  31. * it to find the directory entry again if requested. Naively, that would just
  32. * mean using the ciphertext filenames. However, since the ciphertext filenames
  33. * can contain illegal characters ('\0' and '/'), they must be encoded in some
  34. * way. We use base64url. But that can cause names to exceed NAME_MAX (255
  35. * bytes), so we also need to use a strong hash to abbreviate long names.
  36. *
  37. * The filesystem may also need another kind of hash, the "dirhash", to quickly
  38. * find the directory entry. Since filesystems normally compute the dirhash
  39. * over the on-disk filename (i.e. the ciphertext), it's not computable from
  40. * no-key names that abbreviate the ciphertext using the strong hash to fit in
  41. * NAME_MAX. It's also not computable if it's a keyed hash taken over the
  42. * plaintext (but it may still be available in the on-disk directory entry);
  43. * casefolded directories use this type of dirhash. At least in these cases,
  44. * each no-key name must include the name's dirhash too.
  45. *
  46. * To meet all these requirements, we base64url-encode the following
  47. * variable-length structure. It contains the dirhash, or 0's if the filesystem
  48. * didn't provide one; up to 149 bytes of the ciphertext name; and for
  49. * ciphertexts longer than 149 bytes, also the SHA-256 of the remaining bytes.
  50. *
  51. * This ensures that each no-key name contains everything needed to find the
  52. * directory entry again, contains only legal characters, doesn't exceed
  53. * NAME_MAX, is unambiguous unless there's a SHA-256 collision, and that we only
  54. * take the performance hit of SHA-256 on very long filenames (which are rare).
  55. */
  56. struct fscrypt_nokey_name {
  57. u32 dirhash[2];
  58. u8 bytes[149];
  59. u8 sha256[SHA256_DIGEST_SIZE];
  60. }; /* 189 bytes => 252 bytes base64url-encoded, which is <= NAME_MAX (255) */
  61. /*
  62. * Decoded size of max-size no-key name, i.e. a name that was abbreviated using
  63. * the strong hash and thus includes the 'sha256' field. This isn't simply
  64. * sizeof(struct fscrypt_nokey_name), as the padding at the end isn't included.
  65. */
  66. #define FSCRYPT_NOKEY_NAME_MAX offsetofend(struct fscrypt_nokey_name, sha256)
  67. /* Encoded size of max-size no-key name */
  68. #define FSCRYPT_NOKEY_NAME_MAX_ENCODED \
  69. BASE64_CHARS(FSCRYPT_NOKEY_NAME_MAX)
  70. static inline bool fscrypt_is_dot_dotdot(const struct qstr *str)
  71. {
  72. return name_is_dot_dotdot(str->name, str->len);
  73. }
  74. /**
  75. * fscrypt_fname_encrypt() - encrypt a filename
  76. * @inode: inode of the parent directory (for regular filenames)
  77. * or of the symlink (for symlink targets). Key must already be
  78. * set up.
  79. * @iname: the filename to encrypt
  80. * @out: (output) the encrypted filename
  81. * @olen: size of the encrypted filename. It must be at least @iname->len.
  82. * Any extra space is filled with NUL padding before encryption.
  83. *
  84. * Return: 0 on success, -errno on failure
  85. */
  86. int fscrypt_fname_encrypt(const struct inode *inode, const struct qstr *iname,
  87. u8 *out, unsigned int olen)
  88. {
  89. const struct fscrypt_inode_info *ci = fscrypt_get_inode_info_raw(inode);
  90. struct crypto_sync_skcipher *tfm = ci->ci_enc_key.tfm;
  91. SYNC_SKCIPHER_REQUEST_ON_STACK(req, tfm);
  92. union fscrypt_iv iv;
  93. struct scatterlist sg;
  94. int err;
  95. /*
  96. * Copy the filename to the output buffer for encrypting in-place and
  97. * pad it with the needed number of NUL bytes.
  98. */
  99. if (WARN_ON_ONCE(olen < iname->len))
  100. return -ENOBUFS;
  101. memcpy(out, iname->name, iname->len);
  102. memset(out + iname->len, 0, olen - iname->len);
  103. fscrypt_generate_iv(&iv, 0, ci);
  104. skcipher_request_set_callback(
  105. req, CRYPTO_TFM_REQ_MAY_BACKLOG | CRYPTO_TFM_REQ_MAY_SLEEP,
  106. NULL, NULL);
  107. sg_init_one(&sg, out, olen);
  108. skcipher_request_set_crypt(req, &sg, &sg, olen, &iv);
  109. err = crypto_skcipher_encrypt(req);
  110. if (err)
  111. fscrypt_err(inode, "Filename encryption failed: %d", err);
  112. return err;
  113. }
  114. EXPORT_SYMBOL_GPL(fscrypt_fname_encrypt);
  115. /**
  116. * fname_decrypt() - decrypt a filename
  117. * @inode: inode of the parent directory (for regular filenames)
  118. * or of the symlink (for symlink targets)
  119. * @iname: the encrypted filename to decrypt
  120. * @oname: (output) the decrypted filename. The caller must have allocated
  121. * enough space for this, e.g. using fscrypt_fname_alloc_buffer().
  122. *
  123. * Return: 0 on success, -errno on failure
  124. */
  125. static int fname_decrypt(const struct inode *inode,
  126. const struct fscrypt_str *iname,
  127. struct fscrypt_str *oname)
  128. {
  129. const struct fscrypt_inode_info *ci = fscrypt_get_inode_info_raw(inode);
  130. struct crypto_sync_skcipher *tfm = ci->ci_enc_key.tfm;
  131. SYNC_SKCIPHER_REQUEST_ON_STACK(req, tfm);
  132. union fscrypt_iv iv;
  133. struct scatterlist src_sg, dst_sg;
  134. int err;
  135. fscrypt_generate_iv(&iv, 0, ci);
  136. skcipher_request_set_callback(
  137. req, CRYPTO_TFM_REQ_MAY_BACKLOG | CRYPTO_TFM_REQ_MAY_SLEEP,
  138. NULL, NULL);
  139. sg_init_one(&src_sg, iname->name, iname->len);
  140. sg_init_one(&dst_sg, oname->name, oname->len);
  141. skcipher_request_set_crypt(req, &src_sg, &dst_sg, iname->len, &iv);
  142. err = crypto_skcipher_decrypt(req);
  143. if (err) {
  144. fscrypt_err(inode, "Filename decryption failed: %d", err);
  145. return err;
  146. }
  147. oname->len = strnlen(oname->name, iname->len);
  148. return 0;
  149. }
  150. bool __fscrypt_fname_encrypted_size(const union fscrypt_policy *policy,
  151. u32 orig_len, u32 max_len,
  152. u32 *encrypted_len_ret)
  153. {
  154. int padding = 4 << (fscrypt_policy_flags(policy) &
  155. FSCRYPT_POLICY_FLAGS_PAD_MASK);
  156. u32 encrypted_len;
  157. if (orig_len > max_len)
  158. return false;
  159. encrypted_len = max_t(u32, orig_len, FSCRYPT_FNAME_MIN_MSG_LEN);
  160. encrypted_len = round_up(encrypted_len, padding);
  161. *encrypted_len_ret = min(encrypted_len, max_len);
  162. return true;
  163. }
  164. /**
  165. * fscrypt_fname_encrypted_size() - calculate length of encrypted filename
  166. * @inode: parent inode of dentry name being encrypted. Key must
  167. * already be set up.
  168. * @orig_len: length of the original filename
  169. * @max_len: maximum length to return
  170. * @encrypted_len_ret: where calculated length should be returned (on success)
  171. *
  172. * Filenames that are shorter than the maximum length may have their lengths
  173. * increased slightly by encryption, due to padding that is applied.
  174. *
  175. * Return: false if the orig_len is greater than max_len. Otherwise, true and
  176. * fill out encrypted_len_ret with the length (up to max_len).
  177. */
  178. bool fscrypt_fname_encrypted_size(const struct inode *inode, u32 orig_len,
  179. u32 max_len, u32 *encrypted_len_ret)
  180. {
  181. const struct fscrypt_inode_info *ci = fscrypt_get_inode_info_raw(inode);
  182. return __fscrypt_fname_encrypted_size(&ci->ci_policy, orig_len, max_len,
  183. encrypted_len_ret);
  184. }
  185. EXPORT_SYMBOL_GPL(fscrypt_fname_encrypted_size);
  186. /**
  187. * fscrypt_fname_alloc_buffer() - allocate a buffer for presented filenames
  188. * @max_encrypted_len: maximum length of encrypted filenames the buffer will be
  189. * used to present
  190. * @crypto_str: (output) buffer to allocate
  191. *
  192. * Allocate a buffer that is large enough to hold any decrypted or encoded
  193. * filename (null-terminated), for the given maximum encrypted filename length.
  194. *
  195. * Return: 0 on success, -errno on failure
  196. */
  197. int fscrypt_fname_alloc_buffer(u32 max_encrypted_len,
  198. struct fscrypt_str *crypto_str)
  199. {
  200. u32 max_presented_len = max_t(u32, FSCRYPT_NOKEY_NAME_MAX_ENCODED,
  201. max_encrypted_len);
  202. crypto_str->name = kmalloc(max_presented_len + 1, GFP_NOFS);
  203. if (!crypto_str->name)
  204. return -ENOMEM;
  205. crypto_str->len = max_presented_len;
  206. return 0;
  207. }
  208. EXPORT_SYMBOL(fscrypt_fname_alloc_buffer);
  209. /**
  210. * fscrypt_fname_free_buffer() - free a buffer for presented filenames
  211. * @crypto_str: the buffer to free
  212. *
  213. * Free a buffer that was allocated by fscrypt_fname_alloc_buffer().
  214. */
  215. void fscrypt_fname_free_buffer(struct fscrypt_str *crypto_str)
  216. {
  217. if (!crypto_str)
  218. return;
  219. kfree(crypto_str->name);
  220. crypto_str->name = NULL;
  221. }
  222. EXPORT_SYMBOL(fscrypt_fname_free_buffer);
  223. /**
  224. * fscrypt_fname_disk_to_usr() - convert an encrypted filename to
  225. * user-presentable form
  226. * @inode: inode of the parent directory (for regular filenames)
  227. * or of the symlink (for symlink targets)
  228. * @hash: first part of the name's dirhash, if applicable. This only needs to
  229. * be provided if the filename is located in an indexed directory whose
  230. * encryption key may be unavailable. Not needed for symlink targets.
  231. * @minor_hash: second part of the name's dirhash, if applicable
  232. * @iname: encrypted filename to convert. May also be "." or "..", which
  233. * aren't actually encrypted.
  234. * @oname: output buffer for the user-presentable filename. The caller must
  235. * have allocated enough space for this, e.g. using
  236. * fscrypt_fname_alloc_buffer().
  237. *
  238. * If the key is available, we'll decrypt the disk name. Otherwise, we'll
  239. * encode it for presentation in fscrypt_nokey_name format.
  240. * See struct fscrypt_nokey_name for details.
  241. *
  242. * Return: 0 on success, -errno on failure
  243. */
  244. int fscrypt_fname_disk_to_usr(const struct inode *inode,
  245. u32 hash, u32 minor_hash,
  246. const struct fscrypt_str *iname,
  247. struct fscrypt_str *oname)
  248. {
  249. const struct qstr qname = FSTR_TO_QSTR(iname);
  250. struct fscrypt_nokey_name nokey_name;
  251. u32 size; /* size of the unencoded no-key name */
  252. if (fscrypt_is_dot_dotdot(&qname)) {
  253. oname->name[0] = '.';
  254. oname->name[iname->len - 1] = '.';
  255. oname->len = iname->len;
  256. return 0;
  257. }
  258. if (iname->len < FSCRYPT_FNAME_MIN_MSG_LEN)
  259. return -EUCLEAN;
  260. if (fscrypt_has_encryption_key(inode))
  261. return fname_decrypt(inode, iname, oname);
  262. /*
  263. * Sanity check that struct fscrypt_nokey_name doesn't have padding
  264. * between fields and that its encoded size never exceeds NAME_MAX.
  265. */
  266. BUILD_BUG_ON(offsetofend(struct fscrypt_nokey_name, dirhash) !=
  267. offsetof(struct fscrypt_nokey_name, bytes));
  268. BUILD_BUG_ON(offsetofend(struct fscrypt_nokey_name, bytes) !=
  269. offsetof(struct fscrypt_nokey_name, sha256));
  270. BUILD_BUG_ON(FSCRYPT_NOKEY_NAME_MAX_ENCODED > NAME_MAX);
  271. nokey_name.dirhash[0] = hash;
  272. nokey_name.dirhash[1] = minor_hash;
  273. if (iname->len <= sizeof(nokey_name.bytes)) {
  274. memcpy(nokey_name.bytes, iname->name, iname->len);
  275. size = offsetof(struct fscrypt_nokey_name, bytes[iname->len]);
  276. } else {
  277. memcpy(nokey_name.bytes, iname->name, sizeof(nokey_name.bytes));
  278. /* Compute strong hash of remaining part of name. */
  279. sha256(&iname->name[sizeof(nokey_name.bytes)],
  280. iname->len - sizeof(nokey_name.bytes),
  281. nokey_name.sha256);
  282. size = FSCRYPT_NOKEY_NAME_MAX;
  283. }
  284. oname->len = base64_encode((const u8 *)&nokey_name, size,
  285. oname->name, false, BASE64_URLSAFE);
  286. return 0;
  287. }
  288. EXPORT_SYMBOL(fscrypt_fname_disk_to_usr);
  289. /**
  290. * fscrypt_setup_filename() - prepare to search a possibly encrypted directory
  291. * @dir: the directory that will be searched
  292. * @iname: the user-provided filename being searched for
  293. * @lookup: 1 if we're allowed to proceed without the key because it's
  294. * ->lookup() or we're finding the dir_entry for deletion; 0 if we cannot
  295. * proceed without the key because we're going to create the dir_entry.
  296. * @fname: the filename information to be filled in
  297. *
  298. * Given a user-provided filename @iname, this function sets @fname->disk_name
  299. * to the name that would be stored in the on-disk directory entry, if possible.
  300. * If the directory is unencrypted this is simply @iname. Else, if we have the
  301. * directory's encryption key, then @iname is the plaintext, so we encrypt it to
  302. * get the disk_name.
  303. *
  304. * Else, for keyless @lookup operations, @iname should be a no-key name, so we
  305. * decode it to get the struct fscrypt_nokey_name. Non-@lookup operations will
  306. * be impossible in this case, so we fail them with ENOKEY.
  307. *
  308. * If successful, fscrypt_free_filename() must be called later to clean up.
  309. *
  310. * Return: 0 on success, -errno on failure
  311. */
  312. int fscrypt_setup_filename(struct inode *dir, const struct qstr *iname,
  313. int lookup, struct fscrypt_name *fname)
  314. {
  315. struct fscrypt_nokey_name *nokey_name;
  316. int ret;
  317. memset(fname, 0, sizeof(struct fscrypt_name));
  318. fname->usr_fname = iname;
  319. if (!IS_ENCRYPTED(dir) || fscrypt_is_dot_dotdot(iname)) {
  320. fname->disk_name.name = (unsigned char *)iname->name;
  321. fname->disk_name.len = iname->len;
  322. return 0;
  323. }
  324. ret = fscrypt_get_encryption_info(dir, lookup);
  325. if (ret)
  326. return ret;
  327. if (fscrypt_has_encryption_key(dir)) {
  328. if (!fscrypt_fname_encrypted_size(dir, iname->len, NAME_MAX,
  329. &fname->crypto_buf.len))
  330. return -ENAMETOOLONG;
  331. fname->crypto_buf.name = kmalloc(fname->crypto_buf.len,
  332. GFP_NOFS);
  333. if (!fname->crypto_buf.name)
  334. return -ENOMEM;
  335. ret = fscrypt_fname_encrypt(dir, iname, fname->crypto_buf.name,
  336. fname->crypto_buf.len);
  337. if (ret)
  338. goto errout;
  339. fname->disk_name.name = fname->crypto_buf.name;
  340. fname->disk_name.len = fname->crypto_buf.len;
  341. return 0;
  342. }
  343. if (!lookup)
  344. return -ENOKEY;
  345. fname->is_nokey_name = true;
  346. /*
  347. * We don't have the key and we are doing a lookup; decode the
  348. * user-supplied name
  349. */
  350. if (iname->len > FSCRYPT_NOKEY_NAME_MAX_ENCODED)
  351. return -ENOENT;
  352. fname->crypto_buf.name = kmalloc(FSCRYPT_NOKEY_NAME_MAX, GFP_KERNEL);
  353. if (fname->crypto_buf.name == NULL)
  354. return -ENOMEM;
  355. ret = base64_decode(iname->name, iname->len,
  356. fname->crypto_buf.name, false, BASE64_URLSAFE);
  357. if (ret < (int)offsetof(struct fscrypt_nokey_name, bytes[1]) ||
  358. (ret > offsetof(struct fscrypt_nokey_name, sha256) &&
  359. ret != FSCRYPT_NOKEY_NAME_MAX)) {
  360. ret = -ENOENT;
  361. goto errout;
  362. }
  363. fname->crypto_buf.len = ret;
  364. nokey_name = (void *)fname->crypto_buf.name;
  365. fname->hash = nokey_name->dirhash[0];
  366. fname->minor_hash = nokey_name->dirhash[1];
  367. if (ret != FSCRYPT_NOKEY_NAME_MAX) {
  368. /* The full ciphertext filename is available. */
  369. fname->disk_name.name = nokey_name->bytes;
  370. fname->disk_name.len =
  371. ret - offsetof(struct fscrypt_nokey_name, bytes);
  372. }
  373. return 0;
  374. errout:
  375. kfree(fname->crypto_buf.name);
  376. return ret;
  377. }
  378. EXPORT_SYMBOL(fscrypt_setup_filename);
  379. /**
  380. * fscrypt_match_name() - test whether the given name matches a directory entry
  381. * @fname: the name being searched for
  382. * @de_name: the name from the directory entry
  383. * @de_name_len: the length of @de_name in bytes
  384. *
  385. * Normally @fname->disk_name will be set, and in that case we simply compare
  386. * that to the name stored in the directory entry. The only exception is that
  387. * if we don't have the key for an encrypted directory and the name we're
  388. * looking for is very long, then we won't have the full disk_name and instead
  389. * we'll need to match against a fscrypt_nokey_name that includes a strong hash.
  390. *
  391. * Return: %true if the name matches, otherwise %false.
  392. */
  393. bool fscrypt_match_name(const struct fscrypt_name *fname,
  394. const u8 *de_name, u32 de_name_len)
  395. {
  396. const struct fscrypt_nokey_name *nokey_name =
  397. (const void *)fname->crypto_buf.name;
  398. u8 digest[SHA256_DIGEST_SIZE];
  399. if (likely(fname->disk_name.name)) {
  400. if (de_name_len != fname->disk_name.len)
  401. return false;
  402. return !memcmp(de_name, fname->disk_name.name, de_name_len);
  403. }
  404. if (de_name_len <= sizeof(nokey_name->bytes))
  405. return false;
  406. if (memcmp(de_name, nokey_name->bytes, sizeof(nokey_name->bytes)))
  407. return false;
  408. sha256(&de_name[sizeof(nokey_name->bytes)],
  409. de_name_len - sizeof(nokey_name->bytes), digest);
  410. return !memcmp(digest, nokey_name->sha256, sizeof(digest));
  411. }
  412. EXPORT_SYMBOL_GPL(fscrypt_match_name);
  413. /**
  414. * fscrypt_fname_siphash() - calculate the SipHash of a filename
  415. * @dir: the parent directory
  416. * @name: the filename to calculate the SipHash of
  417. *
  418. * Given a plaintext filename @name and a directory @dir which uses SipHash as
  419. * its dirhash method and has had its fscrypt key set up, this function
  420. * calculates the SipHash of that name using the directory's secret dirhash key.
  421. *
  422. * Return: the SipHash of @name using the hash key of @dir
  423. */
  424. u64 fscrypt_fname_siphash(const struct inode *dir, const struct qstr *name)
  425. {
  426. const struct fscrypt_inode_info *ci = fscrypt_get_inode_info_raw(dir);
  427. WARN_ON_ONCE(!ci->ci_dirhash_key_initialized);
  428. return siphash(name->name, name->len, &ci->ci_dirhash_key);
  429. }
  430. EXPORT_SYMBOL_GPL(fscrypt_fname_siphash);
  431. /*
  432. * Validate dentries in encrypted directories to make sure we aren't potentially
  433. * caching stale dentries after a key has been added.
  434. */
  435. int fscrypt_d_revalidate(struct inode *dir, const struct qstr *name,
  436. struct dentry *dentry, unsigned int flags)
  437. {
  438. int err;
  439. /*
  440. * Plaintext names are always valid, since fscrypt doesn't support
  441. * reverting to no-key names without evicting the directory's inode
  442. * -- which implies eviction of the dentries in the directory.
  443. */
  444. if (!(dentry->d_flags & DCACHE_NOKEY_NAME))
  445. return 1;
  446. /*
  447. * No-key name; valid if the directory's key is still unavailable.
  448. *
  449. * Note in RCU mode we have to bail if we get here -
  450. * fscrypt_get_encryption_info() may block.
  451. */
  452. if (flags & LOOKUP_RCU)
  453. return -ECHILD;
  454. /*
  455. * Pass allow_unsupported=true, so that files with an unsupported
  456. * encryption policy can be deleted.
  457. */
  458. err = fscrypt_get_encryption_info(dir, true);
  459. if (err < 0)
  460. return err;
  461. return !fscrypt_has_encryption_key(dir);
  462. }
  463. EXPORT_SYMBOL_GPL(fscrypt_d_revalidate);