keyring.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233
  1. /* Keyring handling
  2. *
  3. * Copyright (C) 2004-2005, 2008 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 <linux/uaccess.h>
  20. #include "internal.h"
  21. #define rcu_dereference_locked_keyring(keyring) \
  22. (rcu_dereference_protected( \
  23. (keyring)->payload.subscriptions, \
  24. rwsem_is_locked((struct rw_semaphore *)&(keyring)->sem)))
  25. #define KEY_LINK_FIXQUOTA 1UL
  26. /*
  27. * When plumbing the depths of the key tree, this sets a hard limit
  28. * set on how deep we're willing to go.
  29. */
  30. #define KEYRING_SEARCH_MAX_DEPTH 6
  31. /*
  32. * We keep all named keyrings in a hash to speed looking them up.
  33. */
  34. #define KEYRING_NAME_HASH_SIZE (1 << 5)
  35. static struct list_head keyring_name_hash[KEYRING_NAME_HASH_SIZE];
  36. static DEFINE_RWLOCK(keyring_name_lock);
  37. static inline unsigned keyring_hash(const char *desc)
  38. {
  39. unsigned bucket = 0;
  40. for (; *desc; desc++)
  41. bucket += (unsigned char)*desc;
  42. return bucket & (KEYRING_NAME_HASH_SIZE - 1);
  43. }
  44. /*
  45. * The keyring key type definition. Keyrings are simply keys of this type and
  46. * can be treated as ordinary keys in addition to having their own special
  47. * operations.
  48. */
  49. static int keyring_instantiate(struct key *keyring,
  50. const void *data, size_t datalen);
  51. static int keyring_match(const struct key *keyring, const void *criterion);
  52. static void keyring_revoke(struct key *keyring);
  53. static void keyring_destroy(struct key *keyring);
  54. static void keyring_describe(const struct key *keyring, struct seq_file *m);
  55. static long keyring_read(const struct key *keyring,
  56. char __user *buffer, size_t buflen);
  57. struct key_type key_type_keyring = {
  58. .name = "keyring",
  59. .def_datalen = sizeof(struct keyring_list),
  60. .instantiate = keyring_instantiate,
  61. .match = keyring_match,
  62. .revoke = keyring_revoke,
  63. .destroy = keyring_destroy,
  64. .describe = keyring_describe,
  65. .read = keyring_read,
  66. };
  67. EXPORT_SYMBOL(key_type_keyring);
  68. /*
  69. * Semaphore to serialise link/link calls to prevent two link calls in parallel
  70. * introducing a cycle.
  71. */
  72. static DECLARE_RWSEM(keyring_serialise_link_sem);
  73. /*
  74. * Publish the name of a keyring so that it can be found by name (if it has
  75. * one).
  76. */
  77. static void keyring_publish_name(struct key *keyring)
  78. {
  79. int bucket;
  80. if (keyring->description) {
  81. bucket = keyring_hash(keyring->description);
  82. write_lock(&keyring_name_lock);
  83. if (!keyring_name_hash[bucket].next)
  84. INIT_LIST_HEAD(&keyring_name_hash[bucket]);
  85. list_add_tail(&keyring->type_data.link,
  86. &keyring_name_hash[bucket]);
  87. write_unlock(&keyring_name_lock);
  88. }
  89. }
  90. /*
  91. * Initialise a keyring.
  92. *
  93. * Returns 0 on success, -EINVAL if given any data.
  94. */
  95. static int keyring_instantiate(struct key *keyring,
  96. const void *data, size_t datalen)
  97. {
  98. int ret;
  99. ret = -EINVAL;
  100. if (datalen == 0) {
  101. /* make the keyring available by name if it has one */
  102. keyring_publish_name(keyring);
  103. ret = 0;
  104. }
  105. return ret;
  106. }
  107. /*
  108. * Match keyrings on their name
  109. */
  110. static int keyring_match(const struct key *keyring, const void *description)
  111. {
  112. return keyring->description &&
  113. strcmp(keyring->description, description) == 0;
  114. }
  115. /*
  116. * Clean up a keyring when it is destroyed. Unpublish its name if it had one
  117. * and dispose of its data.
  118. */
  119. static void keyring_destroy(struct key *keyring)
  120. {
  121. struct keyring_list *klist;
  122. int loop;
  123. if (keyring->description) {
  124. write_lock(&keyring_name_lock);
  125. if (keyring->type_data.link.next != NULL &&
  126. !list_empty(&keyring->type_data.link))
  127. list_del(&keyring->type_data.link);
  128. write_unlock(&keyring_name_lock);
  129. }
  130. klist = rcu_dereference_check(keyring->payload.subscriptions,
  131. atomic_read(&keyring->usage) == 0);
  132. if (klist) {
  133. for (loop = klist->nkeys - 1; loop >= 0; loop--)
  134. key_put(klist->keys[loop]);
  135. kfree(klist);
  136. }
  137. }
  138. /*
  139. * Describe a keyring for /proc.
  140. */
  141. static void keyring_describe(const struct key *keyring, struct seq_file *m)
  142. {
  143. struct keyring_list *klist;
  144. if (keyring->description)
  145. seq_puts(m, keyring->description);
  146. else
  147. seq_puts(m, "[anon]");
  148. if (key_is_instantiated(keyring)) {
  149. rcu_read_lock();
  150. klist = rcu_dereference(keyring->payload.subscriptions);
  151. if (klist)
  152. seq_printf(m, ": %u/%u", klist->nkeys, klist->maxkeys);
  153. else
  154. seq_puts(m, ": empty");
  155. rcu_read_unlock();
  156. }
  157. }
  158. /*
  159. * Read a list of key IDs from the keyring's contents in binary form
  160. *
  161. * The keyring's semaphore is read-locked by the caller.
  162. */
  163. static long keyring_read(const struct key *keyring,
  164. char __user *buffer, size_t buflen)
  165. {
  166. struct keyring_list *klist;
  167. struct key *key;
  168. size_t qty, tmp;
  169. int loop, ret;
  170. ret = 0;
  171. klist = rcu_dereference_locked_keyring(keyring);
  172. if (klist) {
  173. /* calculate how much data we could return */
  174. qty = klist->nkeys * sizeof(key_serial_t);
  175. if (buffer && buflen > 0) {
  176. if (buflen > qty)
  177. buflen = qty;
  178. /* copy the IDs of the subscribed keys into the
  179. * buffer */
  180. ret = -EFAULT;
  181. for (loop = 0; loop < klist->nkeys; loop++) {
  182. key = klist->keys[loop];
  183. tmp = sizeof(key_serial_t);
  184. if (tmp > buflen)
  185. tmp = buflen;
  186. if (copy_to_user(buffer,
  187. &key->serial,
  188. tmp) != 0)
  189. goto error;
  190. buflen -= tmp;
  191. if (buflen == 0)
  192. break;
  193. buffer += tmp;
  194. }
  195. }
  196. ret = qty;
  197. }
  198. error:
  199. return ret;
  200. }
  201. /*
  202. * Allocate a keyring and link into the destination keyring.
  203. */
  204. struct key *keyring_alloc(const char *description, uid_t uid, gid_t gid,
  205. const struct cred *cred, unsigned long flags,
  206. struct key *dest)
  207. {
  208. struct key *keyring;
  209. int ret;
  210. keyring = key_alloc(&key_type_keyring, description,
  211. uid, gid, cred,
  212. (KEY_POS_ALL & ~KEY_POS_SETATTR) | KEY_USR_ALL,
  213. flags);
  214. if (!IS_ERR(keyring)) {
  215. ret = key_instantiate_and_link(keyring, NULL, 0, dest, NULL);
  216. if (ret < 0) {
  217. key_put(keyring);
  218. keyring = ERR_PTR(ret);
  219. }
  220. }
  221. return keyring;
  222. }
  223. /**
  224. * keyring_search_aux - Search a keyring tree for a key matching some criteria
  225. * @keyring_ref: A pointer to the keyring with possession indicator.
  226. * @cred: The credentials to use for permissions checks.
  227. * @type: The type of key to search for.
  228. * @description: Parameter for @match.
  229. * @match: Function to rule on whether or not a key is the one required.
  230. * @no_state_check: Don't check if a matching key is bad
  231. *
  232. * Search the supplied keyring tree for a key that matches the criteria given.
  233. * The root keyring and any linked keyrings must grant Search permission to the
  234. * caller to be searchable and keys can only be found if they too grant Search
  235. * to the caller. The possession flag on the root keyring pointer controls use
  236. * of the possessor bits in permissions checking of the entire tree. In
  237. * addition, the LSM gets to forbid keyring searches and key matches.
  238. *
  239. * The search is performed as a breadth-then-depth search up to the prescribed
  240. * limit (KEYRING_SEARCH_MAX_DEPTH).
  241. *
  242. * Keys are matched to the type provided and are then filtered by the match
  243. * function, which is given the description to use in any way it sees fit. The
  244. * match function may use any attributes of a key that it wishes to to
  245. * determine the match. Normally the match function from the key type would be
  246. * used.
  247. *
  248. * RCU is used to prevent the keyring key lists from disappearing without the
  249. * need to take lots of locks.
  250. *
  251. * Returns a pointer to the found key and increments the key usage count if
  252. * successful; -EAGAIN if no matching keys were found, or if expired or revoked
  253. * keys were found; -ENOKEY if only negative keys were found; -ENOTDIR if the
  254. * specified keyring wasn't a keyring.
  255. *
  256. * In the case of a successful return, the possession attribute from
  257. * @keyring_ref is propagated to the returned key reference.
  258. */
  259. key_ref_t keyring_search_aux(key_ref_t keyring_ref,
  260. const struct cred *cred,
  261. struct key_type *type,
  262. const void *description,
  263. key_match_func_t match,
  264. bool no_state_check)
  265. {
  266. struct {
  267. struct keyring_list *keylist;
  268. int kix;
  269. } stack[KEYRING_SEARCH_MAX_DEPTH];
  270. struct keyring_list *keylist;
  271. struct timespec now;
  272. unsigned long possessed, kflags;
  273. struct key *keyring, *key;
  274. key_ref_t key_ref;
  275. long err;
  276. int sp, nkeys, kix;
  277. keyring = key_ref_to_ptr(keyring_ref);
  278. possessed = is_key_possessed(keyring_ref);
  279. key_check(keyring);
  280. /* top keyring must have search permission to begin the search */
  281. err = key_task_permission(keyring_ref, cred, KEY_SEARCH);
  282. if (err < 0) {
  283. key_ref = ERR_PTR(err);
  284. goto error;
  285. }
  286. key_ref = ERR_PTR(-ENOTDIR);
  287. if (keyring->type != &key_type_keyring)
  288. goto error;
  289. rcu_read_lock();
  290. now = current_kernel_time();
  291. err = -EAGAIN;
  292. sp = 0;
  293. /* firstly we should check to see if this top-level keyring is what we
  294. * are looking for */
  295. key_ref = ERR_PTR(-EAGAIN);
  296. kflags = keyring->flags;
  297. if (keyring->type == type && match(keyring, description)) {
  298. key = keyring;
  299. if (no_state_check)
  300. goto found;
  301. /* check it isn't negative and hasn't expired or been
  302. * revoked */
  303. if (kflags & (1 << KEY_FLAG_REVOKED))
  304. goto error_2;
  305. if (key->expiry && now.tv_sec >= key->expiry)
  306. goto error_2;
  307. key_ref = ERR_PTR(key->type_data.reject_error);
  308. if (kflags & (1 << KEY_FLAG_NEGATIVE))
  309. goto error_2;
  310. goto found;
  311. }
  312. /* otherwise, the top keyring must not be revoked, expired, or
  313. * negatively instantiated if we are to search it */
  314. key_ref = ERR_PTR(-EAGAIN);
  315. if (kflags & ((1 << KEY_FLAG_REVOKED) | (1 << KEY_FLAG_NEGATIVE)) ||
  316. (keyring->expiry && now.tv_sec >= keyring->expiry))
  317. goto error_2;
  318. /* start processing a new keyring */
  319. descend:
  320. if (test_bit(KEY_FLAG_REVOKED, &keyring->flags))
  321. goto not_this_keyring;
  322. keylist = rcu_dereference(keyring->payload.subscriptions);
  323. if (!keylist)
  324. goto not_this_keyring;
  325. /* iterate through the keys in this keyring first */
  326. nkeys = keylist->nkeys;
  327. smp_rmb();
  328. for (kix = 0; kix < nkeys; kix++) {
  329. key = keylist->keys[kix];
  330. kflags = key->flags;
  331. /* ignore keys not of this type */
  332. if (key->type != type)
  333. continue;
  334. /* skip revoked keys and expired keys */
  335. if (!no_state_check) {
  336. if (kflags & (1 << KEY_FLAG_REVOKED))
  337. continue;
  338. if (key->expiry && now.tv_sec >= key->expiry)
  339. continue;
  340. }
  341. /* keys that don't match */
  342. if (!match(key, description))
  343. continue;
  344. /* key must have search permissions */
  345. if (key_task_permission(make_key_ref(key, possessed),
  346. cred, KEY_SEARCH) < 0)
  347. continue;
  348. if (no_state_check)
  349. goto found;
  350. /* we set a different error code if we pass a negative key */
  351. if (kflags & (1 << KEY_FLAG_NEGATIVE)) {
  352. err = key->type_data.reject_error;
  353. continue;
  354. }
  355. goto found;
  356. }
  357. /* search through the keyrings nested in this one */
  358. kix = 0;
  359. ascend:
  360. nkeys = keylist->nkeys;
  361. smp_rmb();
  362. for (; kix < nkeys; kix++) {
  363. key = keylist->keys[kix];
  364. if (key->type != &key_type_keyring)
  365. continue;
  366. /* recursively search nested keyrings
  367. * - only search keyrings for which we have search permission
  368. */
  369. if (sp >= KEYRING_SEARCH_MAX_DEPTH)
  370. continue;
  371. if (key_task_permission(make_key_ref(key, possessed),
  372. cred, KEY_SEARCH) < 0)
  373. continue;
  374. /* stack the current position */
  375. stack[sp].keylist = keylist;
  376. stack[sp].kix = kix;
  377. sp++;
  378. /* begin again with the new keyring */
  379. keyring = key;
  380. goto descend;
  381. }
  382. /* the keyring we're looking at was disqualified or didn't contain a
  383. * matching key */
  384. not_this_keyring:
  385. if (sp > 0) {
  386. /* resume the processing of a keyring higher up in the tree */
  387. sp--;
  388. keylist = stack[sp].keylist;
  389. kix = stack[sp].kix + 1;
  390. goto ascend;
  391. }
  392. key_ref = ERR_PTR(err);
  393. goto error_2;
  394. /* we found a viable match */
  395. found:
  396. atomic_inc(&key->usage);
  397. key_check(key);
  398. key_ref = make_key_ref(key, possessed);
  399. error_2:
  400. rcu_read_unlock();
  401. error:
  402. return key_ref;
  403. }
  404. /**
  405. * keyring_search - Search the supplied keyring tree for a matching key
  406. * @keyring: The root of the keyring tree to be searched.
  407. * @type: The type of keyring we want to find.
  408. * @description: The name of the keyring we want to find.
  409. *
  410. * As keyring_search_aux() above, but using the current task's credentials and
  411. * type's default matching function.
  412. */
  413. key_ref_t keyring_search(key_ref_t keyring,
  414. struct key_type *type,
  415. const char *description)
  416. {
  417. if (!type->match)
  418. return ERR_PTR(-ENOKEY);
  419. return keyring_search_aux(keyring, current->cred,
  420. type, description, type->match, false);
  421. }
  422. EXPORT_SYMBOL(keyring_search);
  423. /*
  424. * Search the given keyring only (no recursion).
  425. *
  426. * The caller must guarantee that the keyring is a keyring and that the
  427. * permission is granted to search the keyring as no check is made here.
  428. *
  429. * RCU is used to make it unnecessary to lock the keyring key list here.
  430. *
  431. * Returns a pointer to the found key with usage count incremented if
  432. * successful and returns -ENOKEY if not found. Revoked keys and keys not
  433. * providing the requested permission are skipped over.
  434. *
  435. * If successful, the possession indicator is propagated from the keyring ref
  436. * to the returned key reference.
  437. */
  438. key_ref_t __keyring_search_one(key_ref_t keyring_ref,
  439. const struct key_type *ktype,
  440. const char *description,
  441. key_perm_t perm)
  442. {
  443. struct keyring_list *klist;
  444. unsigned long possessed;
  445. struct key *keyring, *key;
  446. int nkeys, loop;
  447. keyring = key_ref_to_ptr(keyring_ref);
  448. possessed = is_key_possessed(keyring_ref);
  449. rcu_read_lock();
  450. klist = rcu_dereference(keyring->payload.subscriptions);
  451. if (klist) {
  452. nkeys = klist->nkeys;
  453. smp_rmb();
  454. for (loop = 0; loop < nkeys ; loop++) {
  455. key = klist->keys[loop];
  456. if (key->type == ktype &&
  457. (!key->type->match ||
  458. key->type->match(key, description)) &&
  459. key_permission(make_key_ref(key, possessed),
  460. perm) == 0 &&
  461. !test_bit(KEY_FLAG_REVOKED, &key->flags)
  462. )
  463. goto found;
  464. }
  465. }
  466. rcu_read_unlock();
  467. return ERR_PTR(-ENOKEY);
  468. found:
  469. atomic_inc(&key->usage);
  470. rcu_read_unlock();
  471. return make_key_ref(key, possessed);
  472. }
  473. /*
  474. * Find a keyring with the specified name.
  475. *
  476. * All named keyrings in the current user namespace are searched, provided they
  477. * grant Search permission directly to the caller (unless this check is
  478. * skipped). Keyrings whose usage points have reached zero or who have been
  479. * revoked are skipped.
  480. *
  481. * Returns a pointer to the keyring with the keyring's refcount having being
  482. * incremented on success. -ENOKEY is returned if a key could not be found.
  483. */
  484. struct key *find_keyring_by_name(const char *name, bool skip_perm_check)
  485. {
  486. struct key *keyring;
  487. int bucket;
  488. if (!name)
  489. return ERR_PTR(-EINVAL);
  490. bucket = keyring_hash(name);
  491. read_lock(&keyring_name_lock);
  492. if (keyring_name_hash[bucket].next) {
  493. /* search this hash bucket for a keyring with a matching name
  494. * that's readable and that hasn't been revoked */
  495. list_for_each_entry(keyring,
  496. &keyring_name_hash[bucket],
  497. type_data.link
  498. ) {
  499. if (keyring->user->user_ns != current_user_ns())
  500. continue;
  501. if (test_bit(KEY_FLAG_REVOKED, &keyring->flags))
  502. continue;
  503. if (strcmp(keyring->description, name) != 0)
  504. continue;
  505. if (!skip_perm_check &&
  506. key_permission(make_key_ref(keyring, 0),
  507. KEY_SEARCH) < 0)
  508. continue;
  509. /* we've got a match but we might end up racing with
  510. * key_cleanup() if the keyring is currently 'dead'
  511. * (ie. it has a zero usage count) */
  512. if (!atomic_inc_not_zero(&keyring->usage))
  513. continue;
  514. goto out;
  515. }
  516. }
  517. keyring = ERR_PTR(-ENOKEY);
  518. out:
  519. read_unlock(&keyring_name_lock);
  520. return keyring;
  521. }
  522. /*
  523. * See if a cycle will will be created by inserting acyclic tree B in acyclic
  524. * tree A at the topmost level (ie: as a direct child of A).
  525. *
  526. * Since we are adding B to A at the top level, checking for cycles should just
  527. * be a matter of seeing if node A is somewhere in tree B.
  528. */
  529. static int keyring_detect_cycle(struct key *A, struct key *B)
  530. {
  531. struct {
  532. struct keyring_list *keylist;
  533. int kix;
  534. } stack[KEYRING_SEARCH_MAX_DEPTH];
  535. struct keyring_list *keylist;
  536. struct key *subtree, *key;
  537. int sp, nkeys, kix, ret;
  538. rcu_read_lock();
  539. ret = -EDEADLK;
  540. if (A == B)
  541. goto cycle_detected;
  542. subtree = B;
  543. sp = 0;
  544. /* start processing a new keyring */
  545. descend:
  546. if (test_bit(KEY_FLAG_REVOKED, &subtree->flags))
  547. goto not_this_keyring;
  548. keylist = rcu_dereference(subtree->payload.subscriptions);
  549. if (!keylist)
  550. goto not_this_keyring;
  551. kix = 0;
  552. ascend:
  553. /* iterate through the remaining keys in this keyring */
  554. nkeys = keylist->nkeys;
  555. smp_rmb();
  556. for (; kix < nkeys; kix++) {
  557. key = keylist->keys[kix];
  558. if (key == A)
  559. goto cycle_detected;
  560. /* recursively check nested keyrings */
  561. if (key->type == &key_type_keyring) {
  562. if (sp >= KEYRING_SEARCH_MAX_DEPTH)
  563. goto too_deep;
  564. /* stack the current position */
  565. stack[sp].keylist = keylist;
  566. stack[sp].kix = kix;
  567. sp++;
  568. /* begin again with the new keyring */
  569. subtree = key;
  570. goto descend;
  571. }
  572. }
  573. /* the keyring we're looking at was disqualified or didn't contain a
  574. * matching key */
  575. not_this_keyring:
  576. if (sp > 0) {
  577. /* resume the checking of a keyring higher up in the tree */
  578. sp--;
  579. keylist = stack[sp].keylist;
  580. kix = stack[sp].kix + 1;
  581. goto ascend;
  582. }
  583. ret = 0; /* no cycles detected */
  584. error:
  585. rcu_read_unlock();
  586. return ret;
  587. too_deep:
  588. ret = -ELOOP;
  589. goto error;
  590. cycle_detected:
  591. ret = -EDEADLK;
  592. goto error;
  593. }
  594. /*
  595. * Dispose of a keyring list after the RCU grace period, freeing the unlinked
  596. * key
  597. */
  598. static void keyring_unlink_rcu_disposal(struct rcu_head *rcu)
  599. {
  600. struct keyring_list *klist =
  601. container_of(rcu, struct keyring_list, rcu);
  602. if (klist->delkey != USHRT_MAX)
  603. key_put(klist->keys[klist->delkey]);
  604. kfree(klist);
  605. }
  606. /*
  607. * Preallocate memory so that a key can be linked into to a keyring.
  608. */
  609. int __key_link_begin(struct key *keyring, const struct key_type *type,
  610. const char *description, unsigned long *_prealloc)
  611. __acquires(&keyring->sem)
  612. {
  613. struct keyring_list *klist, *nklist;
  614. unsigned long prealloc;
  615. unsigned max;
  616. size_t size;
  617. int loop, ret;
  618. kenter("%d,%s,%s,", key_serial(keyring), type->name, description);
  619. if (keyring->type != &key_type_keyring)
  620. return -ENOTDIR;
  621. down_write(&keyring->sem);
  622. ret = -EKEYREVOKED;
  623. if (test_bit(KEY_FLAG_REVOKED, &keyring->flags))
  624. goto error_krsem;
  625. /* serialise link/link calls to prevent parallel calls causing a cycle
  626. * when linking two keyring in opposite orders */
  627. if (type == &key_type_keyring)
  628. down_write(&keyring_serialise_link_sem);
  629. klist = rcu_dereference_locked_keyring(keyring);
  630. /* see if there's a matching key we can displace */
  631. if (klist && klist->nkeys > 0) {
  632. for (loop = klist->nkeys - 1; loop >= 0; loop--) {
  633. if (klist->keys[loop]->type == type &&
  634. strcmp(klist->keys[loop]->description,
  635. description) == 0
  636. ) {
  637. /* found a match - we'll replace this one with
  638. * the new key */
  639. size = sizeof(struct key *) * klist->maxkeys;
  640. size += sizeof(*klist);
  641. BUG_ON(size > PAGE_SIZE);
  642. ret = -ENOMEM;
  643. nklist = kmemdup(klist, size, GFP_KERNEL);
  644. if (!nklist)
  645. goto error_sem;
  646. /* note replacement slot */
  647. klist->delkey = nklist->delkey = loop;
  648. prealloc = (unsigned long)nklist;
  649. goto done;
  650. }
  651. }
  652. }
  653. /* check that we aren't going to overrun the user's quota */
  654. ret = key_payload_reserve(keyring,
  655. keyring->datalen + KEYQUOTA_LINK_BYTES);
  656. if (ret < 0)
  657. goto error_sem;
  658. if (klist && klist->nkeys < klist->maxkeys) {
  659. /* there's sufficient slack space to append directly */
  660. nklist = NULL;
  661. prealloc = KEY_LINK_FIXQUOTA;
  662. } else {
  663. /* grow the key list */
  664. max = 4;
  665. if (klist)
  666. max += klist->maxkeys;
  667. ret = -ENFILE;
  668. if (max > USHRT_MAX - 1)
  669. goto error_quota;
  670. size = sizeof(*klist) + sizeof(struct key *) * max;
  671. if (size > PAGE_SIZE)
  672. goto error_quota;
  673. ret = -ENOMEM;
  674. nklist = kmalloc(size, GFP_KERNEL);
  675. if (!nklist)
  676. goto error_quota;
  677. nklist->maxkeys = max;
  678. if (klist) {
  679. memcpy(nklist->keys, klist->keys,
  680. sizeof(struct key *) * klist->nkeys);
  681. nklist->delkey = klist->nkeys;
  682. nklist->nkeys = klist->nkeys + 1;
  683. klist->delkey = USHRT_MAX;
  684. } else {
  685. nklist->nkeys = 1;
  686. nklist->delkey = 0;
  687. }
  688. /* add the key into the new space */
  689. nklist->keys[nklist->delkey] = NULL;
  690. }
  691. prealloc = (unsigned long)nklist | KEY_LINK_FIXQUOTA;
  692. done:
  693. *_prealloc = prealloc;
  694. kleave(" = 0");
  695. return 0;
  696. error_quota:
  697. /* undo the quota changes */
  698. key_payload_reserve(keyring,
  699. keyring->datalen - KEYQUOTA_LINK_BYTES);
  700. error_sem:
  701. if (type == &key_type_keyring)
  702. up_write(&keyring_serialise_link_sem);
  703. error_krsem:
  704. up_write(&keyring->sem);
  705. kleave(" = %d", ret);
  706. return ret;
  707. }
  708. /*
  709. * Check already instantiated keys aren't going to be a problem.
  710. *
  711. * The caller must have called __key_link_begin(). Don't need to call this for
  712. * keys that were created since __key_link_begin() was called.
  713. */
  714. int __key_link_check_live_key(struct key *keyring, struct key *key)
  715. {
  716. if (key->type == &key_type_keyring)
  717. /* check that we aren't going to create a cycle by linking one
  718. * keyring to another */
  719. return keyring_detect_cycle(keyring, key);
  720. return 0;
  721. }
  722. /*
  723. * Link a key into to a keyring.
  724. *
  725. * Must be called with __key_link_begin() having being called. Discards any
  726. * already extant link to matching key if there is one, so that each keyring
  727. * holds at most one link to any given key of a particular type+description
  728. * combination.
  729. */
  730. void __key_link(struct key *keyring, struct key *key,
  731. unsigned long *_prealloc)
  732. {
  733. struct keyring_list *klist, *nklist;
  734. nklist = (struct keyring_list *)(*_prealloc & ~KEY_LINK_FIXQUOTA);
  735. *_prealloc = 0;
  736. kenter("%d,%d,%p", keyring->serial, key->serial, nklist);
  737. klist = rcu_dereference_locked_keyring(keyring);
  738. atomic_inc(&key->usage);
  739. /* there's a matching key we can displace or an empty slot in a newly
  740. * allocated list we can fill */
  741. if (nklist) {
  742. kdebug("replace %hu/%hu/%hu",
  743. nklist->delkey, nklist->nkeys, nklist->maxkeys);
  744. nklist->keys[nklist->delkey] = key;
  745. rcu_assign_pointer(keyring->payload.subscriptions, nklist);
  746. /* dispose of the old keyring list and, if there was one, the
  747. * displaced key */
  748. if (klist) {
  749. kdebug("dispose %hu/%hu/%hu",
  750. klist->delkey, klist->nkeys, klist->maxkeys);
  751. call_rcu(&klist->rcu, keyring_unlink_rcu_disposal);
  752. }
  753. } else {
  754. /* there's sufficient slack space to append directly */
  755. klist->keys[klist->nkeys] = key;
  756. smp_wmb();
  757. klist->nkeys++;
  758. }
  759. }
  760. /*
  761. * Finish linking a key into to a keyring.
  762. *
  763. * Must be called with __key_link_begin() having being called.
  764. */
  765. void __key_link_end(struct key *keyring, struct key_type *type,
  766. unsigned long prealloc)
  767. __releases(&keyring->sem)
  768. {
  769. BUG_ON(type == NULL);
  770. BUG_ON(type->name == NULL);
  771. kenter("%d,%s,%lx", keyring->serial, type->name, prealloc);
  772. if (type == &key_type_keyring)
  773. up_write(&keyring_serialise_link_sem);
  774. if (prealloc) {
  775. if (prealloc & KEY_LINK_FIXQUOTA)
  776. key_payload_reserve(keyring,
  777. keyring->datalen -
  778. KEYQUOTA_LINK_BYTES);
  779. kfree((struct keyring_list *)(prealloc & ~KEY_LINK_FIXQUOTA));
  780. }
  781. up_write(&keyring->sem);
  782. }
  783. /**
  784. * key_link - Link a key to a keyring
  785. * @keyring: The keyring to make the link in.
  786. * @key: The key to link to.
  787. *
  788. * Make a link in a keyring to a key, such that the keyring holds a reference
  789. * on that key and the key can potentially be found by searching that keyring.
  790. *
  791. * This function will write-lock the keyring's semaphore and will consume some
  792. * of the user's key data quota to hold the link.
  793. *
  794. * Returns 0 if successful, -ENOTDIR if the keyring isn't a keyring,
  795. * -EKEYREVOKED if the keyring has been revoked, -ENFILE if the keyring is
  796. * full, -EDQUOT if there is insufficient key data quota remaining to add
  797. * another link or -ENOMEM if there's insufficient memory.
  798. *
  799. * It is assumed that the caller has checked that it is permitted for a link to
  800. * be made (the keyring should have Write permission and the key Link
  801. * permission).
  802. */
  803. int key_link(struct key *keyring, struct key *key)
  804. {
  805. unsigned long prealloc;
  806. int ret;
  807. key_check(keyring);
  808. key_check(key);
  809. ret = __key_link_begin(keyring, key->type, key->description, &prealloc);
  810. if (ret == 0) {
  811. ret = __key_link_check_live_key(keyring, key);
  812. if (ret == 0)
  813. __key_link(keyring, key, &prealloc);
  814. __key_link_end(keyring, key->type, prealloc);
  815. }
  816. return ret;
  817. }
  818. EXPORT_SYMBOL(key_link);
  819. /**
  820. * key_unlink - Unlink the first link to a key from a keyring.
  821. * @keyring: The keyring to remove the link from.
  822. * @key: The key the link is to.
  823. *
  824. * Remove a link from a keyring to a key.
  825. *
  826. * This function will write-lock the keyring's semaphore.
  827. *
  828. * Returns 0 if successful, -ENOTDIR if the keyring isn't a keyring, -ENOENT if
  829. * the key isn't linked to by the keyring or -ENOMEM if there's insufficient
  830. * memory.
  831. *
  832. * It is assumed that the caller has checked that it is permitted for a link to
  833. * be removed (the keyring should have Write permission; no permissions are
  834. * required on the key).
  835. */
  836. int key_unlink(struct key *keyring, struct key *key)
  837. {
  838. struct keyring_list *klist, *nklist;
  839. int loop, ret;
  840. key_check(keyring);
  841. key_check(key);
  842. ret = -ENOTDIR;
  843. if (keyring->type != &key_type_keyring)
  844. goto error;
  845. down_write(&keyring->sem);
  846. klist = rcu_dereference_locked_keyring(keyring);
  847. if (klist) {
  848. /* search the keyring for the key */
  849. for (loop = 0; loop < klist->nkeys; loop++)
  850. if (klist->keys[loop] == key)
  851. goto key_is_present;
  852. }
  853. up_write(&keyring->sem);
  854. ret = -ENOENT;
  855. goto error;
  856. key_is_present:
  857. /* we need to copy the key list for RCU purposes */
  858. nklist = kmalloc(sizeof(*klist) +
  859. sizeof(struct key *) * klist->maxkeys,
  860. GFP_KERNEL);
  861. if (!nklist)
  862. goto nomem;
  863. nklist->maxkeys = klist->maxkeys;
  864. nklist->nkeys = klist->nkeys - 1;
  865. if (loop > 0)
  866. memcpy(&nklist->keys[0],
  867. &klist->keys[0],
  868. loop * sizeof(struct key *));
  869. if (loop < nklist->nkeys)
  870. memcpy(&nklist->keys[loop],
  871. &klist->keys[loop + 1],
  872. (nklist->nkeys - loop) * sizeof(struct key *));
  873. /* adjust the user's quota */
  874. key_payload_reserve(keyring,
  875. keyring->datalen - KEYQUOTA_LINK_BYTES);
  876. rcu_assign_pointer(keyring->payload.subscriptions, nklist);
  877. up_write(&keyring->sem);
  878. /* schedule for later cleanup */
  879. klist->delkey = loop;
  880. call_rcu(&klist->rcu, keyring_unlink_rcu_disposal);
  881. ret = 0;
  882. error:
  883. return ret;
  884. nomem:
  885. ret = -ENOMEM;
  886. up_write(&keyring->sem);
  887. goto error;
  888. }
  889. EXPORT_SYMBOL(key_unlink);
  890. /*
  891. * Dispose of a keyring list after the RCU grace period, releasing the keys it
  892. * links to.
  893. */
  894. static void keyring_clear_rcu_disposal(struct rcu_head *rcu)
  895. {
  896. struct keyring_list *klist;
  897. int loop;
  898. klist = container_of(rcu, struct keyring_list, rcu);
  899. for (loop = klist->nkeys - 1; loop >= 0; loop--)
  900. key_put(klist->keys[loop]);
  901. kfree(klist);
  902. }
  903. /**
  904. * keyring_clear - Clear a keyring
  905. * @keyring: The keyring to clear.
  906. *
  907. * Clear the contents of the specified keyring.
  908. *
  909. * Returns 0 if successful or -ENOTDIR if the keyring isn't a keyring.
  910. */
  911. int keyring_clear(struct key *keyring)
  912. {
  913. struct keyring_list *klist;
  914. int ret;
  915. ret = -ENOTDIR;
  916. if (keyring->type == &key_type_keyring) {
  917. /* detach the pointer block with the locks held */
  918. down_write(&keyring->sem);
  919. klist = rcu_dereference_locked_keyring(keyring);
  920. if (klist) {
  921. /* adjust the quota */
  922. key_payload_reserve(keyring,
  923. sizeof(struct keyring_list));
  924. rcu_assign_pointer(keyring->payload.subscriptions,
  925. NULL);
  926. }
  927. up_write(&keyring->sem);
  928. /* free the keys after the locks have been dropped */
  929. if (klist)
  930. call_rcu(&klist->rcu, keyring_clear_rcu_disposal);
  931. ret = 0;
  932. }
  933. return ret;
  934. }
  935. EXPORT_SYMBOL(keyring_clear);
  936. /*
  937. * Dispose of the links from a revoked keyring.
  938. *
  939. * This is called with the key sem write-locked.
  940. */
  941. static void keyring_revoke(struct key *keyring)
  942. {
  943. struct keyring_list *klist;
  944. klist = rcu_dereference_locked_keyring(keyring);
  945. /* adjust the quota */
  946. key_payload_reserve(keyring, 0);
  947. if (klist) {
  948. rcu_assign_pointer(keyring->payload.subscriptions, NULL);
  949. call_rcu(&klist->rcu, keyring_clear_rcu_disposal);
  950. }
  951. }
  952. /*
  953. * Determine whether a key is dead.
  954. */
  955. static bool key_is_dead(struct key *key, time_t limit)
  956. {
  957. return test_bit(KEY_FLAG_DEAD, &key->flags) ||
  958. (key->expiry > 0 && key->expiry <= limit);
  959. }
  960. /*
  961. * Collect garbage from the contents of a keyring, replacing the old list with
  962. * a new one with the pointers all shuffled down.
  963. *
  964. * Dead keys are classed as oned that are flagged as being dead or are revoked,
  965. * expired or negative keys that were revoked or expired before the specified
  966. * limit.
  967. */
  968. void keyring_gc(struct key *keyring, time_t limit)
  969. {
  970. struct keyring_list *klist, *new;
  971. struct key *key;
  972. int loop, keep, max;
  973. kenter("{%x,%s}", key_serial(keyring), keyring->description);
  974. down_write(&keyring->sem);
  975. klist = rcu_dereference_locked_keyring(keyring);
  976. if (!klist)
  977. goto no_klist;
  978. /* work out how many subscriptions we're keeping */
  979. keep = 0;
  980. for (loop = klist->nkeys - 1; loop >= 0; loop--)
  981. if (!key_is_dead(klist->keys[loop], limit))
  982. keep++;
  983. if (keep == klist->nkeys)
  984. goto just_return;
  985. /* allocate a new keyring payload */
  986. max = roundup(keep, 4);
  987. new = kmalloc(sizeof(struct keyring_list) + max * sizeof(struct key *),
  988. GFP_KERNEL);
  989. if (!new)
  990. goto nomem;
  991. new->maxkeys = max;
  992. new->nkeys = 0;
  993. new->delkey = 0;
  994. /* install the live keys
  995. * - must take care as expired keys may be updated back to life
  996. */
  997. keep = 0;
  998. for (loop = klist->nkeys - 1; loop >= 0; loop--) {
  999. key = klist->keys[loop];
  1000. if (!key_is_dead(key, limit)) {
  1001. if (keep >= max)
  1002. goto discard_new;
  1003. new->keys[keep++] = key_get(key);
  1004. }
  1005. }
  1006. new->nkeys = keep;
  1007. /* adjust the quota */
  1008. key_payload_reserve(keyring,
  1009. sizeof(struct keyring_list) +
  1010. KEYQUOTA_LINK_BYTES * keep);
  1011. if (keep == 0) {
  1012. rcu_assign_pointer(keyring->payload.subscriptions, NULL);
  1013. kfree(new);
  1014. } else {
  1015. rcu_assign_pointer(keyring->payload.subscriptions, new);
  1016. }
  1017. up_write(&keyring->sem);
  1018. call_rcu(&klist->rcu, keyring_clear_rcu_disposal);
  1019. kleave(" [yes]");
  1020. return;
  1021. discard_new:
  1022. new->nkeys = keep;
  1023. keyring_clear_rcu_disposal(&new->rcu);
  1024. up_write(&keyring->sem);
  1025. kleave(" [discard]");
  1026. return;
  1027. just_return:
  1028. up_write(&keyring->sem);
  1029. kleave(" [no dead]");
  1030. return;
  1031. no_klist:
  1032. up_write(&keyring->sem);
  1033. kleave(" [no_klist]");
  1034. return;
  1035. nomem:
  1036. up_write(&keyring->sem);
  1037. kleave(" [oom]");
  1038. }