keyring.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281
  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 kflags;
  286. struct key *keyring, *key;
  287. key_ref_t key_ref;
  288. bool possessed;
  289. long err;
  290. int sp, nkeys, kix;
  291. keyring = key_ref_to_ptr(keyring_ref);
  292. possessed = is_key_possessed(keyring_ref);
  293. key_check(keyring);
  294. /* top keyring must have search permission to begin the search */
  295. err = key_task_permission(keyring_ref, cred, KEY_SEARCH);
  296. if (err < 0) {
  297. key_ref = ERR_PTR(err);
  298. goto error;
  299. }
  300. key_ref = ERR_PTR(-ENOTDIR);
  301. if (keyring->type != &key_type_keyring)
  302. goto error;
  303. rcu_read_lock();
  304. now = current_kernel_time();
  305. err = -EAGAIN;
  306. sp = 0;
  307. /* firstly we should check to see if this top-level keyring is what we
  308. * are looking for */
  309. key_ref = ERR_PTR(-EAGAIN);
  310. kflags = keyring->flags;
  311. if (keyring->type == type && match(keyring, description)) {
  312. key = keyring;
  313. if (no_state_check)
  314. goto found;
  315. /* check it isn't negative and hasn't expired or been
  316. * revoked */
  317. if (kflags & (1 << KEY_FLAG_REVOKED))
  318. goto error_2;
  319. if (key->expiry && now.tv_sec >= key->expiry)
  320. goto error_2;
  321. key_ref = ERR_PTR(key->type_data.reject_error);
  322. if (kflags & (1 << KEY_FLAG_NEGATIVE))
  323. goto error_2;
  324. goto found;
  325. }
  326. /* otherwise, the top keyring must not be revoked, expired, or
  327. * negatively instantiated if we are to search it */
  328. key_ref = ERR_PTR(-EAGAIN);
  329. if (kflags & ((1 << KEY_FLAG_INVALIDATED) |
  330. (1 << KEY_FLAG_REVOKED) |
  331. (1 << KEY_FLAG_NEGATIVE)) ||
  332. (keyring->expiry && now.tv_sec >= keyring->expiry))
  333. goto error_2;
  334. /* start processing a new keyring */
  335. descend:
  336. kflags = keyring->flags;
  337. if (kflags & ((1 << KEY_FLAG_INVALIDATED) |
  338. (1 << KEY_FLAG_REVOKED)))
  339. goto not_this_keyring;
  340. keylist = rcu_dereference(keyring->payload.subscriptions);
  341. if (!keylist)
  342. goto not_this_keyring;
  343. /* iterate through the keys in this keyring first */
  344. nkeys = keylist->nkeys;
  345. smp_rmb();
  346. for (kix = 0; kix < nkeys; kix++) {
  347. key = rcu_dereference(keylist->keys[kix]);
  348. kflags = key->flags;
  349. /* ignore keys not of this type */
  350. if (key->type != type)
  351. continue;
  352. /* skip invalidated, revoked and expired keys */
  353. if (!no_state_check) {
  354. if (kflags & ((1 << KEY_FLAG_INVALIDATED) |
  355. (1 << KEY_FLAG_REVOKED)))
  356. continue;
  357. if (key->expiry && now.tv_sec >= key->expiry)
  358. continue;
  359. }
  360. /* keys that don't match */
  361. if (!match(key, description))
  362. continue;
  363. /* key must have search permissions */
  364. if (key_task_permission(make_key_ref(key, possessed),
  365. cred, KEY_SEARCH) < 0)
  366. continue;
  367. if (no_state_check)
  368. goto found;
  369. /* we set a different error code if we pass a negative key */
  370. if (kflags & (1 << KEY_FLAG_NEGATIVE)) {
  371. err = key->type_data.reject_error;
  372. continue;
  373. }
  374. goto found;
  375. }
  376. /* search through the keyrings nested in this one */
  377. kix = 0;
  378. ascend:
  379. nkeys = keylist->nkeys;
  380. smp_rmb();
  381. for (; kix < nkeys; kix++) {
  382. key = rcu_dereference(keylist->keys[kix]);
  383. if (key->type != &key_type_keyring)
  384. continue;
  385. /* recursively search nested keyrings
  386. * - only search keyrings for which we have search permission
  387. */
  388. if (sp >= KEYRING_SEARCH_MAX_DEPTH)
  389. continue;
  390. if (key_task_permission(make_key_ref(key, possessed),
  391. cred, KEY_SEARCH) < 0)
  392. continue;
  393. /* stack the current position */
  394. stack[sp].keyring = keyring;
  395. stack[sp].keylist = keylist;
  396. stack[sp].kix = kix;
  397. sp++;
  398. /* begin again with the new keyring */
  399. keyring = key;
  400. goto descend;
  401. }
  402. /* the keyring we're looking at was disqualified or didn't contain a
  403. * matching key */
  404. not_this_keyring:
  405. if (sp > 0) {
  406. /* resume the processing of a keyring higher up in the tree */
  407. sp--;
  408. keyring = stack[sp].keyring;
  409. keylist = stack[sp].keylist;
  410. kix = stack[sp].kix + 1;
  411. goto ascend;
  412. }
  413. key_ref = ERR_PTR(err);
  414. goto error_2;
  415. /* we found a viable match */
  416. found:
  417. atomic_inc(&key->usage);
  418. key->last_used_at = now.tv_sec;
  419. keyring->last_used_at = now.tv_sec;
  420. while (sp > 0)
  421. stack[--sp].keyring->last_used_at = now.tv_sec;
  422. key_check(key);
  423. key_ref = make_key_ref(key, possessed);
  424. error_2:
  425. rcu_read_unlock();
  426. error:
  427. return key_ref;
  428. }
  429. /**
  430. * keyring_search - Search the supplied keyring tree for a matching key
  431. * @keyring: The root of the keyring tree to be searched.
  432. * @type: The type of keyring we want to find.
  433. * @description: The name of the keyring we want to find.
  434. *
  435. * As keyring_search_aux() above, but using the current task's credentials and
  436. * type's default matching function.
  437. */
  438. key_ref_t keyring_search(key_ref_t keyring,
  439. struct key_type *type,
  440. const char *description)
  441. {
  442. if (!type->match)
  443. return ERR_PTR(-ENOKEY);
  444. return keyring_search_aux(keyring, current->cred,
  445. type, description, type->match, false);
  446. }
  447. EXPORT_SYMBOL(keyring_search);
  448. /*
  449. * Search the given keyring only (no recursion).
  450. *
  451. * The caller must guarantee that the keyring is a keyring and that the
  452. * permission is granted to search the keyring as no check is made here.
  453. *
  454. * RCU is used to make it unnecessary to lock the keyring key list here.
  455. *
  456. * Returns a pointer to the found key with usage count incremented if
  457. * successful and returns -ENOKEY if not found. Revoked keys and keys not
  458. * providing the requested permission are skipped over.
  459. *
  460. * If successful, the possession indicator is propagated from the keyring ref
  461. * to the returned key reference.
  462. */
  463. key_ref_t __keyring_search_one(key_ref_t keyring_ref,
  464. const struct keyring_index_key *index_key,
  465. key_perm_t perm)
  466. {
  467. struct keyring_list *klist;
  468. struct key *keyring, *key;
  469. bool possessed;
  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 == index_key->type &&
  481. (!key->type->match ||
  482. key->type->match(key, index_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 keyring_index_key *index_key,
  638. 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,",
  649. key_serial(keyring), index_key->type->name, index_key->description);
  650. if (keyring->type != &key_type_keyring)
  651. return -ENOTDIR;
  652. down_write(&keyring->sem);
  653. ret = -EKEYREVOKED;
  654. if (test_bit(KEY_FLAG_REVOKED, &keyring->flags))
  655. goto error_krsem;
  656. /* serialise link/link calls to prevent parallel calls causing a cycle
  657. * when linking two keyring in opposite orders */
  658. if (index_key->type == &key_type_keyring)
  659. down_write(&keyring_serialise_link_sem);
  660. klist = rcu_dereference_locked_keyring(keyring);
  661. /* see if there's a matching key we can displace */
  662. lru = -1;
  663. if (klist && klist->nkeys > 0) {
  664. lowest_lru = TIME_T_MAX;
  665. for (loop = klist->nkeys - 1; loop >= 0; loop--) {
  666. struct key *key = rcu_deref_link_locked(klist, loop,
  667. keyring);
  668. if (key->type == index_key->type &&
  669. strcmp(key->description, index_key->description) == 0) {
  670. /* Found a match - we'll replace the link with
  671. * one to the new key. We record the slot
  672. * position.
  673. */
  674. klist->delkey = loop;
  675. prealloc = 0;
  676. goto done;
  677. }
  678. if (key->last_used_at < lowest_lru) {
  679. lowest_lru = key->last_used_at;
  680. lru = loop;
  681. }
  682. }
  683. }
  684. /* If the keyring is full then do an LRU discard */
  685. if (klist &&
  686. klist->nkeys == klist->maxkeys &&
  687. klist->maxkeys >= MAX_KEYRING_LINKS) {
  688. kdebug("LRU discard %d\n", lru);
  689. klist->delkey = lru;
  690. prealloc = 0;
  691. goto done;
  692. }
  693. /* check that we aren't going to overrun the user's quota */
  694. ret = key_payload_reserve(keyring,
  695. keyring->datalen + KEYQUOTA_LINK_BYTES);
  696. if (ret < 0)
  697. goto error_sem;
  698. if (klist && klist->nkeys < klist->maxkeys) {
  699. /* there's sufficient slack space to append directly */
  700. klist->delkey = klist->nkeys;
  701. prealloc = KEY_LINK_FIXQUOTA;
  702. } else {
  703. /* grow the key list */
  704. max = 4;
  705. if (klist) {
  706. max += klist->maxkeys;
  707. if (max > MAX_KEYRING_LINKS)
  708. max = MAX_KEYRING_LINKS;
  709. BUG_ON(max <= klist->maxkeys);
  710. }
  711. size = sizeof(*klist) + sizeof(struct key *) * max;
  712. ret = -ENOMEM;
  713. nklist = kmalloc(size, GFP_KERNEL);
  714. if (!nklist)
  715. goto error_quota;
  716. nklist->maxkeys = max;
  717. if (klist) {
  718. memcpy(nklist->keys, klist->keys,
  719. sizeof(struct key *) * klist->nkeys);
  720. nklist->delkey = klist->nkeys;
  721. nklist->nkeys = klist->nkeys + 1;
  722. klist->delkey = USHRT_MAX;
  723. } else {
  724. nklist->nkeys = 1;
  725. nklist->delkey = 0;
  726. }
  727. /* add the key into the new space */
  728. RCU_INIT_POINTER(nklist->keys[nklist->delkey], NULL);
  729. prealloc = (unsigned long)nklist | KEY_LINK_FIXQUOTA;
  730. }
  731. done:
  732. *_prealloc = prealloc;
  733. kleave(" = 0");
  734. return 0;
  735. error_quota:
  736. /* undo the quota changes */
  737. key_payload_reserve(keyring,
  738. keyring->datalen - KEYQUOTA_LINK_BYTES);
  739. error_sem:
  740. if (index_key->type == &key_type_keyring)
  741. up_write(&keyring_serialise_link_sem);
  742. error_krsem:
  743. up_write(&keyring->sem);
  744. kleave(" = %d", ret);
  745. return ret;
  746. }
  747. /*
  748. * Check already instantiated keys aren't going to be a problem.
  749. *
  750. * The caller must have called __key_link_begin(). Don't need to call this for
  751. * keys that were created since __key_link_begin() was called.
  752. */
  753. int __key_link_check_live_key(struct key *keyring, struct key *key)
  754. {
  755. if (key->type == &key_type_keyring)
  756. /* check that we aren't going to create a cycle by linking one
  757. * keyring to another */
  758. return keyring_detect_cycle(keyring, key);
  759. return 0;
  760. }
  761. /*
  762. * Link a key into to a keyring.
  763. *
  764. * Must be called with __key_link_begin() having being called. Discards any
  765. * already extant link to matching key if there is one, so that each keyring
  766. * holds at most one link to any given key of a particular type+description
  767. * combination.
  768. */
  769. void __key_link(struct key *keyring, struct key *key,
  770. unsigned long *_prealloc)
  771. {
  772. struct keyring_list *klist, *nklist;
  773. struct key *discard;
  774. nklist = (struct keyring_list *)(*_prealloc & ~KEY_LINK_FIXQUOTA);
  775. *_prealloc = 0;
  776. kenter("%d,%d,%p", keyring->serial, key->serial, nklist);
  777. klist = rcu_dereference_locked_keyring(keyring);
  778. atomic_inc(&key->usage);
  779. keyring->last_used_at = key->last_used_at =
  780. current_kernel_time().tv_sec;
  781. /* there's a matching key we can displace or an empty slot in a newly
  782. * allocated list we can fill */
  783. if (nklist) {
  784. kdebug("reissue %hu/%hu/%hu",
  785. nklist->delkey, nklist->nkeys, nklist->maxkeys);
  786. RCU_INIT_POINTER(nklist->keys[nklist->delkey], key);
  787. rcu_assign_pointer(keyring->payload.subscriptions, nklist);
  788. /* dispose of the old keyring list and, if there was one, the
  789. * displaced key */
  790. if (klist) {
  791. kdebug("dispose %hu/%hu/%hu",
  792. klist->delkey, klist->nkeys, klist->maxkeys);
  793. call_rcu(&klist->rcu, keyring_unlink_rcu_disposal);
  794. }
  795. } else if (klist->delkey < klist->nkeys) {
  796. kdebug("replace %hu/%hu/%hu",
  797. klist->delkey, klist->nkeys, klist->maxkeys);
  798. discard = rcu_dereference_protected(
  799. klist->keys[klist->delkey],
  800. rwsem_is_locked(&keyring->sem));
  801. rcu_assign_pointer(klist->keys[klist->delkey], key);
  802. /* The garbage collector will take care of RCU
  803. * synchronisation */
  804. key_put(discard);
  805. } else {
  806. /* there's sufficient slack space to append directly */
  807. kdebug("append %hu/%hu/%hu",
  808. klist->delkey, klist->nkeys, klist->maxkeys);
  809. RCU_INIT_POINTER(klist->keys[klist->delkey], key);
  810. smp_wmb();
  811. klist->nkeys++;
  812. }
  813. }
  814. /*
  815. * Finish linking a key into to a keyring.
  816. *
  817. * Must be called with __key_link_begin() having being called.
  818. */
  819. void __key_link_end(struct key *keyring,
  820. const struct keyring_index_key *index_key,
  821. unsigned long prealloc)
  822. __releases(&keyring->sem)
  823. __releases(&keyring_serialise_link_sem)
  824. {
  825. BUG_ON(index_key->type == NULL);
  826. BUG_ON(index_key->type->name == NULL);
  827. kenter("%d,%s,%lx", keyring->serial, index_key->type->name, prealloc);
  828. if (index_key->type == &key_type_keyring)
  829. up_write(&keyring_serialise_link_sem);
  830. if (prealloc) {
  831. if (prealloc & KEY_LINK_FIXQUOTA)
  832. key_payload_reserve(keyring,
  833. keyring->datalen -
  834. KEYQUOTA_LINK_BYTES);
  835. kfree((struct keyring_list *)(prealloc & ~KEY_LINK_FIXQUOTA));
  836. }
  837. up_write(&keyring->sem);
  838. }
  839. /**
  840. * key_link - Link a key to a keyring
  841. * @keyring: The keyring to make the link in.
  842. * @key: The key to link to.
  843. *
  844. * Make a link in a keyring to a key, such that the keyring holds a reference
  845. * on that key and the key can potentially be found by searching that keyring.
  846. *
  847. * This function will write-lock the keyring's semaphore and will consume some
  848. * of the user's key data quota to hold the link.
  849. *
  850. * Returns 0 if successful, -ENOTDIR if the keyring isn't a keyring,
  851. * -EKEYREVOKED if the keyring has been revoked, -ENFILE if the keyring is
  852. * full, -EDQUOT if there is insufficient key data quota remaining to add
  853. * another link or -ENOMEM if there's insufficient memory.
  854. *
  855. * It is assumed that the caller has checked that it is permitted for a link to
  856. * be made (the keyring should have Write permission and the key Link
  857. * permission).
  858. */
  859. int key_link(struct key *keyring, struct key *key)
  860. {
  861. unsigned long prealloc;
  862. int ret;
  863. key_check(keyring);
  864. key_check(key);
  865. ret = __key_link_begin(keyring, &key->index_key, &prealloc);
  866. if (ret == 0) {
  867. ret = __key_link_check_live_key(keyring, key);
  868. if (ret == 0)
  869. __key_link(keyring, key, &prealloc);
  870. __key_link_end(keyring, &key->index_key, prealloc);
  871. }
  872. return ret;
  873. }
  874. EXPORT_SYMBOL(key_link);
  875. /**
  876. * key_unlink - Unlink the first link to a key from a keyring.
  877. * @keyring: The keyring to remove the link from.
  878. * @key: The key the link is to.
  879. *
  880. * Remove a link from a keyring to a key.
  881. *
  882. * This function will write-lock the keyring's semaphore.
  883. *
  884. * Returns 0 if successful, -ENOTDIR if the keyring isn't a keyring, -ENOENT if
  885. * the key isn't linked to by the keyring or -ENOMEM if there's insufficient
  886. * memory.
  887. *
  888. * It is assumed that the caller has checked that it is permitted for a link to
  889. * be removed (the keyring should have Write permission; no permissions are
  890. * required on the key).
  891. */
  892. int key_unlink(struct key *keyring, struct key *key)
  893. {
  894. struct keyring_list *klist, *nklist;
  895. int loop, ret;
  896. key_check(keyring);
  897. key_check(key);
  898. ret = -ENOTDIR;
  899. if (keyring->type != &key_type_keyring)
  900. goto error;
  901. down_write(&keyring->sem);
  902. klist = rcu_dereference_locked_keyring(keyring);
  903. if (klist) {
  904. /* search the keyring for the key */
  905. for (loop = 0; loop < klist->nkeys; loop++)
  906. if (rcu_access_pointer(klist->keys[loop]) == key)
  907. goto key_is_present;
  908. }
  909. up_write(&keyring->sem);
  910. ret = -ENOENT;
  911. goto error;
  912. key_is_present:
  913. /* we need to copy the key list for RCU purposes */
  914. nklist = kmalloc(sizeof(*klist) +
  915. sizeof(struct key *) * klist->maxkeys,
  916. GFP_KERNEL);
  917. if (!nklist)
  918. goto nomem;
  919. nklist->maxkeys = klist->maxkeys;
  920. nklist->nkeys = klist->nkeys - 1;
  921. if (loop > 0)
  922. memcpy(&nklist->keys[0],
  923. &klist->keys[0],
  924. loop * sizeof(struct key *));
  925. if (loop < nklist->nkeys)
  926. memcpy(&nklist->keys[loop],
  927. &klist->keys[loop + 1],
  928. (nklist->nkeys - loop) * sizeof(struct key *));
  929. /* adjust the user's quota */
  930. key_payload_reserve(keyring,
  931. keyring->datalen - KEYQUOTA_LINK_BYTES);
  932. rcu_assign_pointer(keyring->payload.subscriptions, nklist);
  933. up_write(&keyring->sem);
  934. /* schedule for later cleanup */
  935. klist->delkey = loop;
  936. call_rcu(&klist->rcu, keyring_unlink_rcu_disposal);
  937. ret = 0;
  938. error:
  939. return ret;
  940. nomem:
  941. ret = -ENOMEM;
  942. up_write(&keyring->sem);
  943. goto error;
  944. }
  945. EXPORT_SYMBOL(key_unlink);
  946. /*
  947. * Dispose of a keyring list after the RCU grace period, releasing the keys it
  948. * links to.
  949. */
  950. static void keyring_clear_rcu_disposal(struct rcu_head *rcu)
  951. {
  952. struct keyring_list *klist;
  953. int loop;
  954. klist = container_of(rcu, struct keyring_list, rcu);
  955. for (loop = klist->nkeys - 1; loop >= 0; loop--)
  956. key_put(rcu_access_pointer(klist->keys[loop]));
  957. kfree(klist);
  958. }
  959. /**
  960. * keyring_clear - Clear a keyring
  961. * @keyring: The keyring to clear.
  962. *
  963. * Clear the contents of the specified keyring.
  964. *
  965. * Returns 0 if successful or -ENOTDIR if the keyring isn't a keyring.
  966. */
  967. int keyring_clear(struct key *keyring)
  968. {
  969. struct keyring_list *klist;
  970. int ret;
  971. ret = -ENOTDIR;
  972. if (keyring->type == &key_type_keyring) {
  973. /* detach the pointer block with the locks held */
  974. down_write(&keyring->sem);
  975. klist = rcu_dereference_locked_keyring(keyring);
  976. if (klist) {
  977. /* adjust the quota */
  978. key_payload_reserve(keyring,
  979. sizeof(struct keyring_list));
  980. rcu_assign_pointer(keyring->payload.subscriptions,
  981. NULL);
  982. }
  983. up_write(&keyring->sem);
  984. /* free the keys after the locks have been dropped */
  985. if (klist)
  986. call_rcu(&klist->rcu, keyring_clear_rcu_disposal);
  987. ret = 0;
  988. }
  989. return ret;
  990. }
  991. EXPORT_SYMBOL(keyring_clear);
  992. /*
  993. * Dispose of the links from a revoked keyring.
  994. *
  995. * This is called with the key sem write-locked.
  996. */
  997. static void keyring_revoke(struct key *keyring)
  998. {
  999. struct keyring_list *klist;
  1000. klist = rcu_dereference_locked_keyring(keyring);
  1001. /* adjust the quota */
  1002. key_payload_reserve(keyring, 0);
  1003. if (klist) {
  1004. rcu_assign_pointer(keyring->payload.subscriptions, NULL);
  1005. call_rcu(&klist->rcu, keyring_clear_rcu_disposal);
  1006. }
  1007. }
  1008. /*
  1009. * Collect garbage from the contents of a keyring, replacing the old list with
  1010. * a new one with the pointers all shuffled down.
  1011. *
  1012. * Dead keys are classed as oned that are flagged as being dead or are revoked,
  1013. * expired or negative keys that were revoked or expired before the specified
  1014. * limit.
  1015. */
  1016. void keyring_gc(struct key *keyring, time_t limit)
  1017. {
  1018. struct keyring_list *klist, *new;
  1019. struct key *key;
  1020. int loop, keep, max;
  1021. kenter("{%x,%s}", key_serial(keyring), keyring->description);
  1022. down_write(&keyring->sem);
  1023. klist = rcu_dereference_locked_keyring(keyring);
  1024. if (!klist)
  1025. goto no_klist;
  1026. /* work out how many subscriptions we're keeping */
  1027. keep = 0;
  1028. for (loop = klist->nkeys - 1; loop >= 0; loop--)
  1029. if (!key_is_dead(rcu_deref_link_locked(klist, loop, keyring),
  1030. limit))
  1031. keep++;
  1032. if (keep == klist->nkeys)
  1033. goto just_return;
  1034. /* allocate a new keyring payload */
  1035. max = roundup(keep, 4);
  1036. new = kmalloc(sizeof(struct keyring_list) + max * sizeof(struct key *),
  1037. GFP_KERNEL);
  1038. if (!new)
  1039. goto nomem;
  1040. new->maxkeys = max;
  1041. new->nkeys = 0;
  1042. new->delkey = 0;
  1043. /* install the live keys
  1044. * - must take care as expired keys may be updated back to life
  1045. */
  1046. keep = 0;
  1047. for (loop = klist->nkeys - 1; loop >= 0; loop--) {
  1048. key = rcu_deref_link_locked(klist, loop, keyring);
  1049. if (!key_is_dead(key, limit)) {
  1050. if (keep >= max)
  1051. goto discard_new;
  1052. RCU_INIT_POINTER(new->keys[keep++], key_get(key));
  1053. }
  1054. }
  1055. new->nkeys = keep;
  1056. /* adjust the quota */
  1057. key_payload_reserve(keyring,
  1058. sizeof(struct keyring_list) +
  1059. KEYQUOTA_LINK_BYTES * keep);
  1060. if (keep == 0) {
  1061. rcu_assign_pointer(keyring->payload.subscriptions, NULL);
  1062. kfree(new);
  1063. } else {
  1064. rcu_assign_pointer(keyring->payload.subscriptions, new);
  1065. }
  1066. up_write(&keyring->sem);
  1067. call_rcu(&klist->rcu, keyring_clear_rcu_disposal);
  1068. kleave(" [yes]");
  1069. return;
  1070. discard_new:
  1071. new->nkeys = keep;
  1072. keyring_clear_rcu_disposal(&new->rcu);
  1073. up_write(&keyring->sem);
  1074. kleave(" [discard]");
  1075. return;
  1076. just_return:
  1077. up_write(&keyring->sem);
  1078. kleave(" [no dead]");
  1079. return;
  1080. no_klist:
  1081. up_write(&keyring->sem);
  1082. kleave(" [no_klist]");
  1083. return;
  1084. nomem:
  1085. up_write(&keyring->sem);
  1086. kleave(" [oom]");
  1087. }