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. 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, unsigned long flags,
  218. struct key *dest)
  219. {
  220. struct key *keyring;
  221. int ret;
  222. keyring = key_alloc(&key_type_keyring, description,
  223. uid, gid, cred,
  224. (KEY_POS_ALL & ~KEY_POS_SETATTR) | KEY_USR_ALL,
  225. flags);
  226. if (!IS_ERR(keyring)) {
  227. ret = key_instantiate_and_link(keyring, NULL, 0, dest, NULL);
  228. if (ret < 0) {
  229. key_put(keyring);
  230. keyring = ERR_PTR(ret);
  231. }
  232. }
  233. return keyring;
  234. }
  235. /**
  236. * keyring_search_aux - Search a keyring tree for a key matching some criteria
  237. * @keyring_ref: A pointer to the keyring with possession indicator.
  238. * @cred: The credentials to use for permissions checks.
  239. * @type: The type of key to search for.
  240. * @description: Parameter for @match.
  241. * @match: Function to rule on whether or not a key is the one required.
  242. * @no_state_check: Don't check if a matching key is bad
  243. *
  244. * Search the supplied keyring tree for a key that matches the criteria given.
  245. * The root keyring and any linked keyrings must grant Search permission to the
  246. * caller to be searchable and keys can only be found if they too grant Search
  247. * to the caller. The possession flag on the root keyring pointer controls use
  248. * of the possessor bits in permissions checking of the entire tree. In
  249. * addition, the LSM gets to forbid keyring searches and key matches.
  250. *
  251. * The search is performed as a breadth-then-depth search up to the prescribed
  252. * limit (KEYRING_SEARCH_MAX_DEPTH).
  253. *
  254. * Keys are matched to the type provided and are then filtered by the match
  255. * function, which is given the description to use in any way it sees fit. The
  256. * match function may use any attributes of a key that it wishes to to
  257. * determine the match. Normally the match function from the key type would be
  258. * used.
  259. *
  260. * RCU is used to prevent the keyring key lists from disappearing without the
  261. * need to take lots of locks.
  262. *
  263. * Returns a pointer to the found key and increments the key usage count if
  264. * successful; -EAGAIN if no matching keys were found, or if expired or revoked
  265. * keys were found; -ENOKEY if only negative keys were found; -ENOTDIR if the
  266. * specified keyring wasn't a keyring.
  267. *
  268. * In the case of a successful return, the possession attribute from
  269. * @keyring_ref is propagated to the returned key reference.
  270. */
  271. key_ref_t keyring_search_aux(key_ref_t keyring_ref,
  272. const struct cred *cred,
  273. struct key_type *type,
  274. const void *description,
  275. key_match_func_t match,
  276. bool no_state_check)
  277. {
  278. struct {
  279. /* Need a separate keylist pointer for RCU purposes */
  280. struct key *keyring;
  281. struct keyring_list *keylist;
  282. int kix;
  283. } stack[KEYRING_SEARCH_MAX_DEPTH];
  284. struct keyring_list *keylist;
  285. struct timespec now;
  286. unsigned long possessed, kflags;
  287. struct key *keyring, *key;
  288. key_ref_t key_ref;
  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 key_type *ktype,
  465. const char *description,
  466. key_perm_t perm)
  467. {
  468. struct keyring_list *klist;
  469. unsigned long possessed;
  470. struct key *keyring, *key;
  471. int nkeys, loop;
  472. keyring = key_ref_to_ptr(keyring_ref);
  473. possessed = is_key_possessed(keyring_ref);
  474. rcu_read_lock();
  475. klist = rcu_dereference(keyring->payload.subscriptions);
  476. if (klist) {
  477. nkeys = klist->nkeys;
  478. smp_rmb();
  479. for (loop = 0; loop < nkeys ; loop++) {
  480. key = rcu_dereference(klist->keys[loop]);
  481. if (key->type == ktype &&
  482. (!key->type->match ||
  483. key->type->match(key, description)) &&
  484. key_permission(make_key_ref(key, possessed),
  485. perm) == 0 &&
  486. !(key->flags & ((1 << KEY_FLAG_INVALIDATED) |
  487. (1 << KEY_FLAG_REVOKED)))
  488. )
  489. goto found;
  490. }
  491. }
  492. rcu_read_unlock();
  493. return ERR_PTR(-ENOKEY);
  494. found:
  495. atomic_inc(&key->usage);
  496. keyring->last_used_at = key->last_used_at =
  497. current_kernel_time().tv_sec;
  498. rcu_read_unlock();
  499. return make_key_ref(key, possessed);
  500. }
  501. /*
  502. * Find a keyring with the specified name.
  503. *
  504. * All named keyrings in the current user namespace are searched, provided they
  505. * grant Search permission directly to the caller (unless this check is
  506. * skipped). Keyrings whose usage points have reached zero or who have been
  507. * revoked are skipped.
  508. *
  509. * Returns a pointer to the keyring with the keyring's refcount having being
  510. * incremented on success. -ENOKEY is returned if a key could not be found.
  511. */
  512. struct key *find_keyring_by_name(const char *name, bool skip_perm_check)
  513. {
  514. struct key *keyring;
  515. int bucket;
  516. if (!name)
  517. return ERR_PTR(-EINVAL);
  518. bucket = keyring_hash(name);
  519. read_lock(&keyring_name_lock);
  520. if (keyring_name_hash[bucket].next) {
  521. /* search this hash bucket for a keyring with a matching name
  522. * that's readable and that hasn't been revoked */
  523. list_for_each_entry(keyring,
  524. &keyring_name_hash[bucket],
  525. type_data.link
  526. ) {
  527. if (keyring->user->user_ns != current_user_ns())
  528. continue;
  529. if (test_bit(KEY_FLAG_REVOKED, &keyring->flags))
  530. continue;
  531. if (strcmp(keyring->description, name) != 0)
  532. continue;
  533. if (!skip_perm_check &&
  534. key_permission(make_key_ref(keyring, 0),
  535. KEY_SEARCH) < 0)
  536. continue;
  537. /* we've got a match but we might end up racing with
  538. * key_cleanup() if the keyring is currently 'dead'
  539. * (ie. it has a zero usage count) */
  540. if (!atomic_inc_not_zero(&keyring->usage))
  541. continue;
  542. keyring->last_used_at = current_kernel_time().tv_sec;
  543. goto out;
  544. }
  545. }
  546. keyring = ERR_PTR(-ENOKEY);
  547. out:
  548. read_unlock(&keyring_name_lock);
  549. return keyring;
  550. }
  551. /*
  552. * See if a cycle will will be created by inserting acyclic tree B in acyclic
  553. * tree A at the topmost level (ie: as a direct child of A).
  554. *
  555. * Since we are adding B to A at the top level, checking for cycles should just
  556. * be a matter of seeing if node A is somewhere in tree B.
  557. */
  558. static int keyring_detect_cycle(struct key *A, struct key *B)
  559. {
  560. struct {
  561. struct keyring_list *keylist;
  562. int kix;
  563. } stack[KEYRING_SEARCH_MAX_DEPTH];
  564. struct keyring_list *keylist;
  565. struct key *subtree, *key;
  566. int sp, nkeys, kix, ret;
  567. rcu_read_lock();
  568. ret = -EDEADLK;
  569. if (A == B)
  570. goto cycle_detected;
  571. subtree = B;
  572. sp = 0;
  573. /* start processing a new keyring */
  574. descend:
  575. if (test_bit(KEY_FLAG_REVOKED, &subtree->flags))
  576. goto not_this_keyring;
  577. keylist = rcu_dereference(subtree->payload.subscriptions);
  578. if (!keylist)
  579. goto not_this_keyring;
  580. kix = 0;
  581. ascend:
  582. /* iterate through the remaining keys in this keyring */
  583. nkeys = keylist->nkeys;
  584. smp_rmb();
  585. for (; kix < nkeys; kix++) {
  586. key = rcu_dereference(keylist->keys[kix]);
  587. if (key == A)
  588. goto cycle_detected;
  589. /* recursively check nested keyrings */
  590. if (key->type == &key_type_keyring) {
  591. if (sp >= KEYRING_SEARCH_MAX_DEPTH)
  592. goto too_deep;
  593. /* stack the current position */
  594. stack[sp].keylist = keylist;
  595. stack[sp].kix = kix;
  596. sp++;
  597. /* begin again with the new keyring */
  598. subtree = key;
  599. goto descend;
  600. }
  601. }
  602. /* the keyring we're looking at was disqualified or didn't contain a
  603. * matching key */
  604. not_this_keyring:
  605. if (sp > 0) {
  606. /* resume the checking of a keyring higher up in the tree */
  607. sp--;
  608. keylist = stack[sp].keylist;
  609. kix = stack[sp].kix + 1;
  610. goto ascend;
  611. }
  612. ret = 0; /* no cycles detected */
  613. error:
  614. rcu_read_unlock();
  615. return ret;
  616. too_deep:
  617. ret = -ELOOP;
  618. goto error;
  619. cycle_detected:
  620. ret = -EDEADLK;
  621. goto error;
  622. }
  623. /*
  624. * Dispose of a keyring list after the RCU grace period, freeing the unlinked
  625. * key
  626. */
  627. static void keyring_unlink_rcu_disposal(struct rcu_head *rcu)
  628. {
  629. struct keyring_list *klist =
  630. container_of(rcu, struct keyring_list, rcu);
  631. if (klist->delkey != USHRT_MAX)
  632. key_put(rcu_access_pointer(klist->keys[klist->delkey]));
  633. kfree(klist);
  634. }
  635. /*
  636. * Preallocate memory so that a key can be linked into to a keyring.
  637. */
  638. int __key_link_begin(struct key *keyring, const struct key_type *type,
  639. const char *description, unsigned long *_prealloc)
  640. __acquires(&keyring->sem)
  641. __acquires(&keyring_serialise_link_sem)
  642. {
  643. struct keyring_list *klist, *nklist;
  644. unsigned long prealloc;
  645. unsigned max;
  646. time_t lowest_lru;
  647. size_t size;
  648. int loop, lru, ret;
  649. kenter("%d,%s,%s,", key_serial(keyring), type->name, 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 (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 == type &&
  669. strcmp(key->description, 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 (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, struct key_type *type,
  820. unsigned long prealloc)
  821. __releases(&keyring->sem)
  822. __releases(&keyring_serialise_link_sem)
  823. {
  824. BUG_ON(type == NULL);
  825. BUG_ON(type->name == NULL);
  826. kenter("%d,%s,%lx", keyring->serial, type->name, prealloc);
  827. if (type == &key_type_keyring)
  828. up_write(&keyring_serialise_link_sem);
  829. if (prealloc) {
  830. if (prealloc & KEY_LINK_FIXQUOTA)
  831. key_payload_reserve(keyring,
  832. keyring->datalen -
  833. KEYQUOTA_LINK_BYTES);
  834. kfree((struct keyring_list *)(prealloc & ~KEY_LINK_FIXQUOTA));
  835. }
  836. up_write(&keyring->sem);
  837. }
  838. /**
  839. * key_link - Link a key to a keyring
  840. * @keyring: The keyring to make the link in.
  841. * @key: The key to link to.
  842. *
  843. * Make a link in a keyring to a key, such that the keyring holds a reference
  844. * on that key and the key can potentially be found by searching that keyring.
  845. *
  846. * This function will write-lock the keyring's semaphore and will consume some
  847. * of the user's key data quota to hold the link.
  848. *
  849. * Returns 0 if successful, -ENOTDIR if the keyring isn't a keyring,
  850. * -EKEYREVOKED if the keyring has been revoked, -ENFILE if the keyring is
  851. * full, -EDQUOT if there is insufficient key data quota remaining to add
  852. * another link or -ENOMEM if there's insufficient memory.
  853. *
  854. * It is assumed that the caller has checked that it is permitted for a link to
  855. * be made (the keyring should have Write permission and the key Link
  856. * permission).
  857. */
  858. int key_link(struct key *keyring, struct key *key)
  859. {
  860. unsigned long prealloc;
  861. int ret;
  862. key_check(keyring);
  863. key_check(key);
  864. ret = __key_link_begin(keyring, key->type, key->description, &prealloc);
  865. if (ret == 0) {
  866. ret = __key_link_check_live_key(keyring, key);
  867. if (ret == 0)
  868. __key_link(keyring, key, &prealloc);
  869. __key_link_end(keyring, key->type, prealloc);
  870. }
  871. return ret;
  872. }
  873. EXPORT_SYMBOL(key_link);
  874. /**
  875. * key_unlink - Unlink the first link to a key from a keyring.
  876. * @keyring: The keyring to remove the link from.
  877. * @key: The key the link is to.
  878. *
  879. * Remove a link from a keyring to a key.
  880. *
  881. * This function will write-lock the keyring's semaphore.
  882. *
  883. * Returns 0 if successful, -ENOTDIR if the keyring isn't a keyring, -ENOENT if
  884. * the key isn't linked to by the keyring or -ENOMEM if there's insufficient
  885. * memory.
  886. *
  887. * It is assumed that the caller has checked that it is permitted for a link to
  888. * be removed (the keyring should have Write permission; no permissions are
  889. * required on the key).
  890. */
  891. int key_unlink(struct key *keyring, struct key *key)
  892. {
  893. struct keyring_list *klist, *nklist;
  894. int loop, ret;
  895. key_check(keyring);
  896. key_check(key);
  897. ret = -ENOTDIR;
  898. if (keyring->type != &key_type_keyring)
  899. goto error;
  900. down_write(&keyring->sem);
  901. klist = rcu_dereference_locked_keyring(keyring);
  902. if (klist) {
  903. /* search the keyring for the key */
  904. for (loop = 0; loop < klist->nkeys; loop++)
  905. if (rcu_access_pointer(klist->keys[loop]) == key)
  906. goto key_is_present;
  907. }
  908. up_write(&keyring->sem);
  909. ret = -ENOENT;
  910. goto error;
  911. key_is_present:
  912. /* we need to copy the key list for RCU purposes */
  913. nklist = kmalloc(sizeof(*klist) +
  914. sizeof(struct key *) * klist->maxkeys,
  915. GFP_KERNEL);
  916. if (!nklist)
  917. goto nomem;
  918. nklist->maxkeys = klist->maxkeys;
  919. nklist->nkeys = klist->nkeys - 1;
  920. if (loop > 0)
  921. memcpy(&nklist->keys[0],
  922. &klist->keys[0],
  923. loop * sizeof(struct key *));
  924. if (loop < nklist->nkeys)
  925. memcpy(&nklist->keys[loop],
  926. &klist->keys[loop + 1],
  927. (nklist->nkeys - loop) * sizeof(struct key *));
  928. /* adjust the user's quota */
  929. key_payload_reserve(keyring,
  930. keyring->datalen - KEYQUOTA_LINK_BYTES);
  931. rcu_assign_pointer(keyring->payload.subscriptions, nklist);
  932. up_write(&keyring->sem);
  933. /* schedule for later cleanup */
  934. klist->delkey = loop;
  935. call_rcu(&klist->rcu, keyring_unlink_rcu_disposal);
  936. ret = 0;
  937. error:
  938. return ret;
  939. nomem:
  940. ret = -ENOMEM;
  941. up_write(&keyring->sem);
  942. goto error;
  943. }
  944. EXPORT_SYMBOL(key_unlink);
  945. /*
  946. * Dispose of a keyring list after the RCU grace period, releasing the keys it
  947. * links to.
  948. */
  949. static void keyring_clear_rcu_disposal(struct rcu_head *rcu)
  950. {
  951. struct keyring_list *klist;
  952. int loop;
  953. klist = container_of(rcu, struct keyring_list, rcu);
  954. for (loop = klist->nkeys - 1; loop >= 0; loop--)
  955. key_put(rcu_access_pointer(klist->keys[loop]));
  956. kfree(klist);
  957. }
  958. /**
  959. * keyring_clear - Clear a keyring
  960. * @keyring: The keyring to clear.
  961. *
  962. * Clear the contents of the specified keyring.
  963. *
  964. * Returns 0 if successful or -ENOTDIR if the keyring isn't a keyring.
  965. */
  966. int keyring_clear(struct key *keyring)
  967. {
  968. struct keyring_list *klist;
  969. int ret;
  970. ret = -ENOTDIR;
  971. if (keyring->type == &key_type_keyring) {
  972. /* detach the pointer block with the locks held */
  973. down_write(&keyring->sem);
  974. klist = rcu_dereference_locked_keyring(keyring);
  975. if (klist) {
  976. /* adjust the quota */
  977. key_payload_reserve(keyring,
  978. sizeof(struct keyring_list));
  979. rcu_assign_pointer(keyring->payload.subscriptions,
  980. NULL);
  981. }
  982. up_write(&keyring->sem);
  983. /* free the keys after the locks have been dropped */
  984. if (klist)
  985. call_rcu(&klist->rcu, keyring_clear_rcu_disposal);
  986. ret = 0;
  987. }
  988. return ret;
  989. }
  990. EXPORT_SYMBOL(keyring_clear);
  991. /*
  992. * Dispose of the links from a revoked keyring.
  993. *
  994. * This is called with the key sem write-locked.
  995. */
  996. static void keyring_revoke(struct key *keyring)
  997. {
  998. struct keyring_list *klist;
  999. klist = rcu_dereference_locked_keyring(keyring);
  1000. /* adjust the quota */
  1001. key_payload_reserve(keyring, 0);
  1002. if (klist) {
  1003. rcu_assign_pointer(keyring->payload.subscriptions, NULL);
  1004. call_rcu(&klist->rcu, keyring_clear_rcu_disposal);
  1005. }
  1006. }
  1007. /*
  1008. * Collect garbage from the contents of a keyring, replacing the old list with
  1009. * a new one with the pointers all shuffled down.
  1010. *
  1011. * Dead keys are classed as oned that are flagged as being dead or are revoked,
  1012. * expired or negative keys that were revoked or expired before the specified
  1013. * limit.
  1014. */
  1015. void keyring_gc(struct key *keyring, time_t limit)
  1016. {
  1017. struct keyring_list *klist, *new;
  1018. struct key *key;
  1019. int loop, keep, max;
  1020. kenter("{%x,%s}", key_serial(keyring), keyring->description);
  1021. down_write(&keyring->sem);
  1022. klist = rcu_dereference_locked_keyring(keyring);
  1023. if (!klist)
  1024. goto no_klist;
  1025. /* work out how many subscriptions we're keeping */
  1026. keep = 0;
  1027. for (loop = klist->nkeys - 1; loop >= 0; loop--)
  1028. if (!key_is_dead(rcu_deref_link_locked(klist, loop, keyring),
  1029. limit))
  1030. keep++;
  1031. if (keep == klist->nkeys)
  1032. goto just_return;
  1033. /* allocate a new keyring payload */
  1034. max = roundup(keep, 4);
  1035. new = kmalloc(sizeof(struct keyring_list) + max * sizeof(struct key *),
  1036. GFP_KERNEL);
  1037. if (!new)
  1038. goto nomem;
  1039. new->maxkeys = max;
  1040. new->nkeys = 0;
  1041. new->delkey = 0;
  1042. /* install the live keys
  1043. * - must take care as expired keys may be updated back to life
  1044. */
  1045. keep = 0;
  1046. for (loop = klist->nkeys - 1; loop >= 0; loop--) {
  1047. key = rcu_deref_link_locked(klist, loop, keyring);
  1048. if (!key_is_dead(key, limit)) {
  1049. if (keep >= max)
  1050. goto discard_new;
  1051. RCU_INIT_POINTER(new->keys[keep++], key_get(key));
  1052. }
  1053. }
  1054. new->nkeys = keep;
  1055. /* adjust the quota */
  1056. key_payload_reserve(keyring,
  1057. sizeof(struct keyring_list) +
  1058. KEYQUOTA_LINK_BYTES * keep);
  1059. if (keep == 0) {
  1060. rcu_assign_pointer(keyring->payload.subscriptions, NULL);
  1061. kfree(new);
  1062. } else {
  1063. rcu_assign_pointer(keyring->payload.subscriptions, new);
  1064. }
  1065. up_write(&keyring->sem);
  1066. call_rcu(&klist->rcu, keyring_clear_rcu_disposal);
  1067. kleave(" [yes]");
  1068. return;
  1069. discard_new:
  1070. new->nkeys = keep;
  1071. keyring_clear_rcu_disposal(&new->rcu);
  1072. up_write(&keyring->sem);
  1073. kleave(" [discard]");
  1074. return;
  1075. just_return:
  1076. up_write(&keyring->sem);
  1077. kleave(" [no dead]");
  1078. return;
  1079. no_klist:
  1080. up_write(&keyring->sem);
  1081. kleave(" [no_klist]");
  1082. return;
  1083. nomem:
  1084. up_write(&keyring->sem);
  1085. kleave(" [oom]");
  1086. }