key.c 31 KB

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