key.c 29 KB

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