keyring.c 32 KB

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