keyring.c 31 KB

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