keyring.c 32 KB

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