keyring.c 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428
  1. /* Keyring handling
  2. *
  3. * Copyright (C) 2004-2005, 2008, 2013 Red Hat, Inc. All Rights Reserved.
  4. * Written by David Howells (dhowells@redhat.com)
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU General Public License
  8. * as published by the Free Software Foundation; either version
  9. * 2 of the License, or (at your option) any later version.
  10. */
  11. #include <linux/module.h>
  12. #include <linux/init.h>
  13. #include <linux/sched.h>
  14. #include <linux/slab.h>
  15. #include <linux/security.h>
  16. #include <linux/seq_file.h>
  17. #include <linux/err.h>
  18. #include <keys/keyring-type.h>
  19. #include <keys/user-type.h>
  20. #include <linux/assoc_array_priv.h>
  21. #include <linux/uaccess.h>
  22. #include "internal.h"
  23. /*
  24. * When plumbing the depths of the key tree, this sets a hard limit
  25. * set on how deep we're willing to go.
  26. */
  27. #define KEYRING_SEARCH_MAX_DEPTH 6
  28. /*
  29. * We keep all named keyrings in a hash to speed looking them up.
  30. */
  31. #define KEYRING_NAME_HASH_SIZE (1 << 5)
  32. /*
  33. * We mark pointers we pass to the associative array with bit 1 set if
  34. * they're keyrings and clear otherwise.
  35. */
  36. #define KEYRING_PTR_SUBTYPE 0x2UL
  37. static inline bool keyring_ptr_is_keyring(const struct assoc_array_ptr *x)
  38. {
  39. return (unsigned long)x & KEYRING_PTR_SUBTYPE;
  40. }
  41. static inline struct key *keyring_ptr_to_key(const struct assoc_array_ptr *x)
  42. {
  43. void *object = assoc_array_ptr_to_leaf(x);
  44. return (struct key *)((unsigned long)object & ~KEYRING_PTR_SUBTYPE);
  45. }
  46. static inline void *keyring_key_to_ptr(struct key *key)
  47. {
  48. if (key->type == &key_type_keyring)
  49. return (void *)((unsigned long)key | KEYRING_PTR_SUBTYPE);
  50. return key;
  51. }
  52. static struct list_head keyring_name_hash[KEYRING_NAME_HASH_SIZE];
  53. static DEFINE_RWLOCK(keyring_name_lock);
  54. static inline unsigned keyring_hash(const char *desc)
  55. {
  56. unsigned bucket = 0;
  57. for (; *desc; desc++)
  58. bucket += (unsigned char)*desc;
  59. return bucket & (KEYRING_NAME_HASH_SIZE - 1);
  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 DECLARE_RWSEM(keyring_serialise_link_sem);
  92. /*
  93. * Publish the name of a keyring so that it can be found by name (if it has
  94. * one).
  95. */
  96. static void keyring_publish_name(struct key *keyring)
  97. {
  98. int bucket;
  99. if (keyring->description) {
  100. bucket = keyring_hash(keyring->description);
  101. write_lock(&keyring_name_lock);
  102. if (!keyring_name_hash[bucket].next)
  103. INIT_LIST_HEAD(&keyring_name_hash[bucket]);
  104. list_add_tail(&keyring->name_link,
  105. &keyring_name_hash[bucket]);
  106. write_unlock(&keyring_name_lock);
  107. }
  108. }
  109. /*
  110. * Preparse a keyring payload
  111. */
  112. static int keyring_preparse(struct key_preparsed_payload *prep)
  113. {
  114. return prep->datalen != 0 ? -EINVAL : 0;
  115. }
  116. /*
  117. * Free a preparse of a user defined key payload
  118. */
  119. static void keyring_free_preparse(struct key_preparsed_payload *prep)
  120. {
  121. }
  122. /*
  123. * Initialise a keyring.
  124. *
  125. * Returns 0 on success, -EINVAL if given any data.
  126. */
  127. static int keyring_instantiate(struct key *keyring,
  128. struct key_preparsed_payload *prep)
  129. {
  130. assoc_array_init(&keyring->keys);
  131. /* make the keyring available by name if it has one */
  132. keyring_publish_name(keyring);
  133. return 0;
  134. }
  135. /*
  136. * Multiply 64-bits by 32-bits to 96-bits and fold back to 64-bit. Ideally we'd
  137. * fold the carry back too, but that requires inline asm.
  138. */
  139. static u64 mult_64x32_and_fold(u64 x, u32 y)
  140. {
  141. u64 hi = (u64)(u32)(x >> 32) * y;
  142. u64 lo = (u64)(u32)(x) * y;
  143. return lo + ((u64)(u32)hi << 32) + (u32)(hi >> 32);
  144. }
  145. /*
  146. * Hash a key type and description.
  147. */
  148. static unsigned long hash_key_type_and_desc(const struct keyring_index_key *index_key)
  149. {
  150. const unsigned level_shift = ASSOC_ARRAY_LEVEL_STEP;
  151. const unsigned long fan_mask = ASSOC_ARRAY_FAN_MASK;
  152. const char *description = index_key->description;
  153. unsigned long hash, type;
  154. u32 piece;
  155. u64 acc;
  156. int n, desc_len = index_key->desc_len;
  157. type = (unsigned long)index_key->type;
  158. acc = mult_64x32_and_fold(type, desc_len + 13);
  159. acc = mult_64x32_and_fold(acc, 9207);
  160. for (;;) {
  161. n = desc_len;
  162. if (n <= 0)
  163. break;
  164. if (n > 4)
  165. n = 4;
  166. piece = 0;
  167. memcpy(&piece, description, n);
  168. description += n;
  169. desc_len -= n;
  170. acc = mult_64x32_and_fold(acc, piece);
  171. acc = mult_64x32_and_fold(acc, 9207);
  172. }
  173. /* Fold the hash down to 32 bits if need be. */
  174. hash = acc;
  175. if (ASSOC_ARRAY_KEY_CHUNK_SIZE == 32)
  176. hash ^= acc >> 32;
  177. /* Squidge all the keyrings into a separate part of the tree to
  178. * ordinary keys by making sure the lowest level segment in the hash is
  179. * zero for keyrings and non-zero otherwise.
  180. */
  181. if (index_key->type != &key_type_keyring && (hash & fan_mask) == 0)
  182. return hash | (hash >> (ASSOC_ARRAY_KEY_CHUNK_SIZE - level_shift)) | 1;
  183. if (index_key->type == &key_type_keyring && (hash & fan_mask) != 0)
  184. return (hash + (hash << level_shift)) & ~fan_mask;
  185. return hash;
  186. }
  187. /*
  188. * Build the next index key chunk.
  189. *
  190. * On 32-bit systems the index key is laid out as:
  191. *
  192. * 0 4 5 9...
  193. * hash desclen typeptr desc[]
  194. *
  195. * On 64-bit systems:
  196. *
  197. * 0 8 9 17...
  198. * hash desclen typeptr desc[]
  199. *
  200. * We return it one word-sized chunk at a time.
  201. */
  202. static unsigned long keyring_get_key_chunk(const void *data, int level)
  203. {
  204. const struct keyring_index_key *index_key = data;
  205. unsigned long chunk = 0;
  206. long offset = 0;
  207. int desc_len = index_key->desc_len, n = sizeof(chunk);
  208. level /= ASSOC_ARRAY_KEY_CHUNK_SIZE;
  209. switch (level) {
  210. case 0:
  211. return hash_key_type_and_desc(index_key);
  212. case 1:
  213. return ((unsigned long)index_key->type << 8) | desc_len;
  214. case 2:
  215. if (desc_len == 0)
  216. return (u8)((unsigned long)index_key->type >>
  217. (ASSOC_ARRAY_KEY_CHUNK_SIZE - 8));
  218. n--;
  219. offset = 1;
  220. default:
  221. offset += sizeof(chunk) - 1;
  222. offset += (level - 3) * sizeof(chunk);
  223. if (offset >= desc_len)
  224. return 0;
  225. desc_len -= offset;
  226. if (desc_len > n)
  227. desc_len = n;
  228. offset += desc_len;
  229. do {
  230. chunk <<= 8;
  231. chunk |= ((u8*)index_key->description)[--offset];
  232. } while (--desc_len > 0);
  233. if (level == 2) {
  234. chunk <<= 8;
  235. chunk |= (u8)((unsigned long)index_key->type >>
  236. (ASSOC_ARRAY_KEY_CHUNK_SIZE - 8));
  237. }
  238. return chunk;
  239. }
  240. }
  241. static unsigned long keyring_get_object_key_chunk(const void *object, int level)
  242. {
  243. const struct key *key = keyring_ptr_to_key(object);
  244. return keyring_get_key_chunk(&key->index_key, level);
  245. }
  246. static bool keyring_compare_object(const void *object, const void *data)
  247. {
  248. const struct keyring_index_key *index_key = data;
  249. const struct key *key = keyring_ptr_to_key(object);
  250. return key->index_key.type == index_key->type &&
  251. key->index_key.desc_len == index_key->desc_len &&
  252. memcmp(key->index_key.description, index_key->description,
  253. index_key->desc_len) == 0;
  254. }
  255. /*
  256. * Compare the index keys of a pair of objects and determine the bit position
  257. * at which they differ - if they differ.
  258. */
  259. static int keyring_diff_objects(const void *object, const void *data)
  260. {
  261. const struct key *key_a = keyring_ptr_to_key(object);
  262. const struct keyring_index_key *a = &key_a->index_key;
  263. const struct keyring_index_key *b = data;
  264. unsigned long seg_a, seg_b;
  265. int level, i;
  266. level = 0;
  267. seg_a = hash_key_type_and_desc(a);
  268. seg_b = hash_key_type_and_desc(b);
  269. if ((seg_a ^ seg_b) != 0)
  270. goto differ;
  271. /* The number of bits contributed by the hash is controlled by a
  272. * constant in the assoc_array headers. Everything else thereafter we
  273. * can deal with as being machine word-size dependent.
  274. */
  275. level += ASSOC_ARRAY_KEY_CHUNK_SIZE / 8;
  276. seg_a = a->desc_len;
  277. seg_b = b->desc_len;
  278. if ((seg_a ^ seg_b) != 0)
  279. goto differ;
  280. /* The next bit may not work on big endian */
  281. level++;
  282. seg_a = (unsigned long)a->type;
  283. seg_b = (unsigned long)b->type;
  284. if ((seg_a ^ seg_b) != 0)
  285. goto differ;
  286. level += sizeof(unsigned long);
  287. if (a->desc_len == 0)
  288. goto same;
  289. i = 0;
  290. if (((unsigned long)a->description | (unsigned long)b->description) &
  291. (sizeof(unsigned long) - 1)) {
  292. do {
  293. seg_a = *(unsigned long *)(a->description + i);
  294. seg_b = *(unsigned long *)(b->description + i);
  295. if ((seg_a ^ seg_b) != 0)
  296. goto differ_plus_i;
  297. i += sizeof(unsigned long);
  298. } while (i < (a->desc_len & (sizeof(unsigned long) - 1)));
  299. }
  300. for (; i < a->desc_len; i++) {
  301. seg_a = *(unsigned char *)(a->description + i);
  302. seg_b = *(unsigned char *)(b->description + i);
  303. if ((seg_a ^ seg_b) != 0)
  304. goto differ_plus_i;
  305. }
  306. same:
  307. return -1;
  308. differ_plus_i:
  309. level += i;
  310. differ:
  311. i = level * 8 + __ffs(seg_a ^ seg_b);
  312. return i;
  313. }
  314. /*
  315. * Free an object after stripping the keyring flag off of the pointer.
  316. */
  317. static void keyring_free_object(void *object)
  318. {
  319. key_put(keyring_ptr_to_key(object));
  320. }
  321. /*
  322. * Operations for keyring management by the index-tree routines.
  323. */
  324. static const struct assoc_array_ops keyring_assoc_array_ops = {
  325. .get_key_chunk = keyring_get_key_chunk,
  326. .get_object_key_chunk = keyring_get_object_key_chunk,
  327. .compare_object = keyring_compare_object,
  328. .diff_objects = keyring_diff_objects,
  329. .free_object = keyring_free_object,
  330. };
  331. /*
  332. * Clean up a keyring when it is destroyed. Unpublish its name if it had one
  333. * and dispose of its data.
  334. *
  335. * The garbage collector detects the final key_put(), removes the keyring from
  336. * the serial number tree and then does RCU synchronisation before coming here,
  337. * so we shouldn't need to worry about code poking around here with the RCU
  338. * readlock held by this time.
  339. */
  340. static void keyring_destroy(struct key *keyring)
  341. {
  342. if (keyring->description) {
  343. write_lock(&keyring_name_lock);
  344. if (keyring->name_link.next != NULL &&
  345. !list_empty(&keyring->name_link))
  346. list_del(&keyring->name_link);
  347. write_unlock(&keyring_name_lock);
  348. }
  349. assoc_array_destroy(&keyring->keys, &keyring_assoc_array_ops);
  350. }
  351. /*
  352. * Describe a keyring for /proc.
  353. */
  354. static void keyring_describe(const struct key *keyring, struct seq_file *m)
  355. {
  356. if (keyring->description)
  357. seq_puts(m, keyring->description);
  358. else
  359. seq_puts(m, "[anon]");
  360. if (key_is_instantiated(keyring)) {
  361. if (keyring->keys.nr_leaves_on_tree != 0)
  362. seq_printf(m, ": %lu", keyring->keys.nr_leaves_on_tree);
  363. else
  364. seq_puts(m, ": empty");
  365. }
  366. }
  367. struct keyring_read_iterator_context {
  368. size_t qty;
  369. size_t count;
  370. key_serial_t __user *buffer;
  371. };
  372. static int keyring_read_iterator(const void *object, void *data)
  373. {
  374. struct keyring_read_iterator_context *ctx = data;
  375. const struct key *key = keyring_ptr_to_key(object);
  376. int ret;
  377. kenter("{%s,%d},,{%zu/%zu}",
  378. key->type->name, key->serial, ctx->count, ctx->qty);
  379. if (ctx->count >= ctx->qty)
  380. return 1;
  381. ret = put_user(key->serial, ctx->buffer);
  382. if (ret < 0)
  383. return ret;
  384. ctx->buffer++;
  385. ctx->count += sizeof(key->serial);
  386. return 0;
  387. }
  388. /*
  389. * Read a list of key IDs from the keyring's contents in binary form
  390. *
  391. * The keyring's semaphore is read-locked by the caller. This prevents someone
  392. * from modifying it under us - which could cause us to read key IDs multiple
  393. * times.
  394. */
  395. static long keyring_read(const struct key *keyring,
  396. char __user *buffer, size_t buflen)
  397. {
  398. struct keyring_read_iterator_context ctx;
  399. unsigned long nr_keys;
  400. int ret;
  401. kenter("{%d},,%zu", key_serial(keyring), buflen);
  402. if (buflen & (sizeof(key_serial_t) - 1))
  403. return -EINVAL;
  404. nr_keys = keyring->keys.nr_leaves_on_tree;
  405. if (nr_keys == 0)
  406. return 0;
  407. /* Calculate how much data we could return */
  408. ctx.qty = nr_keys * sizeof(key_serial_t);
  409. if (!buffer || !buflen)
  410. return ctx.qty;
  411. if (buflen > ctx.qty)
  412. ctx.qty = buflen;
  413. /* Copy the IDs of the subscribed keys into the buffer */
  414. ctx.buffer = (key_serial_t __user *)buffer;
  415. ctx.count = 0;
  416. ret = assoc_array_iterate(&keyring->keys, keyring_read_iterator, &ctx);
  417. if (ret < 0) {
  418. kleave(" = %d [iterate]", ret);
  419. return ret;
  420. }
  421. kleave(" = %zu [ok]", ctx.count);
  422. return ctx.count;
  423. }
  424. /*
  425. * Allocate a keyring and link into the destination keyring.
  426. */
  427. struct key *keyring_alloc(const char *description, kuid_t uid, kgid_t gid,
  428. const struct cred *cred, key_perm_t perm,
  429. unsigned long flags,
  430. int (*restrict_link)(struct key *,
  431. const struct key_type *,
  432. const union key_payload *),
  433. struct key *dest)
  434. {
  435. struct key *keyring;
  436. int ret;
  437. keyring = key_alloc(&key_type_keyring, description,
  438. uid, gid, cred, perm, flags, restrict_link);
  439. if (!IS_ERR(keyring)) {
  440. ret = key_instantiate_and_link(keyring, NULL, 0, dest, NULL);
  441. if (ret < 0) {
  442. key_put(keyring);
  443. keyring = ERR_PTR(ret);
  444. }
  445. }
  446. return keyring;
  447. }
  448. EXPORT_SYMBOL(keyring_alloc);
  449. /**
  450. * restrict_link_reject - Give -EPERM to restrict link
  451. * @keyring: The keyring being added to.
  452. * @type: The type of key being added.
  453. * @payload: The payload of the key intended to be added.
  454. *
  455. * Reject the addition of any links to a keyring. It can be overridden by
  456. * passing KEY_ALLOC_BYPASS_RESTRICTION to key_instantiate_and_link() when
  457. * adding a key to a keyring.
  458. *
  459. * This is meant to be passed as the restrict_link parameter to
  460. * keyring_alloc().
  461. */
  462. int restrict_link_reject(struct key *keyring,
  463. const struct key_type *type,
  464. const union key_payload *payload)
  465. {
  466. return -EPERM;
  467. }
  468. /*
  469. * By default, we keys found by getting an exact match on their descriptions.
  470. */
  471. bool key_default_cmp(const struct key *key,
  472. const struct key_match_data *match_data)
  473. {
  474. return strcmp(key->description, match_data->raw_data) == 0;
  475. }
  476. /*
  477. * Iteration function to consider each key found.
  478. */
  479. static int keyring_search_iterator(const void *object, void *iterator_data)
  480. {
  481. struct keyring_search_context *ctx = iterator_data;
  482. const struct key *key = keyring_ptr_to_key(object);
  483. unsigned long kflags = key->flags;
  484. kenter("{%d}", key->serial);
  485. /* ignore keys not of this type */
  486. if (key->type != ctx->index_key.type) {
  487. kleave(" = 0 [!type]");
  488. return 0;
  489. }
  490. /* skip invalidated, revoked and expired keys */
  491. if (ctx->flags & KEYRING_SEARCH_DO_STATE_CHECK) {
  492. if (kflags & ((1 << KEY_FLAG_INVALIDATED) |
  493. (1 << KEY_FLAG_REVOKED))) {
  494. ctx->result = ERR_PTR(-EKEYREVOKED);
  495. kleave(" = %d [invrev]", ctx->skipped_ret);
  496. goto skipped;
  497. }
  498. if (key->expiry && ctx->now.tv_sec >= key->expiry) {
  499. if (!(ctx->flags & KEYRING_SEARCH_SKIP_EXPIRED))
  500. ctx->result = ERR_PTR(-EKEYEXPIRED);
  501. kleave(" = %d [expire]", ctx->skipped_ret);
  502. goto skipped;
  503. }
  504. }
  505. /* keys that don't match */
  506. if (!ctx->match_data.cmp(key, &ctx->match_data)) {
  507. kleave(" = 0 [!match]");
  508. return 0;
  509. }
  510. /* key must have search permissions */
  511. if (!(ctx->flags & KEYRING_SEARCH_NO_CHECK_PERM) &&
  512. key_task_permission(make_key_ref(key, ctx->possessed),
  513. ctx->cred, KEY_NEED_SEARCH) < 0) {
  514. ctx->result = ERR_PTR(-EACCES);
  515. kleave(" = %d [!perm]", ctx->skipped_ret);
  516. goto skipped;
  517. }
  518. if (ctx->flags & KEYRING_SEARCH_DO_STATE_CHECK) {
  519. /* we set a different error code if we pass a negative key */
  520. if (kflags & (1 << KEY_FLAG_NEGATIVE)) {
  521. smp_rmb();
  522. ctx->result = ERR_PTR(key->reject_error);
  523. kleave(" = %d [neg]", ctx->skipped_ret);
  524. goto skipped;
  525. }
  526. }
  527. /* Found */
  528. ctx->result = make_key_ref(key, ctx->possessed);
  529. kleave(" = 1 [found]");
  530. return 1;
  531. skipped:
  532. return ctx->skipped_ret;
  533. }
  534. /*
  535. * Search inside a keyring for a key. We can search by walking to it
  536. * directly based on its index-key or we can iterate over the entire
  537. * tree looking for it, based on the match function.
  538. */
  539. static int search_keyring(struct key *keyring, struct keyring_search_context *ctx)
  540. {
  541. if (ctx->match_data.lookup_type == KEYRING_SEARCH_LOOKUP_DIRECT) {
  542. const void *object;
  543. object = assoc_array_find(&keyring->keys,
  544. &keyring_assoc_array_ops,
  545. &ctx->index_key);
  546. return object ? ctx->iterator(object, ctx) : 0;
  547. }
  548. return assoc_array_iterate(&keyring->keys, ctx->iterator, ctx);
  549. }
  550. /*
  551. * Search a tree of keyrings that point to other keyrings up to the maximum
  552. * depth.
  553. */
  554. static bool search_nested_keyrings(struct key *keyring,
  555. struct keyring_search_context *ctx)
  556. {
  557. struct {
  558. struct key *keyring;
  559. struct assoc_array_node *node;
  560. int slot;
  561. } stack[KEYRING_SEARCH_MAX_DEPTH];
  562. struct assoc_array_shortcut *shortcut;
  563. struct assoc_array_node *node;
  564. struct assoc_array_ptr *ptr;
  565. struct key *key;
  566. int sp = 0, slot;
  567. kenter("{%d},{%s,%s}",
  568. keyring->serial,
  569. ctx->index_key.type->name,
  570. ctx->index_key.description);
  571. #define STATE_CHECKS (KEYRING_SEARCH_NO_STATE_CHECK | KEYRING_SEARCH_DO_STATE_CHECK)
  572. BUG_ON((ctx->flags & STATE_CHECKS) == 0 ||
  573. (ctx->flags & STATE_CHECKS) == STATE_CHECKS);
  574. if (ctx->index_key.description)
  575. ctx->index_key.desc_len = strlen(ctx->index_key.description);
  576. /* Check to see if this top-level keyring is what we are looking for
  577. * and whether it is valid or not.
  578. */
  579. if (ctx->match_data.lookup_type == KEYRING_SEARCH_LOOKUP_ITERATE ||
  580. keyring_compare_object(keyring, &ctx->index_key)) {
  581. ctx->skipped_ret = 2;
  582. switch (ctx->iterator(keyring_key_to_ptr(keyring), ctx)) {
  583. case 1:
  584. goto found;
  585. case 2:
  586. return false;
  587. default:
  588. break;
  589. }
  590. }
  591. ctx->skipped_ret = 0;
  592. /* Start processing a new keyring */
  593. descend_to_keyring:
  594. kdebug("descend to %d", keyring->serial);
  595. if (keyring->flags & ((1 << KEY_FLAG_INVALIDATED) |
  596. (1 << KEY_FLAG_REVOKED)))
  597. goto not_this_keyring;
  598. /* Search through the keys in this keyring before its searching its
  599. * subtrees.
  600. */
  601. if (search_keyring(keyring, ctx))
  602. goto found;
  603. /* Then manually iterate through the keyrings nested in this one.
  604. *
  605. * Start from the root node of the index tree. Because of the way the
  606. * hash function has been set up, keyrings cluster on the leftmost
  607. * branch of the root node (root slot 0) or in the root node itself.
  608. * Non-keyrings avoid the leftmost branch of the root entirely (root
  609. * slots 1-15).
  610. */
  611. ptr = ACCESS_ONCE(keyring->keys.root);
  612. if (!ptr)
  613. goto not_this_keyring;
  614. if (assoc_array_ptr_is_shortcut(ptr)) {
  615. /* If the root is a shortcut, either the keyring only contains
  616. * keyring pointers (everything clusters behind root slot 0) or
  617. * doesn't contain any keyring pointers.
  618. */
  619. shortcut = assoc_array_ptr_to_shortcut(ptr);
  620. smp_read_barrier_depends();
  621. if ((shortcut->index_key[0] & ASSOC_ARRAY_FAN_MASK) != 0)
  622. goto not_this_keyring;
  623. ptr = ACCESS_ONCE(shortcut->next_node);
  624. node = assoc_array_ptr_to_node(ptr);
  625. goto begin_node;
  626. }
  627. node = assoc_array_ptr_to_node(ptr);
  628. smp_read_barrier_depends();
  629. ptr = node->slots[0];
  630. if (!assoc_array_ptr_is_meta(ptr))
  631. goto begin_node;
  632. descend_to_node:
  633. /* Descend to a more distal node in this keyring's content tree and go
  634. * through that.
  635. */
  636. kdebug("descend");
  637. if (assoc_array_ptr_is_shortcut(ptr)) {
  638. shortcut = assoc_array_ptr_to_shortcut(ptr);
  639. smp_read_barrier_depends();
  640. ptr = ACCESS_ONCE(shortcut->next_node);
  641. BUG_ON(!assoc_array_ptr_is_node(ptr));
  642. }
  643. node = assoc_array_ptr_to_node(ptr);
  644. begin_node:
  645. kdebug("begin_node");
  646. smp_read_barrier_depends();
  647. slot = 0;
  648. ascend_to_node:
  649. /* Go through the slots in a node */
  650. for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
  651. ptr = ACCESS_ONCE(node->slots[slot]);
  652. if (assoc_array_ptr_is_meta(ptr) && node->back_pointer)
  653. goto descend_to_node;
  654. if (!keyring_ptr_is_keyring(ptr))
  655. continue;
  656. key = keyring_ptr_to_key(ptr);
  657. if (sp >= KEYRING_SEARCH_MAX_DEPTH) {
  658. if (ctx->flags & KEYRING_SEARCH_DETECT_TOO_DEEP) {
  659. ctx->result = ERR_PTR(-ELOOP);
  660. return false;
  661. }
  662. goto not_this_keyring;
  663. }
  664. /* Search a nested keyring */
  665. if (!(ctx->flags & KEYRING_SEARCH_NO_CHECK_PERM) &&
  666. key_task_permission(make_key_ref(key, ctx->possessed),
  667. ctx->cred, KEY_NEED_SEARCH) < 0)
  668. continue;
  669. /* stack the current position */
  670. stack[sp].keyring = keyring;
  671. stack[sp].node = node;
  672. stack[sp].slot = slot;
  673. sp++;
  674. /* begin again with the new keyring */
  675. keyring = key;
  676. goto descend_to_keyring;
  677. }
  678. /* We've dealt with all the slots in the current node, so now we need
  679. * to ascend to the parent and continue processing there.
  680. */
  681. ptr = ACCESS_ONCE(node->back_pointer);
  682. slot = node->parent_slot;
  683. if (ptr && assoc_array_ptr_is_shortcut(ptr)) {
  684. shortcut = assoc_array_ptr_to_shortcut(ptr);
  685. smp_read_barrier_depends();
  686. ptr = ACCESS_ONCE(shortcut->back_pointer);
  687. slot = shortcut->parent_slot;
  688. }
  689. if (!ptr)
  690. goto not_this_keyring;
  691. node = assoc_array_ptr_to_node(ptr);
  692. smp_read_barrier_depends();
  693. slot++;
  694. /* If we've ascended to the root (zero backpointer), we must have just
  695. * finished processing the leftmost branch rather than the root slots -
  696. * so there can't be any more keyrings for us to find.
  697. */
  698. if (node->back_pointer) {
  699. kdebug("ascend %d", slot);
  700. goto ascend_to_node;
  701. }
  702. /* The keyring we're looking at was disqualified or didn't contain a
  703. * matching key.
  704. */
  705. not_this_keyring:
  706. kdebug("not_this_keyring %d", sp);
  707. if (sp <= 0) {
  708. kleave(" = false");
  709. return false;
  710. }
  711. /* Resume the processing of a keyring higher up in the tree */
  712. sp--;
  713. keyring = stack[sp].keyring;
  714. node = stack[sp].node;
  715. slot = stack[sp].slot + 1;
  716. kdebug("ascend to %d [%d]", keyring->serial, slot);
  717. goto ascend_to_node;
  718. /* We found a viable match */
  719. found:
  720. key = key_ref_to_ptr(ctx->result);
  721. key_check(key);
  722. if (!(ctx->flags & KEYRING_SEARCH_NO_UPDATE_TIME)) {
  723. key->last_used_at = ctx->now.tv_sec;
  724. keyring->last_used_at = ctx->now.tv_sec;
  725. while (sp > 0)
  726. stack[--sp].keyring->last_used_at = ctx->now.tv_sec;
  727. }
  728. kleave(" = true");
  729. return true;
  730. }
  731. /**
  732. * keyring_search_aux - Search a keyring tree for a key matching some criteria
  733. * @keyring_ref: A pointer to the keyring with possession indicator.
  734. * @ctx: The keyring search context.
  735. *
  736. * Search the supplied keyring tree for a key that matches the criteria given.
  737. * The root keyring and any linked keyrings must grant Search permission to the
  738. * caller to be searchable and keys can only be found if they too grant Search
  739. * to the caller. The possession flag on the root keyring pointer controls use
  740. * of the possessor bits in permissions checking of the entire tree. In
  741. * addition, the LSM gets to forbid keyring searches and key matches.
  742. *
  743. * The search is performed as a breadth-then-depth search up to the prescribed
  744. * limit (KEYRING_SEARCH_MAX_DEPTH).
  745. *
  746. * Keys are matched to the type provided and are then filtered by the match
  747. * function, which is given the description to use in any way it sees fit. The
  748. * match function may use any attributes of a key that it wishes to to
  749. * determine the match. Normally the match function from the key type would be
  750. * used.
  751. *
  752. * RCU can be used to prevent the keyring key lists from disappearing without
  753. * the need to take lots of locks.
  754. *
  755. * Returns a pointer to the found key and increments the key usage count if
  756. * successful; -EAGAIN if no matching keys were found, or if expired or revoked
  757. * keys were found; -ENOKEY if only negative keys were found; -ENOTDIR if the
  758. * specified keyring wasn't a keyring.
  759. *
  760. * In the case of a successful return, the possession attribute from
  761. * @keyring_ref is propagated to the returned key reference.
  762. */
  763. key_ref_t keyring_search_aux(key_ref_t keyring_ref,
  764. struct keyring_search_context *ctx)
  765. {
  766. struct key *keyring;
  767. long err;
  768. ctx->iterator = keyring_search_iterator;
  769. ctx->possessed = is_key_possessed(keyring_ref);
  770. ctx->result = ERR_PTR(-EAGAIN);
  771. keyring = key_ref_to_ptr(keyring_ref);
  772. key_check(keyring);
  773. if (keyring->type != &key_type_keyring)
  774. return ERR_PTR(-ENOTDIR);
  775. if (!(ctx->flags & KEYRING_SEARCH_NO_CHECK_PERM)) {
  776. err = key_task_permission(keyring_ref, ctx->cred, KEY_NEED_SEARCH);
  777. if (err < 0)
  778. return ERR_PTR(err);
  779. }
  780. rcu_read_lock();
  781. ctx->now = current_kernel_time();
  782. if (search_nested_keyrings(keyring, ctx))
  783. __key_get(key_ref_to_ptr(ctx->result));
  784. rcu_read_unlock();
  785. return ctx->result;
  786. }
  787. /**
  788. * keyring_search - Search the supplied keyring tree for a matching key
  789. * @keyring: The root of the keyring tree to be searched.
  790. * @type: The type of keyring we want to find.
  791. * @description: The name of the keyring we want to find.
  792. *
  793. * As keyring_search_aux() above, but using the current task's credentials and
  794. * type's default matching function and preferred search method.
  795. */
  796. key_ref_t keyring_search(key_ref_t keyring,
  797. struct key_type *type,
  798. const char *description)
  799. {
  800. struct keyring_search_context ctx = {
  801. .index_key.type = type,
  802. .index_key.description = description,
  803. .cred = current_cred(),
  804. .match_data.cmp = key_default_cmp,
  805. .match_data.raw_data = description,
  806. .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT,
  807. .flags = KEYRING_SEARCH_DO_STATE_CHECK,
  808. };
  809. key_ref_t key;
  810. int ret;
  811. if (type->match_preparse) {
  812. ret = type->match_preparse(&ctx.match_data);
  813. if (ret < 0)
  814. return ERR_PTR(ret);
  815. }
  816. key = keyring_search_aux(keyring, &ctx);
  817. if (type->match_free)
  818. type->match_free(&ctx.match_data);
  819. return key;
  820. }
  821. EXPORT_SYMBOL(keyring_search);
  822. /*
  823. * Search the given keyring for a key that might be updated.
  824. *
  825. * The caller must guarantee that the keyring is a keyring and that the
  826. * permission is granted to modify the keyring as no check is made here. The
  827. * caller must also hold a lock on the keyring semaphore.
  828. *
  829. * Returns a pointer to the found key with usage count incremented if
  830. * successful and returns NULL if not found. Revoked and invalidated keys are
  831. * skipped over.
  832. *
  833. * If successful, the possession indicator is propagated from the keyring ref
  834. * to the returned key reference.
  835. */
  836. key_ref_t find_key_to_update(key_ref_t keyring_ref,
  837. const struct keyring_index_key *index_key)
  838. {
  839. struct key *keyring, *key;
  840. const void *object;
  841. keyring = key_ref_to_ptr(keyring_ref);
  842. kenter("{%d},{%s,%s}",
  843. keyring->serial, index_key->type->name, index_key->description);
  844. object = assoc_array_find(&keyring->keys, &keyring_assoc_array_ops,
  845. index_key);
  846. if (object)
  847. goto found;
  848. kleave(" = NULL");
  849. return NULL;
  850. found:
  851. key = keyring_ptr_to_key(object);
  852. if (key->flags & ((1 << KEY_FLAG_INVALIDATED) |
  853. (1 << KEY_FLAG_REVOKED))) {
  854. kleave(" = NULL [x]");
  855. return NULL;
  856. }
  857. __key_get(key);
  858. kleave(" = {%d}", key->serial);
  859. return make_key_ref(key, is_key_possessed(keyring_ref));
  860. }
  861. /*
  862. * Find a keyring with the specified name.
  863. *
  864. * All named keyrings in the current user namespace are searched, provided they
  865. * grant Search permission directly to the caller (unless this check is
  866. * skipped). Keyrings whose usage points have reached zero or who have been
  867. * revoked are skipped.
  868. *
  869. * Returns a pointer to the keyring with the keyring's refcount having being
  870. * incremented on success. -ENOKEY is returned if a key could not be found.
  871. */
  872. struct key *find_keyring_by_name(const char *name, bool skip_perm_check)
  873. {
  874. struct key *keyring;
  875. int bucket;
  876. if (!name)
  877. return ERR_PTR(-EINVAL);
  878. bucket = keyring_hash(name);
  879. read_lock(&keyring_name_lock);
  880. if (keyring_name_hash[bucket].next) {
  881. /* search this hash bucket for a keyring with a matching name
  882. * that's readable and that hasn't been revoked */
  883. list_for_each_entry(keyring,
  884. &keyring_name_hash[bucket],
  885. name_link
  886. ) {
  887. if (!kuid_has_mapping(current_user_ns(), keyring->user->uid))
  888. continue;
  889. if (test_bit(KEY_FLAG_REVOKED, &keyring->flags))
  890. continue;
  891. if (strcmp(keyring->description, name) != 0)
  892. continue;
  893. if (!skip_perm_check &&
  894. key_permission(make_key_ref(keyring, 0),
  895. KEY_NEED_SEARCH) < 0)
  896. continue;
  897. /* we've got a match but we might end up racing with
  898. * key_cleanup() if the keyring is currently 'dead'
  899. * (ie. it has a zero usage count) */
  900. if (!atomic_inc_not_zero(&keyring->usage))
  901. continue;
  902. keyring->last_used_at = current_kernel_time().tv_sec;
  903. goto out;
  904. }
  905. }
  906. keyring = ERR_PTR(-ENOKEY);
  907. out:
  908. read_unlock(&keyring_name_lock);
  909. return keyring;
  910. }
  911. static int keyring_detect_cycle_iterator(const void *object,
  912. void *iterator_data)
  913. {
  914. struct keyring_search_context *ctx = iterator_data;
  915. const struct key *key = keyring_ptr_to_key(object);
  916. kenter("{%d}", key->serial);
  917. /* We might get a keyring with matching index-key that is nonetheless a
  918. * different keyring. */
  919. if (key != ctx->match_data.raw_data)
  920. return 0;
  921. ctx->result = ERR_PTR(-EDEADLK);
  922. return 1;
  923. }
  924. /*
  925. * See if a cycle will will be created by inserting acyclic tree B in acyclic
  926. * tree A at the topmost level (ie: as a direct child of A).
  927. *
  928. * Since we are adding B to A at the top level, checking for cycles should just
  929. * be a matter of seeing if node A is somewhere in tree B.
  930. */
  931. static int keyring_detect_cycle(struct key *A, struct key *B)
  932. {
  933. struct keyring_search_context ctx = {
  934. .index_key = A->index_key,
  935. .match_data.raw_data = A,
  936. .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT,
  937. .iterator = keyring_detect_cycle_iterator,
  938. .flags = (KEYRING_SEARCH_NO_STATE_CHECK |
  939. KEYRING_SEARCH_NO_UPDATE_TIME |
  940. KEYRING_SEARCH_NO_CHECK_PERM |
  941. KEYRING_SEARCH_DETECT_TOO_DEEP),
  942. };
  943. rcu_read_lock();
  944. search_nested_keyrings(B, &ctx);
  945. rcu_read_unlock();
  946. return PTR_ERR(ctx.result) == -EAGAIN ? 0 : PTR_ERR(ctx.result);
  947. }
  948. /*
  949. * Preallocate memory so that a key can be linked into to a keyring.
  950. */
  951. int __key_link_begin(struct key *keyring,
  952. const struct keyring_index_key *index_key,
  953. struct assoc_array_edit **_edit)
  954. __acquires(&keyring->sem)
  955. __acquires(&keyring_serialise_link_sem)
  956. {
  957. struct assoc_array_edit *edit;
  958. int ret;
  959. kenter("%d,%s,%s,",
  960. keyring->serial, index_key->type->name, index_key->description);
  961. BUG_ON(index_key->desc_len == 0);
  962. if (keyring->type != &key_type_keyring)
  963. return -ENOTDIR;
  964. down_write(&keyring->sem);
  965. ret = -EKEYREVOKED;
  966. if (test_bit(KEY_FLAG_REVOKED, &keyring->flags))
  967. goto error_krsem;
  968. /* serialise link/link calls to prevent parallel calls causing a cycle
  969. * when linking two keyring in opposite orders */
  970. if (index_key->type == &key_type_keyring)
  971. down_write(&keyring_serialise_link_sem);
  972. /* Create an edit script that will insert/replace the key in the
  973. * keyring tree.
  974. */
  975. edit = assoc_array_insert(&keyring->keys,
  976. &keyring_assoc_array_ops,
  977. index_key,
  978. NULL);
  979. if (IS_ERR(edit)) {
  980. ret = PTR_ERR(edit);
  981. goto error_sem;
  982. }
  983. /* If we're not replacing a link in-place then we're going to need some
  984. * extra quota.
  985. */
  986. if (!edit->dead_leaf) {
  987. ret = key_payload_reserve(keyring,
  988. keyring->datalen + KEYQUOTA_LINK_BYTES);
  989. if (ret < 0)
  990. goto error_cancel;
  991. }
  992. *_edit = edit;
  993. kleave(" = 0");
  994. return 0;
  995. error_cancel:
  996. assoc_array_cancel_edit(edit);
  997. error_sem:
  998. if (index_key->type == &key_type_keyring)
  999. up_write(&keyring_serialise_link_sem);
  1000. error_krsem:
  1001. up_write(&keyring->sem);
  1002. kleave(" = %d", ret);
  1003. return ret;
  1004. }
  1005. /*
  1006. * Check already instantiated keys aren't going to be a problem.
  1007. *
  1008. * The caller must have called __key_link_begin(). Don't need to call this for
  1009. * keys that were created since __key_link_begin() was called.
  1010. */
  1011. int __key_link_check_live_key(struct key *keyring, struct key *key)
  1012. {
  1013. if (key->type == &key_type_keyring)
  1014. /* check that we aren't going to create a cycle by linking one
  1015. * keyring to another */
  1016. return keyring_detect_cycle(keyring, key);
  1017. return 0;
  1018. }
  1019. /*
  1020. * Link a key into to a keyring.
  1021. *
  1022. * Must be called with __key_link_begin() having being called. Discards any
  1023. * already extant link to matching key if there is one, so that each keyring
  1024. * holds at most one link to any given key of a particular type+description
  1025. * combination.
  1026. */
  1027. void __key_link(struct key *key, struct assoc_array_edit **_edit)
  1028. {
  1029. __key_get(key);
  1030. assoc_array_insert_set_object(*_edit, keyring_key_to_ptr(key));
  1031. assoc_array_apply_edit(*_edit);
  1032. *_edit = NULL;
  1033. }
  1034. /*
  1035. * Finish linking a key into to a keyring.
  1036. *
  1037. * Must be called with __key_link_begin() having being called.
  1038. */
  1039. void __key_link_end(struct key *keyring,
  1040. const struct keyring_index_key *index_key,
  1041. struct assoc_array_edit *edit)
  1042. __releases(&keyring->sem)
  1043. __releases(&keyring_serialise_link_sem)
  1044. {
  1045. BUG_ON(index_key->type == NULL);
  1046. kenter("%d,%s,", keyring->serial, index_key->type->name);
  1047. if (index_key->type == &key_type_keyring)
  1048. up_write(&keyring_serialise_link_sem);
  1049. if (edit) {
  1050. if (!edit->dead_leaf) {
  1051. key_payload_reserve(keyring,
  1052. keyring->datalen - KEYQUOTA_LINK_BYTES);
  1053. }
  1054. assoc_array_cancel_edit(edit);
  1055. }
  1056. up_write(&keyring->sem);
  1057. }
  1058. /*
  1059. * Check addition of keys to restricted keyrings.
  1060. */
  1061. static int __key_link_check_restriction(struct key *keyring, struct key *key)
  1062. {
  1063. if (!keyring->restrict_link)
  1064. return 0;
  1065. return keyring->restrict_link(keyring, key->type, &key->payload);
  1066. }
  1067. /**
  1068. * key_link - Link a key to a keyring
  1069. * @keyring: The keyring to make the link in.
  1070. * @key: The key to link to.
  1071. *
  1072. * Make a link in a keyring to a key, such that the keyring holds a reference
  1073. * on that key and the key can potentially be found by searching that keyring.
  1074. *
  1075. * This function will write-lock the keyring's semaphore and will consume some
  1076. * of the user's key data quota to hold the link.
  1077. *
  1078. * Returns 0 if successful, -ENOTDIR if the keyring isn't a keyring,
  1079. * -EKEYREVOKED if the keyring has been revoked, -ENFILE if the keyring is
  1080. * full, -EDQUOT if there is insufficient key data quota remaining to add
  1081. * another link or -ENOMEM if there's insufficient memory.
  1082. *
  1083. * It is assumed that the caller has checked that it is permitted for a link to
  1084. * be made (the keyring should have Write permission and the key Link
  1085. * permission).
  1086. */
  1087. int key_link(struct key *keyring, struct key *key)
  1088. {
  1089. struct assoc_array_edit *edit;
  1090. int ret;
  1091. kenter("{%d,%d}", keyring->serial, atomic_read(&keyring->usage));
  1092. key_check(keyring);
  1093. key_check(key);
  1094. ret = __key_link_begin(keyring, &key->index_key, &edit);
  1095. if (ret == 0) {
  1096. kdebug("begun {%d,%d}", keyring->serial, atomic_read(&keyring->usage));
  1097. ret = __key_link_check_restriction(keyring, key);
  1098. if (ret == 0)
  1099. ret = __key_link_check_live_key(keyring, key);
  1100. if (ret == 0)
  1101. __key_link(key, &edit);
  1102. __key_link_end(keyring, &key->index_key, edit);
  1103. }
  1104. kleave(" = %d {%d,%d}", ret, keyring->serial, atomic_read(&keyring->usage));
  1105. return ret;
  1106. }
  1107. EXPORT_SYMBOL(key_link);
  1108. /**
  1109. * key_unlink - Unlink the first link to a key from a keyring.
  1110. * @keyring: The keyring to remove the link from.
  1111. * @key: The key the link is to.
  1112. *
  1113. * Remove a link from a keyring to a key.
  1114. *
  1115. * This function will write-lock the keyring's semaphore.
  1116. *
  1117. * Returns 0 if successful, -ENOTDIR if the keyring isn't a keyring, -ENOENT if
  1118. * the key isn't linked to by the keyring or -ENOMEM if there's insufficient
  1119. * memory.
  1120. *
  1121. * It is assumed that the caller has checked that it is permitted for a link to
  1122. * be removed (the keyring should have Write permission; no permissions are
  1123. * required on the key).
  1124. */
  1125. int key_unlink(struct key *keyring, struct key *key)
  1126. {
  1127. struct assoc_array_edit *edit;
  1128. int ret;
  1129. key_check(keyring);
  1130. key_check(key);
  1131. if (keyring->type != &key_type_keyring)
  1132. return -ENOTDIR;
  1133. down_write(&keyring->sem);
  1134. edit = assoc_array_delete(&keyring->keys, &keyring_assoc_array_ops,
  1135. &key->index_key);
  1136. if (IS_ERR(edit)) {
  1137. ret = PTR_ERR(edit);
  1138. goto error;
  1139. }
  1140. ret = -ENOENT;
  1141. if (edit == NULL)
  1142. goto error;
  1143. assoc_array_apply_edit(edit);
  1144. key_payload_reserve(keyring, keyring->datalen - KEYQUOTA_LINK_BYTES);
  1145. ret = 0;
  1146. error:
  1147. up_write(&keyring->sem);
  1148. return ret;
  1149. }
  1150. EXPORT_SYMBOL(key_unlink);
  1151. /**
  1152. * keyring_clear - Clear a keyring
  1153. * @keyring: The keyring to clear.
  1154. *
  1155. * Clear the contents of the specified keyring.
  1156. *
  1157. * Returns 0 if successful or -ENOTDIR if the keyring isn't a keyring.
  1158. */
  1159. int keyring_clear(struct key *keyring)
  1160. {
  1161. struct assoc_array_edit *edit;
  1162. int ret;
  1163. if (keyring->type != &key_type_keyring)
  1164. return -ENOTDIR;
  1165. down_write(&keyring->sem);
  1166. edit = assoc_array_clear(&keyring->keys, &keyring_assoc_array_ops);
  1167. if (IS_ERR(edit)) {
  1168. ret = PTR_ERR(edit);
  1169. } else {
  1170. if (edit)
  1171. assoc_array_apply_edit(edit);
  1172. key_payload_reserve(keyring, 0);
  1173. ret = 0;
  1174. }
  1175. up_write(&keyring->sem);
  1176. return ret;
  1177. }
  1178. EXPORT_SYMBOL(keyring_clear);
  1179. /*
  1180. * Dispose of the links from a revoked keyring.
  1181. *
  1182. * This is called with the key sem write-locked.
  1183. */
  1184. static void keyring_revoke(struct key *keyring)
  1185. {
  1186. struct assoc_array_edit *edit;
  1187. edit = assoc_array_clear(&keyring->keys, &keyring_assoc_array_ops);
  1188. if (!IS_ERR(edit)) {
  1189. if (edit)
  1190. assoc_array_apply_edit(edit);
  1191. key_payload_reserve(keyring, 0);
  1192. }
  1193. }
  1194. static bool keyring_gc_select_iterator(void *object, void *iterator_data)
  1195. {
  1196. struct key *key = keyring_ptr_to_key(object);
  1197. time_t *limit = iterator_data;
  1198. if (key_is_dead(key, *limit))
  1199. return false;
  1200. key_get(key);
  1201. return true;
  1202. }
  1203. static int keyring_gc_check_iterator(const void *object, void *iterator_data)
  1204. {
  1205. const struct key *key = keyring_ptr_to_key(object);
  1206. time_t *limit = iterator_data;
  1207. key_check(key);
  1208. return key_is_dead(key, *limit);
  1209. }
  1210. /*
  1211. * Garbage collect pointers from a keyring.
  1212. *
  1213. * Not called with any locks held. The keyring's key struct will not be
  1214. * deallocated under us as only our caller may deallocate it.
  1215. */
  1216. void keyring_gc(struct key *keyring, time_t limit)
  1217. {
  1218. int result;
  1219. kenter("%x{%s}", keyring->serial, keyring->description ?: "");
  1220. if (keyring->flags & ((1 << KEY_FLAG_INVALIDATED) |
  1221. (1 << KEY_FLAG_REVOKED)))
  1222. goto dont_gc;
  1223. /* scan the keyring looking for dead keys */
  1224. rcu_read_lock();
  1225. result = assoc_array_iterate(&keyring->keys,
  1226. keyring_gc_check_iterator, &limit);
  1227. rcu_read_unlock();
  1228. if (result == true)
  1229. goto do_gc;
  1230. dont_gc:
  1231. kleave(" [no gc]");
  1232. return;
  1233. do_gc:
  1234. down_write(&keyring->sem);
  1235. assoc_array_gc(&keyring->keys, &keyring_assoc_array_ops,
  1236. keyring_gc_select_iterator, &limit);
  1237. up_write(&keyring->sem);
  1238. kleave(" [gc]");
  1239. }