keyring.c 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585
  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. if (keyring->restrict_link) {
  350. struct key_restriction *keyres = keyring->restrict_link;
  351. key_put(keyres->key);
  352. kfree(keyres);
  353. }
  354. assoc_array_destroy(&keyring->keys, &keyring_assoc_array_ops);
  355. }
  356. /*
  357. * Describe a keyring for /proc.
  358. */
  359. static void keyring_describe(const struct key *keyring, struct seq_file *m)
  360. {
  361. if (keyring->description)
  362. seq_puts(m, keyring->description);
  363. else
  364. seq_puts(m, "[anon]");
  365. if (key_is_positive(keyring)) {
  366. if (keyring->keys.nr_leaves_on_tree != 0)
  367. seq_printf(m, ": %lu", keyring->keys.nr_leaves_on_tree);
  368. else
  369. seq_puts(m, ": empty");
  370. }
  371. }
  372. struct keyring_read_iterator_context {
  373. size_t buflen;
  374. size_t count;
  375. key_serial_t __user *buffer;
  376. };
  377. static int keyring_read_iterator(const void *object, void *data)
  378. {
  379. struct keyring_read_iterator_context *ctx = data;
  380. const struct key *key = keyring_ptr_to_key(object);
  381. int ret;
  382. kenter("{%s,%d},,{%zu/%zu}",
  383. key->type->name, key->serial, ctx->count, ctx->buflen);
  384. if (ctx->count >= ctx->buflen)
  385. return 1;
  386. ret = put_user(key->serial, ctx->buffer);
  387. if (ret < 0)
  388. return ret;
  389. ctx->buffer++;
  390. ctx->count += sizeof(key->serial);
  391. return 0;
  392. }
  393. /*
  394. * Read a list of key IDs from the keyring's contents in binary form
  395. *
  396. * The keyring's semaphore is read-locked by the caller. This prevents someone
  397. * from modifying it under us - which could cause us to read key IDs multiple
  398. * times.
  399. */
  400. static long keyring_read(const struct key *keyring,
  401. char __user *buffer, size_t buflen)
  402. {
  403. struct keyring_read_iterator_context ctx;
  404. long ret;
  405. kenter("{%d},,%zu", key_serial(keyring), buflen);
  406. if (buflen & (sizeof(key_serial_t) - 1))
  407. return -EINVAL;
  408. /* Copy as many key IDs as fit into the buffer */
  409. if (buffer && buflen) {
  410. ctx.buffer = (key_serial_t __user *)buffer;
  411. ctx.buflen = buflen;
  412. ctx.count = 0;
  413. ret = assoc_array_iterate(&keyring->keys,
  414. keyring_read_iterator, &ctx);
  415. if (ret < 0) {
  416. kleave(" = %ld [iterate]", ret);
  417. return ret;
  418. }
  419. }
  420. /* Return the size of the buffer needed */
  421. ret = keyring->keys.nr_leaves_on_tree * sizeof(key_serial_t);
  422. if (ret <= buflen)
  423. kleave("= %ld [ok]", ret);
  424. else
  425. kleave("= %ld [buffer too small]", ret);
  426. return ret;
  427. }
  428. /*
  429. * Allocate a keyring and link into the destination keyring.
  430. */
  431. struct key *keyring_alloc(const char *description, kuid_t uid, kgid_t gid,
  432. const struct cred *cred, key_perm_t perm,
  433. unsigned long flags,
  434. struct key_restriction *restrict_link,
  435. struct key *dest)
  436. {
  437. struct key *keyring;
  438. int ret;
  439. keyring = key_alloc(&key_type_keyring, description,
  440. uid, gid, cred, perm, flags, restrict_link);
  441. if (!IS_ERR(keyring)) {
  442. ret = key_instantiate_and_link(keyring, NULL, 0, dest, NULL);
  443. if (ret < 0) {
  444. key_put(keyring);
  445. keyring = ERR_PTR(ret);
  446. }
  447. }
  448. return keyring;
  449. }
  450. EXPORT_SYMBOL(keyring_alloc);
  451. /**
  452. * restrict_link_reject - Give -EPERM to restrict link
  453. * @keyring: The keyring being added to.
  454. * @type: The type of key being added.
  455. * @payload: The payload of the key intended to be added.
  456. * @data: Additional data for evaluating restriction.
  457. *
  458. * Reject the addition of any links to a keyring. It can be overridden by
  459. * passing KEY_ALLOC_BYPASS_RESTRICTION to key_instantiate_and_link() when
  460. * adding a key to a keyring.
  461. *
  462. * This is meant to be stored in a key_restriction structure which is passed
  463. * in the restrict_link parameter to keyring_alloc().
  464. */
  465. int restrict_link_reject(struct key *keyring,
  466. const struct key_type *type,
  467. const union key_payload *payload,
  468. struct key *restriction_key)
  469. {
  470. return -EPERM;
  471. }
  472. /*
  473. * By default, we keys found by getting an exact match on their descriptions.
  474. */
  475. bool key_default_cmp(const struct key *key,
  476. const struct key_match_data *match_data)
  477. {
  478. return strcmp(key->description, match_data->raw_data) == 0;
  479. }
  480. /*
  481. * Iteration function to consider each key found.
  482. */
  483. static int keyring_search_iterator(const void *object, void *iterator_data)
  484. {
  485. struct keyring_search_context *ctx = iterator_data;
  486. const struct key *key = keyring_ptr_to_key(object);
  487. unsigned long kflags = READ_ONCE(key->flags);
  488. short state = READ_ONCE(key->state);
  489. kenter("{%d}", key->serial);
  490. /* ignore keys not of this type */
  491. if (key->type != ctx->index_key.type) {
  492. kleave(" = 0 [!type]");
  493. return 0;
  494. }
  495. /* skip invalidated, revoked and expired keys */
  496. if (ctx->flags & KEYRING_SEARCH_DO_STATE_CHECK) {
  497. time64_t expiry = READ_ONCE(key->expiry);
  498. if (kflags & ((1 << KEY_FLAG_INVALIDATED) |
  499. (1 << KEY_FLAG_REVOKED))) {
  500. ctx->result = ERR_PTR(-EKEYREVOKED);
  501. kleave(" = %d [invrev]", ctx->skipped_ret);
  502. goto skipped;
  503. }
  504. if (expiry && ctx->now >= expiry) {
  505. if (!(ctx->flags & KEYRING_SEARCH_SKIP_EXPIRED))
  506. ctx->result = ERR_PTR(-EKEYEXPIRED);
  507. kleave(" = %d [expire]", ctx->skipped_ret);
  508. goto skipped;
  509. }
  510. }
  511. /* keys that don't match */
  512. if (!ctx->match_data.cmp(key, &ctx->match_data)) {
  513. kleave(" = 0 [!match]");
  514. return 0;
  515. }
  516. /* key must have search permissions */
  517. if (!(ctx->flags & KEYRING_SEARCH_NO_CHECK_PERM) &&
  518. key_task_permission(make_key_ref(key, ctx->possessed),
  519. ctx->cred, KEY_NEED_SEARCH) < 0) {
  520. ctx->result = ERR_PTR(-EACCES);
  521. kleave(" = %d [!perm]", ctx->skipped_ret);
  522. goto skipped;
  523. }
  524. if (ctx->flags & KEYRING_SEARCH_DO_STATE_CHECK) {
  525. /* we set a different error code if we pass a negative key */
  526. if (state < 0) {
  527. ctx->result = ERR_PTR(state);
  528. kleave(" = %d [neg]", ctx->skipped_ret);
  529. goto skipped;
  530. }
  531. }
  532. /* Found */
  533. ctx->result = make_key_ref(key, ctx->possessed);
  534. kleave(" = 1 [found]");
  535. return 1;
  536. skipped:
  537. return ctx->skipped_ret;
  538. }
  539. /*
  540. * Search inside a keyring for a key. We can search by walking to it
  541. * directly based on its index-key or we can iterate over the entire
  542. * tree looking for it, based on the match function.
  543. */
  544. static int search_keyring(struct key *keyring, struct keyring_search_context *ctx)
  545. {
  546. if (ctx->match_data.lookup_type == KEYRING_SEARCH_LOOKUP_DIRECT) {
  547. const void *object;
  548. object = assoc_array_find(&keyring->keys,
  549. &keyring_assoc_array_ops,
  550. &ctx->index_key);
  551. return object ? ctx->iterator(object, ctx) : 0;
  552. }
  553. return assoc_array_iterate(&keyring->keys, ctx->iterator, ctx);
  554. }
  555. /*
  556. * Search a tree of keyrings that point to other keyrings up to the maximum
  557. * depth.
  558. */
  559. static bool search_nested_keyrings(struct key *keyring,
  560. struct keyring_search_context *ctx)
  561. {
  562. struct {
  563. struct key *keyring;
  564. struct assoc_array_node *node;
  565. int slot;
  566. } stack[KEYRING_SEARCH_MAX_DEPTH];
  567. struct assoc_array_shortcut *shortcut;
  568. struct assoc_array_node *node;
  569. struct assoc_array_ptr *ptr;
  570. struct key *key;
  571. int sp = 0, slot;
  572. kenter("{%d},{%s,%s}",
  573. keyring->serial,
  574. ctx->index_key.type->name,
  575. ctx->index_key.description);
  576. #define STATE_CHECKS (KEYRING_SEARCH_NO_STATE_CHECK | KEYRING_SEARCH_DO_STATE_CHECK)
  577. BUG_ON((ctx->flags & STATE_CHECKS) == 0 ||
  578. (ctx->flags & STATE_CHECKS) == STATE_CHECKS);
  579. /* Check to see if this top-level keyring is what we are looking for
  580. * and whether it is valid or not.
  581. */
  582. if (ctx->match_data.lookup_type == KEYRING_SEARCH_LOOKUP_ITERATE ||
  583. keyring_compare_object(keyring, &ctx->index_key)) {
  584. ctx->skipped_ret = 2;
  585. switch (ctx->iterator(keyring_key_to_ptr(keyring), ctx)) {
  586. case 1:
  587. goto found;
  588. case 2:
  589. return false;
  590. default:
  591. break;
  592. }
  593. }
  594. ctx->skipped_ret = 0;
  595. /* Start processing a new keyring */
  596. descend_to_keyring:
  597. kdebug("descend to %d", keyring->serial);
  598. if (keyring->flags & ((1 << KEY_FLAG_INVALIDATED) |
  599. (1 << KEY_FLAG_REVOKED)))
  600. goto not_this_keyring;
  601. /* Search through the keys in this keyring before its searching its
  602. * subtrees.
  603. */
  604. if (search_keyring(keyring, ctx))
  605. goto found;
  606. /* Then manually iterate through the keyrings nested in this one.
  607. *
  608. * Start from the root node of the index tree. Because of the way the
  609. * hash function has been set up, keyrings cluster on the leftmost
  610. * branch of the root node (root slot 0) or in the root node itself.
  611. * Non-keyrings avoid the leftmost branch of the root entirely (root
  612. * slots 1-15).
  613. */
  614. ptr = READ_ONCE(keyring->keys.root);
  615. if (!ptr)
  616. goto not_this_keyring;
  617. if (assoc_array_ptr_is_shortcut(ptr)) {
  618. /* If the root is a shortcut, either the keyring only contains
  619. * keyring pointers (everything clusters behind root slot 0) or
  620. * doesn't contain any keyring pointers.
  621. */
  622. shortcut = assoc_array_ptr_to_shortcut(ptr);
  623. if ((shortcut->index_key[0] & ASSOC_ARRAY_FAN_MASK) != 0)
  624. goto not_this_keyring;
  625. ptr = READ_ONCE(shortcut->next_node);
  626. node = assoc_array_ptr_to_node(ptr);
  627. goto begin_node;
  628. }
  629. node = assoc_array_ptr_to_node(ptr);
  630. ptr = node->slots[0];
  631. if (!assoc_array_ptr_is_meta(ptr))
  632. goto begin_node;
  633. descend_to_node:
  634. /* Descend to a more distal node in this keyring's content tree and go
  635. * through that.
  636. */
  637. kdebug("descend");
  638. if (assoc_array_ptr_is_shortcut(ptr)) {
  639. shortcut = assoc_array_ptr_to_shortcut(ptr);
  640. ptr = READ_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. slot = 0;
  647. ascend_to_node:
  648. /* Go through the slots in a node */
  649. for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
  650. ptr = READ_ONCE(node->slots[slot]);
  651. if (assoc_array_ptr_is_meta(ptr) && node->back_pointer)
  652. goto descend_to_node;
  653. if (!keyring_ptr_is_keyring(ptr))
  654. continue;
  655. key = keyring_ptr_to_key(ptr);
  656. if (sp >= KEYRING_SEARCH_MAX_DEPTH) {
  657. if (ctx->flags & KEYRING_SEARCH_DETECT_TOO_DEEP) {
  658. ctx->result = ERR_PTR(-ELOOP);
  659. return false;
  660. }
  661. goto not_this_keyring;
  662. }
  663. /* Search a nested keyring */
  664. if (!(ctx->flags & KEYRING_SEARCH_NO_CHECK_PERM) &&
  665. key_task_permission(make_key_ref(key, ctx->possessed),
  666. ctx->cred, KEY_NEED_SEARCH) < 0)
  667. continue;
  668. /* stack the current position */
  669. stack[sp].keyring = keyring;
  670. stack[sp].node = node;
  671. stack[sp].slot = slot;
  672. sp++;
  673. /* begin again with the new keyring */
  674. keyring = key;
  675. goto descend_to_keyring;
  676. }
  677. /* We've dealt with all the slots in the current node, so now we need
  678. * to ascend to the parent and continue processing there.
  679. */
  680. ptr = READ_ONCE(node->back_pointer);
  681. slot = node->parent_slot;
  682. if (ptr && assoc_array_ptr_is_shortcut(ptr)) {
  683. shortcut = assoc_array_ptr_to_shortcut(ptr);
  684. ptr = READ_ONCE(shortcut->back_pointer);
  685. slot = shortcut->parent_slot;
  686. }
  687. if (!ptr)
  688. goto not_this_keyring;
  689. node = assoc_array_ptr_to_node(ptr);
  690. slot++;
  691. /* If we've ascended to the root (zero backpointer), we must have just
  692. * finished processing the leftmost branch rather than the root slots -
  693. * so there can't be any more keyrings for us to find.
  694. */
  695. if (node->back_pointer) {
  696. kdebug("ascend %d", slot);
  697. goto ascend_to_node;
  698. }
  699. /* The keyring we're looking at was disqualified or didn't contain a
  700. * matching key.
  701. */
  702. not_this_keyring:
  703. kdebug("not_this_keyring %d", sp);
  704. if (sp <= 0) {
  705. kleave(" = false");
  706. return false;
  707. }
  708. /* Resume the processing of a keyring higher up in the tree */
  709. sp--;
  710. keyring = stack[sp].keyring;
  711. node = stack[sp].node;
  712. slot = stack[sp].slot + 1;
  713. kdebug("ascend to %d [%d]", keyring->serial, slot);
  714. goto ascend_to_node;
  715. /* We found a viable match */
  716. found:
  717. key = key_ref_to_ptr(ctx->result);
  718. key_check(key);
  719. if (!(ctx->flags & KEYRING_SEARCH_NO_UPDATE_TIME)) {
  720. key->last_used_at = ctx->now;
  721. keyring->last_used_at = ctx->now;
  722. while (sp > 0)
  723. stack[--sp].keyring->last_used_at = ctx->now;
  724. }
  725. kleave(" = true");
  726. return true;
  727. }
  728. /**
  729. * keyring_search_aux - Search a keyring tree for a key matching some criteria
  730. * @keyring_ref: A pointer to the keyring with possession indicator.
  731. * @ctx: The keyring search context.
  732. *
  733. * Search the supplied keyring tree for a key that matches the criteria given.
  734. * The root keyring and any linked keyrings must grant Search permission to the
  735. * caller to be searchable and keys can only be found if they too grant Search
  736. * to the caller. The possession flag on the root keyring pointer controls use
  737. * of the possessor bits in permissions checking of the entire tree. In
  738. * addition, the LSM gets to forbid keyring searches and key matches.
  739. *
  740. * The search is performed as a breadth-then-depth search up to the prescribed
  741. * limit (KEYRING_SEARCH_MAX_DEPTH).
  742. *
  743. * Keys are matched to the type provided and are then filtered by the match
  744. * function, which is given the description to use in any way it sees fit. The
  745. * match function may use any attributes of a key that it wishes to to
  746. * determine the match. Normally the match function from the key type would be
  747. * used.
  748. *
  749. * RCU can be used to prevent the keyring key lists from disappearing without
  750. * the need to take lots of locks.
  751. *
  752. * Returns a pointer to the found key and increments the key usage count if
  753. * successful; -EAGAIN if no matching keys were found, or if expired or revoked
  754. * keys were found; -ENOKEY if only negative keys were found; -ENOTDIR if the
  755. * specified keyring wasn't a keyring.
  756. *
  757. * In the case of a successful return, the possession attribute from
  758. * @keyring_ref is propagated to the returned key reference.
  759. */
  760. key_ref_t keyring_search_aux(key_ref_t keyring_ref,
  761. struct keyring_search_context *ctx)
  762. {
  763. struct key *keyring;
  764. long err;
  765. ctx->iterator = keyring_search_iterator;
  766. ctx->possessed = is_key_possessed(keyring_ref);
  767. ctx->result = ERR_PTR(-EAGAIN);
  768. keyring = key_ref_to_ptr(keyring_ref);
  769. key_check(keyring);
  770. if (keyring->type != &key_type_keyring)
  771. return ERR_PTR(-ENOTDIR);
  772. if (!(ctx->flags & KEYRING_SEARCH_NO_CHECK_PERM)) {
  773. err = key_task_permission(keyring_ref, ctx->cred, KEY_NEED_SEARCH);
  774. if (err < 0)
  775. return ERR_PTR(err);
  776. }
  777. rcu_read_lock();
  778. ctx->now = ktime_get_real_seconds();
  779. if (search_nested_keyrings(keyring, ctx))
  780. __key_get(key_ref_to_ptr(ctx->result));
  781. rcu_read_unlock();
  782. return ctx->result;
  783. }
  784. /**
  785. * keyring_search - Search the supplied keyring tree for a matching key
  786. * @keyring: The root of the keyring tree to be searched.
  787. * @type: The type of keyring we want to find.
  788. * @description: The name of the keyring we want to find.
  789. *
  790. * As keyring_search_aux() above, but using the current task's credentials and
  791. * type's default matching function and preferred search method.
  792. */
  793. key_ref_t keyring_search(key_ref_t keyring,
  794. struct key_type *type,
  795. const char *description)
  796. {
  797. struct keyring_search_context ctx = {
  798. .index_key.type = type,
  799. .index_key.description = description,
  800. .index_key.desc_len = strlen(description),
  801. .cred = current_cred(),
  802. .match_data.cmp = key_default_cmp,
  803. .match_data.raw_data = description,
  804. .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT,
  805. .flags = KEYRING_SEARCH_DO_STATE_CHECK,
  806. };
  807. key_ref_t key;
  808. int ret;
  809. if (type->match_preparse) {
  810. ret = type->match_preparse(&ctx.match_data);
  811. if (ret < 0)
  812. return ERR_PTR(ret);
  813. }
  814. key = keyring_search_aux(keyring, &ctx);
  815. if (type->match_free)
  816. type->match_free(&ctx.match_data);
  817. return key;
  818. }
  819. EXPORT_SYMBOL(keyring_search);
  820. static struct key_restriction *keyring_restriction_alloc(
  821. key_restrict_link_func_t check)
  822. {
  823. struct key_restriction *keyres =
  824. kzalloc(sizeof(struct key_restriction), GFP_KERNEL);
  825. if (!keyres)
  826. return ERR_PTR(-ENOMEM);
  827. keyres->check = check;
  828. return keyres;
  829. }
  830. /*
  831. * Semaphore to serialise restriction setup to prevent reference count
  832. * cycles through restriction key pointers.
  833. */
  834. static DECLARE_RWSEM(keyring_serialise_restrict_sem);
  835. /*
  836. * Check for restriction cycles that would prevent keyring garbage collection.
  837. * keyring_serialise_restrict_sem must be held.
  838. */
  839. static bool keyring_detect_restriction_cycle(const struct key *dest_keyring,
  840. struct key_restriction *keyres)
  841. {
  842. while (keyres && keyres->key &&
  843. keyres->key->type == &key_type_keyring) {
  844. if (keyres->key == dest_keyring)
  845. return true;
  846. keyres = keyres->key->restrict_link;
  847. }
  848. return false;
  849. }
  850. /**
  851. * keyring_restrict - Look up and apply a restriction to a keyring
  852. *
  853. * @keyring: The keyring to be restricted
  854. * @restriction: The restriction options to apply to the keyring
  855. */
  856. int keyring_restrict(key_ref_t keyring_ref, const char *type,
  857. const char *restriction)
  858. {
  859. struct key *keyring;
  860. struct key_type *restrict_type = NULL;
  861. struct key_restriction *restrict_link;
  862. int ret = 0;
  863. keyring = key_ref_to_ptr(keyring_ref);
  864. key_check(keyring);
  865. if (keyring->type != &key_type_keyring)
  866. return -ENOTDIR;
  867. if (!type) {
  868. restrict_link = keyring_restriction_alloc(restrict_link_reject);
  869. } else {
  870. restrict_type = key_type_lookup(type);
  871. if (IS_ERR(restrict_type))
  872. return PTR_ERR(restrict_type);
  873. if (!restrict_type->lookup_restriction) {
  874. ret = -ENOENT;
  875. goto error;
  876. }
  877. restrict_link = restrict_type->lookup_restriction(restriction);
  878. }
  879. if (IS_ERR(restrict_link)) {
  880. ret = PTR_ERR(restrict_link);
  881. goto error;
  882. }
  883. down_write(&keyring->sem);
  884. down_write(&keyring_serialise_restrict_sem);
  885. if (keyring->restrict_link)
  886. ret = -EEXIST;
  887. else if (keyring_detect_restriction_cycle(keyring, restrict_link))
  888. ret = -EDEADLK;
  889. else
  890. keyring->restrict_link = restrict_link;
  891. up_write(&keyring_serialise_restrict_sem);
  892. up_write(&keyring->sem);
  893. if (ret < 0) {
  894. key_put(restrict_link->key);
  895. kfree(restrict_link);
  896. }
  897. error:
  898. if (restrict_type)
  899. key_type_put(restrict_type);
  900. return ret;
  901. }
  902. EXPORT_SYMBOL(keyring_restrict);
  903. /*
  904. * Search the given keyring for a key that might be updated.
  905. *
  906. * The caller must guarantee that the keyring is a keyring and that the
  907. * permission is granted to modify the keyring as no check is made here. The
  908. * caller must also hold a lock on the keyring semaphore.
  909. *
  910. * Returns a pointer to the found key with usage count incremented if
  911. * successful and returns NULL if not found. Revoked and invalidated keys are
  912. * skipped over.
  913. *
  914. * If successful, the possession indicator is propagated from the keyring ref
  915. * to the returned key reference.
  916. */
  917. key_ref_t find_key_to_update(key_ref_t keyring_ref,
  918. const struct keyring_index_key *index_key)
  919. {
  920. struct key *keyring, *key;
  921. const void *object;
  922. keyring = key_ref_to_ptr(keyring_ref);
  923. kenter("{%d},{%s,%s}",
  924. keyring->serial, index_key->type->name, index_key->description);
  925. object = assoc_array_find(&keyring->keys, &keyring_assoc_array_ops,
  926. index_key);
  927. if (object)
  928. goto found;
  929. kleave(" = NULL");
  930. return NULL;
  931. found:
  932. key = keyring_ptr_to_key(object);
  933. if (key->flags & ((1 << KEY_FLAG_INVALIDATED) |
  934. (1 << KEY_FLAG_REVOKED))) {
  935. kleave(" = NULL [x]");
  936. return NULL;
  937. }
  938. __key_get(key);
  939. kleave(" = {%d}", key->serial);
  940. return make_key_ref(key, is_key_possessed(keyring_ref));
  941. }
  942. /*
  943. * Find a keyring with the specified name.
  944. *
  945. * Only keyrings that have nonzero refcount, are not revoked, and are owned by a
  946. * user in the current user namespace are considered. If @uid_keyring is %true,
  947. * the keyring additionally must have been allocated as a user or user session
  948. * keyring; otherwise, it must grant Search permission directly to the caller.
  949. *
  950. * Returns a pointer to the keyring with the keyring's refcount having being
  951. * incremented on success. -ENOKEY is returned if a key could not be found.
  952. */
  953. struct key *find_keyring_by_name(const char *name, bool uid_keyring)
  954. {
  955. struct key *keyring;
  956. int bucket;
  957. if (!name)
  958. return ERR_PTR(-EINVAL);
  959. bucket = keyring_hash(name);
  960. read_lock(&keyring_name_lock);
  961. if (keyring_name_hash[bucket].next) {
  962. /* search this hash bucket for a keyring with a matching name
  963. * that's readable and that hasn't been revoked */
  964. list_for_each_entry(keyring,
  965. &keyring_name_hash[bucket],
  966. name_link
  967. ) {
  968. if (!kuid_has_mapping(current_user_ns(), keyring->user->uid))
  969. continue;
  970. if (test_bit(KEY_FLAG_REVOKED, &keyring->flags))
  971. continue;
  972. if (strcmp(keyring->description, name) != 0)
  973. continue;
  974. if (uid_keyring) {
  975. if (!test_bit(KEY_FLAG_UID_KEYRING,
  976. &keyring->flags))
  977. continue;
  978. } else {
  979. if (key_permission(make_key_ref(keyring, 0),
  980. KEY_NEED_SEARCH) < 0)
  981. continue;
  982. }
  983. /* we've got a match but we might end up racing with
  984. * key_cleanup() if the keyring is currently 'dead'
  985. * (ie. it has a zero usage count) */
  986. if (!refcount_inc_not_zero(&keyring->usage))
  987. continue;
  988. keyring->last_used_at = ktime_get_real_seconds();
  989. goto out;
  990. }
  991. }
  992. keyring = ERR_PTR(-ENOKEY);
  993. out:
  994. read_unlock(&keyring_name_lock);
  995. return keyring;
  996. }
  997. static int keyring_detect_cycle_iterator(const void *object,
  998. void *iterator_data)
  999. {
  1000. struct keyring_search_context *ctx = iterator_data;
  1001. const struct key *key = keyring_ptr_to_key(object);
  1002. kenter("{%d}", key->serial);
  1003. /* We might get a keyring with matching index-key that is nonetheless a
  1004. * different keyring. */
  1005. if (key != ctx->match_data.raw_data)
  1006. return 0;
  1007. ctx->result = ERR_PTR(-EDEADLK);
  1008. return 1;
  1009. }
  1010. /*
  1011. * See if a cycle will will be created by inserting acyclic tree B in acyclic
  1012. * tree A at the topmost level (ie: as a direct child of A).
  1013. *
  1014. * Since we are adding B to A at the top level, checking for cycles should just
  1015. * be a matter of seeing if node A is somewhere in tree B.
  1016. */
  1017. static int keyring_detect_cycle(struct key *A, struct key *B)
  1018. {
  1019. struct keyring_search_context ctx = {
  1020. .index_key = A->index_key,
  1021. .match_data.raw_data = A,
  1022. .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT,
  1023. .iterator = keyring_detect_cycle_iterator,
  1024. .flags = (KEYRING_SEARCH_NO_STATE_CHECK |
  1025. KEYRING_SEARCH_NO_UPDATE_TIME |
  1026. KEYRING_SEARCH_NO_CHECK_PERM |
  1027. KEYRING_SEARCH_DETECT_TOO_DEEP),
  1028. };
  1029. rcu_read_lock();
  1030. search_nested_keyrings(B, &ctx);
  1031. rcu_read_unlock();
  1032. return PTR_ERR(ctx.result) == -EAGAIN ? 0 : PTR_ERR(ctx.result);
  1033. }
  1034. /*
  1035. * Preallocate memory so that a key can be linked into to a keyring.
  1036. */
  1037. int __key_link_begin(struct key *keyring,
  1038. const struct keyring_index_key *index_key,
  1039. struct assoc_array_edit **_edit)
  1040. __acquires(&keyring->sem)
  1041. __acquires(&keyring_serialise_link_sem)
  1042. {
  1043. struct assoc_array_edit *edit;
  1044. int ret;
  1045. kenter("%d,%s,%s,",
  1046. keyring->serial, index_key->type->name, index_key->description);
  1047. BUG_ON(index_key->desc_len == 0);
  1048. if (keyring->type != &key_type_keyring)
  1049. return -ENOTDIR;
  1050. down_write(&keyring->sem);
  1051. ret = -EKEYREVOKED;
  1052. if (test_bit(KEY_FLAG_REVOKED, &keyring->flags))
  1053. goto error_krsem;
  1054. /* serialise link/link calls to prevent parallel calls causing a cycle
  1055. * when linking two keyring in opposite orders */
  1056. if (index_key->type == &key_type_keyring)
  1057. down_write(&keyring_serialise_link_sem);
  1058. /* Create an edit script that will insert/replace the key in the
  1059. * keyring tree.
  1060. */
  1061. edit = assoc_array_insert(&keyring->keys,
  1062. &keyring_assoc_array_ops,
  1063. index_key,
  1064. NULL);
  1065. if (IS_ERR(edit)) {
  1066. ret = PTR_ERR(edit);
  1067. goto error_sem;
  1068. }
  1069. /* If we're not replacing a link in-place then we're going to need some
  1070. * extra quota.
  1071. */
  1072. if (!edit->dead_leaf) {
  1073. ret = key_payload_reserve(keyring,
  1074. keyring->datalen + KEYQUOTA_LINK_BYTES);
  1075. if (ret < 0)
  1076. goto error_cancel;
  1077. }
  1078. *_edit = edit;
  1079. kleave(" = 0");
  1080. return 0;
  1081. error_cancel:
  1082. assoc_array_cancel_edit(edit);
  1083. error_sem:
  1084. if (index_key->type == &key_type_keyring)
  1085. up_write(&keyring_serialise_link_sem);
  1086. error_krsem:
  1087. up_write(&keyring->sem);
  1088. kleave(" = %d", ret);
  1089. return ret;
  1090. }
  1091. /*
  1092. * Check already instantiated keys aren't going to be a problem.
  1093. *
  1094. * The caller must have called __key_link_begin(). Don't need to call this for
  1095. * keys that were created since __key_link_begin() was called.
  1096. */
  1097. int __key_link_check_live_key(struct key *keyring, struct key *key)
  1098. {
  1099. if (key->type == &key_type_keyring)
  1100. /* check that we aren't going to create a cycle by linking one
  1101. * keyring to another */
  1102. return keyring_detect_cycle(keyring, key);
  1103. return 0;
  1104. }
  1105. /*
  1106. * Link a key into to a keyring.
  1107. *
  1108. * Must be called with __key_link_begin() having being called. Discards any
  1109. * already extant link to matching key if there is one, so that each keyring
  1110. * holds at most one link to any given key of a particular type+description
  1111. * combination.
  1112. */
  1113. void __key_link(struct key *key, struct assoc_array_edit **_edit)
  1114. {
  1115. __key_get(key);
  1116. assoc_array_insert_set_object(*_edit, keyring_key_to_ptr(key));
  1117. assoc_array_apply_edit(*_edit);
  1118. *_edit = NULL;
  1119. }
  1120. /*
  1121. * Finish linking a key into to a keyring.
  1122. *
  1123. * Must be called with __key_link_begin() having being called.
  1124. */
  1125. void __key_link_end(struct key *keyring,
  1126. const struct keyring_index_key *index_key,
  1127. struct assoc_array_edit *edit)
  1128. __releases(&keyring->sem)
  1129. __releases(&keyring_serialise_link_sem)
  1130. {
  1131. BUG_ON(index_key->type == NULL);
  1132. kenter("%d,%s,", keyring->serial, index_key->type->name);
  1133. if (index_key->type == &key_type_keyring)
  1134. up_write(&keyring_serialise_link_sem);
  1135. if (edit) {
  1136. if (!edit->dead_leaf) {
  1137. key_payload_reserve(keyring,
  1138. keyring->datalen - KEYQUOTA_LINK_BYTES);
  1139. }
  1140. assoc_array_cancel_edit(edit);
  1141. }
  1142. up_write(&keyring->sem);
  1143. }
  1144. /*
  1145. * Check addition of keys to restricted keyrings.
  1146. */
  1147. static int __key_link_check_restriction(struct key *keyring, struct key *key)
  1148. {
  1149. if (!keyring->restrict_link || !keyring->restrict_link->check)
  1150. return 0;
  1151. return keyring->restrict_link->check(keyring, key->type, &key->payload,
  1152. keyring->restrict_link->key);
  1153. }
  1154. /**
  1155. * key_link - Link a key to a keyring
  1156. * @keyring: The keyring to make the link in.
  1157. * @key: The key to link to.
  1158. *
  1159. * Make a link in a keyring to a key, such that the keyring holds a reference
  1160. * on that key and the key can potentially be found by searching that keyring.
  1161. *
  1162. * This function will write-lock the keyring's semaphore and will consume some
  1163. * of the user's key data quota to hold the link.
  1164. *
  1165. * Returns 0 if successful, -ENOTDIR if the keyring isn't a keyring,
  1166. * -EKEYREVOKED if the keyring has been revoked, -ENFILE if the keyring is
  1167. * full, -EDQUOT if there is insufficient key data quota remaining to add
  1168. * another link or -ENOMEM if there's insufficient memory.
  1169. *
  1170. * It is assumed that the caller has checked that it is permitted for a link to
  1171. * be made (the keyring should have Write permission and the key Link
  1172. * permission).
  1173. */
  1174. int key_link(struct key *keyring, struct key *key)
  1175. {
  1176. struct assoc_array_edit *edit;
  1177. int ret;
  1178. kenter("{%d,%d}", keyring->serial, refcount_read(&keyring->usage));
  1179. key_check(keyring);
  1180. key_check(key);
  1181. ret = __key_link_begin(keyring, &key->index_key, &edit);
  1182. if (ret == 0) {
  1183. kdebug("begun {%d,%d}", keyring->serial, refcount_read(&keyring->usage));
  1184. ret = __key_link_check_restriction(keyring, key);
  1185. if (ret == 0)
  1186. ret = __key_link_check_live_key(keyring, key);
  1187. if (ret == 0)
  1188. __key_link(key, &edit);
  1189. __key_link_end(keyring, &key->index_key, edit);
  1190. }
  1191. kleave(" = %d {%d,%d}", ret, keyring->serial, refcount_read(&keyring->usage));
  1192. return ret;
  1193. }
  1194. EXPORT_SYMBOL(key_link);
  1195. /**
  1196. * key_unlink - Unlink the first link to a key from a keyring.
  1197. * @keyring: The keyring to remove the link from.
  1198. * @key: The key the link is to.
  1199. *
  1200. * Remove a link from a keyring to a key.
  1201. *
  1202. * This function will write-lock the keyring's semaphore.
  1203. *
  1204. * Returns 0 if successful, -ENOTDIR if the keyring isn't a keyring, -ENOENT if
  1205. * the key isn't linked to by the keyring or -ENOMEM if there's insufficient
  1206. * memory.
  1207. *
  1208. * It is assumed that the caller has checked that it is permitted for a link to
  1209. * be removed (the keyring should have Write permission; no permissions are
  1210. * required on the key).
  1211. */
  1212. int key_unlink(struct key *keyring, struct key *key)
  1213. {
  1214. struct assoc_array_edit *edit;
  1215. int ret;
  1216. key_check(keyring);
  1217. key_check(key);
  1218. if (keyring->type != &key_type_keyring)
  1219. return -ENOTDIR;
  1220. down_write(&keyring->sem);
  1221. edit = assoc_array_delete(&keyring->keys, &keyring_assoc_array_ops,
  1222. &key->index_key);
  1223. if (IS_ERR(edit)) {
  1224. ret = PTR_ERR(edit);
  1225. goto error;
  1226. }
  1227. ret = -ENOENT;
  1228. if (edit == NULL)
  1229. goto error;
  1230. assoc_array_apply_edit(edit);
  1231. key_payload_reserve(keyring, keyring->datalen - KEYQUOTA_LINK_BYTES);
  1232. ret = 0;
  1233. error:
  1234. up_write(&keyring->sem);
  1235. return ret;
  1236. }
  1237. EXPORT_SYMBOL(key_unlink);
  1238. /**
  1239. * keyring_clear - Clear a keyring
  1240. * @keyring: The keyring to clear.
  1241. *
  1242. * Clear the contents of the specified keyring.
  1243. *
  1244. * Returns 0 if successful or -ENOTDIR if the keyring isn't a keyring.
  1245. */
  1246. int keyring_clear(struct key *keyring)
  1247. {
  1248. struct assoc_array_edit *edit;
  1249. int ret;
  1250. if (keyring->type != &key_type_keyring)
  1251. return -ENOTDIR;
  1252. down_write(&keyring->sem);
  1253. edit = assoc_array_clear(&keyring->keys, &keyring_assoc_array_ops);
  1254. if (IS_ERR(edit)) {
  1255. ret = PTR_ERR(edit);
  1256. } else {
  1257. if (edit)
  1258. assoc_array_apply_edit(edit);
  1259. key_payload_reserve(keyring, 0);
  1260. ret = 0;
  1261. }
  1262. up_write(&keyring->sem);
  1263. return ret;
  1264. }
  1265. EXPORT_SYMBOL(keyring_clear);
  1266. /*
  1267. * Dispose of the links from a revoked keyring.
  1268. *
  1269. * This is called with the key sem write-locked.
  1270. */
  1271. static void keyring_revoke(struct key *keyring)
  1272. {
  1273. struct assoc_array_edit *edit;
  1274. edit = assoc_array_clear(&keyring->keys, &keyring_assoc_array_ops);
  1275. if (!IS_ERR(edit)) {
  1276. if (edit)
  1277. assoc_array_apply_edit(edit);
  1278. key_payload_reserve(keyring, 0);
  1279. }
  1280. }
  1281. static bool keyring_gc_select_iterator(void *object, void *iterator_data)
  1282. {
  1283. struct key *key = keyring_ptr_to_key(object);
  1284. time64_t *limit = iterator_data;
  1285. if (key_is_dead(key, *limit))
  1286. return false;
  1287. key_get(key);
  1288. return true;
  1289. }
  1290. static int keyring_gc_check_iterator(const void *object, void *iterator_data)
  1291. {
  1292. const struct key *key = keyring_ptr_to_key(object);
  1293. time64_t *limit = iterator_data;
  1294. key_check(key);
  1295. return key_is_dead(key, *limit);
  1296. }
  1297. /*
  1298. * Garbage collect pointers from a keyring.
  1299. *
  1300. * Not called with any locks held. The keyring's key struct will not be
  1301. * deallocated under us as only our caller may deallocate it.
  1302. */
  1303. void keyring_gc(struct key *keyring, time64_t limit)
  1304. {
  1305. int result;
  1306. kenter("%x{%s}", keyring->serial, keyring->description ?: "");
  1307. if (keyring->flags & ((1 << KEY_FLAG_INVALIDATED) |
  1308. (1 << KEY_FLAG_REVOKED)))
  1309. goto dont_gc;
  1310. /* scan the keyring looking for dead keys */
  1311. rcu_read_lock();
  1312. result = assoc_array_iterate(&keyring->keys,
  1313. keyring_gc_check_iterator, &limit);
  1314. rcu_read_unlock();
  1315. if (result == true)
  1316. goto do_gc;
  1317. dont_gc:
  1318. kleave(" [no gc]");
  1319. return;
  1320. do_gc:
  1321. down_write(&keyring->sem);
  1322. assoc_array_gc(&keyring->keys, &keyring_assoc_array_ops,
  1323. keyring_gc_select_iterator, &limit);
  1324. up_write(&keyring->sem);
  1325. kleave(" [gc]");
  1326. }
  1327. /*
  1328. * Garbage collect restriction pointers from a keyring.
  1329. *
  1330. * Keyring restrictions are associated with a key type, and must be cleaned
  1331. * up if the key type is unregistered. The restriction is altered to always
  1332. * reject additional keys so a keyring cannot be opened up by unregistering
  1333. * a key type.
  1334. *
  1335. * Not called with any keyring locks held. The keyring's key struct will not
  1336. * be deallocated under us as only our caller may deallocate it.
  1337. *
  1338. * The caller is required to hold key_types_sem and dead_type->sem. This is
  1339. * fulfilled by key_gc_keytype() holding the locks on behalf of
  1340. * key_garbage_collector(), which it invokes on a workqueue.
  1341. */
  1342. void keyring_restriction_gc(struct key *keyring, struct key_type *dead_type)
  1343. {
  1344. struct key_restriction *keyres;
  1345. kenter("%x{%s}", keyring->serial, keyring->description ?: "");
  1346. /*
  1347. * keyring->restrict_link is only assigned at key allocation time
  1348. * or with the key type locked, so the only values that could be
  1349. * concurrently assigned to keyring->restrict_link are for key
  1350. * types other than dead_type. Given this, it's ok to check
  1351. * the key type before acquiring keyring->sem.
  1352. */
  1353. if (!dead_type || !keyring->restrict_link ||
  1354. keyring->restrict_link->keytype != dead_type) {
  1355. kleave(" [no restriction gc]");
  1356. return;
  1357. }
  1358. /* Lock the keyring to ensure that a link is not in progress */
  1359. down_write(&keyring->sem);
  1360. keyres = keyring->restrict_link;
  1361. keyres->check = restrict_link_reject;
  1362. key_put(keyres->key);
  1363. keyres->key = NULL;
  1364. keyres->keytype = NULL;
  1365. up_write(&keyring->sem);
  1366. kleave(" [restriction gc]");
  1367. }