keyring.c 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794
  1. // SPDX-License-Identifier: GPL-2.0-or-later
  2. /* Keyring handling
  3. *
  4. * Copyright (C) 2004-2005, 2008, 2013 Red Hat, Inc. All Rights Reserved.
  5. * Written by David Howells (dhowells@redhat.com)
  6. */
  7. #include <linux/export.h>
  8. #include <linux/init.h>
  9. #include <linux/sched.h>
  10. #include <linux/slab.h>
  11. #include <linux/security.h>
  12. #include <linux/seq_file.h>
  13. #include <linux/err.h>
  14. #include <linux/user_namespace.h>
  15. #include <linux/nsproxy.h>
  16. #include <keys/keyring-type.h>
  17. #include <keys/user-type.h>
  18. #include <linux/assoc_array_priv.h>
  19. #include <linux/uaccess.h>
  20. #include <net/net_namespace.h>
  21. #include "internal.h"
  22. /*
  23. * When plumbing the depths of the key tree, this sets a hard limit
  24. * set on how deep we're willing to go.
  25. */
  26. #define KEYRING_SEARCH_MAX_DEPTH 6
  27. /*
  28. * We mark pointers we pass to the associative array with bit 1 set if
  29. * they're keyrings and clear otherwise.
  30. */
  31. #define KEYRING_PTR_SUBTYPE 0x2UL
  32. static inline bool keyring_ptr_is_keyring(const struct assoc_array_ptr *x)
  33. {
  34. return (unsigned long)x & KEYRING_PTR_SUBTYPE;
  35. }
  36. static inline struct key *keyring_ptr_to_key(const struct assoc_array_ptr *x)
  37. {
  38. void *object = assoc_array_ptr_to_leaf(x);
  39. return (struct key *)((unsigned long)object & ~KEYRING_PTR_SUBTYPE);
  40. }
  41. static inline void *keyring_key_to_ptr(struct key *key)
  42. {
  43. if (key->type == &key_type_keyring)
  44. return (void *)((unsigned long)key | KEYRING_PTR_SUBTYPE);
  45. return key;
  46. }
  47. static DEFINE_RWLOCK(keyring_name_lock);
  48. /*
  49. * Clean up the bits of user_namespace that belong to us.
  50. */
  51. void key_free_user_ns(struct user_namespace *ns)
  52. {
  53. write_lock(&keyring_name_lock);
  54. list_del_init(&ns->keyring_name_list);
  55. write_unlock(&keyring_name_lock);
  56. key_put(ns->user_keyring_register);
  57. #ifdef CONFIG_PERSISTENT_KEYRINGS
  58. key_put(ns->persistent_keyring_register);
  59. #endif
  60. }
  61. /*
  62. * The keyring key type definition. Keyrings are simply keys of this type and
  63. * can be treated as ordinary keys in addition to having their own special
  64. * operations.
  65. */
  66. static int keyring_preparse(struct key_preparsed_payload *prep);
  67. static void keyring_free_preparse(struct key_preparsed_payload *prep);
  68. static int keyring_instantiate(struct key *keyring,
  69. struct key_preparsed_payload *prep);
  70. static void keyring_revoke(struct key *keyring);
  71. static void keyring_destroy(struct key *keyring);
  72. static void keyring_describe(const struct key *keyring, struct seq_file *m);
  73. static long keyring_read(const struct key *keyring,
  74. char __user *buffer, size_t buflen);
  75. struct key_type key_type_keyring = {
  76. .name = "keyring",
  77. .def_datalen = 0,
  78. .preparse = keyring_preparse,
  79. .free_preparse = keyring_free_preparse,
  80. .instantiate = keyring_instantiate,
  81. .revoke = keyring_revoke,
  82. .destroy = keyring_destroy,
  83. .describe = keyring_describe,
  84. .read = keyring_read,
  85. };
  86. EXPORT_SYMBOL(key_type_keyring);
  87. /*
  88. * Semaphore to serialise link/link calls to prevent two link calls in parallel
  89. * introducing a cycle.
  90. */
  91. static DEFINE_MUTEX(keyring_serialise_link_lock);
  92. /*
  93. * Publish the name of a keyring so that it can be found by name (if it has
  94. * one and it doesn't begin with a dot).
  95. */
  96. static void keyring_publish_name(struct key *keyring)
  97. {
  98. struct user_namespace *ns = current_user_ns();
  99. if (keyring->description &&
  100. keyring->description[0] &&
  101. keyring->description[0] != '.') {
  102. write_lock(&keyring_name_lock);
  103. list_add_tail(&keyring->name_link, &ns->keyring_name_list);
  104. write_unlock(&keyring_name_lock);
  105. }
  106. }
  107. /*
  108. * Preparse a keyring payload
  109. */
  110. static int keyring_preparse(struct key_preparsed_payload *prep)
  111. {
  112. return prep->datalen != 0 ? -EINVAL : 0;
  113. }
  114. /*
  115. * Free a preparse of a user defined key payload
  116. */
  117. static void keyring_free_preparse(struct key_preparsed_payload *prep)
  118. {
  119. }
  120. /*
  121. * Initialise a keyring.
  122. *
  123. * Returns 0 on success, -EINVAL if given any data.
  124. */
  125. static int keyring_instantiate(struct key *keyring,
  126. struct key_preparsed_payload *prep)
  127. {
  128. assoc_array_init(&keyring->keys);
  129. /* make the keyring available by name if it has one */
  130. keyring_publish_name(keyring);
  131. return 0;
  132. }
  133. /*
  134. * Multiply 64-bits by 32-bits to 96-bits and fold back to 64-bit. Ideally we'd
  135. * fold the carry back too, but that requires inline asm.
  136. */
  137. static u64 mult_64x32_and_fold(u64 x, u32 y)
  138. {
  139. u64 hi = (u64)(u32)(x >> 32) * y;
  140. u64 lo = (u64)(u32)(x) * y;
  141. return lo + ((u64)(u32)hi << 32) + (u32)(hi >> 32);
  142. }
  143. /*
  144. * Hash a key type and description.
  145. */
  146. static void hash_key_type_and_desc(struct keyring_index_key *index_key)
  147. {
  148. const unsigned level_shift = ASSOC_ARRAY_LEVEL_STEP;
  149. const unsigned long fan_mask = ASSOC_ARRAY_FAN_MASK;
  150. const char *description = index_key->description;
  151. unsigned long hash, type;
  152. u32 piece;
  153. u64 acc;
  154. int n, desc_len = index_key->desc_len;
  155. type = (unsigned long)index_key->type;
  156. acc = mult_64x32_and_fold(type, desc_len + 13);
  157. acc = mult_64x32_and_fold(acc, 9207);
  158. piece = (unsigned long)index_key->domain_tag;
  159. acc = mult_64x32_and_fold(acc, piece);
  160. acc = mult_64x32_and_fold(acc, 9207);
  161. for (;;) {
  162. n = desc_len;
  163. if (n <= 0)
  164. break;
  165. if (n > 4)
  166. n = 4;
  167. piece = 0;
  168. memcpy(&piece, description, n);
  169. description += n;
  170. desc_len -= n;
  171. acc = mult_64x32_and_fold(acc, piece);
  172. acc = mult_64x32_and_fold(acc, 9207);
  173. }
  174. /* Fold the hash down to 32 bits if need be. */
  175. hash = acc;
  176. if (ASSOC_ARRAY_KEY_CHUNK_SIZE == 32)
  177. hash ^= acc >> 32;
  178. /* Squidge all the keyrings into a separate part of the tree to
  179. * ordinary keys by making sure the lowest level segment in the hash is
  180. * zero for keyrings and non-zero otherwise.
  181. */
  182. if (index_key->type != &key_type_keyring && (hash & fan_mask) == 0)
  183. hash |= (hash >> (ASSOC_ARRAY_KEY_CHUNK_SIZE - level_shift)) | 1;
  184. else if (index_key->type == &key_type_keyring && (hash & fan_mask) != 0)
  185. hash = (hash + (hash << level_shift)) & ~fan_mask;
  186. index_key->hash = hash;
  187. }
  188. /*
  189. * Finalise an index key to include a part of the description actually in the
  190. * index key, to set the domain tag and to calculate the hash.
  191. */
  192. void key_set_index_key(struct keyring_index_key *index_key)
  193. {
  194. static struct key_tag default_domain_tag = { .usage = REFCOUNT_INIT(1), };
  195. size_t n = min_t(size_t, index_key->desc_len, sizeof(index_key->desc));
  196. memcpy(index_key->desc, index_key->description, n);
  197. if (!index_key->domain_tag) {
  198. if (index_key->type->flags & KEY_TYPE_NET_DOMAIN)
  199. index_key->domain_tag = current->nsproxy->net_ns->key_domain;
  200. else
  201. index_key->domain_tag = &default_domain_tag;
  202. }
  203. hash_key_type_and_desc(index_key);
  204. }
  205. /**
  206. * key_put_tag - Release a ref on a tag.
  207. * @tag: The tag to release.
  208. *
  209. * This releases a reference the given tag and returns true if that ref was the
  210. * last one.
  211. */
  212. bool key_put_tag(struct key_tag *tag)
  213. {
  214. if (refcount_dec_and_test(&tag->usage)) {
  215. kfree_rcu(tag, rcu);
  216. return true;
  217. }
  218. return false;
  219. }
  220. /**
  221. * key_remove_domain - Kill off a key domain and gc its keys
  222. * @domain_tag: The domain tag to release.
  223. *
  224. * This marks a domain tag as being dead and releases a ref on it. If that
  225. * wasn't the last reference, the garbage collector is poked to try and delete
  226. * all keys that were in the domain.
  227. */
  228. void key_remove_domain(struct key_tag *domain_tag)
  229. {
  230. domain_tag->removed = true;
  231. if (!key_put_tag(domain_tag))
  232. key_schedule_gc_links();
  233. }
  234. /*
  235. * Build the next index key chunk.
  236. *
  237. * We return it one word-sized chunk at a time.
  238. */
  239. static unsigned long keyring_get_key_chunk(const void *data, int level)
  240. {
  241. const struct keyring_index_key *index_key = data;
  242. unsigned long chunk = 0;
  243. const u8 *d;
  244. int desc_len = index_key->desc_len, n = sizeof(chunk);
  245. level /= ASSOC_ARRAY_KEY_CHUNK_SIZE;
  246. switch (level) {
  247. case 0:
  248. return index_key->hash;
  249. case 1:
  250. return index_key->x;
  251. case 2:
  252. return (unsigned long)index_key->type;
  253. case 3:
  254. return (unsigned long)index_key->domain_tag;
  255. default:
  256. level -= 4;
  257. if (desc_len <= sizeof(index_key->desc))
  258. return 0;
  259. d = index_key->description + sizeof(index_key->desc);
  260. d += level * sizeof(long);
  261. desc_len -= sizeof(index_key->desc);
  262. if (desc_len > n)
  263. desc_len = n;
  264. do {
  265. chunk <<= 8;
  266. chunk |= *d++;
  267. } while (--desc_len > 0);
  268. return chunk;
  269. }
  270. }
  271. static unsigned long keyring_get_object_key_chunk(const void *object, int level)
  272. {
  273. const struct key *key = keyring_ptr_to_key(object);
  274. return keyring_get_key_chunk(&key->index_key, level);
  275. }
  276. static bool keyring_compare_object(const void *object, const void *data)
  277. {
  278. const struct keyring_index_key *index_key = data;
  279. const struct key *key = keyring_ptr_to_key(object);
  280. return key->index_key.type == index_key->type &&
  281. key->index_key.domain_tag == index_key->domain_tag &&
  282. key->index_key.desc_len == index_key->desc_len &&
  283. memcmp(key->index_key.description, index_key->description,
  284. index_key->desc_len) == 0;
  285. }
  286. /*
  287. * Compare the index keys of a pair of objects and determine the bit position
  288. * at which they differ - if they differ.
  289. */
  290. static int keyring_diff_objects(const void *object, const void *data)
  291. {
  292. const struct key *key_a = keyring_ptr_to_key(object);
  293. const struct keyring_index_key *a = &key_a->index_key;
  294. const struct keyring_index_key *b = data;
  295. unsigned long seg_a, seg_b;
  296. int level, i;
  297. level = 0;
  298. seg_a = a->hash;
  299. seg_b = b->hash;
  300. if ((seg_a ^ seg_b) != 0)
  301. goto differ;
  302. level += ASSOC_ARRAY_KEY_CHUNK_SIZE / 8;
  303. /* The number of bits contributed by the hash is controlled by a
  304. * constant in the assoc_array headers. Everything else thereafter we
  305. * can deal with as being machine word-size dependent.
  306. */
  307. seg_a = a->x;
  308. seg_b = b->x;
  309. if ((seg_a ^ seg_b) != 0)
  310. goto differ;
  311. level += sizeof(unsigned long);
  312. /* The next bit may not work on big endian */
  313. seg_a = (unsigned long)a->type;
  314. seg_b = (unsigned long)b->type;
  315. if ((seg_a ^ seg_b) != 0)
  316. goto differ;
  317. level += sizeof(unsigned long);
  318. seg_a = (unsigned long)a->domain_tag;
  319. seg_b = (unsigned long)b->domain_tag;
  320. if ((seg_a ^ seg_b) != 0)
  321. goto differ;
  322. level += sizeof(unsigned long);
  323. i = sizeof(a->desc);
  324. if (a->desc_len <= i)
  325. goto same;
  326. for (; i < a->desc_len; i++) {
  327. seg_a = *(unsigned char *)(a->description + i);
  328. seg_b = *(unsigned char *)(b->description + i);
  329. if ((seg_a ^ seg_b) != 0)
  330. goto differ_plus_i;
  331. }
  332. same:
  333. return -1;
  334. differ_plus_i:
  335. level += i;
  336. differ:
  337. i = level * 8 + __ffs(seg_a ^ seg_b);
  338. return i;
  339. }
  340. /*
  341. * Free an object after stripping the keyring flag off of the pointer.
  342. */
  343. static void keyring_free_object(void *object)
  344. {
  345. key_put(keyring_ptr_to_key(object));
  346. }
  347. /*
  348. * Operations for keyring management by the index-tree routines.
  349. */
  350. static const struct assoc_array_ops keyring_assoc_array_ops = {
  351. .get_key_chunk = keyring_get_key_chunk,
  352. .get_object_key_chunk = keyring_get_object_key_chunk,
  353. .compare_object = keyring_compare_object,
  354. .diff_objects = keyring_diff_objects,
  355. .free_object = keyring_free_object,
  356. };
  357. /*
  358. * Clean up a keyring when it is destroyed. Unpublish its name if it had one
  359. * and dispose of its data.
  360. *
  361. * The garbage collector detects the final key_put(), removes the keyring from
  362. * the serial number tree and then does RCU synchronisation before coming here,
  363. * so we shouldn't need to worry about code poking around here with the RCU
  364. * readlock held by this time.
  365. */
  366. static void keyring_destroy(struct key *keyring)
  367. {
  368. if (keyring->description) {
  369. write_lock(&keyring_name_lock);
  370. if (keyring->name_link.next != NULL &&
  371. !list_empty(&keyring->name_link))
  372. list_del(&keyring->name_link);
  373. write_unlock(&keyring_name_lock);
  374. }
  375. if (keyring->restrict_link) {
  376. struct key_restriction *keyres = keyring->restrict_link;
  377. key_put(keyres->key);
  378. kfree(keyres);
  379. }
  380. assoc_array_destroy(&keyring->keys, &keyring_assoc_array_ops);
  381. }
  382. /*
  383. * Describe a keyring for /proc.
  384. */
  385. static void keyring_describe(const struct key *keyring, struct seq_file *m)
  386. {
  387. if (keyring->description)
  388. seq_puts(m, keyring->description);
  389. else
  390. seq_puts(m, "[anon]");
  391. if (key_is_positive(keyring)) {
  392. if (keyring->keys.nr_leaves_on_tree != 0)
  393. seq_printf(m, ": %lu", keyring->keys.nr_leaves_on_tree);
  394. else
  395. seq_puts(m, ": empty");
  396. }
  397. }
  398. struct keyring_read_iterator_context {
  399. size_t buflen;
  400. size_t count;
  401. key_serial_t __user *buffer;
  402. };
  403. static int keyring_read_iterator(const void *object, void *data)
  404. {
  405. struct keyring_read_iterator_context *ctx = data;
  406. const struct key *key = keyring_ptr_to_key(object);
  407. kenter("{%s,%d},,{%zu/%zu}",
  408. key->type->name, key->serial, ctx->count, ctx->buflen);
  409. if (ctx->count >= ctx->buflen)
  410. return 1;
  411. *ctx->buffer++ = key->serial;
  412. ctx->count += sizeof(key->serial);
  413. return 0;
  414. }
  415. /*
  416. * Read a list of key IDs from the keyring's contents in binary form
  417. *
  418. * The keyring's semaphore is read-locked by the caller. This prevents someone
  419. * from modifying it under us - which could cause us to read key IDs multiple
  420. * times.
  421. */
  422. static long keyring_read(const struct key *keyring,
  423. char __user *buffer, size_t buflen)
  424. {
  425. struct keyring_read_iterator_context ctx;
  426. long ret;
  427. kenter("{%d},,%zu", key_serial(keyring), buflen);
  428. if (buflen & (sizeof(key_serial_t) - 1))
  429. return -EINVAL;
  430. /* Copy as many key IDs as fit into the buffer */
  431. if (buffer && buflen) {
  432. ctx.buffer = (key_serial_t __user *)buffer;
  433. ctx.buflen = buflen;
  434. ctx.count = 0;
  435. ret = assoc_array_iterate(&keyring->keys,
  436. keyring_read_iterator, &ctx);
  437. if (ret < 0) {
  438. kleave(" = %ld [iterate]", ret);
  439. return ret;
  440. }
  441. }
  442. /* Return the size of the buffer needed */
  443. ret = keyring->keys.nr_leaves_on_tree * sizeof(key_serial_t);
  444. if (ret <= buflen)
  445. kleave("= %ld [ok]", ret);
  446. else
  447. kleave("= %ld [buffer too small]", ret);
  448. return ret;
  449. }
  450. /*
  451. * Allocate a keyring and link into the destination keyring.
  452. */
  453. struct key *keyring_alloc(const char *description, kuid_t uid, kgid_t gid,
  454. const struct cred *cred, key_perm_t perm,
  455. unsigned long flags,
  456. struct key_restriction *restrict_link,
  457. struct key *dest)
  458. {
  459. struct key *keyring;
  460. int ret;
  461. keyring = key_alloc(&key_type_keyring, description,
  462. uid, gid, cred, perm, flags, restrict_link);
  463. if (!IS_ERR(keyring)) {
  464. ret = key_instantiate_and_link(keyring, NULL, 0, dest, NULL);
  465. if (ret < 0) {
  466. key_put(keyring);
  467. keyring = ERR_PTR(ret);
  468. }
  469. }
  470. return keyring;
  471. }
  472. EXPORT_SYMBOL(keyring_alloc);
  473. /**
  474. * restrict_link_reject - Give -EPERM to restrict link
  475. * @keyring: The keyring being added to.
  476. * @type: The type of key being added.
  477. * @payload: The payload of the key intended to be added.
  478. * @restriction_key: Keys providing additional data for evaluating restriction.
  479. *
  480. * Reject the addition of any links to a keyring. It can be overridden by
  481. * passing KEY_ALLOC_BYPASS_RESTRICTION to key_instantiate_and_link() when
  482. * adding a key to a keyring.
  483. *
  484. * This is meant to be stored in a key_restriction structure which is passed
  485. * in the restrict_link parameter to keyring_alloc().
  486. */
  487. int restrict_link_reject(struct key *keyring,
  488. const struct key_type *type,
  489. const union key_payload *payload,
  490. struct key *restriction_key)
  491. {
  492. return -EPERM;
  493. }
  494. /*
  495. * By default, we keys found by getting an exact match on their descriptions.
  496. */
  497. bool key_default_cmp(const struct key *key,
  498. const struct key_match_data *match_data)
  499. {
  500. return strcmp(key->description, match_data->raw_data) == 0;
  501. }
  502. /*
  503. * Iteration function to consider each key found.
  504. */
  505. static int keyring_search_iterator(const void *object, void *iterator_data)
  506. {
  507. struct keyring_search_context *ctx = iterator_data;
  508. const struct key *key = keyring_ptr_to_key(object);
  509. unsigned long kflags = READ_ONCE(key->flags);
  510. short state = READ_ONCE(key->state);
  511. kenter("{%d}", key->serial);
  512. /* ignore keys not of this type */
  513. if (key->type != ctx->index_key.type) {
  514. kleave(" = 0 [!type]");
  515. return 0;
  516. }
  517. /* skip invalidated, revoked and expired keys */
  518. if (ctx->flags & KEYRING_SEARCH_DO_STATE_CHECK) {
  519. time64_t expiry = READ_ONCE(key->expiry);
  520. if (kflags & ((1 << KEY_FLAG_INVALIDATED) |
  521. (1 << KEY_FLAG_REVOKED))) {
  522. ctx->result = ERR_PTR(-EKEYREVOKED);
  523. kleave(" = %d [invrev]", ctx->skipped_ret);
  524. goto skipped;
  525. }
  526. if (expiry && ctx->now >= expiry) {
  527. if (!(ctx->flags & KEYRING_SEARCH_SKIP_EXPIRED))
  528. ctx->result = ERR_PTR(-EKEYEXPIRED);
  529. kleave(" = %d [expire]", ctx->skipped_ret);
  530. goto skipped;
  531. }
  532. }
  533. /* keys that don't match */
  534. if (!ctx->match_data.cmp(key, &ctx->match_data)) {
  535. kleave(" = 0 [!match]");
  536. return 0;
  537. }
  538. /* key must have search permissions */
  539. if (!(ctx->flags & KEYRING_SEARCH_NO_CHECK_PERM) &&
  540. key_task_permission(make_key_ref(key, ctx->possessed),
  541. ctx->cred, KEY_NEED_SEARCH) < 0) {
  542. ctx->result = ERR_PTR(-EACCES);
  543. kleave(" = %d [!perm]", ctx->skipped_ret);
  544. goto skipped;
  545. }
  546. if (ctx->flags & KEYRING_SEARCH_DO_STATE_CHECK) {
  547. /* we set a different error code if we pass a negative key */
  548. if (state < 0) {
  549. ctx->result = ERR_PTR(state);
  550. kleave(" = %d [neg]", ctx->skipped_ret);
  551. goto skipped;
  552. }
  553. }
  554. /* Found */
  555. ctx->result = make_key_ref(key, ctx->possessed);
  556. kleave(" = 1 [found]");
  557. return 1;
  558. skipped:
  559. return ctx->skipped_ret;
  560. }
  561. /*
  562. * Search inside a keyring for a key. We can search by walking to it
  563. * directly based on its index-key or we can iterate over the entire
  564. * tree looking for it, based on the match function.
  565. */
  566. static int search_keyring(struct key *keyring, struct keyring_search_context *ctx)
  567. {
  568. if (ctx->match_data.lookup_type == KEYRING_SEARCH_LOOKUP_DIRECT) {
  569. const void *object;
  570. object = assoc_array_find(&keyring->keys,
  571. &keyring_assoc_array_ops,
  572. &ctx->index_key);
  573. return object ? ctx->iterator(object, ctx) : 0;
  574. }
  575. return assoc_array_iterate(&keyring->keys, ctx->iterator, ctx);
  576. }
  577. /*
  578. * Search a tree of keyrings that point to other keyrings up to the maximum
  579. * depth.
  580. */
  581. static bool search_nested_keyrings(struct key *keyring,
  582. struct keyring_search_context *ctx)
  583. {
  584. struct {
  585. struct key *keyring;
  586. struct assoc_array_node *node;
  587. int slot;
  588. } stack[KEYRING_SEARCH_MAX_DEPTH];
  589. struct assoc_array_shortcut *shortcut;
  590. struct assoc_array_node *node;
  591. struct assoc_array_ptr *ptr;
  592. struct key *key;
  593. int sp = 0, slot;
  594. kenter("{%d},{%s,%s}",
  595. keyring->serial,
  596. ctx->index_key.type->name,
  597. ctx->index_key.description);
  598. #define STATE_CHECKS (KEYRING_SEARCH_NO_STATE_CHECK | KEYRING_SEARCH_DO_STATE_CHECK)
  599. BUG_ON((ctx->flags & STATE_CHECKS) == 0 ||
  600. (ctx->flags & STATE_CHECKS) == STATE_CHECKS);
  601. if (ctx->index_key.description)
  602. key_set_index_key(&ctx->index_key);
  603. /* Check to see if this top-level keyring is what we are looking for
  604. * and whether it is valid or not.
  605. */
  606. if (ctx->match_data.lookup_type == KEYRING_SEARCH_LOOKUP_ITERATE ||
  607. keyring_compare_object(keyring, &ctx->index_key)) {
  608. ctx->skipped_ret = 2;
  609. switch (ctx->iterator(keyring_key_to_ptr(keyring), ctx)) {
  610. case 1:
  611. goto found;
  612. case 2:
  613. return false;
  614. default:
  615. break;
  616. }
  617. }
  618. ctx->skipped_ret = 0;
  619. /* Start processing a new keyring */
  620. descend_to_keyring:
  621. kdebug("descend to %d", keyring->serial);
  622. if (keyring->flags & ((1 << KEY_FLAG_INVALIDATED) |
  623. (1 << KEY_FLAG_REVOKED)))
  624. goto not_this_keyring;
  625. /* Search through the keys in this keyring before its searching its
  626. * subtrees.
  627. */
  628. if (search_keyring(keyring, ctx))
  629. goto found;
  630. /* Then manually iterate through the keyrings nested in this one.
  631. *
  632. * Start from the root node of the index tree. Because of the way the
  633. * hash function has been set up, keyrings cluster on the leftmost
  634. * branch of the root node (root slot 0) or in the root node itself.
  635. * Non-keyrings avoid the leftmost branch of the root entirely (root
  636. * slots 1-15).
  637. */
  638. if (!(ctx->flags & KEYRING_SEARCH_RECURSE))
  639. goto not_this_keyring;
  640. ptr = READ_ONCE(keyring->keys.root);
  641. if (!ptr)
  642. goto not_this_keyring;
  643. if (assoc_array_ptr_is_shortcut(ptr)) {
  644. /* If the root is a shortcut, either the keyring only contains
  645. * keyring pointers (everything clusters behind root slot 0) or
  646. * doesn't contain any keyring pointers.
  647. */
  648. shortcut = assoc_array_ptr_to_shortcut(ptr);
  649. if ((shortcut->index_key[0] & ASSOC_ARRAY_FAN_MASK) != 0)
  650. goto not_this_keyring;
  651. ptr = READ_ONCE(shortcut->next_node);
  652. node = assoc_array_ptr_to_node(ptr);
  653. goto begin_node;
  654. }
  655. node = assoc_array_ptr_to_node(ptr);
  656. ptr = node->slots[0];
  657. if (!assoc_array_ptr_is_meta(ptr))
  658. goto begin_node;
  659. descend_to_node:
  660. /* Descend to a more distal node in this keyring's content tree and go
  661. * through that.
  662. */
  663. kdebug("descend");
  664. if (assoc_array_ptr_is_shortcut(ptr)) {
  665. shortcut = assoc_array_ptr_to_shortcut(ptr);
  666. ptr = READ_ONCE(shortcut->next_node);
  667. BUG_ON(!assoc_array_ptr_is_node(ptr));
  668. }
  669. node = assoc_array_ptr_to_node(ptr);
  670. begin_node:
  671. kdebug("begin_node");
  672. slot = 0;
  673. ascend_to_node:
  674. /* Go through the slots in a node */
  675. for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
  676. ptr = READ_ONCE(node->slots[slot]);
  677. if (assoc_array_ptr_is_meta(ptr) && node->back_pointer)
  678. goto descend_to_node;
  679. if (!keyring_ptr_is_keyring(ptr))
  680. continue;
  681. key = keyring_ptr_to_key(ptr);
  682. if (sp >= KEYRING_SEARCH_MAX_DEPTH) {
  683. if (ctx->flags & KEYRING_SEARCH_DETECT_TOO_DEEP) {
  684. ctx->result = ERR_PTR(-ELOOP);
  685. return false;
  686. }
  687. goto not_this_keyring;
  688. }
  689. /* Search a nested keyring */
  690. if (!(ctx->flags & KEYRING_SEARCH_NO_CHECK_PERM) &&
  691. key_task_permission(make_key_ref(key, ctx->possessed),
  692. ctx->cred, KEY_NEED_SEARCH) < 0)
  693. continue;
  694. /* stack the current position */
  695. stack[sp].keyring = keyring;
  696. stack[sp].node = node;
  697. stack[sp].slot = slot;
  698. sp++;
  699. /* begin again with the new keyring */
  700. keyring = key;
  701. goto descend_to_keyring;
  702. }
  703. /* We've dealt with all the slots in the current node, so now we need
  704. * to ascend to the parent and continue processing there.
  705. */
  706. ptr = READ_ONCE(node->back_pointer);
  707. slot = node->parent_slot;
  708. if (ptr && assoc_array_ptr_is_shortcut(ptr)) {
  709. shortcut = assoc_array_ptr_to_shortcut(ptr);
  710. ptr = READ_ONCE(shortcut->back_pointer);
  711. slot = shortcut->parent_slot;
  712. }
  713. if (!ptr)
  714. goto not_this_keyring;
  715. node = assoc_array_ptr_to_node(ptr);
  716. slot++;
  717. /* If we've ascended to the root (zero backpointer), we must have just
  718. * finished processing the leftmost branch rather than the root slots -
  719. * so there can't be any more keyrings for us to find.
  720. */
  721. if (node->back_pointer) {
  722. kdebug("ascend %d", slot);
  723. goto ascend_to_node;
  724. }
  725. /* The keyring we're looking at was disqualified or didn't contain a
  726. * matching key.
  727. */
  728. not_this_keyring:
  729. kdebug("not_this_keyring %d", sp);
  730. if (sp <= 0) {
  731. kleave(" = false");
  732. return false;
  733. }
  734. /* Resume the processing of a keyring higher up in the tree */
  735. sp--;
  736. keyring = stack[sp].keyring;
  737. node = stack[sp].node;
  738. slot = stack[sp].slot + 1;
  739. kdebug("ascend to %d [%d]", keyring->serial, slot);
  740. goto ascend_to_node;
  741. /* We found a viable match */
  742. found:
  743. key = key_ref_to_ptr(ctx->result);
  744. key_check(key);
  745. if (!(ctx->flags & KEYRING_SEARCH_NO_UPDATE_TIME)) {
  746. key->last_used_at = ctx->now;
  747. keyring->last_used_at = ctx->now;
  748. while (sp > 0)
  749. stack[--sp].keyring->last_used_at = ctx->now;
  750. }
  751. kleave(" = true");
  752. return true;
  753. }
  754. /**
  755. * keyring_search_rcu - Search a keyring tree for a matching key under RCU
  756. * @keyring_ref: A pointer to the keyring with possession indicator.
  757. * @ctx: The keyring search context.
  758. *
  759. * Search the supplied keyring tree for a key that matches the criteria given.
  760. * The root keyring and any linked keyrings must grant Search permission to the
  761. * caller to be searchable and keys can only be found if they too grant Search
  762. * to the caller. The possession flag on the root keyring pointer controls use
  763. * of the possessor bits in permissions checking of the entire tree. In
  764. * addition, the LSM gets to forbid keyring searches and key matches.
  765. *
  766. * The search is performed as a breadth-then-depth search up to the prescribed
  767. * limit (KEYRING_SEARCH_MAX_DEPTH). The caller must hold the RCU read lock to
  768. * prevent keyrings from being destroyed or rearranged whilst they are being
  769. * searched.
  770. *
  771. * Keys are matched to the type provided and are then filtered by the match
  772. * function, which is given the description to use in any way it sees fit. The
  773. * match function may use any attributes of a key that it wishes to to
  774. * determine the match. Normally the match function from the key type would be
  775. * used.
  776. *
  777. * RCU can be used to prevent the keyring key lists from disappearing without
  778. * the need to take lots of locks.
  779. *
  780. * Returns a pointer to the found key and increments the key usage count if
  781. * successful; -EAGAIN if no matching keys were found, or if expired or revoked
  782. * keys were found; -ENOKEY if only negative keys were found; -ENOTDIR if the
  783. * specified keyring wasn't a keyring.
  784. *
  785. * In the case of a successful return, the possession attribute from
  786. * @keyring_ref is propagated to the returned key reference.
  787. */
  788. key_ref_t keyring_search_rcu(key_ref_t keyring_ref,
  789. struct keyring_search_context *ctx)
  790. {
  791. struct key *keyring;
  792. long err;
  793. ctx->iterator = keyring_search_iterator;
  794. ctx->possessed = is_key_possessed(keyring_ref);
  795. ctx->result = ERR_PTR(-EAGAIN);
  796. keyring = key_ref_to_ptr(keyring_ref);
  797. key_check(keyring);
  798. if (keyring->type != &key_type_keyring)
  799. return ERR_PTR(-ENOTDIR);
  800. if (!(ctx->flags & KEYRING_SEARCH_NO_CHECK_PERM)) {
  801. err = key_task_permission(keyring_ref, ctx->cred, KEY_NEED_SEARCH);
  802. if (err < 0)
  803. return ERR_PTR(err);
  804. }
  805. ctx->now = ktime_get_real_seconds();
  806. if (search_nested_keyrings(keyring, ctx))
  807. __key_get(key_ref_to_ptr(ctx->result));
  808. return ctx->result;
  809. }
  810. /**
  811. * keyring_search - Search the supplied keyring tree for a matching key
  812. * @keyring: The root of the keyring tree to be searched.
  813. * @type: The type of keyring we want to find.
  814. * @description: The name of the keyring we want to find.
  815. * @recurse: True to search the children of @keyring also
  816. *
  817. * As keyring_search_rcu() above, but using the current task's credentials and
  818. * type's default matching function and preferred search method.
  819. */
  820. key_ref_t keyring_search(key_ref_t keyring,
  821. struct key_type *type,
  822. const char *description,
  823. bool recurse)
  824. {
  825. struct keyring_search_context ctx = {
  826. .index_key.type = type,
  827. .index_key.description = description,
  828. .index_key.desc_len = strlen(description),
  829. .cred = current_cred(),
  830. .match_data.cmp = key_default_cmp,
  831. .match_data.raw_data = description,
  832. .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT,
  833. .flags = KEYRING_SEARCH_DO_STATE_CHECK,
  834. };
  835. key_ref_t key;
  836. int ret;
  837. if (recurse)
  838. ctx.flags |= KEYRING_SEARCH_RECURSE;
  839. if (type->match_preparse) {
  840. ret = type->match_preparse(&ctx.match_data);
  841. if (ret < 0)
  842. return ERR_PTR(ret);
  843. }
  844. rcu_read_lock();
  845. key = keyring_search_rcu(keyring, &ctx);
  846. rcu_read_unlock();
  847. if (type->match_free)
  848. type->match_free(&ctx.match_data);
  849. return key;
  850. }
  851. EXPORT_SYMBOL(keyring_search);
  852. static struct key_restriction *keyring_restriction_alloc(
  853. key_restrict_link_func_t check)
  854. {
  855. struct key_restriction *keyres =
  856. kzalloc(sizeof(struct key_restriction), GFP_KERNEL);
  857. if (!keyres)
  858. return ERR_PTR(-ENOMEM);
  859. keyres->check = check;
  860. return keyres;
  861. }
  862. /*
  863. * Semaphore to serialise restriction setup to prevent reference count
  864. * cycles through restriction key pointers.
  865. */
  866. static DECLARE_RWSEM(keyring_serialise_restrict_sem);
  867. /*
  868. * Check for restriction cycles that would prevent keyring garbage collection.
  869. * keyring_serialise_restrict_sem must be held.
  870. */
  871. static bool keyring_detect_restriction_cycle(const struct key *dest_keyring,
  872. struct key_restriction *keyres)
  873. {
  874. while (keyres && keyres->key &&
  875. keyres->key->type == &key_type_keyring) {
  876. if (keyres->key == dest_keyring)
  877. return true;
  878. keyres = keyres->key->restrict_link;
  879. }
  880. return false;
  881. }
  882. /**
  883. * keyring_restrict - Look up and apply a restriction to a keyring
  884. * @keyring_ref: The keyring to be restricted
  885. * @type: The key type that will provide the restriction checker.
  886. * @restriction: The restriction options to apply to the keyring
  887. *
  888. * Look up a keyring and apply a restriction to it. The restriction is managed
  889. * by the specific key type, but can be configured by the options specified in
  890. * the restriction string.
  891. */
  892. int keyring_restrict(key_ref_t keyring_ref, const char *type,
  893. const char *restriction)
  894. {
  895. struct key *keyring;
  896. struct key_type *restrict_type = NULL;
  897. struct key_restriction *restrict_link;
  898. int ret = 0;
  899. keyring = key_ref_to_ptr(keyring_ref);
  900. key_check(keyring);
  901. if (keyring->type != &key_type_keyring)
  902. return -ENOTDIR;
  903. if (!type) {
  904. restrict_link = keyring_restriction_alloc(restrict_link_reject);
  905. } else {
  906. restrict_type = key_type_lookup(type);
  907. if (IS_ERR(restrict_type))
  908. return PTR_ERR(restrict_type);
  909. if (!restrict_type->lookup_restriction) {
  910. ret = -ENOENT;
  911. goto error;
  912. }
  913. restrict_link = restrict_type->lookup_restriction(restriction);
  914. }
  915. if (IS_ERR(restrict_link)) {
  916. ret = PTR_ERR(restrict_link);
  917. goto error;
  918. }
  919. down_write(&keyring->sem);
  920. down_write(&keyring_serialise_restrict_sem);
  921. if (keyring->restrict_link) {
  922. ret = -EEXIST;
  923. } else if (keyring_detect_restriction_cycle(keyring, restrict_link)) {
  924. ret = -EDEADLK;
  925. } else {
  926. keyring->restrict_link = restrict_link;
  927. notify_key(keyring, NOTIFY_KEY_SETATTR, 0);
  928. }
  929. up_write(&keyring_serialise_restrict_sem);
  930. up_write(&keyring->sem);
  931. if (ret < 0) {
  932. key_put(restrict_link->key);
  933. kfree(restrict_link);
  934. }
  935. error:
  936. if (restrict_type)
  937. key_type_put(restrict_type);
  938. return ret;
  939. }
  940. EXPORT_SYMBOL(keyring_restrict);
  941. /*
  942. * Search the given keyring for a key that might be updated.
  943. *
  944. * The caller must guarantee that the keyring is a keyring and that the
  945. * permission is granted to modify the keyring as no check is made here. The
  946. * caller must also hold a lock on the keyring semaphore.
  947. *
  948. * Returns a pointer to the found key with usage count incremented if
  949. * successful and returns NULL if not found. Revoked and invalidated keys are
  950. * skipped over.
  951. *
  952. * If successful, the possession indicator is propagated from the keyring ref
  953. * to the returned key reference.
  954. */
  955. key_ref_t find_key_to_update(key_ref_t keyring_ref,
  956. const struct keyring_index_key *index_key)
  957. {
  958. struct key *keyring, *key;
  959. const void *object;
  960. keyring = key_ref_to_ptr(keyring_ref);
  961. kenter("{%d},{%s,%s}",
  962. keyring->serial, index_key->type->name, index_key->description);
  963. object = assoc_array_find(&keyring->keys, &keyring_assoc_array_ops,
  964. index_key);
  965. if (object)
  966. goto found;
  967. kleave(" = NULL");
  968. return NULL;
  969. found:
  970. key = keyring_ptr_to_key(object);
  971. if (key->flags & ((1 << KEY_FLAG_INVALIDATED) |
  972. (1 << KEY_FLAG_REVOKED))) {
  973. kleave(" = NULL [x]");
  974. return NULL;
  975. }
  976. __key_get(key);
  977. kleave(" = {%d}", key->serial);
  978. return make_key_ref(key, is_key_possessed(keyring_ref));
  979. }
  980. /*
  981. * Find a keyring with the specified name.
  982. *
  983. * Only keyrings that have nonzero refcount, are not revoked, and are owned by a
  984. * user in the current user namespace are considered. If @uid_keyring is %true,
  985. * the keyring additionally must have been allocated as a user or user session
  986. * keyring; otherwise, it must grant Search permission directly to the caller.
  987. *
  988. * Returns a pointer to the keyring with the keyring's refcount having being
  989. * incremented on success. -ENOKEY is returned if a key could not be found.
  990. */
  991. struct key *find_keyring_by_name(const char *name, bool uid_keyring)
  992. {
  993. struct user_namespace *ns = current_user_ns();
  994. struct key *keyring;
  995. if (!name)
  996. return ERR_PTR(-EINVAL);
  997. read_lock(&keyring_name_lock);
  998. /* Search this hash bucket for a keyring with a matching name that
  999. * grants Search permission and that hasn't been revoked
  1000. */
  1001. list_for_each_entry(keyring, &ns->keyring_name_list, name_link) {
  1002. if (!kuid_has_mapping(ns, keyring->user->uid))
  1003. continue;
  1004. if (test_bit(KEY_FLAG_REVOKED, &keyring->flags))
  1005. continue;
  1006. if (strcmp(keyring->description, name) != 0)
  1007. continue;
  1008. if (uid_keyring) {
  1009. if (!test_bit(KEY_FLAG_UID_KEYRING,
  1010. &keyring->flags))
  1011. continue;
  1012. } else {
  1013. if (key_permission(make_key_ref(keyring, 0),
  1014. KEY_NEED_SEARCH) < 0)
  1015. continue;
  1016. }
  1017. /* we've got a match but we might end up racing with
  1018. * key_cleanup() if the keyring is currently 'dead'
  1019. * (ie. it has a zero usage count) */
  1020. if (!refcount_inc_not_zero(&keyring->usage))
  1021. continue;
  1022. keyring->last_used_at = ktime_get_real_seconds();
  1023. goto out;
  1024. }
  1025. keyring = ERR_PTR(-ENOKEY);
  1026. out:
  1027. read_unlock(&keyring_name_lock);
  1028. return keyring;
  1029. }
  1030. static int keyring_detect_cycle_iterator(const void *object,
  1031. void *iterator_data)
  1032. {
  1033. struct keyring_search_context *ctx = iterator_data;
  1034. const struct key *key = keyring_ptr_to_key(object);
  1035. kenter("{%d}", key->serial);
  1036. /* We might get a keyring with matching index-key that is nonetheless a
  1037. * different keyring. */
  1038. if (key != ctx->match_data.raw_data)
  1039. return 0;
  1040. ctx->result = ERR_PTR(-EDEADLK);
  1041. return 1;
  1042. }
  1043. /*
  1044. * See if a cycle will will be created by inserting acyclic tree B in acyclic
  1045. * tree A at the topmost level (ie: as a direct child of A).
  1046. *
  1047. * Since we are adding B to A at the top level, checking for cycles should just
  1048. * be a matter of seeing if node A is somewhere in tree B.
  1049. */
  1050. static int keyring_detect_cycle(struct key *A, struct key *B)
  1051. {
  1052. struct keyring_search_context ctx = {
  1053. .index_key = A->index_key,
  1054. .match_data.raw_data = A,
  1055. .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT,
  1056. .iterator = keyring_detect_cycle_iterator,
  1057. .flags = (KEYRING_SEARCH_NO_STATE_CHECK |
  1058. KEYRING_SEARCH_NO_UPDATE_TIME |
  1059. KEYRING_SEARCH_NO_CHECK_PERM |
  1060. KEYRING_SEARCH_DETECT_TOO_DEEP |
  1061. KEYRING_SEARCH_RECURSE),
  1062. };
  1063. rcu_read_lock();
  1064. search_nested_keyrings(B, &ctx);
  1065. rcu_read_unlock();
  1066. return PTR_ERR(ctx.result) == -EAGAIN ? 0 : PTR_ERR(ctx.result);
  1067. }
  1068. /*
  1069. * Lock keyring for link.
  1070. */
  1071. int __key_link_lock(struct key *keyring,
  1072. const struct keyring_index_key *index_key)
  1073. __acquires(&keyring->sem)
  1074. __acquires(&keyring_serialise_link_lock)
  1075. {
  1076. if (keyring->type != &key_type_keyring)
  1077. return -ENOTDIR;
  1078. down_write(&keyring->sem);
  1079. /* Serialise link/link calls to prevent parallel calls causing a cycle
  1080. * when linking two keyring in opposite orders.
  1081. */
  1082. if (index_key->type == &key_type_keyring)
  1083. mutex_lock(&keyring_serialise_link_lock);
  1084. return 0;
  1085. }
  1086. /*
  1087. * Lock keyrings for move (link/unlink combination).
  1088. */
  1089. int __key_move_lock(struct key *l_keyring, struct key *u_keyring,
  1090. const struct keyring_index_key *index_key)
  1091. __acquires(&l_keyring->sem)
  1092. __acquires(&u_keyring->sem)
  1093. __acquires(&keyring_serialise_link_lock)
  1094. {
  1095. if (l_keyring->type != &key_type_keyring ||
  1096. u_keyring->type != &key_type_keyring)
  1097. return -ENOTDIR;
  1098. /* We have to be very careful here to take the keyring locks in the
  1099. * right order, lest we open ourselves to deadlocking against another
  1100. * move operation.
  1101. */
  1102. if (l_keyring < u_keyring) {
  1103. down_write(&l_keyring->sem);
  1104. down_write_nested(&u_keyring->sem, 1);
  1105. } else {
  1106. down_write(&u_keyring->sem);
  1107. down_write_nested(&l_keyring->sem, 1);
  1108. }
  1109. /* Serialise link/link calls to prevent parallel calls causing a cycle
  1110. * when linking two keyring in opposite orders.
  1111. */
  1112. if (index_key->type == &key_type_keyring)
  1113. mutex_lock(&keyring_serialise_link_lock);
  1114. return 0;
  1115. }
  1116. /*
  1117. * Preallocate memory so that a key can be linked into to a keyring.
  1118. */
  1119. int __key_link_begin(struct key *keyring,
  1120. const struct keyring_index_key *index_key,
  1121. struct assoc_array_edit **_edit)
  1122. {
  1123. struct assoc_array_edit *edit;
  1124. int ret;
  1125. kenter("%d,%s,%s,",
  1126. keyring->serial, index_key->type->name, index_key->description);
  1127. BUG_ON(index_key->desc_len == 0);
  1128. BUG_ON(*_edit != NULL);
  1129. *_edit = NULL;
  1130. ret = -EKEYREVOKED;
  1131. if (test_bit(KEY_FLAG_REVOKED, &keyring->flags))
  1132. goto error;
  1133. /* Create an edit script that will insert/replace the key in the
  1134. * keyring tree.
  1135. */
  1136. edit = assoc_array_insert(&keyring->keys,
  1137. &keyring_assoc_array_ops,
  1138. index_key,
  1139. NULL);
  1140. if (IS_ERR(edit)) {
  1141. ret = PTR_ERR(edit);
  1142. goto error;
  1143. }
  1144. /* If we're not replacing a link in-place then we're going to need some
  1145. * extra quota.
  1146. */
  1147. if (!edit->dead_leaf) {
  1148. ret = key_payload_reserve(keyring,
  1149. keyring->datalen + KEYQUOTA_LINK_BYTES);
  1150. if (ret < 0)
  1151. goto error_cancel;
  1152. }
  1153. *_edit = edit;
  1154. kleave(" = 0");
  1155. return 0;
  1156. error_cancel:
  1157. assoc_array_cancel_edit(edit);
  1158. error:
  1159. kleave(" = %d", ret);
  1160. return ret;
  1161. }
  1162. /*
  1163. * Check already instantiated keys aren't going to be a problem.
  1164. *
  1165. * The caller must have called __key_link_begin(). Don't need to call this for
  1166. * keys that were created since __key_link_begin() was called.
  1167. */
  1168. int __key_link_check_live_key(struct key *keyring, struct key *key)
  1169. {
  1170. if (key->type == &key_type_keyring)
  1171. /* check that we aren't going to create a cycle by linking one
  1172. * keyring to another */
  1173. return keyring_detect_cycle(keyring, key);
  1174. return 0;
  1175. }
  1176. /*
  1177. * Link a key into to a keyring.
  1178. *
  1179. * Must be called with __key_link_begin() having being called. Discards any
  1180. * already extant link to matching key if there is one, so that each keyring
  1181. * holds at most one link to any given key of a particular type+description
  1182. * combination.
  1183. */
  1184. void __key_link(struct key *keyring, struct key *key,
  1185. struct assoc_array_edit **_edit)
  1186. {
  1187. __key_get(key);
  1188. assoc_array_insert_set_object(*_edit, keyring_key_to_ptr(key));
  1189. assoc_array_apply_edit(*_edit);
  1190. *_edit = NULL;
  1191. notify_key(keyring, NOTIFY_KEY_LINKED, key_serial(key));
  1192. }
  1193. /*
  1194. * Finish linking a key into to a keyring.
  1195. *
  1196. * Must be called with __key_link_begin() having being called.
  1197. */
  1198. void __key_link_end(struct key *keyring,
  1199. const struct keyring_index_key *index_key,
  1200. struct assoc_array_edit *edit)
  1201. __releases(&keyring->sem)
  1202. __releases(&keyring_serialise_link_lock)
  1203. {
  1204. BUG_ON(index_key->type == NULL);
  1205. kenter("%d,%s,", keyring->serial, index_key->type->name);
  1206. if (edit) {
  1207. if (!edit->dead_leaf) {
  1208. key_payload_reserve(keyring,
  1209. keyring->datalen - KEYQUOTA_LINK_BYTES);
  1210. }
  1211. assoc_array_cancel_edit(edit);
  1212. }
  1213. up_write(&keyring->sem);
  1214. if (index_key->type == &key_type_keyring)
  1215. mutex_unlock(&keyring_serialise_link_lock);
  1216. }
  1217. /*
  1218. * Check addition of keys to restricted keyrings.
  1219. */
  1220. static int __key_link_check_restriction(struct key *keyring, struct key *key)
  1221. {
  1222. if (!keyring->restrict_link || !keyring->restrict_link->check)
  1223. return 0;
  1224. return keyring->restrict_link->check(keyring, key->type, &key->payload,
  1225. keyring->restrict_link->key);
  1226. }
  1227. /**
  1228. * key_link - Link a key to a keyring
  1229. * @keyring: The keyring to make the link in.
  1230. * @key: The key to link to.
  1231. *
  1232. * Make a link in a keyring to a key, such that the keyring holds a reference
  1233. * on that key and the key can potentially be found by searching that keyring.
  1234. *
  1235. * This function will write-lock the keyring's semaphore and will consume some
  1236. * of the user's key data quota to hold the link.
  1237. *
  1238. * Returns 0 if successful, -ENOTDIR if the keyring isn't a keyring,
  1239. * -EKEYREVOKED if the keyring has been revoked, -ENFILE if the keyring is
  1240. * full, -EDQUOT if there is insufficient key data quota remaining to add
  1241. * another link or -ENOMEM if there's insufficient memory.
  1242. *
  1243. * It is assumed that the caller has checked that it is permitted for a link to
  1244. * be made (the keyring should have Write permission and the key Link
  1245. * permission).
  1246. */
  1247. int key_link(struct key *keyring, struct key *key)
  1248. {
  1249. struct assoc_array_edit *edit = NULL;
  1250. int ret;
  1251. kenter("{%d,%d}", keyring->serial, refcount_read(&keyring->usage));
  1252. key_check(keyring);
  1253. key_check(key);
  1254. ret = __key_link_lock(keyring, &key->index_key);
  1255. if (ret < 0)
  1256. goto error;
  1257. ret = __key_link_begin(keyring, &key->index_key, &edit);
  1258. if (ret < 0)
  1259. goto error_end;
  1260. kdebug("begun {%d,%d}", keyring->serial, refcount_read(&keyring->usage));
  1261. ret = __key_link_check_restriction(keyring, key);
  1262. if (ret == 0)
  1263. ret = __key_link_check_live_key(keyring, key);
  1264. if (ret == 0)
  1265. __key_link(keyring, key, &edit);
  1266. error_end:
  1267. __key_link_end(keyring, &key->index_key, edit);
  1268. error:
  1269. kleave(" = %d {%d,%d}", ret, keyring->serial, refcount_read(&keyring->usage));
  1270. return ret;
  1271. }
  1272. EXPORT_SYMBOL(key_link);
  1273. /*
  1274. * Lock a keyring for unlink.
  1275. */
  1276. static int __key_unlink_lock(struct key *keyring)
  1277. __acquires(&keyring->sem)
  1278. {
  1279. if (keyring->type != &key_type_keyring)
  1280. return -ENOTDIR;
  1281. down_write(&keyring->sem);
  1282. return 0;
  1283. }
  1284. /*
  1285. * Begin the process of unlinking a key from a keyring.
  1286. */
  1287. static int __key_unlink_begin(struct key *keyring, struct key *key,
  1288. struct assoc_array_edit **_edit)
  1289. {
  1290. struct assoc_array_edit *edit;
  1291. BUG_ON(*_edit != NULL);
  1292. edit = assoc_array_delete(&keyring->keys, &keyring_assoc_array_ops,
  1293. &key->index_key);
  1294. if (IS_ERR(edit))
  1295. return PTR_ERR(edit);
  1296. if (!edit)
  1297. return -ENOENT;
  1298. *_edit = edit;
  1299. return 0;
  1300. }
  1301. /*
  1302. * Apply an unlink change.
  1303. */
  1304. static void __key_unlink(struct key *keyring, struct key *key,
  1305. struct assoc_array_edit **_edit)
  1306. {
  1307. assoc_array_apply_edit(*_edit);
  1308. notify_key(keyring, NOTIFY_KEY_UNLINKED, key_serial(key));
  1309. *_edit = NULL;
  1310. key_payload_reserve(keyring, keyring->datalen - KEYQUOTA_LINK_BYTES);
  1311. }
  1312. /*
  1313. * Finish unlinking a key from to a keyring.
  1314. */
  1315. static void __key_unlink_end(struct key *keyring,
  1316. struct key *key,
  1317. struct assoc_array_edit *edit)
  1318. __releases(&keyring->sem)
  1319. {
  1320. if (edit)
  1321. assoc_array_cancel_edit(edit);
  1322. up_write(&keyring->sem);
  1323. }
  1324. /**
  1325. * key_unlink - Unlink the first link to a key from a keyring.
  1326. * @keyring: The keyring to remove the link from.
  1327. * @key: The key the link is to.
  1328. *
  1329. * Remove a link from a keyring to a key.
  1330. *
  1331. * This function will write-lock the keyring's semaphore.
  1332. *
  1333. * Returns 0 if successful, -ENOTDIR if the keyring isn't a keyring, -ENOENT if
  1334. * the key isn't linked to by the keyring or -ENOMEM if there's insufficient
  1335. * memory.
  1336. *
  1337. * It is assumed that the caller has checked that it is permitted for a link to
  1338. * be removed (the keyring should have Write permission; no permissions are
  1339. * required on the key).
  1340. */
  1341. int key_unlink(struct key *keyring, struct key *key)
  1342. {
  1343. struct assoc_array_edit *edit = NULL;
  1344. int ret;
  1345. key_check(keyring);
  1346. key_check(key);
  1347. ret = __key_unlink_lock(keyring);
  1348. if (ret < 0)
  1349. return ret;
  1350. ret = __key_unlink_begin(keyring, key, &edit);
  1351. if (ret == 0)
  1352. __key_unlink(keyring, key, &edit);
  1353. __key_unlink_end(keyring, key, edit);
  1354. return ret;
  1355. }
  1356. EXPORT_SYMBOL(key_unlink);
  1357. /**
  1358. * key_move - Move a key from one keyring to another
  1359. * @key: The key to move
  1360. * @from_keyring: The keyring to remove the link from.
  1361. * @to_keyring: The keyring to make the link in.
  1362. * @flags: Qualifying flags, such as KEYCTL_MOVE_EXCL.
  1363. *
  1364. * Make a link in @to_keyring to a key, such that the keyring holds a reference
  1365. * on that key and the key can potentially be found by searching that keyring
  1366. * whilst simultaneously removing a link to the key from @from_keyring.
  1367. *
  1368. * This function will write-lock both keyring's semaphores and will consume
  1369. * some of the user's key data quota to hold the link on @to_keyring.
  1370. *
  1371. * Returns 0 if successful, -ENOTDIR if either keyring isn't a keyring,
  1372. * -EKEYREVOKED if either keyring has been revoked, -ENFILE if the second
  1373. * keyring is full, -EDQUOT if there is insufficient key data quota remaining
  1374. * to add another link or -ENOMEM if there's insufficient memory. If
  1375. * KEYCTL_MOVE_EXCL is set, then -EEXIST will be returned if there's already a
  1376. * matching key in @to_keyring.
  1377. *
  1378. * It is assumed that the caller has checked that it is permitted for a link to
  1379. * be made (the keyring should have Write permission and the key Link
  1380. * permission).
  1381. */
  1382. int key_move(struct key *key,
  1383. struct key *from_keyring,
  1384. struct key *to_keyring,
  1385. unsigned int flags)
  1386. {
  1387. struct assoc_array_edit *from_edit = NULL, *to_edit = NULL;
  1388. int ret;
  1389. kenter("%d,%d,%d", key->serial, from_keyring->serial, to_keyring->serial);
  1390. if (from_keyring == to_keyring)
  1391. return 0;
  1392. key_check(key);
  1393. key_check(from_keyring);
  1394. key_check(to_keyring);
  1395. ret = __key_move_lock(from_keyring, to_keyring, &key->index_key);
  1396. if (ret < 0)
  1397. goto out;
  1398. ret = __key_unlink_begin(from_keyring, key, &from_edit);
  1399. if (ret < 0)
  1400. goto error;
  1401. ret = __key_link_begin(to_keyring, &key->index_key, &to_edit);
  1402. if (ret < 0)
  1403. goto error;
  1404. ret = -EEXIST;
  1405. if (to_edit->dead_leaf && (flags & KEYCTL_MOVE_EXCL))
  1406. goto error;
  1407. ret = __key_link_check_restriction(to_keyring, key);
  1408. if (ret < 0)
  1409. goto error;
  1410. ret = __key_link_check_live_key(to_keyring, key);
  1411. if (ret < 0)
  1412. goto error;
  1413. __key_unlink(from_keyring, key, &from_edit);
  1414. __key_link(to_keyring, key, &to_edit);
  1415. error:
  1416. __key_link_end(to_keyring, &key->index_key, to_edit);
  1417. __key_unlink_end(from_keyring, key, from_edit);
  1418. out:
  1419. kleave(" = %d", ret);
  1420. return ret;
  1421. }
  1422. EXPORT_SYMBOL(key_move);
  1423. /**
  1424. * keyring_clear - Clear a keyring
  1425. * @keyring: The keyring to clear.
  1426. *
  1427. * Clear the contents of the specified keyring.
  1428. *
  1429. * Returns 0 if successful or -ENOTDIR if the keyring isn't a keyring.
  1430. */
  1431. int keyring_clear(struct key *keyring)
  1432. {
  1433. struct assoc_array_edit *edit;
  1434. int ret;
  1435. if (keyring->type != &key_type_keyring)
  1436. return -ENOTDIR;
  1437. down_write(&keyring->sem);
  1438. edit = assoc_array_clear(&keyring->keys, &keyring_assoc_array_ops);
  1439. if (IS_ERR(edit)) {
  1440. ret = PTR_ERR(edit);
  1441. } else {
  1442. if (edit)
  1443. assoc_array_apply_edit(edit);
  1444. notify_key(keyring, NOTIFY_KEY_CLEARED, 0);
  1445. key_payload_reserve(keyring, 0);
  1446. ret = 0;
  1447. }
  1448. up_write(&keyring->sem);
  1449. return ret;
  1450. }
  1451. EXPORT_SYMBOL(keyring_clear);
  1452. /*
  1453. * Dispose of the links from a revoked keyring.
  1454. *
  1455. * This is called with the key sem write-locked.
  1456. */
  1457. static void keyring_revoke(struct key *keyring)
  1458. {
  1459. struct assoc_array_edit *edit;
  1460. edit = assoc_array_clear(&keyring->keys, &keyring_assoc_array_ops);
  1461. if (!IS_ERR(edit)) {
  1462. if (edit)
  1463. assoc_array_apply_edit(edit);
  1464. key_payload_reserve(keyring, 0);
  1465. }
  1466. }
  1467. static bool keyring_gc_select_iterator(void *object, void *iterator_data)
  1468. {
  1469. struct key *key = keyring_ptr_to_key(object);
  1470. time64_t *limit = iterator_data;
  1471. if (key_is_dead(key, *limit))
  1472. return false;
  1473. key_get(key);
  1474. return true;
  1475. }
  1476. static int keyring_gc_check_iterator(const void *object, void *iterator_data)
  1477. {
  1478. const struct key *key = keyring_ptr_to_key(object);
  1479. time64_t *limit = iterator_data;
  1480. key_check(key);
  1481. return key_is_dead(key, *limit);
  1482. }
  1483. /*
  1484. * Garbage collect pointers from a keyring.
  1485. *
  1486. * Not called with any locks held. The keyring's key struct will not be
  1487. * deallocated under us as only our caller may deallocate it.
  1488. */
  1489. void keyring_gc(struct key *keyring, time64_t limit)
  1490. {
  1491. int result;
  1492. kenter("%x{%s}", keyring->serial, keyring->description ?: "");
  1493. if (keyring->flags & ((1 << KEY_FLAG_INVALIDATED) |
  1494. (1 << KEY_FLAG_REVOKED)))
  1495. goto dont_gc;
  1496. /* scan the keyring looking for dead keys */
  1497. rcu_read_lock();
  1498. result = assoc_array_iterate(&keyring->keys,
  1499. keyring_gc_check_iterator, &limit);
  1500. rcu_read_unlock();
  1501. if (result == true)
  1502. goto do_gc;
  1503. dont_gc:
  1504. kleave(" [no gc]");
  1505. return;
  1506. do_gc:
  1507. down_write(&keyring->sem);
  1508. assoc_array_gc(&keyring->keys, &keyring_assoc_array_ops,
  1509. keyring_gc_select_iterator, &limit);
  1510. up_write(&keyring->sem);
  1511. kleave(" [gc]");
  1512. }
  1513. /*
  1514. * Garbage collect restriction pointers from a keyring.
  1515. *
  1516. * Keyring restrictions are associated with a key type, and must be cleaned
  1517. * up if the key type is unregistered. The restriction is altered to always
  1518. * reject additional keys so a keyring cannot be opened up by unregistering
  1519. * a key type.
  1520. *
  1521. * Not called with any keyring locks held. The keyring's key struct will not
  1522. * be deallocated under us as only our caller may deallocate it.
  1523. *
  1524. * The caller is required to hold key_types_sem and dead_type->sem. This is
  1525. * fulfilled by key_gc_keytype() holding the locks on behalf of
  1526. * key_garbage_collector(), which it invokes on a workqueue.
  1527. */
  1528. void keyring_restriction_gc(struct key *keyring, struct key_type *dead_type)
  1529. {
  1530. struct key_restriction *keyres;
  1531. kenter("%x{%s}", keyring->serial, keyring->description ?: "");
  1532. /*
  1533. * keyring->restrict_link is only assigned at key allocation time
  1534. * or with the key type locked, so the only values that could be
  1535. * concurrently assigned to keyring->restrict_link are for key
  1536. * types other than dead_type. Given this, it's ok to check
  1537. * the key type before acquiring keyring->sem.
  1538. */
  1539. if (!dead_type || !keyring->restrict_link ||
  1540. keyring->restrict_link->keytype != dead_type) {
  1541. kleave(" [no restriction gc]");
  1542. return;
  1543. }
  1544. /* Lock the keyring to ensure that a link is not in progress */
  1545. down_write(&keyring->sem);
  1546. keyres = keyring->restrict_link;
  1547. keyres->check = restrict_link_reject;
  1548. key_put(keyres->key);
  1549. keyres->key = NULL;
  1550. keyres->keytype = NULL;
  1551. up_write(&keyring->sem);
  1552. kleave(" [restriction gc]");
  1553. }