key.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146
  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 = 1000000; /* root's key count quota */
  27. unsigned int key_quota_root_maxbytes = 25000000; /* 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_zalloc(key_jar, GFP_KERNEL);
  236. if (!key)
  237. goto no_memory_2;
  238. key->index_key.desc_len = desclen;
  239. key->index_key.description = kmemdup(desc, desclen + 1, GFP_KERNEL);
  240. if (!key->index_key.description)
  241. goto no_memory_3;
  242. atomic_set(&key->usage, 1);
  243. init_rwsem(&key->sem);
  244. lockdep_set_class(&key->sem, &type->lock_class);
  245. key->index_key.type = type;
  246. key->user = user;
  247. key->quotalen = quotalen;
  248. key->datalen = type->def_datalen;
  249. key->uid = uid;
  250. key->gid = gid;
  251. key->perm = perm;
  252. if (!(flags & KEY_ALLOC_NOT_IN_QUOTA))
  253. key->flags |= 1 << KEY_FLAG_IN_QUOTA;
  254. if (flags & KEY_ALLOC_TRUSTED)
  255. key->flags |= 1 << KEY_FLAG_TRUSTED;
  256. if (flags & KEY_ALLOC_BUILT_IN)
  257. key->flags |= 1 << KEY_FLAG_BUILTIN;
  258. #ifdef KEY_DEBUGGING
  259. key->magic = KEY_DEBUG_MAGIC;
  260. #endif
  261. /* let the security module know about the key */
  262. ret = security_key_alloc(key, cred, flags);
  263. if (ret < 0)
  264. goto security_error;
  265. /* publish the key by giving it a serial number */
  266. atomic_inc(&user->nkeys);
  267. key_alloc_serial(key);
  268. error:
  269. return key;
  270. security_error:
  271. kfree(key->description);
  272. kmem_cache_free(key_jar, key);
  273. if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) {
  274. spin_lock(&user->lock);
  275. user->qnkeys--;
  276. user->qnbytes -= quotalen;
  277. spin_unlock(&user->lock);
  278. }
  279. key_user_put(user);
  280. key = ERR_PTR(ret);
  281. goto error;
  282. no_memory_3:
  283. kmem_cache_free(key_jar, key);
  284. no_memory_2:
  285. if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) {
  286. spin_lock(&user->lock);
  287. user->qnkeys--;
  288. user->qnbytes -= quotalen;
  289. spin_unlock(&user->lock);
  290. }
  291. key_user_put(user);
  292. no_memory_1:
  293. key = ERR_PTR(-ENOMEM);
  294. goto error;
  295. no_quota:
  296. spin_unlock(&user->lock);
  297. key_user_put(user);
  298. key = ERR_PTR(-EDQUOT);
  299. goto error;
  300. }
  301. EXPORT_SYMBOL(key_alloc);
  302. /**
  303. * key_payload_reserve - Adjust data quota reservation for the key's payload
  304. * @key: The key to make the reservation for.
  305. * @datalen: The amount of data payload the caller now wants.
  306. *
  307. * Adjust the amount of the owning user's key data quota that a key reserves.
  308. * If the amount is increased, then -EDQUOT may be returned if there isn't
  309. * enough free quota available.
  310. *
  311. * If successful, 0 is returned.
  312. */
  313. int key_payload_reserve(struct key *key, size_t datalen)
  314. {
  315. int delta = (int)datalen - key->datalen;
  316. int ret = 0;
  317. key_check(key);
  318. /* contemplate the quota adjustment */
  319. if (delta != 0 && test_bit(KEY_FLAG_IN_QUOTA, &key->flags)) {
  320. unsigned maxbytes = uid_eq(key->user->uid, GLOBAL_ROOT_UID) ?
  321. key_quota_root_maxbytes : key_quota_maxbytes;
  322. spin_lock(&key->user->lock);
  323. if (delta > 0 &&
  324. (key->user->qnbytes + delta >= maxbytes ||
  325. key->user->qnbytes + delta < key->user->qnbytes)) {
  326. ret = -EDQUOT;
  327. }
  328. else {
  329. key->user->qnbytes += delta;
  330. key->quotalen += delta;
  331. }
  332. spin_unlock(&key->user->lock);
  333. }
  334. /* change the recorded data length if that didn't generate an error */
  335. if (ret == 0)
  336. key->datalen = datalen;
  337. return ret;
  338. }
  339. EXPORT_SYMBOL(key_payload_reserve);
  340. /*
  341. * Instantiate a key and link it into the target keyring atomically. Must be
  342. * called with the target keyring's semaphore writelocked. The target key's
  343. * semaphore need not be locked as instantiation is serialised by
  344. * key_construction_mutex.
  345. */
  346. static int __key_instantiate_and_link(struct key *key,
  347. struct key_preparsed_payload *prep,
  348. struct key *keyring,
  349. struct key *authkey,
  350. struct assoc_array_edit **_edit)
  351. {
  352. int ret, awaken;
  353. key_check(key);
  354. key_check(keyring);
  355. awaken = 0;
  356. ret = -EBUSY;
  357. mutex_lock(&key_construction_mutex);
  358. /* can't instantiate twice */
  359. if (!test_bit(KEY_FLAG_INSTANTIATED, &key->flags)) {
  360. /* instantiate the key */
  361. ret = key->type->instantiate(key, prep);
  362. if (ret == 0) {
  363. /* mark the key as being instantiated */
  364. atomic_inc(&key->user->nikeys);
  365. set_bit(KEY_FLAG_INSTANTIATED, &key->flags);
  366. if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags))
  367. awaken = 1;
  368. /* and link it into the destination keyring */
  369. if (keyring) {
  370. if (test_bit(KEY_FLAG_KEEP, &keyring->flags))
  371. set_bit(KEY_FLAG_KEEP, &key->flags);
  372. __key_link(key, _edit);
  373. }
  374. /* disable the authorisation key */
  375. if (authkey)
  376. key_revoke(authkey);
  377. if (prep->expiry != TIME_T_MAX) {
  378. key->expiry = prep->expiry;
  379. key_schedule_gc(prep->expiry + key_gc_delay);
  380. }
  381. }
  382. }
  383. mutex_unlock(&key_construction_mutex);
  384. /* wake up anyone waiting for a key to be constructed */
  385. if (awaken)
  386. wake_up_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT);
  387. return ret;
  388. }
  389. /**
  390. * key_instantiate_and_link - Instantiate a key and link it into the keyring.
  391. * @key: The key to instantiate.
  392. * @data: The data to use to instantiate the keyring.
  393. * @datalen: The length of @data.
  394. * @keyring: Keyring to create a link in on success (or NULL).
  395. * @authkey: The authorisation token permitting instantiation.
  396. *
  397. * Instantiate a key that's in the uninstantiated state using the provided data
  398. * and, if successful, link it in to the destination keyring if one is
  399. * supplied.
  400. *
  401. * If successful, 0 is returned, the authorisation token is revoked and anyone
  402. * waiting for the key is woken up. If the key was already instantiated,
  403. * -EBUSY will be returned.
  404. */
  405. int key_instantiate_and_link(struct key *key,
  406. const void *data,
  407. size_t datalen,
  408. struct key *keyring,
  409. struct key *authkey)
  410. {
  411. struct key_preparsed_payload prep;
  412. struct assoc_array_edit *edit;
  413. int ret;
  414. memset(&prep, 0, sizeof(prep));
  415. prep.data = data;
  416. prep.datalen = datalen;
  417. prep.quotalen = key->type->def_datalen;
  418. prep.expiry = TIME_T_MAX;
  419. if (key->type->preparse) {
  420. ret = key->type->preparse(&prep);
  421. if (ret < 0)
  422. goto error;
  423. }
  424. if (keyring) {
  425. ret = __key_link_begin(keyring, &key->index_key, &edit);
  426. if (ret < 0)
  427. goto error;
  428. }
  429. ret = __key_instantiate_and_link(key, &prep, keyring, authkey, &edit);
  430. if (keyring)
  431. __key_link_end(keyring, &key->index_key, edit);
  432. error:
  433. if (key->type->preparse)
  434. key->type->free_preparse(&prep);
  435. return ret;
  436. }
  437. EXPORT_SYMBOL(key_instantiate_and_link);
  438. /**
  439. * key_reject_and_link - Negatively instantiate a key and link it into the keyring.
  440. * @key: The key to instantiate.
  441. * @timeout: The timeout on the negative key.
  442. * @error: The error to return when the key is hit.
  443. * @keyring: Keyring to create a link in on success (or NULL).
  444. * @authkey: The authorisation token permitting instantiation.
  445. *
  446. * Negatively instantiate a key that's in the uninstantiated state and, if
  447. * successful, set its timeout and stored error and link it in to the
  448. * destination keyring if one is supplied. The key and any links to the key
  449. * will be automatically garbage collected after the timeout expires.
  450. *
  451. * Negative keys are used to rate limit repeated request_key() calls by causing
  452. * them to return the stored error code (typically ENOKEY) until the negative
  453. * key expires.
  454. *
  455. * If successful, 0 is returned, the authorisation token is revoked and anyone
  456. * waiting for the key is woken up. If the key was already instantiated,
  457. * -EBUSY will be returned.
  458. */
  459. int key_reject_and_link(struct key *key,
  460. unsigned timeout,
  461. unsigned error,
  462. struct key *keyring,
  463. struct key *authkey)
  464. {
  465. struct assoc_array_edit *edit;
  466. struct timespec now;
  467. int ret, awaken, link_ret = 0;
  468. key_check(key);
  469. key_check(keyring);
  470. awaken = 0;
  471. ret = -EBUSY;
  472. if (keyring)
  473. link_ret = __key_link_begin(keyring, &key->index_key, &edit);
  474. mutex_lock(&key_construction_mutex);
  475. /* can't instantiate twice */
  476. if (!test_bit(KEY_FLAG_INSTANTIATED, &key->flags)) {
  477. /* mark the key as being negatively instantiated */
  478. atomic_inc(&key->user->nikeys);
  479. key->reject_error = -error;
  480. smp_wmb();
  481. set_bit(KEY_FLAG_NEGATIVE, &key->flags);
  482. set_bit(KEY_FLAG_INSTANTIATED, &key->flags);
  483. now = current_kernel_time();
  484. key->expiry = now.tv_sec + timeout;
  485. key_schedule_gc(key->expiry + key_gc_delay);
  486. if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags))
  487. awaken = 1;
  488. ret = 0;
  489. /* and link it into the destination keyring */
  490. if (keyring && link_ret == 0)
  491. __key_link(key, &edit);
  492. /* disable the authorisation key */
  493. if (authkey)
  494. key_revoke(authkey);
  495. }
  496. mutex_unlock(&key_construction_mutex);
  497. if (keyring)
  498. __key_link_end(keyring, &key->index_key, edit);
  499. /* wake up anyone waiting for a key to be constructed */
  500. if (awaken)
  501. wake_up_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT);
  502. return ret == 0 ? link_ret : ret;
  503. }
  504. EXPORT_SYMBOL(key_reject_and_link);
  505. /**
  506. * key_put - Discard a reference to a key.
  507. * @key: The key to discard a reference from.
  508. *
  509. * Discard a reference to a key, and when all the references are gone, we
  510. * schedule the cleanup task to come and pull it out of the tree in process
  511. * context at some later time.
  512. */
  513. void key_put(struct key *key)
  514. {
  515. if (key) {
  516. key_check(key);
  517. if (atomic_dec_and_test(&key->usage))
  518. schedule_work(&key_gc_work);
  519. }
  520. }
  521. EXPORT_SYMBOL(key_put);
  522. /*
  523. * Find a key by its serial number.
  524. */
  525. struct key *key_lookup(key_serial_t id)
  526. {
  527. struct rb_node *n;
  528. struct key *key;
  529. spin_lock(&key_serial_lock);
  530. /* search the tree for the specified key */
  531. n = key_serial_tree.rb_node;
  532. while (n) {
  533. key = rb_entry(n, struct key, serial_node);
  534. if (id < key->serial)
  535. n = n->rb_left;
  536. else if (id > key->serial)
  537. n = n->rb_right;
  538. else
  539. goto found;
  540. }
  541. not_found:
  542. key = ERR_PTR(-ENOKEY);
  543. goto error;
  544. found:
  545. /* pretend it doesn't exist if it is awaiting deletion */
  546. if (atomic_read(&key->usage) == 0)
  547. goto not_found;
  548. /* this races with key_put(), but that doesn't matter since key_put()
  549. * doesn't actually change the key
  550. */
  551. __key_get(key);
  552. error:
  553. spin_unlock(&key_serial_lock);
  554. return key;
  555. }
  556. /*
  557. * Find and lock the specified key type against removal.
  558. *
  559. * We return with the sem read-locked if successful. If the type wasn't
  560. * available -ENOKEY is returned instead.
  561. */
  562. struct key_type *key_type_lookup(const char *type)
  563. {
  564. struct key_type *ktype;
  565. down_read(&key_types_sem);
  566. /* look up the key type to see if it's one of the registered kernel
  567. * types */
  568. list_for_each_entry(ktype, &key_types_list, link) {
  569. if (strcmp(ktype->name, type) == 0)
  570. goto found_kernel_type;
  571. }
  572. up_read(&key_types_sem);
  573. ktype = ERR_PTR(-ENOKEY);
  574. found_kernel_type:
  575. return ktype;
  576. }
  577. void key_set_timeout(struct key *key, unsigned timeout)
  578. {
  579. struct timespec now;
  580. time_t expiry = 0;
  581. /* make the changes with the locks held to prevent races */
  582. down_write(&key->sem);
  583. if (timeout > 0) {
  584. now = current_kernel_time();
  585. expiry = now.tv_sec + timeout;
  586. }
  587. key->expiry = expiry;
  588. key_schedule_gc(key->expiry + key_gc_delay);
  589. up_write(&key->sem);
  590. }
  591. EXPORT_SYMBOL_GPL(key_set_timeout);
  592. /*
  593. * Unlock a key type locked by key_type_lookup().
  594. */
  595. void key_type_put(struct key_type *ktype)
  596. {
  597. up_read(&key_types_sem);
  598. }
  599. /*
  600. * Attempt to update an existing key.
  601. *
  602. * The key is given to us with an incremented refcount that we need to discard
  603. * if we get an error.
  604. */
  605. static inline key_ref_t __key_update(key_ref_t key_ref,
  606. struct key_preparsed_payload *prep)
  607. {
  608. struct key *key = key_ref_to_ptr(key_ref);
  609. int ret;
  610. /* need write permission on the key to update it */
  611. ret = key_permission(key_ref, KEY_NEED_WRITE);
  612. if (ret < 0)
  613. goto error;
  614. ret = -EEXIST;
  615. if (!key->type->update)
  616. goto error;
  617. down_write(&key->sem);
  618. ret = key->type->update(key, prep);
  619. if (ret == 0)
  620. /* updating a negative key instantiates it */
  621. clear_bit(KEY_FLAG_NEGATIVE, &key->flags);
  622. up_write(&key->sem);
  623. if (ret < 0)
  624. goto error;
  625. out:
  626. return key_ref;
  627. error:
  628. key_put(key);
  629. key_ref = ERR_PTR(ret);
  630. goto out;
  631. }
  632. /**
  633. * key_create_or_update - Update or create and instantiate a key.
  634. * @keyring_ref: A pointer to the destination keyring with possession flag.
  635. * @type: The type of key.
  636. * @description: The searchable description for the key.
  637. * @payload: The data to use to instantiate or update the key.
  638. * @plen: The length of @payload.
  639. * @perm: The permissions mask for a new key.
  640. * @flags: The quota flags for a new key.
  641. *
  642. * Search the destination keyring for a key of the same description and if one
  643. * is found, update it, otherwise create and instantiate a new one and create a
  644. * link to it from that keyring.
  645. *
  646. * If perm is KEY_PERM_UNDEF then an appropriate key permissions mask will be
  647. * concocted.
  648. *
  649. * Returns a pointer to the new key if successful, -ENODEV if the key type
  650. * wasn't available, -ENOTDIR if the keyring wasn't a keyring, -EACCES if the
  651. * caller isn't permitted to modify the keyring or the LSM did not permit
  652. * creation of the key.
  653. *
  654. * On success, the possession flag from the keyring ref will be tacked on to
  655. * the key ref before it is returned.
  656. */
  657. key_ref_t key_create_or_update(key_ref_t keyring_ref,
  658. const char *type,
  659. const char *description,
  660. const void *payload,
  661. size_t plen,
  662. key_perm_t perm,
  663. unsigned long flags)
  664. {
  665. struct keyring_index_key index_key = {
  666. .description = description,
  667. };
  668. struct key_preparsed_payload prep;
  669. struct assoc_array_edit *edit;
  670. const struct cred *cred = current_cred();
  671. struct key *keyring, *key = NULL;
  672. key_ref_t key_ref;
  673. int ret;
  674. /* look up the key type to see if it's one of the registered kernel
  675. * types */
  676. index_key.type = key_type_lookup(type);
  677. if (IS_ERR(index_key.type)) {
  678. key_ref = ERR_PTR(-ENODEV);
  679. goto error;
  680. }
  681. key_ref = ERR_PTR(-EINVAL);
  682. if (!index_key.type->instantiate ||
  683. (!index_key.description && !index_key.type->preparse))
  684. goto error_put_type;
  685. keyring = key_ref_to_ptr(keyring_ref);
  686. key_check(keyring);
  687. key_ref = ERR_PTR(-ENOTDIR);
  688. if (keyring->type != &key_type_keyring)
  689. goto error_put_type;
  690. memset(&prep, 0, sizeof(prep));
  691. prep.data = payload;
  692. prep.datalen = plen;
  693. prep.quotalen = index_key.type->def_datalen;
  694. prep.trusted = flags & KEY_ALLOC_TRUSTED;
  695. prep.expiry = TIME_T_MAX;
  696. if (index_key.type->preparse) {
  697. ret = index_key.type->preparse(&prep);
  698. if (ret < 0) {
  699. key_ref = ERR_PTR(ret);
  700. goto error_free_prep;
  701. }
  702. if (!index_key.description)
  703. index_key.description = prep.description;
  704. key_ref = ERR_PTR(-EINVAL);
  705. if (!index_key.description)
  706. goto error_free_prep;
  707. }
  708. index_key.desc_len = strlen(index_key.description);
  709. key_ref = ERR_PTR(-EPERM);
  710. if (!prep.trusted && test_bit(KEY_FLAG_TRUSTED_ONLY, &keyring->flags))
  711. goto error_free_prep;
  712. flags |= prep.trusted ? KEY_ALLOC_TRUSTED : 0;
  713. ret = __key_link_begin(keyring, &index_key, &edit);
  714. if (ret < 0) {
  715. key_ref = ERR_PTR(ret);
  716. goto error_free_prep;
  717. }
  718. /* if we're going to allocate a new key, we're going to have
  719. * to modify the keyring */
  720. ret = key_permission(keyring_ref, KEY_NEED_WRITE);
  721. if (ret < 0) {
  722. key_ref = ERR_PTR(ret);
  723. goto error_link_end;
  724. }
  725. /* if it's possible to update this type of key, search for an existing
  726. * key of the same type and description in the destination keyring and
  727. * update that instead if possible
  728. */
  729. if (index_key.type->update) {
  730. key_ref = find_key_to_update(keyring_ref, &index_key);
  731. if (key_ref)
  732. goto found_matching_key;
  733. }
  734. /* if the client doesn't provide, decide on the permissions we want */
  735. if (perm == KEY_PERM_UNDEF) {
  736. perm = KEY_POS_VIEW | KEY_POS_SEARCH | KEY_POS_LINK | KEY_POS_SETATTR;
  737. perm |= KEY_USR_VIEW;
  738. if (index_key.type->read)
  739. perm |= KEY_POS_READ;
  740. if (index_key.type == &key_type_keyring ||
  741. index_key.type->update)
  742. perm |= KEY_POS_WRITE;
  743. }
  744. /* allocate a new key */
  745. key = key_alloc(index_key.type, index_key.description,
  746. cred->fsuid, cred->fsgid, cred, perm, flags);
  747. if (IS_ERR(key)) {
  748. key_ref = ERR_CAST(key);
  749. goto error_link_end;
  750. }
  751. /* instantiate it and link it into the target keyring */
  752. ret = __key_instantiate_and_link(key, &prep, keyring, NULL, &edit);
  753. if (ret < 0) {
  754. key_put(key);
  755. key_ref = ERR_PTR(ret);
  756. goto error_link_end;
  757. }
  758. key_ref = make_key_ref(key, is_key_possessed(keyring_ref));
  759. error_link_end:
  760. __key_link_end(keyring, &index_key, edit);
  761. error_free_prep:
  762. if (index_key.type->preparse)
  763. index_key.type->free_preparse(&prep);
  764. error_put_type:
  765. key_type_put(index_key.type);
  766. error:
  767. return key_ref;
  768. found_matching_key:
  769. /* we found a matching key, so we're going to try to update it
  770. * - we can drop the locks first as we have the key pinned
  771. */
  772. __key_link_end(keyring, &index_key, edit);
  773. key_ref = __key_update(key_ref, &prep);
  774. goto error_free_prep;
  775. }
  776. EXPORT_SYMBOL(key_create_or_update);
  777. /**
  778. * key_update - Update a key's contents.
  779. * @key_ref: The pointer (plus possession flag) to the key.
  780. * @payload: The data to be used to update the key.
  781. * @plen: The length of @payload.
  782. *
  783. * Attempt to update the contents of a key with the given payload data. The
  784. * caller must be granted Write permission on the key. Negative keys can be
  785. * instantiated by this method.
  786. *
  787. * Returns 0 on success, -EACCES if not permitted and -EOPNOTSUPP if the key
  788. * type does not support updating. The key type may return other errors.
  789. */
  790. int key_update(key_ref_t key_ref, const void *payload, size_t plen)
  791. {
  792. struct key_preparsed_payload prep;
  793. struct key *key = key_ref_to_ptr(key_ref);
  794. int ret;
  795. key_check(key);
  796. /* the key must be writable */
  797. ret = key_permission(key_ref, KEY_NEED_WRITE);
  798. if (ret < 0)
  799. goto error;
  800. /* attempt to update it if supported */
  801. ret = -EOPNOTSUPP;
  802. if (!key->type->update)
  803. goto error;
  804. memset(&prep, 0, sizeof(prep));
  805. prep.data = payload;
  806. prep.datalen = plen;
  807. prep.quotalen = key->type->def_datalen;
  808. prep.expiry = TIME_T_MAX;
  809. if (key->type->preparse) {
  810. ret = key->type->preparse(&prep);
  811. if (ret < 0)
  812. goto error;
  813. }
  814. down_write(&key->sem);
  815. ret = key->type->update(key, &prep);
  816. if (ret == 0)
  817. /* updating a negative key instantiates it */
  818. clear_bit(KEY_FLAG_NEGATIVE, &key->flags);
  819. up_write(&key->sem);
  820. error:
  821. if (key->type->preparse)
  822. key->type->free_preparse(&prep);
  823. return ret;
  824. }
  825. EXPORT_SYMBOL(key_update);
  826. /**
  827. * key_revoke - Revoke a key.
  828. * @key: The key to be revoked.
  829. *
  830. * Mark a key as being revoked and ask the type to free up its resources. The
  831. * revocation timeout is set and the key and all its links will be
  832. * automatically garbage collected after key_gc_delay amount of time if they
  833. * are not manually dealt with first.
  834. */
  835. void key_revoke(struct key *key)
  836. {
  837. struct timespec now;
  838. time_t time;
  839. key_check(key);
  840. /* make sure no one's trying to change or use the key when we mark it
  841. * - we tell lockdep that we might nest because we might be revoking an
  842. * authorisation key whilst holding the sem on a key we've just
  843. * instantiated
  844. */
  845. down_write_nested(&key->sem, 1);
  846. if (!test_and_set_bit(KEY_FLAG_REVOKED, &key->flags) &&
  847. key->type->revoke)
  848. key->type->revoke(key);
  849. /* set the death time to no more than the expiry time */
  850. now = current_kernel_time();
  851. time = now.tv_sec;
  852. if (key->revoked_at == 0 || key->revoked_at > time) {
  853. key->revoked_at = time;
  854. key_schedule_gc(key->revoked_at + key_gc_delay);
  855. }
  856. up_write(&key->sem);
  857. }
  858. EXPORT_SYMBOL(key_revoke);
  859. /**
  860. * key_invalidate - Invalidate a key.
  861. * @key: The key to be invalidated.
  862. *
  863. * Mark a key as being invalidated and have it cleaned up immediately. The key
  864. * is ignored by all searches and other operations from this point.
  865. */
  866. void key_invalidate(struct key *key)
  867. {
  868. kenter("%d", key_serial(key));
  869. key_check(key);
  870. if (!test_bit(KEY_FLAG_INVALIDATED, &key->flags)) {
  871. down_write_nested(&key->sem, 1);
  872. if (!test_and_set_bit(KEY_FLAG_INVALIDATED, &key->flags))
  873. key_schedule_gc_links();
  874. up_write(&key->sem);
  875. }
  876. }
  877. EXPORT_SYMBOL(key_invalidate);
  878. /**
  879. * generic_key_instantiate - Simple instantiation of a key from preparsed data
  880. * @key: The key to be instantiated
  881. * @prep: The preparsed data to load.
  882. *
  883. * Instantiate a key from preparsed data. We assume we can just copy the data
  884. * in directly and clear the old pointers.
  885. *
  886. * This can be pointed to directly by the key type instantiate op pointer.
  887. */
  888. int generic_key_instantiate(struct key *key, struct key_preparsed_payload *prep)
  889. {
  890. int ret;
  891. pr_devel("==>%s()\n", __func__);
  892. ret = key_payload_reserve(key, prep->quotalen);
  893. if (ret == 0) {
  894. rcu_assign_keypointer(key, prep->payload.data[0]);
  895. key->payload.data[1] = prep->payload.data[1];
  896. key->payload.data[2] = prep->payload.data[2];
  897. key->payload.data[3] = prep->payload.data[3];
  898. prep->payload.data[0] = NULL;
  899. prep->payload.data[1] = NULL;
  900. prep->payload.data[2] = NULL;
  901. prep->payload.data[3] = NULL;
  902. }
  903. pr_devel("<==%s() = %d\n", __func__, ret);
  904. return ret;
  905. }
  906. EXPORT_SYMBOL(generic_key_instantiate);
  907. /**
  908. * register_key_type - Register a type of key.
  909. * @ktype: The new key type.
  910. *
  911. * Register a new key type.
  912. *
  913. * Returns 0 on success or -EEXIST if a type of this name already exists.
  914. */
  915. int register_key_type(struct key_type *ktype)
  916. {
  917. struct key_type *p;
  918. int ret;
  919. memset(&ktype->lock_class, 0, sizeof(ktype->lock_class));
  920. ret = -EEXIST;
  921. down_write(&key_types_sem);
  922. /* disallow key types with the same name */
  923. list_for_each_entry(p, &key_types_list, link) {
  924. if (strcmp(p->name, ktype->name) == 0)
  925. goto out;
  926. }
  927. /* store the type */
  928. list_add(&ktype->link, &key_types_list);
  929. pr_notice("Key type %s registered\n", ktype->name);
  930. ret = 0;
  931. out:
  932. up_write(&key_types_sem);
  933. return ret;
  934. }
  935. EXPORT_SYMBOL(register_key_type);
  936. /**
  937. * unregister_key_type - Unregister a type of key.
  938. * @ktype: The key type.
  939. *
  940. * Unregister a key type and mark all the extant keys of this type as dead.
  941. * Those keys of this type are then destroyed to get rid of their payloads and
  942. * they and their links will be garbage collected as soon as possible.
  943. */
  944. void unregister_key_type(struct key_type *ktype)
  945. {
  946. down_write(&key_types_sem);
  947. list_del_init(&ktype->link);
  948. downgrade_write(&key_types_sem);
  949. key_gc_keytype(ktype);
  950. pr_notice("Key type %s unregistered\n", ktype->name);
  951. up_read(&key_types_sem);
  952. }
  953. EXPORT_SYMBOL(unregister_key_type);
  954. /*
  955. * Initialise the key management state.
  956. */
  957. void __init key_init(void)
  958. {
  959. /* allocate a slab in which we can store keys */
  960. key_jar = kmem_cache_create("key_jar", sizeof(struct key),
  961. 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL);
  962. /* add the special key types */
  963. list_add_tail(&key_type_keyring.link, &key_types_list);
  964. list_add_tail(&key_type_dead.link, &key_types_list);
  965. list_add_tail(&key_type_user.link, &key_types_list);
  966. list_add_tail(&key_type_logon.link, &key_types_list);
  967. /* record the root user tracking */
  968. rb_link_node(&root_key_user.node,
  969. NULL,
  970. &key_user_tree.rb_node);
  971. rb_insert_color(&root_key_user.node,
  972. &key_user_tree);
  973. }