keyring.c 42 KB

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