key.c 31 KB

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