key.c 30 KB

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