key.c 29 KB

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