key.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101
  1. /* Basic authentication token and access key management
  2. *
  3. * Copyright (C) 2004-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/poison.h>
  14. #include <linux/sched.h>
  15. #include <linux/slab.h>
  16. #include <linux/security.h>
  17. #include <linux/workqueue.h>
  18. #include <linux/random.h>
  19. #include <linux/err.h>
  20. #include "internal.h"
  21. struct kmem_cache *key_jar;
  22. struct rb_root key_serial_tree; /* tree of keys indexed by serial */
  23. DEFINE_SPINLOCK(key_serial_lock);
  24. struct rb_root key_user_tree; /* tree of quota records indexed by UID */
  25. DEFINE_SPINLOCK(key_user_lock);
  26. unsigned int key_quota_root_maxkeys = 200; /* root's key count quota */
  27. unsigned int key_quota_root_maxbytes = 20000; /* root's key space quota */
  28. unsigned int key_quota_maxkeys = 200; /* general key count quota */
  29. unsigned int key_quota_maxbytes = 20000; /* general key space quota */
  30. static LIST_HEAD(key_types_list);
  31. static DECLARE_RWSEM(key_types_sem);
  32. /* We serialise key instantiation and link */
  33. DEFINE_MUTEX(key_construction_mutex);
  34. #ifdef KEY_DEBUGGING
  35. void __key_check(const struct key *key)
  36. {
  37. printk("__key_check: key %p {%08x} should be {%08x}\n",
  38. key, key->magic, KEY_DEBUG_MAGIC);
  39. BUG();
  40. }
  41. #endif
  42. /*
  43. * Get the key quota record for a user, allocating a new record if one doesn't
  44. * already exist.
  45. */
  46. struct key_user *key_user_lookup(kuid_t uid)
  47. {
  48. struct key_user *candidate = NULL, *user;
  49. struct rb_node *parent = NULL;
  50. struct rb_node **p;
  51. try_again:
  52. p = &key_user_tree.rb_node;
  53. spin_lock(&key_user_lock);
  54. /* search the tree for a user record with a matching UID */
  55. while (*p) {
  56. parent = *p;
  57. user = rb_entry(parent, struct key_user, node);
  58. if (uid_lt(uid, user->uid))
  59. p = &(*p)->rb_left;
  60. else if (uid_gt(uid, user->uid))
  61. p = &(*p)->rb_right;
  62. else
  63. goto found;
  64. }
  65. /* if we get here, we failed to find a match in the tree */
  66. if (!candidate) {
  67. /* allocate a candidate user record if we don't already have
  68. * one */
  69. spin_unlock(&key_user_lock);
  70. user = NULL;
  71. candidate = kmalloc(sizeof(struct key_user), GFP_KERNEL);
  72. if (unlikely(!candidate))
  73. goto out;
  74. /* the allocation may have scheduled, so we need to repeat the
  75. * search lest someone else added the record whilst we were
  76. * asleep */
  77. goto try_again;
  78. }
  79. /* if we get here, then the user record still hadn't appeared on the
  80. * second pass - so we use the candidate record */
  81. atomic_set(&candidate->usage, 1);
  82. atomic_set(&candidate->nkeys, 0);
  83. atomic_set(&candidate->nikeys, 0);
  84. candidate->uid = uid;
  85. candidate->qnkeys = 0;
  86. candidate->qnbytes = 0;
  87. spin_lock_init(&candidate->lock);
  88. mutex_init(&candidate->cons_lock);
  89. rb_link_node(&candidate->node, parent, p);
  90. rb_insert_color(&candidate->node, &key_user_tree);
  91. spin_unlock(&key_user_lock);
  92. user = candidate;
  93. goto out;
  94. /* okay - we found a user record for this UID */
  95. found:
  96. atomic_inc(&user->usage);
  97. spin_unlock(&key_user_lock);
  98. kfree(candidate);
  99. out:
  100. return user;
  101. }
  102. /*
  103. * Dispose of a user structure
  104. */
  105. void key_user_put(struct key_user *user)
  106. {
  107. if (atomic_dec_and_lock(&user->usage, &key_user_lock)) {
  108. rb_erase(&user->node, &key_user_tree);
  109. spin_unlock(&key_user_lock);
  110. kfree(user);
  111. }
  112. }
  113. /*
  114. * Allocate a serial number for a key. These are assigned randomly to avoid
  115. * security issues through covert channel problems.
  116. */
  117. static inline void key_alloc_serial(struct key *key)
  118. {
  119. struct rb_node *parent, **p;
  120. struct key *xkey;
  121. /* propose a random serial number and look for a hole for it in the
  122. * serial number tree */
  123. do {
  124. get_random_bytes(&key->serial, sizeof(key->serial));
  125. key->serial >>= 1; /* negative numbers are not permitted */
  126. } while (key->serial < 3);
  127. spin_lock(&key_serial_lock);
  128. attempt_insertion:
  129. parent = NULL;
  130. p = &key_serial_tree.rb_node;
  131. while (*p) {
  132. parent = *p;
  133. xkey = rb_entry(parent, struct key, serial_node);
  134. if (key->serial < xkey->serial)
  135. p = &(*p)->rb_left;
  136. else if (key->serial > xkey->serial)
  137. p = &(*p)->rb_right;
  138. else
  139. goto serial_exists;
  140. }
  141. /* we've found a suitable hole - arrange for this key to occupy it */
  142. rb_link_node(&key->serial_node, parent, p);
  143. rb_insert_color(&key->serial_node, &key_serial_tree);
  144. spin_unlock(&key_serial_lock);
  145. return;
  146. /* we found a key with the proposed serial number - walk the tree from
  147. * that point looking for the next unused serial number */
  148. serial_exists:
  149. for (;;) {
  150. key->serial++;
  151. if (key->serial < 3) {
  152. key->serial = 3;
  153. goto attempt_insertion;
  154. }
  155. parent = rb_next(parent);
  156. if (!parent)
  157. goto attempt_insertion;
  158. xkey = rb_entry(parent, struct key, serial_node);
  159. if (key->serial < xkey->serial)
  160. goto attempt_insertion;
  161. }
  162. }
  163. /**
  164. * key_alloc - Allocate a key of the specified type.
  165. * @type: The type of key to allocate.
  166. * @desc: The key description to allow the key to be searched out.
  167. * @uid: The owner of the new key.
  168. * @gid: The group ID for the new key's group permissions.
  169. * @cred: The credentials specifying UID namespace.
  170. * @perm: The permissions mask of the new key.
  171. * @flags: Flags specifying quota properties.
  172. *
  173. * Allocate a key of the specified type with the attributes given. The key is
  174. * returned in an uninstantiated state and the caller needs to instantiate the
  175. * key before returning.
  176. *
  177. * The user's key count quota is updated to reflect the creation of the key and
  178. * the user's key data quota has the default for the key type reserved. The
  179. * instantiation function should amend this as necessary. If insufficient
  180. * quota is available, -EDQUOT will be returned.
  181. *
  182. * The LSM security modules can prevent a key being created, in which case
  183. * -EACCES will be returned.
  184. *
  185. * Returns a pointer to the new key if successful and an error code otherwise.
  186. *
  187. * Note that the caller needs to ensure the key type isn't uninstantiated.
  188. * Internally this can be done by locking key_types_sem. Externally, this can
  189. * be done by either never unregistering the key type, or making sure
  190. * key_alloc() calls don't race with module unloading.
  191. */
  192. struct key *key_alloc(struct key_type *type, const char *desc,
  193. kuid_t uid, kgid_t gid, const struct cred *cred,
  194. key_perm_t perm, unsigned long flags)
  195. {
  196. struct key_user *user = NULL;
  197. struct key *key;
  198. size_t desclen, quotalen;
  199. int ret;
  200. key = ERR_PTR(-EINVAL);
  201. if (!desc || !*desc)
  202. goto error;
  203. if (type->vet_description) {
  204. ret = type->vet_description(desc);
  205. if (ret < 0) {
  206. key = ERR_PTR(ret);
  207. goto error;
  208. }
  209. }
  210. desclen = strlen(desc);
  211. quotalen = desclen + 1 + type->def_datalen;
  212. /* get hold of the key tracking for this user */
  213. user = key_user_lookup(uid);
  214. if (!user)
  215. goto no_memory_1;
  216. /* check that the user's quota permits allocation of another key and
  217. * its description */
  218. if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) {
  219. unsigned maxkeys = uid_eq(uid, GLOBAL_ROOT_UID) ?
  220. key_quota_root_maxkeys : key_quota_maxkeys;
  221. unsigned maxbytes = uid_eq(uid, GLOBAL_ROOT_UID) ?
  222. key_quota_root_maxbytes : key_quota_maxbytes;
  223. spin_lock(&user->lock);
  224. if (!(flags & KEY_ALLOC_QUOTA_OVERRUN)) {
  225. if (user->qnkeys + 1 >= maxkeys ||
  226. user->qnbytes + quotalen >= maxbytes ||
  227. user->qnbytes + quotalen < user->qnbytes)
  228. goto no_quota;
  229. }
  230. user->qnkeys++;
  231. user->qnbytes += quotalen;
  232. spin_unlock(&user->lock);
  233. }
  234. /* allocate and initialise the key and its description */
  235. key = kmem_cache_alloc(key_jar, GFP_KERNEL);
  236. if (!key)
  237. goto no_memory_2;
  238. if (desc) {
  239. key->index_key.desc_len = desclen;
  240. key->index_key.description = kmemdup(desc, desclen + 1, GFP_KERNEL);
  241. if (!key->description)
  242. goto no_memory_3;
  243. }
  244. atomic_set(&key->usage, 1);
  245. init_rwsem(&key->sem);
  246. lockdep_set_class(&key->sem, &type->lock_class);
  247. key->index_key.type = type;
  248. key->user = user;
  249. key->quotalen = quotalen;
  250. key->datalen = type->def_datalen;
  251. key->uid = uid;
  252. key->gid = gid;
  253. key->perm = perm;
  254. key->flags = 0;
  255. key->expiry = 0;
  256. key->payload.data = NULL;
  257. key->security = NULL;
  258. if (!(flags & KEY_ALLOC_NOT_IN_QUOTA))
  259. key->flags |= 1 << KEY_FLAG_IN_QUOTA;
  260. memset(&key->type_data, 0, sizeof(key->type_data));
  261. #ifdef KEY_DEBUGGING
  262. key->magic = KEY_DEBUG_MAGIC;
  263. #endif
  264. /* let the security module know about the key */
  265. ret = security_key_alloc(key, cred, flags);
  266. if (ret < 0)
  267. goto security_error;
  268. /* publish the key by giving it a serial number */
  269. atomic_inc(&user->nkeys);
  270. key_alloc_serial(key);
  271. error:
  272. return key;
  273. security_error:
  274. kfree(key->description);
  275. kmem_cache_free(key_jar, key);
  276. if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) {
  277. spin_lock(&user->lock);
  278. user->qnkeys--;
  279. user->qnbytes -= quotalen;
  280. spin_unlock(&user->lock);
  281. }
  282. key_user_put(user);
  283. key = ERR_PTR(ret);
  284. goto error;
  285. no_memory_3:
  286. kmem_cache_free(key_jar, key);
  287. no_memory_2:
  288. if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) {
  289. spin_lock(&user->lock);
  290. user->qnkeys--;
  291. user->qnbytes -= quotalen;
  292. spin_unlock(&user->lock);
  293. }
  294. key_user_put(user);
  295. no_memory_1:
  296. key = ERR_PTR(-ENOMEM);
  297. goto error;
  298. no_quota:
  299. spin_unlock(&user->lock);
  300. key_user_put(user);
  301. key = ERR_PTR(-EDQUOT);
  302. goto error;
  303. }
  304. EXPORT_SYMBOL(key_alloc);
  305. /**
  306. * key_payload_reserve - Adjust data quota reservation for the key's payload
  307. * @key: The key to make the reservation for.
  308. * @datalen: The amount of data payload the caller now wants.
  309. *
  310. * Adjust the amount of the owning user's key data quota that a key reserves.
  311. * If the amount is increased, then -EDQUOT may be returned if there isn't
  312. * enough free quota available.
  313. *
  314. * If successful, 0 is returned.
  315. */
  316. int key_payload_reserve(struct key *key, size_t datalen)
  317. {
  318. int delta = (int)datalen - key->datalen;
  319. int ret = 0;
  320. key_check(key);
  321. /* contemplate the quota adjustment */
  322. if (delta != 0 && test_bit(KEY_FLAG_IN_QUOTA, &key->flags)) {
  323. unsigned maxbytes = uid_eq(key->user->uid, GLOBAL_ROOT_UID) ?
  324. key_quota_root_maxbytes : key_quota_maxbytes;
  325. spin_lock(&key->user->lock);
  326. if (delta > 0 &&
  327. (key->user->qnbytes + delta >= maxbytes ||
  328. key->user->qnbytes + delta < key->user->qnbytes)) {
  329. ret = -EDQUOT;
  330. }
  331. else {
  332. key->user->qnbytes += delta;
  333. key->quotalen += delta;
  334. }
  335. spin_unlock(&key->user->lock);
  336. }
  337. /* change the recorded data length if that didn't generate an error */
  338. if (ret == 0)
  339. key->datalen = datalen;
  340. return ret;
  341. }
  342. EXPORT_SYMBOL(key_payload_reserve);
  343. /*
  344. * Instantiate a key and link it into the target keyring atomically. Must be
  345. * called with the target keyring's semaphore writelocked. The target key's
  346. * semaphore need not be locked as instantiation is serialised by
  347. * key_construction_mutex.
  348. */
  349. static int __key_instantiate_and_link(struct key *key,
  350. struct key_preparsed_payload *prep,
  351. struct key *keyring,
  352. struct key *authkey,
  353. unsigned long *_prealloc)
  354. {
  355. int ret, awaken;
  356. key_check(key);
  357. key_check(keyring);
  358. awaken = 0;
  359. ret = -EBUSY;
  360. mutex_lock(&key_construction_mutex);
  361. /* can't instantiate twice */
  362. if (!test_bit(KEY_FLAG_INSTANTIATED, &key->flags)) {
  363. /* instantiate the key */
  364. ret = key->type->instantiate(key, prep);
  365. if (ret == 0) {
  366. /* mark the key as being instantiated */
  367. atomic_inc(&key->user->nikeys);
  368. set_bit(KEY_FLAG_INSTANTIATED, &key->flags);
  369. if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags))
  370. awaken = 1;
  371. /* and link it into the destination keyring */
  372. if (keyring)
  373. __key_link(keyring, key, _prealloc);
  374. /* disable the authorisation key */
  375. if (authkey)
  376. key_revoke(authkey);
  377. }
  378. }
  379. mutex_unlock(&key_construction_mutex);
  380. /* wake up anyone waiting for a key to be constructed */
  381. if (awaken)
  382. wake_up_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT);
  383. return ret;
  384. }
  385. /**
  386. * key_instantiate_and_link - Instantiate a key and link it into the keyring.
  387. * @key: The key to instantiate.
  388. * @data: The data to use to instantiate the keyring.
  389. * @datalen: The length of @data.
  390. * @keyring: Keyring to create a link in on success (or NULL).
  391. * @authkey: The authorisation token permitting instantiation.
  392. *
  393. * Instantiate a key that's in the uninstantiated state using the provided data
  394. * and, if successful, link it in to the destination keyring if one is
  395. * supplied.
  396. *
  397. * If successful, 0 is returned, the authorisation token is revoked and anyone
  398. * waiting for the key is woken up. If the key was already instantiated,
  399. * -EBUSY will be returned.
  400. */
  401. int key_instantiate_and_link(struct key *key,
  402. const void *data,
  403. size_t datalen,
  404. struct key *keyring,
  405. struct key *authkey)
  406. {
  407. struct key_preparsed_payload prep;
  408. unsigned long prealloc;
  409. int ret;
  410. memset(&prep, 0, sizeof(prep));
  411. prep.data = data;
  412. prep.datalen = datalen;
  413. prep.quotalen = key->type->def_datalen;
  414. if (key->type->preparse) {
  415. ret = key->type->preparse(&prep);
  416. if (ret < 0)
  417. goto error;
  418. }
  419. if (keyring) {
  420. ret = __key_link_begin(keyring, &key->index_key, &prealloc);
  421. if (ret < 0)
  422. goto error_free_preparse;
  423. }
  424. ret = __key_instantiate_and_link(key, &prep, keyring, authkey,
  425. &prealloc);
  426. if (keyring)
  427. __key_link_end(keyring, &key->index_key, prealloc);
  428. error_free_preparse:
  429. if (key->type->preparse)
  430. key->type->free_preparse(&prep);
  431. error:
  432. return ret;
  433. }
  434. EXPORT_SYMBOL(key_instantiate_and_link);
  435. /**
  436. * key_reject_and_link - Negatively instantiate a key and link it into the keyring.
  437. * @key: The key to instantiate.
  438. * @timeout: The timeout on the negative key.
  439. * @error: The error to return when the key is hit.
  440. * @keyring: Keyring to create a link in on success (or NULL).
  441. * @authkey: The authorisation token permitting instantiation.
  442. *
  443. * Negatively instantiate a key that's in the uninstantiated state and, if
  444. * successful, set its timeout and stored error and link it in to the
  445. * destination keyring if one is supplied. The key and any links to the key
  446. * will be automatically garbage collected after the timeout expires.
  447. *
  448. * Negative keys are used to rate limit repeated request_key() calls by causing
  449. * them to return the stored error code (typically ENOKEY) until the negative
  450. * key expires.
  451. *
  452. * If successful, 0 is returned, the authorisation token is revoked and anyone
  453. * waiting for the key is woken up. If the key was already instantiated,
  454. * -EBUSY will be returned.
  455. */
  456. int key_reject_and_link(struct key *key,
  457. unsigned timeout,
  458. unsigned error,
  459. struct key *keyring,
  460. struct key *authkey)
  461. {
  462. unsigned long prealloc;
  463. struct timespec now;
  464. int ret, awaken, link_ret = 0;
  465. key_check(key);
  466. key_check(keyring);
  467. awaken = 0;
  468. ret = -EBUSY;
  469. if (keyring)
  470. link_ret = __key_link_begin(keyring, &key->index_key, &prealloc);
  471. mutex_lock(&key_construction_mutex);
  472. /* can't instantiate twice */
  473. if (!test_bit(KEY_FLAG_INSTANTIATED, &key->flags)) {
  474. /* mark the key as being negatively instantiated */
  475. atomic_inc(&key->user->nikeys);
  476. set_bit(KEY_FLAG_NEGATIVE, &key->flags);
  477. set_bit(KEY_FLAG_INSTANTIATED, &key->flags);
  478. key->type_data.reject_error = -error;
  479. now = current_kernel_time();
  480. key->expiry = now.tv_sec + timeout;
  481. key_schedule_gc(key->expiry + key_gc_delay);
  482. if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags))
  483. awaken = 1;
  484. ret = 0;
  485. /* and link it into the destination keyring */
  486. if (keyring && link_ret == 0)
  487. __key_link(keyring, key, &prealloc);
  488. /* disable the authorisation key */
  489. if (authkey)
  490. key_revoke(authkey);
  491. }
  492. mutex_unlock(&key_construction_mutex);
  493. if (keyring)
  494. __key_link_end(keyring, &key->index_key, prealloc);
  495. /* wake up anyone waiting for a key to be constructed */
  496. if (awaken)
  497. wake_up_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT);
  498. return ret == 0 ? link_ret : ret;
  499. }
  500. EXPORT_SYMBOL(key_reject_and_link);
  501. /**
  502. * key_put - Discard a reference to a key.
  503. * @key: The key to discard a reference from.
  504. *
  505. * Discard a reference to a key, and when all the references are gone, we
  506. * schedule the cleanup task to come and pull it out of the tree in process
  507. * context at some later time.
  508. */
  509. void key_put(struct key *key)
  510. {
  511. if (key) {
  512. key_check(key);
  513. if (atomic_dec_and_test(&key->usage))
  514. schedule_work(&key_gc_work);
  515. }
  516. }
  517. EXPORT_SYMBOL(key_put);
  518. /*
  519. * Find a key by its serial number.
  520. */
  521. struct key *key_lookup(key_serial_t id)
  522. {
  523. struct rb_node *n;
  524. struct key *key;
  525. spin_lock(&key_serial_lock);
  526. /* search the tree for the specified key */
  527. n = key_serial_tree.rb_node;
  528. while (n) {
  529. key = rb_entry(n, struct key, serial_node);
  530. if (id < key->serial)
  531. n = n->rb_left;
  532. else if (id > key->serial)
  533. n = n->rb_right;
  534. else
  535. goto found;
  536. }
  537. not_found:
  538. key = ERR_PTR(-ENOKEY);
  539. goto error;
  540. found:
  541. /* pretend it doesn't exist if it is awaiting deletion */
  542. if (atomic_read(&key->usage) == 0)
  543. goto not_found;
  544. /* this races with key_put(), but that doesn't matter since key_put()
  545. * doesn't actually change the key
  546. */
  547. __key_get(key);
  548. error:
  549. spin_unlock(&key_serial_lock);
  550. return key;
  551. }
  552. /*
  553. * Find and lock the specified key type against removal.
  554. *
  555. * We return with the sem read-locked if successful. If the type wasn't
  556. * available -ENOKEY is returned instead.
  557. */
  558. struct key_type *key_type_lookup(const char *type)
  559. {
  560. struct key_type *ktype;
  561. down_read(&key_types_sem);
  562. /* look up the key type to see if it's one of the registered kernel
  563. * types */
  564. list_for_each_entry(ktype, &key_types_list, link) {
  565. if (strcmp(ktype->name, type) == 0)
  566. goto found_kernel_type;
  567. }
  568. up_read(&key_types_sem);
  569. ktype = ERR_PTR(-ENOKEY);
  570. found_kernel_type:
  571. return ktype;
  572. }
  573. void key_set_timeout(struct key *key, unsigned timeout)
  574. {
  575. struct timespec now;
  576. time_t expiry = 0;
  577. /* make the changes with the locks held to prevent races */
  578. down_write(&key->sem);
  579. if (timeout > 0) {
  580. now = current_kernel_time();
  581. expiry = now.tv_sec + timeout;
  582. }
  583. key->expiry = expiry;
  584. key_schedule_gc(key->expiry + key_gc_delay);
  585. up_write(&key->sem);
  586. }
  587. EXPORT_SYMBOL_GPL(key_set_timeout);
  588. /*
  589. * Unlock a key type locked by key_type_lookup().
  590. */
  591. void key_type_put(struct key_type *ktype)
  592. {
  593. up_read(&key_types_sem);
  594. }
  595. /*
  596. * Attempt to update an existing key.
  597. *
  598. * The key is given to us with an incremented refcount that we need to discard
  599. * if we get an error.
  600. */
  601. static inline key_ref_t __key_update(key_ref_t key_ref,
  602. struct key_preparsed_payload *prep)
  603. {
  604. struct key *key = key_ref_to_ptr(key_ref);
  605. int ret;
  606. /* need write permission on the key to update it */
  607. ret = key_permission(key_ref, KEY_WRITE);
  608. if (ret < 0)
  609. goto error;
  610. ret = -EEXIST;
  611. if (!key->type->update)
  612. goto error;
  613. down_write(&key->sem);
  614. ret = key->type->update(key, prep);
  615. if (ret == 0)
  616. /* updating a negative key instantiates it */
  617. clear_bit(KEY_FLAG_NEGATIVE, &key->flags);
  618. up_write(&key->sem);
  619. if (ret < 0)
  620. goto error;
  621. out:
  622. return key_ref;
  623. error:
  624. key_put(key);
  625. key_ref = ERR_PTR(ret);
  626. goto out;
  627. }
  628. /**
  629. * key_create_or_update - Update or create and instantiate a key.
  630. * @keyring_ref: A pointer to the destination keyring with possession flag.
  631. * @type: The type of key.
  632. * @description: The searchable description for the key.
  633. * @payload: The data to use to instantiate or update the key.
  634. * @plen: The length of @payload.
  635. * @perm: The permissions mask for a new key.
  636. * @flags: The quota flags for a new key.
  637. *
  638. * Search the destination keyring for a key of the same description and if one
  639. * is found, update it, otherwise create and instantiate a new one and create a
  640. * link to it from that keyring.
  641. *
  642. * If perm is KEY_PERM_UNDEF then an appropriate key permissions mask will be
  643. * concocted.
  644. *
  645. * Returns a pointer to the new key if successful, -ENODEV if the key type
  646. * wasn't available, -ENOTDIR if the keyring wasn't a keyring, -EACCES if the
  647. * caller isn't permitted to modify the keyring or the LSM did not permit
  648. * creation of the key.
  649. *
  650. * On success, the possession flag from the keyring ref will be tacked on to
  651. * the key ref before it is returned.
  652. */
  653. key_ref_t key_create_or_update(key_ref_t keyring_ref,
  654. const char *type,
  655. const char *description,
  656. const void *payload,
  657. size_t plen,
  658. key_perm_t perm,
  659. unsigned long flags)
  660. {
  661. struct keyring_index_key index_key = {
  662. .description = description,
  663. };
  664. struct key_preparsed_payload prep;
  665. const struct cred *cred = current_cred();
  666. unsigned long prealloc;
  667. struct key *keyring, *key = NULL;
  668. key_ref_t key_ref;
  669. int ret;
  670. /* look up the key type to see if it's one of the registered kernel
  671. * types */
  672. index_key.type = key_type_lookup(type);
  673. if (IS_ERR(index_key.type)) {
  674. key_ref = ERR_PTR(-ENODEV);
  675. goto error;
  676. }
  677. key_ref = ERR_PTR(-EINVAL);
  678. if (!index_key.type->match || !index_key.type->instantiate ||
  679. (!index_key.description && !index_key.type->preparse))
  680. goto error_put_type;
  681. keyring = key_ref_to_ptr(keyring_ref);
  682. key_check(keyring);
  683. key_ref = ERR_PTR(-ENOTDIR);
  684. if (keyring->type != &key_type_keyring)
  685. goto error_put_type;
  686. memset(&prep, 0, sizeof(prep));
  687. prep.data = payload;
  688. prep.datalen = plen;
  689. prep.quotalen = index_key.type->def_datalen;
  690. if (index_key.type->preparse) {
  691. ret = index_key.type->preparse(&prep);
  692. if (ret < 0) {
  693. key_ref = ERR_PTR(ret);
  694. goto error_put_type;
  695. }
  696. if (!index_key.description)
  697. index_key.description = prep.description;
  698. key_ref = ERR_PTR(-EINVAL);
  699. if (!index_key.description)
  700. goto error_free_prep;
  701. }
  702. index_key.desc_len = strlen(index_key.description);
  703. ret = __key_link_begin(keyring, &index_key, &prealloc);
  704. if (ret < 0) {
  705. key_ref = ERR_PTR(ret);
  706. goto error_free_prep;
  707. }
  708. /* if we're going to allocate a new key, we're going to have
  709. * to modify the keyring */
  710. ret = key_permission(keyring_ref, KEY_WRITE);
  711. if (ret < 0) {
  712. key_ref = ERR_PTR(ret);
  713. goto error_link_end;
  714. }
  715. /* if it's possible to update this type of key, search for an existing
  716. * key of the same type and description in the destination keyring and
  717. * update that instead if possible
  718. */
  719. if (index_key.type->update) {
  720. key_ref = __keyring_search_one(keyring_ref, &index_key, 0);
  721. if (!IS_ERR(key_ref))
  722. goto found_matching_key;
  723. }
  724. /* if the client doesn't provide, decide on the permissions we want */
  725. if (perm == KEY_PERM_UNDEF) {
  726. perm = KEY_POS_VIEW | KEY_POS_SEARCH | KEY_POS_LINK | KEY_POS_SETATTR;
  727. perm |= KEY_USR_VIEW;
  728. if (index_key.type->read)
  729. perm |= KEY_POS_READ;
  730. if (index_key.type == &key_type_keyring ||
  731. index_key.type->update)
  732. perm |= KEY_POS_WRITE;
  733. }
  734. /* allocate a new key */
  735. key = key_alloc(index_key.type, index_key.description,
  736. cred->fsuid, cred->fsgid, cred, perm, flags);
  737. if (IS_ERR(key)) {
  738. key_ref = ERR_CAST(key);
  739. goto error_link_end;
  740. }
  741. /* instantiate it and link it into the target keyring */
  742. ret = __key_instantiate_and_link(key, &prep, keyring, NULL, &prealloc);
  743. if (ret < 0) {
  744. key_put(key);
  745. key_ref = ERR_PTR(ret);
  746. goto error_link_end;
  747. }
  748. key_ref = make_key_ref(key, is_key_possessed(keyring_ref));
  749. error_link_end:
  750. __key_link_end(keyring, &index_key, prealloc);
  751. error_free_prep:
  752. if (index_key.type->preparse)
  753. index_key.type->free_preparse(&prep);
  754. error_put_type:
  755. key_type_put(index_key.type);
  756. error:
  757. return key_ref;
  758. found_matching_key:
  759. /* we found a matching key, so we're going to try to update it
  760. * - we can drop the locks first as we have the key pinned
  761. */
  762. __key_link_end(keyring, &index_key, prealloc);
  763. key_ref = __key_update(key_ref, &prep);
  764. goto error_free_prep;
  765. }
  766. EXPORT_SYMBOL(key_create_or_update);
  767. /**
  768. * key_update - Update a key's contents.
  769. * @key_ref: The pointer (plus possession flag) to the key.
  770. * @payload: The data to be used to update the key.
  771. * @plen: The length of @payload.
  772. *
  773. * Attempt to update the contents of a key with the given payload data. The
  774. * caller must be granted Write permission on the key. Negative keys can be
  775. * instantiated by this method.
  776. *
  777. * Returns 0 on success, -EACCES if not permitted and -EOPNOTSUPP if the key
  778. * type does not support updating. The key type may return other errors.
  779. */
  780. int key_update(key_ref_t key_ref, const void *payload, size_t plen)
  781. {
  782. struct key_preparsed_payload prep;
  783. struct key *key = key_ref_to_ptr(key_ref);
  784. int ret;
  785. key_check(key);
  786. /* the key must be writable */
  787. ret = key_permission(key_ref, KEY_WRITE);
  788. if (ret < 0)
  789. goto error;
  790. /* attempt to update it if supported */
  791. ret = -EOPNOTSUPP;
  792. if (!key->type->update)
  793. goto error;
  794. memset(&prep, 0, sizeof(prep));
  795. prep.data = payload;
  796. prep.datalen = plen;
  797. prep.quotalen = key->type->def_datalen;
  798. if (key->type->preparse) {
  799. ret = key->type->preparse(&prep);
  800. if (ret < 0)
  801. goto error;
  802. }
  803. down_write(&key->sem);
  804. ret = key->type->update(key, &prep);
  805. if (ret == 0)
  806. /* updating a negative key instantiates it */
  807. clear_bit(KEY_FLAG_NEGATIVE, &key->flags);
  808. up_write(&key->sem);
  809. if (key->type->preparse)
  810. key->type->free_preparse(&prep);
  811. error:
  812. return ret;
  813. }
  814. EXPORT_SYMBOL(key_update);
  815. /**
  816. * key_revoke - Revoke a key.
  817. * @key: The key to be revoked.
  818. *
  819. * Mark a key as being revoked and ask the type to free up its resources. The
  820. * revocation timeout is set and the key and all its links will be
  821. * automatically garbage collected after key_gc_delay amount of time if they
  822. * are not manually dealt with first.
  823. */
  824. void key_revoke(struct key *key)
  825. {
  826. struct timespec now;
  827. time_t time;
  828. key_check(key);
  829. /* make sure no one's trying to change or use the key when we mark it
  830. * - we tell lockdep that we might nest because we might be revoking an
  831. * authorisation key whilst holding the sem on a key we've just
  832. * instantiated
  833. */
  834. down_write_nested(&key->sem, 1);
  835. if (!test_and_set_bit(KEY_FLAG_REVOKED, &key->flags) &&
  836. key->type->revoke)
  837. key->type->revoke(key);
  838. /* set the death time to no more than the expiry time */
  839. now = current_kernel_time();
  840. time = now.tv_sec;
  841. if (key->revoked_at == 0 || key->revoked_at > time) {
  842. key->revoked_at = time;
  843. key_schedule_gc(key->revoked_at + key_gc_delay);
  844. }
  845. up_write(&key->sem);
  846. }
  847. EXPORT_SYMBOL(key_revoke);
  848. /**
  849. * key_invalidate - Invalidate a key.
  850. * @key: The key to be invalidated.
  851. *
  852. * Mark a key as being invalidated and have it cleaned up immediately. The key
  853. * is ignored by all searches and other operations from this point.
  854. */
  855. void key_invalidate(struct key *key)
  856. {
  857. kenter("%d", key_serial(key));
  858. key_check(key);
  859. if (!test_bit(KEY_FLAG_INVALIDATED, &key->flags)) {
  860. down_write_nested(&key->sem, 1);
  861. if (!test_and_set_bit(KEY_FLAG_INVALIDATED, &key->flags))
  862. key_schedule_gc_links();
  863. up_write(&key->sem);
  864. }
  865. }
  866. EXPORT_SYMBOL(key_invalidate);
  867. /**
  868. * register_key_type - Register a type of key.
  869. * @ktype: The new key type.
  870. *
  871. * Register a new key type.
  872. *
  873. * Returns 0 on success or -EEXIST if a type of this name already exists.
  874. */
  875. int register_key_type(struct key_type *ktype)
  876. {
  877. struct key_type *p;
  878. int ret;
  879. memset(&ktype->lock_class, 0, sizeof(ktype->lock_class));
  880. ret = -EEXIST;
  881. down_write(&key_types_sem);
  882. /* disallow key types with the same name */
  883. list_for_each_entry(p, &key_types_list, link) {
  884. if (strcmp(p->name, ktype->name) == 0)
  885. goto out;
  886. }
  887. /* store the type */
  888. list_add(&ktype->link, &key_types_list);
  889. pr_notice("Key type %s registered\n", ktype->name);
  890. ret = 0;
  891. out:
  892. up_write(&key_types_sem);
  893. return ret;
  894. }
  895. EXPORT_SYMBOL(register_key_type);
  896. /**
  897. * unregister_key_type - Unregister a type of key.
  898. * @ktype: The key type.
  899. *
  900. * Unregister a key type and mark all the extant keys of this type as dead.
  901. * Those keys of this type are then destroyed to get rid of their payloads and
  902. * they and their links will be garbage collected as soon as possible.
  903. */
  904. void unregister_key_type(struct key_type *ktype)
  905. {
  906. down_write(&key_types_sem);
  907. list_del_init(&ktype->link);
  908. downgrade_write(&key_types_sem);
  909. key_gc_keytype(ktype);
  910. pr_notice("Key type %s unregistered\n", ktype->name);
  911. up_read(&key_types_sem);
  912. }
  913. EXPORT_SYMBOL(unregister_key_type);
  914. /*
  915. * Initialise the key management state.
  916. */
  917. void __init key_init(void)
  918. {
  919. /* allocate a slab in which we can store keys */
  920. key_jar = kmem_cache_create("key_jar", sizeof(struct key),
  921. 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL);
  922. /* add the special key types */
  923. list_add_tail(&key_type_keyring.link, &key_types_list);
  924. list_add_tail(&key_type_dead.link, &key_types_list);
  925. list_add_tail(&key_type_user.link, &key_types_list);
  926. list_add_tail(&key_type_logon.link, &key_types_list);
  927. /* record the root user tracking */
  928. rb_link_node(&root_key_user.node,
  929. NULL,
  930. &key_user_tree.rb_node);
  931. rb_insert_color(&root_key_user.node,
  932. &key_user_tree);
  933. }