verity.c 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * fs-verity: read-only file-based integrity/authenticity
  4. *
  5. * Copyright (C) 2018, Google, Inc.
  6. *
  7. * Written by Jaegeuk Kim, Michael Halcrow, and Eric Biggers.
  8. */
  9. #include "fsverity_private.h"
  10. #include <asm/unaligned.h>
  11. #include <crypto/hash.h>
  12. #include <linux/bio.h>
  13. #include <linux/list.h>
  14. #include <linux/list_sort.h>
  15. #include <linux/module.h>
  16. #include <linux/mount.h>
  17. #include <linux/printk.h>
  18. #include <linux/ratelimit.h>
  19. #include <linux/slab.h>
  20. #include <linux/uaccess.h>
  21. #include <linux/workqueue.h>
  22. /* Allocated at module initialization time */
  23. static struct workqueue_struct *fsverity_read_workqueue;
  24. static struct kmem_cache *fsverity_info_cachep;
  25. /* List of supported hash algorithms */
  26. static struct fsverity_hash_alg {
  27. struct crypto_shash *tfm; /* allocated on demand */
  28. const char *name;
  29. unsigned int digest_size;
  30. } fsverity_hash_algs[] = {
  31. [FS_VERITY_ALG_SHA256] = {
  32. .name = "sha256",
  33. .digest_size = 32,
  34. },
  35. [FS_VERITY_ALG_CRC32] = {
  36. .name = "crc32",
  37. .digest_size = 4,
  38. },
  39. };
  40. /*
  41. * Translate the given fs-verity hash algorithm number into a struct describing
  42. * the algorithm, and ensure it has a hash transform ready to go. The hash
  43. * transforms are allocated on-demand firstly to not waste resources when they
  44. * aren't needed, and secondly because the fs-verity module may be loaded
  45. * earlier than the needed crypto modules.
  46. */
  47. static const struct fsverity_hash_alg *get_hash_algorithm(unsigned int num)
  48. {
  49. struct fsverity_hash_alg *alg;
  50. struct crypto_shash *tfm;
  51. int err;
  52. if (num >= ARRAY_SIZE(fsverity_hash_algs) ||
  53. !fsverity_hash_algs[num].name) {
  54. pr_warn("Unknown hash algorithm: %u\n", num);
  55. return ERR_PTR(-EINVAL);
  56. }
  57. alg = &fsverity_hash_algs[num];
  58. retry:
  59. /* pairs with cmpxchg_release() below */
  60. tfm = smp_load_acquire(&alg->tfm);
  61. if (tfm)
  62. return alg;
  63. tfm = crypto_alloc_shash(alg->name, 0, 0);
  64. if (IS_ERR(tfm)) {
  65. if (PTR_ERR(tfm) == -ENOENT)
  66. pr_warn("Algorithm %u (%s) is unavailable\n",
  67. num, alg->name);
  68. else
  69. pr_warn("Error allocating algorithm %u (%s): %ld\n",
  70. num, alg->name, PTR_ERR(tfm));
  71. return ERR_CAST(tfm);
  72. }
  73. err = -EINVAL;
  74. if (WARN_ON(alg->digest_size != crypto_shash_digestsize(tfm)))
  75. goto err_free_tfm;
  76. pr_debug("Allocated '%s' transform; implementation '%s'\n",
  77. alg->name, crypto_shash_alg(tfm)->base.cra_driver_name);
  78. /* Set the initial value if required by the algorithm */
  79. if (num == FS_VERITY_ALG_CRC32) {
  80. __le32 initial_value = cpu_to_le32(0xFFFFFFFF);
  81. err = crypto_shash_setkey(tfm, (u8 *)&initial_value, 4);
  82. if (err) {
  83. pr_warn("Error setting CRC-32 initial value: %d\n",
  84. err);
  85. goto err_free_tfm;
  86. }
  87. }
  88. /* pairs with smp_load_acquire() above */
  89. if (cmpxchg_release(&alg->tfm, NULL, tfm) != NULL) {
  90. crypto_free_shash(tfm);
  91. goto retry;
  92. }
  93. return alg;
  94. err_free_tfm:
  95. crypto_free_shash(tfm);
  96. return ERR_PTR(err);
  97. }
  98. static int finalize_hash(struct fsverity_info *vi, struct shash_desc *desc,
  99. u8 *out)
  100. {
  101. int err;
  102. err = crypto_shash_final(desc, out);
  103. if (err)
  104. return err;
  105. /* For CRC-32, invert at the end and convert to big-endian format */
  106. if (vi->hash_alg == &fsverity_hash_algs[FS_VERITY_ALG_CRC32])
  107. put_unaligned_be32(~get_unaligned_le32(out), out);
  108. return 0;
  109. }
  110. static struct fsverity_info *get_fsverity_info(const struct inode *inode)
  111. {
  112. /* pairs with cmpxchg_release() in set_fsverity_info() */
  113. return smp_load_acquire(&inode->i_verity_info);
  114. }
  115. static bool set_fsverity_info(struct inode *inode, struct fsverity_info *vi)
  116. {
  117. /* pairs with smp_load_acquire() in get_fsverity_info() */
  118. if (cmpxchg_release(&inode->i_verity_info, NULL, vi) != NULL)
  119. return false;
  120. /*
  121. * Set the in-memory i_size to the data i_size. But it should *not* be
  122. * written to disk, since then it would no longer be possible to find
  123. * the fs-verity footer.
  124. */
  125. i_size_write(inode, vi->data_i_size);
  126. return true;
  127. }
  128. static void dump_fsverity_footer(const struct fsverity_footer *ftr)
  129. {
  130. pr_debug("magic = %.*s\n", (int)sizeof(ftr->magic), ftr->magic);
  131. pr_debug("major_version = %u\n", ftr->major_version);
  132. pr_debug("minor_version = %u\n", ftr->minor_version);
  133. pr_debug("log_blocksize = %u\n", ftr->log_blocksize);
  134. pr_debug("log_arity = %u\n", ftr->log_arity);
  135. pr_debug("meta_algorithm = %u\n", le16_to_cpu(ftr->meta_algorithm));
  136. pr_debug("data_algorithm = %u\n", le16_to_cpu(ftr->data_algorithm));
  137. pr_debug("flags = %#x\n", le32_to_cpu(ftr->flags));
  138. pr_debug("size = %llu\n", le64_to_cpu(ftr->size));
  139. pr_debug("authenticated_ext_count = %u\n",
  140. ftr->authenticated_ext_count);
  141. pr_debug("unauthenticated_ext_count = %u\n",
  142. ftr->unauthenticated_ext_count);
  143. pr_debug("salt = %*phN\n", (int)sizeof(ftr->salt), ftr->salt);
  144. }
  145. static int parse_elide_extension(struct fsverity_info *vi,
  146. const void *_ext, size_t extra_len)
  147. {
  148. const struct fsverity_extension_elide *ext = _ext;
  149. u64 offset = le64_to_cpu(ext->offset);
  150. u64 length = le64_to_cpu(ext->length);
  151. struct fsverity_elision *elision;
  152. pr_debug("Found elide extension: offset=%llu, length=%llu\n",
  153. offset, length);
  154. if ((offset | length) & ~PAGE_MASK) {
  155. pr_warn("Misaligned elision (offset=%llu, length=%llu)\n",
  156. offset, length);
  157. return -EINVAL;
  158. }
  159. if (length < 1) {
  160. pr_warn("Empty elision\n");
  161. return -EINVAL;
  162. }
  163. if (offset >= vi->data_i_size || length > vi->data_i_size - offset) {
  164. pr_warn("Elision offset and/or length too large (offset=%llu, length=%llu)\n",
  165. offset, length);
  166. return -EINVAL;
  167. }
  168. if (length >= vi->elided_i_size) {
  169. pr_warn("Entire file is elided!\n");
  170. return -EINVAL;
  171. }
  172. elision = kmalloc(sizeof(*elision), GFP_NOFS);
  173. if (!elision)
  174. return -ENOMEM;
  175. elision->index = offset >> PAGE_SHIFT;
  176. elision->nr_pages = length >> PAGE_SHIFT;
  177. list_add_tail(&elision->link, &vi->elisions);
  178. vi->elided_i_size -= length;
  179. return 0;
  180. }
  181. static int cmp_elisions(void *priv, struct list_head *_a, struct list_head *_b)
  182. {
  183. const struct fsverity_elision *a, *b;
  184. a = list_entry(_a, struct fsverity_elision, link);
  185. b = list_entry(_b, struct fsverity_elision, link);
  186. if (a->index > b->index)
  187. return 1;
  188. if (a->index < b->index)
  189. return -1;
  190. return 0;
  191. }
  192. /*
  193. * Sort the elisions (if any) in order of increasing offset, then verify they
  194. * don't overlap.
  195. */
  196. static int sort_and_check_elisions(struct fsverity_info *vi)
  197. {
  198. const struct fsverity_elision *elision;
  199. pgoff_t next_unelided_index = 0;
  200. list_sort(NULL, &vi->elisions, cmp_elisions);
  201. list_for_each_entry(elision, &vi->elisions, link) {
  202. if (elision->index < next_unelided_index) {
  203. pr_warn("Elisions overlap\n");
  204. return -EINVAL;
  205. }
  206. next_unelided_index = elision->index + elision->nr_pages;
  207. }
  208. return 0;
  209. }
  210. static int parse_patch_extension(struct fsverity_info *vi,
  211. const void *_ext, size_t extra_len)
  212. {
  213. const struct fsverity_extension_patch *ext = _ext;
  214. u64 offset = le64_to_cpu(ext->offset);
  215. struct fsverity_patch *patch;
  216. pr_debug("Found patch extension: offset=%llu, length=%zu\n",
  217. offset, extra_len);
  218. if (extra_len < 1) {
  219. pr_warn("Patch is empty\n");
  220. return -EINVAL;
  221. }
  222. if (extra_len > FS_VERITY_MAX_PATCH_SIZE) {
  223. pr_warn("Patch is too long (got %zu, limit is %d)\n",
  224. extra_len, FS_VERITY_MAX_PATCH_SIZE);
  225. return -EINVAL;
  226. }
  227. if (offset >= vi->data_i_size || extra_len > vi->data_i_size - offset) {
  228. pr_warn("Patch offset is too large (%llu)\n", offset);
  229. return -EINVAL;
  230. }
  231. pr_debug("databytes=%*phN\n", (int)extra_len, ext->databytes);
  232. patch = kmalloc(sizeof(*patch) + extra_len, GFP_NOFS);
  233. if (!patch)
  234. return -ENOMEM;
  235. patch->index = offset >> PAGE_SHIFT;
  236. patch->offset = offset & ~PAGE_MASK;
  237. patch->length = extra_len;
  238. memcpy(patch->patch, ext->databytes, extra_len);
  239. list_add_tail(&patch->link, &vi->patches);
  240. return 0;
  241. }
  242. static inline u64 patch_begin_byte(const struct fsverity_patch *patch)
  243. {
  244. return ((u64)patch->index << PAGE_SHIFT) + patch->offset;
  245. }
  246. static inline u64 patch_end_byte(const struct fsverity_patch *patch)
  247. {
  248. return patch_begin_byte(patch) + patch->length;
  249. }
  250. static int cmp_patches(void *priv, struct list_head *_a, struct list_head *_b)
  251. {
  252. const struct fsverity_patch *a, *b;
  253. a = list_entry(_a, struct fsverity_patch, link);
  254. b = list_entry(_b, struct fsverity_patch, link);
  255. if (a->index > b->index)
  256. return 1;
  257. if (a->index < b->index)
  258. return -1;
  259. return 0;
  260. }
  261. /*
  262. * Sort the patches (if any) in order of increasing offset, then verify they
  263. * don't overlap and that no page has multiple patches.
  264. */
  265. static int sort_and_check_patches(struct fsverity_info *vi)
  266. {
  267. const struct fsverity_patch *patch;
  268. u64 next_unpatched_byte = 0;
  269. pgoff_t prev_patched_index = 0;
  270. list_sort(NULL, &vi->patches, cmp_patches);
  271. list_for_each_entry(patch, &vi->patches, link) {
  272. u64 begin = patch_begin_byte(patch);
  273. u64 end = patch_end_byte(patch);
  274. if (begin < next_unpatched_byte) {
  275. pr_warn("Patches overlap\n");
  276. return -EINVAL;
  277. }
  278. if (next_unpatched_byte != 0 &&
  279. patch->index <= prev_patched_index) {
  280. pr_warn("Multiple patches per page\n");
  281. return -EINVAL;
  282. }
  283. next_unpatched_byte = end;
  284. prev_patched_index = (end - 1) >> PAGE_SHIFT;
  285. }
  286. return 0;
  287. }
  288. static const struct extension_type {
  289. int (*parse)(struct fsverity_info *vi, const void *_ext,
  290. size_t extra_len);
  291. size_t base_len;
  292. bool unauthenticated;
  293. } extension_types[] = {
  294. [FS_VERITY_EXT_ELIDE] = {
  295. .parse = parse_elide_extension,
  296. .base_len = sizeof(struct fsverity_extension_elide),
  297. },
  298. [FS_VERITY_EXT_PATCH] = {
  299. .parse = parse_patch_extension,
  300. .base_len = sizeof(struct fsverity_extension_patch),
  301. },
  302. };
  303. /*
  304. * Parse the extension items, if any, following the fixed-size portion of the
  305. * fs-verity footer. The fsverity_info is updated accordingly.
  306. *
  307. * Return: On success, the size of the authenticated portion of the footer (the
  308. * fixed-size portion plus the authenticated extensions).
  309. * Otherwise, a -errno value.
  310. */
  311. static int parse_extensions(struct fsverity_info *vi,
  312. const struct fsverity_footer *ftr, size_t limit)
  313. {
  314. const struct fsverity_extension *ext_hdr = (const void *)(ftr + 1);
  315. const void * const end = (const void *)ftr + limit;
  316. const void *auth_end = ext_hdr;
  317. int i;
  318. int err;
  319. int num_extensions = ftr->authenticated_ext_count +
  320. ftr->unauthenticated_ext_count;
  321. for (i = 0; i < num_extensions; i++) {
  322. const struct extension_type *type;
  323. u32 len, rounded_len;
  324. u16 type_code;
  325. bool unauthenticated = (i >= ftr->authenticated_ext_count);
  326. if (end - (const void *)ext_hdr < sizeof(*ext_hdr)) {
  327. pr_warn("Extension list overflows buffer\n");
  328. return -EINVAL;
  329. }
  330. type_code = le16_to_cpu(ext_hdr->type);
  331. if (type_code >= ARRAY_SIZE(extension_types) ||
  332. !extension_types[type_code].parse) {
  333. pr_warn("Unknown extension type: %u\n", type_code);
  334. return -EINVAL;
  335. }
  336. type = &extension_types[type_code];
  337. if (unauthenticated != type->unauthenticated) {
  338. pr_warn("Extension type %u must be %sauthenticated\n",
  339. type_code, type->unauthenticated ? "un" : "");
  340. return -EINVAL;
  341. }
  342. if (ext_hdr->reserved) {
  343. pr_warn("Reserved bits set in extension header\n");
  344. return -EINVAL;
  345. }
  346. len = le32_to_cpu(ext_hdr->length);
  347. if (len < sizeof(*ext_hdr)) {
  348. pr_warn("Invalid length in extension header\n");
  349. return -EINVAL;
  350. }
  351. rounded_len = round_up(len, 8);
  352. if (rounded_len == 0 ||
  353. rounded_len > end - (const void *)ext_hdr) {
  354. pr_warn("Extension item overflows buffer\n");
  355. return -EINVAL;
  356. }
  357. if (len < sizeof(*ext_hdr) + type->base_len) {
  358. pr_warn("Extension length too small for type\n");
  359. return -EINVAL;
  360. }
  361. err = type->parse(vi, ext_hdr + 1,
  362. len - sizeof(*ext_hdr) - type->base_len);
  363. if (err)
  364. return err;
  365. ext_hdr = (const void *)ext_hdr + rounded_len;
  366. if (!unauthenticated)
  367. auth_end = ext_hdr;
  368. }
  369. err = sort_and_check_elisions(vi);
  370. if (err)
  371. return err;
  372. err = sort_and_check_patches(vi);
  373. if (err)
  374. return err;
  375. return auth_end - (const void *)ftr;
  376. }
  377. /*
  378. * Parse an fs-verity footer, loading information into the fsverity_info.
  379. *
  380. * Return: On success, the size of the authenticated portion of the footer (the
  381. * fixed-size portion plus the authenticated extensions).
  382. * Otherwise, a -errno value.
  383. */
  384. static int parse_footer(struct fsverity_info *vi,
  385. const struct fsverity_footer *ftr, size_t limit)
  386. {
  387. unsigned int alg_num;
  388. u32 flags;
  389. int ftr_auth_len;
  390. /* magic */
  391. if (memcmp(ftr->magic, FS_VERITY_MAGIC, sizeof(ftr->magic))) {
  392. pr_warn("fs-verity footer not found\n");
  393. return -EINVAL;
  394. }
  395. /* major_version */
  396. if (ftr->major_version != FS_VERITY_MAJOR) {
  397. pr_warn("Unsupported major version (%u)\n", ftr->major_version);
  398. return -EINVAL;
  399. }
  400. /* minor_version */
  401. if (ftr->minor_version != FS_VERITY_MINOR) {
  402. pr_warn("Unsupported minor version (%u)\n", ftr->minor_version);
  403. return -EINVAL;
  404. }
  405. /* data_algorithm and meta_algorithm */
  406. alg_num = le16_to_cpu(ftr->data_algorithm);
  407. if (alg_num != le16_to_cpu(ftr->meta_algorithm)) {
  408. pr_warn("Unimplemented case: data (%u) and metadata (%u) hash algorithms differ\n",
  409. alg_num, le16_to_cpu(ftr->meta_algorithm));
  410. return -EINVAL;
  411. }
  412. vi->hash_alg = get_hash_algorithm(alg_num);
  413. if (IS_ERR(vi->hash_alg))
  414. return PTR_ERR(vi->hash_alg);
  415. /* log_blocksize */
  416. if (ftr->log_blocksize != PAGE_SHIFT) {
  417. pr_warn("Unsupported log_blocksize (%u). Need block_size == PAGE_SIZE.\n",
  418. ftr->log_blocksize);
  419. return -EINVAL;
  420. }
  421. vi->block_bits = ftr->log_blocksize;
  422. /* log_arity */
  423. vi->log_arity = ftr->log_arity;
  424. if (vi->log_arity !=
  425. vi->block_bits - ilog2(vi->hash_alg->digest_size)) {
  426. pr_warn("Unsupported log_arity (%u)\n", vi->log_arity);
  427. return -EINVAL;
  428. }
  429. /* flags */
  430. flags = le32_to_cpu(ftr->flags);
  431. if (flags & ~FS_VERITY_FLAG_INTEGRITY_ONLY) {
  432. pr_warn("Unsupported flags (%#x)\n", flags);
  433. return -EINVAL;
  434. }
  435. if (flags & FS_VERITY_FLAG_INTEGRITY_ONLY) {
  436. #ifdef CONFIG_FS_VERITY_INTEGRITY_ONLY
  437. pr_warn("Using experimental integrity-only mode!\n");
  438. vi->mode = FS_VERITY_MODE_INTEGRITY_ONLY;
  439. #else
  440. pr_warn("Integrity-only mode not supported\n");
  441. return -EINVAL;
  442. #endif
  443. }
  444. /* reserved fields */
  445. if (ftr->reserved1 ||
  446. memchr_inv(ftr->reserved2, 0, sizeof(ftr->reserved2))) {
  447. pr_warn("Reserved bits set in footer\n");
  448. return -EINVAL;
  449. }
  450. /* size */
  451. vi->data_i_size = le64_to_cpu(ftr->size);
  452. if (vi->data_i_size == 0) {
  453. pr_warn("Original file size is 0; this is not supported\n");
  454. return -EINVAL;
  455. }
  456. if (vi->data_i_size > vi->full_i_size) {
  457. pr_warn("Original file size is too large (%llu)\n",
  458. vi->data_i_size);
  459. return -EINVAL;
  460. }
  461. vi->elided_i_size = vi->data_i_size;
  462. /* salt */
  463. memcpy(vi->salt, ftr->salt, FS_VERITY_SALT_SIZE);
  464. /* extensions */
  465. ftr_auth_len = parse_extensions(vi, ftr, limit);
  466. if (ftr_auth_len < 0)
  467. pr_warn("Invalid or unsupported extensions list\n");
  468. return ftr_auth_len;
  469. }
  470. /*
  471. * Calculate the depth of the Merkle tree, then create a map from level to the
  472. * block offset at which that level's hash blocks start. Level 'depth - 1' is
  473. * the root and is stored first in the file, in the first block following the
  474. * original data. Level 0 is the level directly "above" the data blocks and is
  475. * stored last in the file, just before the fs-verity footer.
  476. */
  477. static int compute_tree_depth_and_offsets(struct fsverity_info *vi)
  478. {
  479. unsigned int hashes_per_block = 1 << vi->log_arity;
  480. u64 blocks = (vi->elided_i_size + (1 << vi->block_bits) - 1) >>
  481. vi->block_bits;
  482. u64 offset = (vi->data_i_size + (1 << vi->block_bits) - 1) >>
  483. vi->block_bits;
  484. int depth = 0;
  485. int i;
  486. while (blocks > 1) {
  487. if (depth >= FS_VERITY_MAX_LEVELS) {
  488. pr_warn("Too many tree levels (max is %d)\n",
  489. FS_VERITY_MAX_LEVELS);
  490. return -EINVAL;
  491. }
  492. blocks = (blocks + hashes_per_block - 1) >> vi->log_arity;
  493. vi->hash_lvl_region_idx[depth++] = blocks;
  494. }
  495. vi->depth = depth;
  496. pr_debug("depth = %d\n", depth);
  497. for (i = depth - 1; i >= 0; i--) {
  498. u64 next_count = vi->hash_lvl_region_idx[i];
  499. vi->hash_lvl_region_idx[i] = offset;
  500. pr_debug("Level %d is [%llu..%llu] (%llu blocks)\n",
  501. i, offset, offset + next_count - 1, next_count);
  502. offset += next_count;
  503. }
  504. return 0;
  505. }
  506. static pgoff_t first_unelided_page(struct fsverity_info *vi)
  507. {
  508. pgoff_t index = 0;
  509. const struct fsverity_elision *elision;
  510. list_for_each_entry(elision, &vi->elisions, link) {
  511. if (index != elision->index)
  512. break;
  513. index += elision->nr_pages;
  514. }
  515. return index;
  516. }
  517. /*
  518. * Compute the hash of the root of the Merkle tree (or of the lone data block
  519. * for files <= blocksize in length) and store it in vi->root_hash.
  520. */
  521. static int compute_root_hash(struct inode *inode, struct fsverity_info *vi)
  522. {
  523. SHASH_DESC_ON_STACK(desc, vi->hash_alg->tfm);
  524. struct page *root_page;
  525. pgoff_t root_idx;
  526. int err;
  527. desc->tfm = vi->hash_alg->tfm;
  528. desc->flags = 0;
  529. if (vi->depth)
  530. root_idx = vi->hash_lvl_region_idx[vi->depth - 1];
  531. else
  532. root_idx = first_unelided_page(vi);
  533. root_page = inode->i_sb->s_vop->read_metadata_page(inode, root_idx);
  534. if (IS_ERR(root_page)) {
  535. pr_warn("Error reading root block: %ld\n", PTR_ERR(root_page));
  536. return PTR_ERR(root_page);
  537. }
  538. err = crypto_shash_init(desc);
  539. if (!err)
  540. err = crypto_shash_update(desc, vi->salt, FS_VERITY_SALT_SIZE);
  541. if (!err) {
  542. /* atomic, since we aren't using CRYPTO_TFM_REQ_MAY_SLEEP */
  543. void *root = kmap_atomic(root_page);
  544. err = crypto_shash_update(desc, root, PAGE_SIZE);
  545. kunmap_atomic(root);
  546. }
  547. if (!err)
  548. err = finalize_hash(vi, desc, vi->root_hash);
  549. if (err)
  550. pr_warn("Error computing Merkle tree root hash: %d\n", err);
  551. else
  552. pr_debug("Computed Merkle tree root hash: %*phN\n",
  553. vi->hash_alg->digest_size, vi->root_hash);
  554. put_page(root_page);
  555. if (vi->depth == 0) {
  556. /*
  557. * The data page must not be left in the page cache, otherwise
  558. * it would appear to have been verified.
  559. */
  560. truncate_inode_pages_range(inode->i_mapping,
  561. (loff_t)root_idx << PAGE_SHIFT,
  562. (((loff_t)root_idx + 1) << PAGE_SHIFT) - 1);
  563. }
  564. return err;
  565. }
  566. /* Compute the file's measurement and store it in vi->measurement */
  567. static int compute_measurement(struct fsverity_info *vi,
  568. const struct fsverity_footer *ftr,
  569. int ftr_auth_len)
  570. {
  571. SHASH_DESC_ON_STACK(desc, vi->hash_alg->tfm);
  572. int err;
  573. desc->tfm = vi->hash_alg->tfm;
  574. desc->flags = 0;
  575. err = crypto_shash_init(desc);
  576. if (!err)
  577. err = crypto_shash_update(desc, (const u8 *)ftr, ftr_auth_len);
  578. if (!err)
  579. err = crypto_shash_update(desc, vi->root_hash,
  580. vi->hash_alg->digest_size);
  581. if (!err)
  582. err = finalize_hash(vi, desc, vi->measurement);
  583. if (err)
  584. pr_warn("Error computing fs-verity measurement: %d\n", err);
  585. else
  586. pr_debug("Computed measurement: %*phN (used ftr_auth_len %d)\n",
  587. vi->hash_alg->digest_size, vi->measurement,
  588. ftr_auth_len);
  589. return err;
  590. }
  591. static struct fsverity_info *alloc_fsverity_info(void)
  592. {
  593. struct fsverity_info *vi;
  594. vi = kmem_cache_zalloc(fsverity_info_cachep, GFP_NOFS);
  595. if (!vi)
  596. return NULL;
  597. vi->mode = FS_VERITY_MODE_NEED_AUTHENTICATION;
  598. INIT_LIST_HEAD(&vi->elisions);
  599. INIT_LIST_HEAD(&vi->patches);
  600. return vi;
  601. }
  602. static void free_fsverity_info(struct fsverity_info *vi)
  603. {
  604. if (!vi)
  605. return;
  606. kmem_cache_free(fsverity_info_cachep, vi);
  607. }
  608. /*
  609. * Read the file's fs-verity footer and create an fsverity_info for it.
  610. *
  611. * TODO(mhalcrow): This logic only works with full-size Merkle
  612. * trees that include all padding and/or when footer/extent
  613. * content fits in one page.
  614. */
  615. static struct fsverity_info *create_fsverity_info(struct inode *inode)
  616. {
  617. struct fsverity_info *vi;
  618. loff_t full_isize = i_size_read(inode);
  619. unsigned int last_validsize = ((full_isize - 1) & ~PAGE_MASK) + 1;
  620. pgoff_t ftr_pgoff = (full_isize - 1) >> PAGE_SHIFT;
  621. struct page *ftr_page = NULL;
  622. const void *ftr_virt;
  623. unsigned int ftr_reverse_offset_loc;
  624. u32 ftr_reverse_offset;
  625. unsigned int ftr_loc;
  626. const struct fsverity_footer *ftr;
  627. int ftr_auth_len;
  628. int err;
  629. pr_debug("full_isize = %lld\n", full_isize);
  630. pr_debug("last_validsize=%u\n", last_validsize);
  631. pr_debug("ftr_pgoff=%lu\n", ftr_pgoff);
  632. if (full_isize <= 0) {
  633. pr_warn("File is empty!\n");
  634. return ERR_PTR(-EINVAL);
  635. }
  636. if (last_validsize < sizeof(*ftr) + sizeof(__le32)) {
  637. pr_warn("Unsupported alignment for fs-verity metadata -- not enough data in last page (only %u bytes)\n",
  638. last_validsize);
  639. return ERR_PTR(-EINVAL);
  640. }
  641. vi = alloc_fsverity_info();
  642. if (!vi)
  643. return ERR_PTR(-ENOMEM);
  644. vi->full_i_size = full_isize;
  645. ftr_page = inode->i_sb->s_vop->read_metadata_page(inode, ftr_pgoff);
  646. if (IS_ERR(ftr_page)) {
  647. err = PTR_ERR(ftr_page);
  648. pr_warn("Error reading footer page: %d\n", err);
  649. ftr_page = NULL;
  650. goto out;
  651. }
  652. ftr_virt = kmap(ftr_page);
  653. ftr_reverse_offset_loc = last_validsize - sizeof(__le32);
  654. pr_debug("ftr_reverse_offset_loc=%u\n", ftr_reverse_offset_loc);
  655. ftr_reverse_offset = get_unaligned_le32(ftr_virt +
  656. ftr_reverse_offset_loc);
  657. pr_debug("ftr_reverse_offset=%u\n", ftr_reverse_offset);
  658. if (ftr_reverse_offset < sizeof(*ftr) + sizeof(__le32)) {
  659. pr_warn("Invalid fs-verity metadata (unexpected ftr_reverse_offset: %u)\n",
  660. ftr_reverse_offset);
  661. err = -EINVAL;
  662. goto out;
  663. }
  664. if (ftr_reverse_offset > last_validsize) {
  665. pr_warn("Unimplemented case - fs-verity footer crosses pages (last_validsize=%u, ftr_reverse_offset=%u)",
  666. last_validsize, ftr_reverse_offset);
  667. err = -EINVAL;
  668. goto out;
  669. }
  670. ftr_loc = last_validsize - ftr_reverse_offset;
  671. if (ftr_loc & 7) {
  672. pr_warn("fs-verity footer is misaligned. last_validsize=%u, ftr_reverse_offset=%u\n",
  673. last_validsize, ftr_reverse_offset);
  674. err = -EINVAL;
  675. goto out;
  676. }
  677. ftr = ftr_virt + ftr_loc;
  678. dump_fsverity_footer(ftr);
  679. ftr_auth_len = parse_footer(vi, ftr, ftr_reverse_offset_loc - ftr_loc);
  680. if (ftr_auth_len < 0) {
  681. err = ftr_auth_len;
  682. goto out;
  683. }
  684. err = compute_tree_depth_and_offsets(vi);
  685. if (err)
  686. goto out;
  687. err = compute_root_hash(inode, vi);
  688. if (err)
  689. goto out;
  690. err = compute_measurement(vi, ftr, ftr_auth_len);
  691. out:
  692. if (ftr_page) {
  693. kunmap(ftr_page);
  694. put_page(ftr_page);
  695. }
  696. if (err) {
  697. free_fsverity_info(vi);
  698. vi = ERR_PTR(err);
  699. }
  700. return vi;
  701. }
  702. /* Ensure the inode has an ->i_verity_info */
  703. static int setup_fsverity_info(struct inode *inode)
  704. {
  705. struct fsverity_info *vi = get_fsverity_info(inode);
  706. if (vi)
  707. return 0;
  708. vi = create_fsverity_info(inode);
  709. if (IS_ERR(vi))
  710. return PTR_ERR(vi);
  711. if (!set_fsverity_info(inode, vi))
  712. free_fsverity_info(vi);
  713. return 0;
  714. }
  715. /**
  716. * fsverity_file_open - prepare to open an fs-verity file
  717. * @inode: the inode being opened
  718. * @filp: the struct file being set up
  719. *
  720. * When opening an fs-verity file, deny the open if it is for writing.
  721. * Otherwise, set up the inode's ->i_verity_info (if not already done) by
  722. * parsing the fs-verity metadata at the end of the file.
  723. *
  724. * When combined with fscrypt, this must be called after fscrypt_file_open().
  725. * Otherwise, we won't have the key set up to decrypt the fs-verity metadata.
  726. *
  727. * TODO: currently userspace has to provide the expected measurement using
  728. * FS_IOC_SET_VERITY_MEASUREMENT, but in the future here we will validate the
  729. * computed measurement against a PKCS#7 message embedded in the fs-verity
  730. * metadata which contains the signed expected measurement.
  731. *
  732. * Return: 0 on success, -errno on failure
  733. */
  734. int fsverity_file_open(struct inode *inode, struct file *filp)
  735. {
  736. if (filp->f_mode & FMODE_WRITE) {
  737. pr_debug("Denying opening fs-verity file (ino %lu) for write\n",
  738. inode->i_ino);
  739. return -EPERM;
  740. }
  741. pr_debug("Opening fs-verity file (ino %lu)\n", inode->i_ino);
  742. return setup_fsverity_info(inode);
  743. }
  744. EXPORT_SYMBOL_GPL(fsverity_file_open);
  745. /**
  746. * fsverity_prepare_setattr - prepare to change an fs-verity inode's attributes
  747. * @dentry: dentry through which the inode is being changed
  748. * @attr: attributes to change
  749. *
  750. * fs-verity files are immutable, so deny truncates. This isn't covered by the
  751. * open-time check because sys_truncate() takes a path, not a file descriptor.
  752. *
  753. * Return: 0 on success, -errno on failure
  754. */
  755. int fsverity_prepare_setattr(struct dentry *dentry, struct iattr *attr)
  756. {
  757. if (attr->ia_valid & ATTR_SIZE) {
  758. pr_debug("Denying truncate of fs-verity file (ino %lu)\n",
  759. d_inode(dentry)->i_ino);
  760. return -EPERM;
  761. }
  762. return 0;
  763. }
  764. EXPORT_SYMBOL_GPL(fsverity_prepare_setattr);
  765. /**
  766. * fsverity_prepare_getattr - prepare to get an fsverity inode's attributes
  767. * @inode: the inode for which the attributes are being retrieved
  768. *
  769. * To make st_size exclude the fs-verity metadata even before the file has been
  770. * opened for the first time, we need to grab the original data size from the
  771. * fs-verity footer. Currently, to implement this we just set up the
  772. * ->i_verity_info, like in the ->open() hook.
  773. *
  774. * However, when combined with fscrypt, on an encrypted file this must only be
  775. * called if the encryption key has been set up!
  776. *
  777. * Return: 0 on success, -errno on failure
  778. */
  779. int fsverity_prepare_getattr(struct inode *inode)
  780. {
  781. return setup_fsverity_info(inode);
  782. }
  783. EXPORT_SYMBOL_GPL(fsverity_prepare_getattr);
  784. /**
  785. * fsverity_cleanup_inode - free the inode's verity info, if present
  786. *
  787. * Filesystems must call this on inode eviction to free ->i_verity_info.
  788. */
  789. void fsverity_cleanup_inode(struct inode *inode)
  790. {
  791. free_fsverity_info(inode->i_verity_info);
  792. inode->i_verity_info = NULL;
  793. }
  794. EXPORT_SYMBOL_GPL(fsverity_cleanup_inode);
  795. /**
  796. * hash_at_level() - compute the location of the block's hash at the given level
  797. *
  798. * @vi: (in) the file's verity info
  799. * @dindex: (in) the index of the data block being verified
  800. * @level: (in) the level of hash we want
  801. * @hindex: (out) the index of the hash block containing the wanted hash
  802. * @hoffset: (out) the byte offset to the wanted hash within the hash block
  803. */
  804. static void hash_at_level(const struct fsverity_info *vi, pgoff_t dindex,
  805. unsigned int level, pgoff_t *hindex,
  806. unsigned int *hoffset)
  807. {
  808. pgoff_t hoffset_in_lvl;
  809. /*
  810. * Compute the offset of the hash within the level's region, in hashes.
  811. * For example, with 4096-byte blocks and 32-byte hashes, there are
  812. * 4096/32 = 128 = 2^7 hashes per hash block, i.e. log_arity = 7. Then,
  813. * if the data block index is 65668 and we want the level 1 hash, it is
  814. * located at 65668 >> 7 = 513 hashes into the level 1 region.
  815. */
  816. hoffset_in_lvl = dindex >> (level * vi->log_arity);
  817. /*
  818. * Compute the index of the hash block containing the wanted hash.
  819. * Continuing the above example, the block would be at index 513 >> 7 =
  820. * 4 within the level 1 region. To this we'd add the index at which the
  821. * level 1 region starts.
  822. */
  823. *hindex = vi->hash_lvl_region_idx[level] +
  824. (hoffset_in_lvl >> vi->log_arity);
  825. /*
  826. * Finally, compute the index of the hash within the block rather than
  827. * the region, and multiply by the hash size to turn it into a byte
  828. * offset. Continuing the above example, the hash would be at byte
  829. * offset (513 & ((1 << 7) - 1)) * 32 = 32 within the block.
  830. */
  831. *hoffset = (hoffset_in_lvl & ((1 << vi->log_arity) - 1)) *
  832. vi->hash_alg->digest_size;
  833. }
  834. /* Extract a hash from a hash page */
  835. static void extract_hash(struct page *hpage, unsigned int hoffset,
  836. unsigned int hsize, u8 *out)
  837. {
  838. void *virt = kmap_atomic(hpage);
  839. memcpy(out, virt + hoffset, hsize);
  840. kunmap_atomic(virt);
  841. }
  842. static int hash_page(struct fsverity_info *vi, struct page *page,
  843. const struct fsverity_patch *patch, u8 *out)
  844. {
  845. SHASH_DESC_ON_STACK(desc, vi->hash_alg->tfm);
  846. void *virt;
  847. int err;
  848. desc->tfm = vi->hash_alg->tfm;
  849. desc->flags = 0;
  850. err = crypto_shash_init(desc);
  851. if (err)
  852. return err;
  853. err = crypto_shash_update(desc, vi->salt, FS_VERITY_SALT_SIZE);
  854. if (err)
  855. return err;
  856. virt = kmap_atomic(page);
  857. if (patch) {
  858. unsigned int patch_offset = patch->offset;
  859. unsigned int patch_length = patch->length;
  860. unsigned int patch_skip = 0;
  861. if (patch->index != page->index) {
  862. /* Patch started on a prior page */
  863. BUG_ON(patch->index > page->index);
  864. patch_skip = (PAGE_SIZE - patch_offset) +
  865. ((page->index - patch->index - 1) <<
  866. PAGE_SHIFT);
  867. patch_offset = 0;
  868. patch_length -= patch_skip;
  869. }
  870. patch_length = min_t(unsigned int, patch_length,
  871. PAGE_SIZE - patch_offset);
  872. err = crypto_shash_update(desc, virt, patch_offset);
  873. if (!err)
  874. err = crypto_shash_update(desc,
  875. patch->patch + patch_skip,
  876. patch_length);
  877. if (!err)
  878. err = crypto_shash_update(desc,
  879. virt + patch_offset + patch_length,
  880. PAGE_SIZE - patch_offset - patch_length);
  881. } else {
  882. /* Normal case: no patch, just hash the page */
  883. err = crypto_shash_update(desc, virt, PAGE_SIZE);
  884. }
  885. kunmap_atomic(virt);
  886. if (err)
  887. return err;
  888. return finalize_hash(vi, desc, out);
  889. }
  890. /*
  891. * Find the patch, if any, that needs to be applied to the page at the specified
  892. * index when verifying.
  893. */
  894. static const struct fsverity_patch *find_patch(struct fsverity_info *vi,
  895. pgoff_t index)
  896. {
  897. const struct fsverity_patch *patch;
  898. list_for_each_entry(patch, &vi->patches, link) {
  899. if (index < patch->index)
  900. break; /* list is sorted, so can stop here */
  901. if (index <= (patch_end_byte(patch) - 1) >> PAGE_SHIFT)
  902. return patch;
  903. }
  904. return NULL;
  905. }
  906. /*
  907. * Determine whether the given page index is elided (bypasses verification). If
  908. * so, return true. Else, return false and adjust the page index to account for
  909. * any previous elisions.
  910. */
  911. static bool page_elided(struct fsverity_info *vi, pgoff_t *index_p)
  912. {
  913. const struct fsverity_elision *elision;
  914. pgoff_t orig_idx = *index_p;
  915. pgoff_t elided_idx = *index_p;
  916. list_for_each_entry(elision, &vi->elisions, link) {
  917. if (orig_idx < elision->index)
  918. break; /* list is sorted, so can stop here */
  919. if (orig_idx < elision->index + elision->nr_pages)
  920. return true;
  921. elided_idx -= elision->nr_pages;
  922. }
  923. *index_p = elided_idx;
  924. return false;
  925. }
  926. static int compare_hashes(const u8 *want_hash, const u8 *real_hash,
  927. int digest_size, struct inode *inode, pgoff_t index,
  928. int level)
  929. {
  930. if (memcmp(want_hash, real_hash, digest_size) == 0)
  931. return 0;
  932. pr_warn_ratelimited("VERIFICATION FAILURE! ino=%lu, index=%lu, level=%d, want_hash=%*phN, real_hash=%*phN\n",
  933. inode->i_ino, index, level,
  934. digest_size, want_hash, digest_size, real_hash);
  935. return -EBADMSG;
  936. }
  937. /**
  938. * fsverity_verify_page - verify a data page
  939. *
  940. * Verify the integrity and/or authenticity of a page that has just been read
  941. * from the file. The page is assumed to be a pagecache page.
  942. *
  943. * Return: true if the page is valid, else false.
  944. */
  945. bool fsverity_verify_page(struct page *data_page)
  946. {
  947. struct address_space *mapping = data_page->mapping;
  948. struct inode *inode = mapping->host;
  949. struct fsverity_info *vi = get_fsverity_info(inode);
  950. pgoff_t index = data_page->index;
  951. int level = 0;
  952. u8 _want_hash[FS_VERITY_MAX_DIGEST_SIZE];
  953. u8 *want_hash = NULL;
  954. u8 real_hash[FS_VERITY_MAX_DIGEST_SIZE];
  955. struct page *hpages[FS_VERITY_MAX_LEVELS];
  956. unsigned int hoffsets[FS_VERITY_MAX_LEVELS];
  957. const struct fsverity_patch *patch;
  958. int err;
  959. /*
  960. * It shouldn't be possible to get here without ->i_verity_info set,
  961. * since it's set on ->open().
  962. */
  963. if (WARN_ON_ONCE(!vi))
  964. return false;
  965. /* The page must not be unlocked until verification has completed. */
  966. if (WARN_ON_ONCE(!PageLocked(data_page)))
  967. return false;
  968. /*
  969. * Reads are forbidden if the measurement being enforced doesn't match
  970. * the expected one. Otherwise reads are allowed, but we warn if they
  971. * are unauthenticated, i.e. if FS_IOC_SET_VERITY_MEASUREMENT hasn't
  972. * been called yet. (Some users need to use unauthenticated reads to
  973. * find a signature stored in the file. Allowing these doesn't actually
  974. * decrease security, since an attacker could just replace the file with
  975. * a non-verity one anyway.)
  976. */
  977. switch (vi->mode) {
  978. case FS_VERITY_MODE_NEED_AUTHENTICATION:
  979. pr_warn_ratelimited("Unauthenticated read; ino=%lu, index=%lu\n",
  980. inode->i_ino, index);
  981. break;
  982. case FS_VERITY_MODE_AUTHENTICATION_FAILED:
  983. pr_warn("Root authentication failed, failing read; inode=%lu, index=%lu\n",
  984. inode->i_ino, index);
  985. return false;
  986. case FS_VERITY_MODE_AUTHENTICATED:
  987. case FS_VERITY_MODE_INTEGRITY_ONLY:
  988. break;
  989. default:
  990. WARN_ON_ONCE(1);
  991. return false;
  992. }
  993. /*
  994. * Since ->i_size is overridden with ->data_i_size, and fs-verity avoids
  995. * recursing into itself when reading hash pages, we shouldn't normally
  996. * get here with a page beyond ->data_i_size. But, it can happen if a
  997. * read is issued at or beyond EOF since the VFS doesn't check i_size
  998. * before calling ->readpage(). Thus, just skip verification if the
  999. * page is beyond ->data_i_size.
  1000. */
  1001. if (index >= (vi->data_i_size + PAGE_SIZE - 1) >> PAGE_SHIFT) {
  1002. pr_debug("Page %lu is in metadata region\n", index);
  1003. return true;
  1004. }
  1005. patch = find_patch(vi, index);
  1006. if (patch)
  1007. pr_debug("Selected patch: index=%lu, offset=%u, length=%u for page index %lu\n",
  1008. patch->index, patch->offset, patch->length, index);
  1009. if (page_elided(vi, &index)) {
  1010. pr_debug("Page %lu is elided, not verifying!\n", index);
  1011. return true;
  1012. }
  1013. if (index != data_page->index)
  1014. pr_debug_ratelimited("Adjusted index because of elisions: %lu => %lu\n",
  1015. data_page->index, index);
  1016. pr_debug_ratelimited("Verifying data page %lu...\n", index);
  1017. /*
  1018. * Starting at the leaves, ascend the tree saving hash pages along the
  1019. * way until we find a verified hash page, indicated by PageChecked; or
  1020. * until we reach the root.
  1021. */
  1022. for (level = 0; level < vi->depth; level++) {
  1023. pgoff_t hindex;
  1024. unsigned int hoffset;
  1025. struct page *hpage;
  1026. hash_at_level(vi, index, level, &hindex, &hoffset);
  1027. pr_debug_ratelimited("Level %d: hindex=%lu, hoffset=%u\n",
  1028. level, hindex, hoffset);
  1029. hpage = inode->i_sb->s_vop->read_metadata_page(inode, hindex);
  1030. if (IS_ERR(hpage)) {
  1031. err = PTR_ERR(hpage);
  1032. goto out;
  1033. }
  1034. if (PageChecked(hpage)) {
  1035. want_hash = _want_hash;
  1036. extract_hash(hpage, hoffset, vi->hash_alg->digest_size,
  1037. want_hash);
  1038. put_page(hpage);
  1039. pr_debug_ratelimited("Hash page already checked, want hash %*phN\n",
  1040. vi->hash_alg->digest_size,
  1041. want_hash);
  1042. break;
  1043. }
  1044. pr_debug_ratelimited("Hash page not yet checked\n");
  1045. hpages[level] = hpage;
  1046. hoffsets[level] = hoffset;
  1047. }
  1048. if (!want_hash) {
  1049. want_hash = vi->root_hash;
  1050. pr_debug("Want root hash: %*phN\n", vi->hash_alg->digest_size,
  1051. want_hash);
  1052. }
  1053. /* Descend the tree verifying hash pages */
  1054. for (; level > 0; level--) {
  1055. struct page *hpage = hpages[level - 1];
  1056. unsigned int hoffset = hoffsets[level - 1];
  1057. err = hash_page(vi, hpage, NULL, real_hash);
  1058. if (err)
  1059. goto out;
  1060. err = compare_hashes(want_hash, real_hash,
  1061. vi->hash_alg->digest_size,
  1062. inode, index, level - 1);
  1063. if (err)
  1064. goto out;
  1065. SetPageChecked(hpage);
  1066. want_hash = _want_hash;
  1067. extract_hash(hpage, hoffset, vi->hash_alg->digest_size,
  1068. want_hash);
  1069. put_page(hpage);
  1070. pr_debug("Verified hash page at level %d, now want hash %*phN\n",
  1071. level - 1, vi->hash_alg->digest_size, want_hash);
  1072. }
  1073. /* Finally, verify the data page */
  1074. err = hash_page(vi, data_page, patch, real_hash);
  1075. if (err)
  1076. goto out;
  1077. err = compare_hashes(want_hash, real_hash, vi->hash_alg->digest_size,
  1078. inode, index, -1);
  1079. out:
  1080. for (; level > 0; level--)
  1081. put_page(hpages[level - 1]);
  1082. if (err) {
  1083. pr_warn_ratelimited("Error verifying page; ino=%lu, index=%lu (err=%d)\n",
  1084. inode->i_ino, data_page->index, err);
  1085. return false;
  1086. }
  1087. return true;
  1088. }
  1089. EXPORT_SYMBOL_GPL(fsverity_verify_page);
  1090. /**
  1091. * fsverity_verify_bio - verify a 'read' bio that has just completed
  1092. *
  1093. * Verify the integrity and/or authenticity of a set of pages that have just
  1094. * been read from the file. The pages are assumed to be pagecache pages. Pages
  1095. * that fail verification are set to the Error state. Verification is skipped
  1096. * for pages already in the Error state, e.g. due to fscrypt decryption failure.
  1097. */
  1098. void fsverity_verify_bio(struct bio *bio)
  1099. {
  1100. struct bio_vec *bv;
  1101. int i;
  1102. bio_for_each_segment_all(bv, bio, i) {
  1103. struct page *page = bv->bv_page;
  1104. if (!PageError(page) && !fsverity_verify_page(page))
  1105. SetPageError(page);
  1106. }
  1107. }
  1108. EXPORT_SYMBOL_GPL(fsverity_verify_bio);
  1109. /**
  1110. * fsverity_enqueue_verify_work - enqueue work on the fs-verity workqueue
  1111. *
  1112. * Enqueue verification work for asynchronous processing.
  1113. */
  1114. void fsverity_enqueue_verify_work(struct work_struct *work)
  1115. {
  1116. queue_work(fsverity_read_workqueue, work);
  1117. }
  1118. EXPORT_SYMBOL_GPL(fsverity_enqueue_verify_work);
  1119. /**
  1120. * fsverity_full_isize - get the full (on-disk) file size
  1121. *
  1122. * If the inode has had its in-memory ->i_size overridden for fs-verity (to
  1123. * exclude the metadata at the end of the file), then return the full i_size
  1124. * which is stored on-disk. Otherwise, just return the in-memory ->i_size.
  1125. *
  1126. * Return: the full (on-disk) file size
  1127. */
  1128. loff_t fsverity_full_isize(struct inode *inode)
  1129. {
  1130. struct fsverity_info *vi = get_fsverity_info(inode);
  1131. if (vi)
  1132. return vi->full_i_size;
  1133. return i_size_read(inode);
  1134. }
  1135. EXPORT_SYMBOL_GPL(fsverity_full_isize);
  1136. /**
  1137. * fsverity_ioctl_set_measurement - set a verity file's expected measurement
  1138. *
  1139. * The FS_IOC_SET_VERITY_MEASUREMENT ioctl informs the kernel which
  1140. * "measurement" (hash of the Merkle tree root hash and the fsverity footer) is
  1141. * expected for an fs-verity file. If the actual measurement matches the
  1142. * expected one, then the ioctl succeeds and further reads from the file are
  1143. * allowed without warnings. Additionally, the inode is pinned in memory so
  1144. * that the "authenticated" status doesn't get lost on eviction. Otherwise,
  1145. * reads from the file are forbidden and the ioctl fails.
  1146. *
  1147. * TODO(mhalcrow): In the future, we're going to want to have a signature
  1148. * attached to the files that we validate whenever we load the authenticated
  1149. * data structure root into memory.
  1150. *
  1151. * Return: 0 on success, -errno on failure
  1152. */
  1153. int fsverity_ioctl_set_measurement(struct file *filp, const void __user *_uarg)
  1154. {
  1155. const struct fsverity_measurement __user *uarg = _uarg;
  1156. struct inode *inode = file_inode(filp);
  1157. struct super_block *sb = inode->i_sb;
  1158. struct fsverity_measurement arg;
  1159. u8 digest[FS_VERITY_MAX_DIGEST_SIZE];
  1160. const struct fsverity_hash_alg *hash_alg;
  1161. struct fsverity_info *vi;
  1162. int err;
  1163. if (!capable(CAP_SYS_ADMIN)) {
  1164. pr_debug("Process '%s' is not authorized to provide fs-verity measurements\n",
  1165. current->comm);
  1166. err = -EACCES;
  1167. goto out;
  1168. }
  1169. if (copy_from_user(&arg, uarg, sizeof(arg))) {
  1170. err = -EFAULT;
  1171. goto out;
  1172. }
  1173. if (arg.reserved1 ||
  1174. memchr_inv(arg.reserved2, 0, sizeof(arg.reserved2))) {
  1175. pr_debug("Reserved fields are set in fsverity_measurement\n");
  1176. err = -EINVAL;
  1177. goto out;
  1178. }
  1179. hash_alg = get_hash_algorithm(arg.digest_algorithm);
  1180. if (IS_ERR(hash_alg)) {
  1181. err = PTR_ERR(hash_alg);
  1182. goto out;
  1183. }
  1184. if (arg.digest_size != hash_alg->digest_size) {
  1185. pr_debug("Wrong digest_size in fsverity_measurement: wanted %u for algorithm '%s', but got %u\n",
  1186. hash_alg->digest_size, hash_alg->name,
  1187. arg.digest_size);
  1188. err = -EINVAL;
  1189. goto out;
  1190. }
  1191. /* Redundant, but just in case */
  1192. if (WARN_ON(hash_alg->digest_size > sizeof(digest))) {
  1193. err = -EINVAL;
  1194. goto out;
  1195. }
  1196. if (copy_from_user(digest, uarg->digest, hash_alg->digest_size)) {
  1197. err = -EFAULT;
  1198. goto out;
  1199. }
  1200. vi = get_fsverity_info(inode);
  1201. if (!vi) {
  1202. pr_debug("File does not have fs-verity enabled\n");
  1203. err = -EINVAL;
  1204. goto out;
  1205. }
  1206. inode_lock(inode);
  1207. if (hash_alg != vi->hash_alg) {
  1208. pr_debug("Hash algorithm mismatch: provided '%s', but file uses '%s'\n",
  1209. hash_alg->name, vi->hash_alg->name);
  1210. err = -EBADMSG;
  1211. vi->mode = FS_VERITY_MODE_AUTHENTICATION_FAILED;
  1212. truncate_inode_pages(inode->i_mapping, 0);
  1213. goto out_unlock;
  1214. }
  1215. if (memcmp(digest, vi->measurement, hash_alg->digest_size)) {
  1216. if (vi->mode == FS_VERITY_MODE_AUTHENTICATED)
  1217. pr_warn("Inconsistent measurements were provided! %*phN and %*phN\n",
  1218. hash_alg->digest_size, digest,
  1219. hash_alg->digest_size, vi->measurement);
  1220. else
  1221. pr_warn("File corrupted! Wanted measurement: %*phN, real measurement: %*phN\n",
  1222. hash_alg->digest_size, digest,
  1223. hash_alg->digest_size, vi->measurement);
  1224. vi->mode = FS_VERITY_MODE_AUTHENTICATION_FAILED;
  1225. truncate_inode_pages(inode->i_mapping, 0);
  1226. err = -EBADMSG;
  1227. goto out_unlock;
  1228. }
  1229. if (vi->mode == FS_VERITY_MODE_AUTHENTICATED) {
  1230. pr_debug("Measurement already being enforced: %*phN\n",
  1231. hash_alg->digest_size, vi->measurement);
  1232. } else {
  1233. pr_debug("Measurement validated: %*phN\n",
  1234. hash_alg->digest_size, vi->measurement);
  1235. vi->mode = FS_VERITY_MODE_AUTHENTICATED;
  1236. /*
  1237. * No need to truncate pages here. Any pages that were read
  1238. * without authentication still had their integrity verified up
  1239. * to ->root_hash, so now we know they are authentic as we've
  1240. * just authenticated ->root_hash.
  1241. */
  1242. /* Pin the inode so that the measurement doesn't go away */
  1243. ihold(inode);
  1244. spin_lock(&sb->s_inode_fsveritylist_lock);
  1245. list_add(&inode->i_fsverity_list, &sb->s_inodes_fsverity);
  1246. spin_unlock(&sb->s_inode_fsveritylist_lock);
  1247. }
  1248. err = 0;
  1249. out_unlock:
  1250. inode_unlock(inode);
  1251. out:
  1252. if (err)
  1253. pr_debug("FS_IOC_SET_VERITY_MEASUREMENT failed on inode %lu (err %d)\n",
  1254. inode->i_ino, err);
  1255. else
  1256. pr_debug("FS_IOC_SET_VERITY_MEASUREMENT succeeded on inode %lu\n",
  1257. inode->i_ino);
  1258. return err;
  1259. }
  1260. EXPORT_SYMBOL_GPL(fsverity_ioctl_set_measurement);
  1261. /**
  1262. * fsverity_ioctl_enable - enable fs-verity on a file
  1263. *
  1264. * Enable the fs-verity bit on a file. Userspace must have already appended the
  1265. * fs-verity metadata to the file.
  1266. *
  1267. * Enabling fs-verity makes the file contents immutable, and the filesystem
  1268. * doesn't allow disabling it (other than by replacing the file).
  1269. *
  1270. * To avoid races with the file contents being modified, no processes must have
  1271. * the file open for writing. This includes the caller!
  1272. *
  1273. * Return: 0 on success, -errno on failure
  1274. */
  1275. int fsverity_ioctl_enable(struct file *filp, const void __user *arg)
  1276. {
  1277. struct inode *inode = file_inode(filp);
  1278. struct fsverity_info *vi;
  1279. int err;
  1280. if (!capable(CAP_SYS_ADMIN)) {
  1281. pr_debug("Process '%s' is not authorized to enable fs-verity\n",
  1282. current->comm);
  1283. err = -EACCES;
  1284. goto out;
  1285. }
  1286. if (arg) {
  1287. pr_debug("FS_IOC_ENABLE_VERITY doesn't take an argument\n");
  1288. err = -EINVAL;
  1289. goto out;
  1290. }
  1291. if (S_ISDIR(inode->i_mode)) {
  1292. pr_debug("Inode is a directory\n");
  1293. err = -EISDIR;
  1294. goto out;
  1295. }
  1296. if (!S_ISREG(inode->i_mode)) {
  1297. pr_debug("Inode is not a regular file\n");
  1298. err = -EINVAL;
  1299. goto out;
  1300. }
  1301. err = mnt_want_write_file(filp);
  1302. if (err)
  1303. goto out;
  1304. /*
  1305. * Temporarily lock out writers via writable file descriptors or
  1306. * truncate(). This should stabilize the contents of the file as well
  1307. * as its size. Note that at the end of this ioctl we will unlock
  1308. * writers, but at that point the fs-verity bit will be set (if the
  1309. * ioctl succeeded), preventing future writers.
  1310. */
  1311. err = deny_write_access(filp);
  1312. if (err) {
  1313. pr_debug("File is open for writing!\n");
  1314. goto out_drop_write;
  1315. }
  1316. /*
  1317. * fsync so that the fs-verity bit can't be persisted to disk prior to
  1318. * the data, causing verification errors after a crash.
  1319. */
  1320. err = vfs_fsync(filp, 1);
  1321. if (err) {
  1322. pr_debug("I/O error occurred during fsync\n");
  1323. goto out_allow_write;
  1324. }
  1325. /* Serialize concurrent use of this ioctl on the same inode */
  1326. inode_lock(inode);
  1327. if (inode->i_sb->s_vop->is_verity(inode)) {
  1328. pr_debug("Fs-verity is already enabled on this file\n");
  1329. err = -EEXIST;
  1330. goto out_unlock;
  1331. }
  1332. /* Validate the fs-verity footer */
  1333. vi = create_fsverity_info(inode);
  1334. if (IS_ERR(vi)) {
  1335. pr_debug("create_fsverity_info() failed\n");
  1336. err = PTR_ERR(vi);
  1337. goto out_unlock;
  1338. }
  1339. /* Set the fs-verity bit */
  1340. err = inode->i_sb->s_vop->set_verity(inode);
  1341. if (err) {
  1342. pr_debug("Filesystem ->set_verity() method failed\n");
  1343. goto out_free_vi;
  1344. }
  1345. /* Invalidate all cached pages, forcing re-verification */
  1346. truncate_inode_pages(inode->i_mapping, 0);
  1347. /* Set ->i_verity_info */
  1348. if (set_fsverity_info(inode, vi))
  1349. vi = NULL;
  1350. err = 0;
  1351. out_free_vi:
  1352. free_fsverity_info(vi);
  1353. out_unlock:
  1354. inode_unlock(inode);
  1355. out_allow_write:
  1356. allow_write_access(filp);
  1357. out_drop_write:
  1358. mnt_drop_write_file(filp);
  1359. out:
  1360. if (err)
  1361. pr_debug("Failed to enable fs-verity on inode %lu (err=%d)\n",
  1362. inode->i_ino, err);
  1363. else
  1364. pr_debug("Successfully enabled fs-verity on inode %lu\n",
  1365. inode->i_ino);
  1366. return err;
  1367. }
  1368. EXPORT_SYMBOL_GPL(fsverity_ioctl_enable);
  1369. static int __init fsverity_module_init(void)
  1370. {
  1371. int err;
  1372. int i;
  1373. /*
  1374. * Use an unbound workqueue to better distribute verification work among
  1375. * multiple CPUs.
  1376. *
  1377. * Use a high-priority workqueue to prioritize verification work, which
  1378. * blocks reads from completing, over regular application tasks.
  1379. */
  1380. err = -ENOMEM;
  1381. fsverity_read_workqueue = alloc_workqueue("fsverity_read_queue",
  1382. WQ_CPU_INTENSIVE |
  1383. WQ_HIGHPRI | WQ_UNBOUND,
  1384. num_online_cpus());
  1385. if (!fsverity_read_workqueue)
  1386. goto error;
  1387. err = -ENOMEM;
  1388. fsverity_info_cachep = KMEM_CACHE(fsverity_info, SLAB_RECLAIM_ACCOUNT);
  1389. if (!fsverity_info_cachep)
  1390. goto error_free_workqueue;
  1391. /*
  1392. * Sanity check the digest sizes (could be a build-time check, but
  1393. * they're in an array)
  1394. */
  1395. for (i = 0; i < ARRAY_SIZE(fsverity_hash_algs); i++) {
  1396. struct fsverity_hash_alg *alg = &fsverity_hash_algs[i];
  1397. if (!alg->name)
  1398. continue;
  1399. BUG_ON(alg->digest_size > FS_VERITY_MAX_DIGEST_SIZE);
  1400. BUG_ON(!is_power_of_2(alg->digest_size));
  1401. }
  1402. pr_debug("Initialized fs-verity\n");
  1403. return 0;
  1404. error_free_workqueue:
  1405. destroy_workqueue(fsverity_read_workqueue);
  1406. error:
  1407. return err;
  1408. }
  1409. static void __exit fsverity_module_exit(void)
  1410. {
  1411. int i;
  1412. destroy_workqueue(fsverity_read_workqueue);
  1413. kmem_cache_destroy(fsverity_info_cachep);
  1414. for (i = 0; i < ARRAY_SIZE(fsverity_hash_algs); i++)
  1415. crypto_free_shash(fsverity_hash_algs[i].tfm);
  1416. }
  1417. module_init(fsverity_module_init)
  1418. module_exit(fsverity_module_exit);
  1419. MODULE_LICENSE("GPL");
  1420. MODULE_DESCRIPTION("fs-verity: read-only file-based integrity/authenticity");