key.c 32 KB

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