key.c 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292
  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 (dhowells@redhat.com)
  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/err.h>
  16. #include "internal.h"
  17. struct kmem_cache *key_jar;
  18. struct rb_root key_serial_tree; /* tree of keys indexed by serial */
  19. DEFINE_SPINLOCK(key_serial_lock);
  20. struct rb_root key_user_tree; /* tree of quota records indexed by UID */
  21. DEFINE_SPINLOCK(key_user_lock);
  22. unsigned int key_quota_root_maxkeys = 1000000; /* root's key count quota */
  23. unsigned int key_quota_root_maxbytes = 25000000; /* root's key space quota */
  24. unsigned int key_quota_maxkeys = 200; /* general key count quota */
  25. unsigned int key_quota_maxbytes = 20000; /* general key space quota */
  26. static LIST_HEAD(key_types_list);
  27. static DECLARE_RWSEM(key_types_sem);
  28. /* We serialise key instantiation and link */
  29. DEFINE_MUTEX(key_construction_mutex);
  30. #ifdef KEY_DEBUGGING
  31. void __key_check(const struct key *key)
  32. {
  33. printk("__key_check: key %p {%08x} should be {%08x}\n",
  34. key, key->magic, KEY_DEBUG_MAGIC);
  35. BUG();
  36. }
  37. #endif
  38. /*
  39. * Get the key quota record for a user, allocating a new record if one doesn't
  40. * already exist.
  41. */
  42. struct key_user *key_user_lookup(kuid_t uid)
  43. {
  44. struct key_user *candidate = NULL, *user;
  45. struct rb_node *parent, **p;
  46. try_again:
  47. parent = NULL;
  48. p = &key_user_tree.rb_node;
  49. spin_lock(&key_user_lock);
  50. /* search the tree for a user record with a matching UID */
  51. while (*p) {
  52. parent = *p;
  53. user = rb_entry(parent, struct key_user, node);
  54. if (uid_lt(uid, user->uid))
  55. p = &(*p)->rb_left;
  56. else if (uid_gt(uid, user->uid))
  57. p = &(*p)->rb_right;
  58. else
  59. goto found;
  60. }
  61. /* if we get here, we failed to find a match in the tree */
  62. if (!candidate) {
  63. /* allocate a candidate user record if we don't already have
  64. * one */
  65. spin_unlock(&key_user_lock);
  66. user = NULL;
  67. candidate = kmalloc(sizeof(struct key_user), GFP_KERNEL);
  68. if (unlikely(!candidate))
  69. goto out;
  70. /* the allocation may have scheduled, so we need to repeat the
  71. * search lest someone else added the record whilst we were
  72. * asleep */
  73. goto try_again;
  74. }
  75. /* if we get here, then the user record still hadn't appeared on the
  76. * second pass - so we use the candidate record */
  77. refcount_set(&candidate->usage, 1);
  78. atomic_set(&candidate->nkeys, 0);
  79. atomic_set(&candidate->nikeys, 0);
  80. candidate->uid = uid;
  81. candidate->qnkeys = 0;
  82. candidate->qnbytes = 0;
  83. spin_lock_init(&candidate->lock);
  84. mutex_init(&candidate->cons_lock);
  85. rb_link_node(&candidate->node, parent, p);
  86. rb_insert_color(&candidate->node, &key_user_tree);
  87. spin_unlock(&key_user_lock);
  88. user = candidate;
  89. goto out;
  90. /* okay - we found a user record for this UID */
  91. found:
  92. refcount_inc(&user->usage);
  93. spin_unlock(&key_user_lock);
  94. kfree(candidate);
  95. out:
  96. return user;
  97. }
  98. /*
  99. * Dispose of a user structure
  100. */
  101. void key_user_put(struct key_user *user)
  102. {
  103. if (refcount_dec_and_lock(&user->usage, &key_user_lock)) {
  104. rb_erase(&user->node, &key_user_tree);
  105. spin_unlock(&key_user_lock);
  106. kfree(user);
  107. }
  108. }
  109. /*
  110. * Allocate a serial number for a key. These are assigned randomly to avoid
  111. * security issues through covert channel problems.
  112. */
  113. static inline void key_alloc_serial(struct key *key)
  114. {
  115. struct rb_node *parent, **p;
  116. struct key *xkey;
  117. /* propose a random serial number and look for a hole for it in the
  118. * serial number tree */
  119. do {
  120. get_random_bytes(&key->serial, sizeof(key->serial));
  121. key->serial >>= 1; /* negative numbers are not permitted */
  122. } while (key->serial < 3);
  123. spin_lock(&key_serial_lock);
  124. attempt_insertion:
  125. parent = NULL;
  126. p = &key_serial_tree.rb_node;
  127. while (*p) {
  128. parent = *p;
  129. xkey = rb_entry(parent, struct key, serial_node);
  130. if (key->serial < xkey->serial)
  131. p = &(*p)->rb_left;
  132. else if (key->serial > xkey->serial)
  133. p = &(*p)->rb_right;
  134. else
  135. goto serial_exists;
  136. }
  137. /* we've found a suitable hole - arrange for this key to occupy it */
  138. rb_link_node(&key->serial_node, parent, p);
  139. rb_insert_color(&key->serial_node, &key_serial_tree);
  140. spin_unlock(&key_serial_lock);
  141. return;
  142. /* we found a key with the proposed serial number - walk the tree from
  143. * that point looking for the next unused serial number */
  144. serial_exists:
  145. for (;;) {
  146. key->serial++;
  147. if (key->serial < 3) {
  148. key->serial = 3;
  149. goto attempt_insertion;
  150. }
  151. parent = rb_next(parent);
  152. if (!parent)
  153. goto attempt_insertion;
  154. xkey = rb_entry(parent, struct key, serial_node);
  155. if (key->serial < xkey->serial)
  156. goto attempt_insertion;
  157. }
  158. }
  159. /**
  160. * key_alloc - Allocate a key of the specified type.
  161. * @type: The type of key to allocate.
  162. * @desc: The key description to allow the key to be searched out.
  163. * @uid: The owner of the new key.
  164. * @gid: The group ID for the new key's group permissions.
  165. * @cred: The credentials specifying UID namespace.
  166. * @perm: The permissions mask of the new key.
  167. * @flags: Flags specifying quota properties.
  168. * @restrict_link: Optional link restriction for new keyrings.
  169. *
  170. * Allocate a key of the specified type with the attributes given. The key is
  171. * returned in an uninstantiated state and the caller needs to instantiate the
  172. * key before returning.
  173. *
  174. * The restrict_link structure (if not NULL) will be freed when the
  175. * keyring is destroyed, so it must be dynamically allocated.
  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. struct key_restriction *restrict_link)
  196. {
  197. struct key_user *user = NULL;
  198. struct key *key;
  199. size_t desclen, quotalen;
  200. int ret;
  201. unsigned long irqflags;
  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_irqsave(&user->lock, irqflags);
  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_irqrestore(&user->lock, irqflags);
  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->expiry = TIME64_MAX;
  256. key->restrict_link = restrict_link;
  257. key->last_used_at = ktime_get_real_seconds();
  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. if (flags & KEY_ALLOC_SET_KEEP)
  265. key->flags |= 1 << KEY_FLAG_KEEP;
  266. #ifdef KEY_DEBUGGING
  267. key->magic = KEY_DEBUG_MAGIC;
  268. #endif
  269. /* let the security module know about the key */
  270. ret = security_key_alloc(key, cred, flags);
  271. if (ret < 0)
  272. goto security_error;
  273. /* publish the key by giving it a serial number */
  274. refcount_inc(&key->domain_tag->usage);
  275. atomic_inc(&user->nkeys);
  276. key_alloc_serial(key);
  277. error:
  278. return key;
  279. security_error:
  280. kfree(key->description);
  281. kmem_cache_free(key_jar, key);
  282. if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) {
  283. spin_lock_irqsave(&user->lock, irqflags);
  284. user->qnkeys--;
  285. user->qnbytes -= quotalen;
  286. spin_unlock_irqrestore(&user->lock, irqflags);
  287. }
  288. key_user_put(user);
  289. key = ERR_PTR(ret);
  290. goto error;
  291. no_memory_3:
  292. kmem_cache_free(key_jar, key);
  293. no_memory_2:
  294. if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) {
  295. spin_lock_irqsave(&user->lock, irqflags);
  296. user->qnkeys--;
  297. user->qnbytes -= quotalen;
  298. spin_unlock_irqrestore(&user->lock, irqflags);
  299. }
  300. key_user_put(user);
  301. no_memory_1:
  302. key = ERR_PTR(-ENOMEM);
  303. goto error;
  304. no_quota:
  305. spin_unlock_irqrestore(&user->lock, irqflags);
  306. key_user_put(user);
  307. key = ERR_PTR(-EDQUOT);
  308. goto error;
  309. }
  310. EXPORT_SYMBOL(key_alloc);
  311. /**
  312. * key_payload_reserve - Adjust data quota reservation for the key's payload
  313. * @key: The key to make the reservation for.
  314. * @datalen: The amount of data payload the caller now wants.
  315. *
  316. * Adjust the amount of the owning user's key data quota that a key reserves.
  317. * If the amount is increased, then -EDQUOT may be returned if there isn't
  318. * enough free quota available.
  319. *
  320. * If successful, 0 is returned.
  321. */
  322. int key_payload_reserve(struct key *key, size_t datalen)
  323. {
  324. int delta = (int)datalen - key->datalen;
  325. int ret = 0;
  326. key_check(key);
  327. /* contemplate the quota adjustment */
  328. if (delta != 0 && test_bit(KEY_FLAG_IN_QUOTA, &key->flags)) {
  329. unsigned maxbytes = uid_eq(key->user->uid, GLOBAL_ROOT_UID) ?
  330. key_quota_root_maxbytes : key_quota_maxbytes;
  331. unsigned long flags;
  332. spin_lock_irqsave(&key->user->lock, flags);
  333. if (delta > 0 &&
  334. (key->user->qnbytes + delta > maxbytes ||
  335. key->user->qnbytes + delta < key->user->qnbytes)) {
  336. ret = -EDQUOT;
  337. }
  338. else {
  339. key->user->qnbytes += delta;
  340. key->quotalen += delta;
  341. }
  342. spin_unlock_irqrestore(&key->user->lock, flags);
  343. }
  344. /* change the recorded data length if that didn't generate an error */
  345. if (ret == 0)
  346. key->datalen = datalen;
  347. return ret;
  348. }
  349. EXPORT_SYMBOL(key_payload_reserve);
  350. /*
  351. * Change the key state to being instantiated.
  352. */
  353. static void mark_key_instantiated(struct key *key, int reject_error)
  354. {
  355. /* Commit the payload before setting the state; barrier versus
  356. * key_read_state().
  357. */
  358. smp_store_release(&key->state,
  359. (reject_error < 0) ? reject_error : KEY_IS_POSITIVE);
  360. }
  361. /*
  362. * Instantiate a key and link it into the target keyring atomically. Must be
  363. * called with the target keyring's semaphore writelocked. The target key's
  364. * semaphore need not be locked as instantiation is serialised by
  365. * key_construction_mutex.
  366. */
  367. static int __key_instantiate_and_link(struct key *key,
  368. struct key_preparsed_payload *prep,
  369. struct key *keyring,
  370. struct key *authkey,
  371. struct assoc_array_edit **_edit)
  372. {
  373. int ret, awaken;
  374. key_check(key);
  375. key_check(keyring);
  376. awaken = 0;
  377. ret = -EBUSY;
  378. mutex_lock(&key_construction_mutex);
  379. /* can't instantiate twice */
  380. if (key->state == KEY_IS_UNINSTANTIATED) {
  381. /* instantiate the key */
  382. ret = key->type->instantiate(key, prep);
  383. if (ret == 0) {
  384. /* mark the key as being instantiated */
  385. atomic_inc(&key->user->nikeys);
  386. mark_key_instantiated(key, 0);
  387. notify_key(key, NOTIFY_KEY_INSTANTIATED, 0);
  388. if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags))
  389. awaken = 1;
  390. /* and link it into the destination keyring */
  391. if (keyring) {
  392. if (test_bit(KEY_FLAG_KEEP, &keyring->flags))
  393. set_bit(KEY_FLAG_KEEP, &key->flags);
  394. __key_link(keyring, key, _edit);
  395. }
  396. /* disable the authorisation key */
  397. if (authkey)
  398. key_invalidate(authkey);
  399. if (prep->expiry != TIME64_MAX)
  400. key_set_expiry(key, prep->expiry);
  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_set_expiry(key, ktime_get_real_seconds() + timeout);
  521. if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags))
  522. awaken = 1;
  523. ret = 0;
  524. /* and link it into the destination keyring */
  525. if (keyring && link_ret == 0)
  526. __key_link(keyring, key, &edit);
  527. /* disable the authorisation key */
  528. if (authkey)
  529. key_invalidate(authkey);
  530. }
  531. mutex_unlock(&key_construction_mutex);
  532. if (keyring && link_ret == 0)
  533. __key_link_end(keyring, &key->index_key, edit);
  534. /* wake up anyone waiting for a key to be constructed */
  535. if (awaken)
  536. wake_up_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT);
  537. return ret == 0 ? link_ret : ret;
  538. }
  539. EXPORT_SYMBOL(key_reject_and_link);
  540. /**
  541. * key_put - Discard a reference to a key.
  542. * @key: The key to discard a reference from.
  543. *
  544. * Discard a reference to a key, and when all the references are gone, we
  545. * schedule the cleanup task to come and pull it out of the tree in process
  546. * context at some later time.
  547. */
  548. void key_put(struct key *key)
  549. {
  550. if (key) {
  551. key_check(key);
  552. if (refcount_dec_and_test(&key->usage)) {
  553. unsigned long flags;
  554. /* deal with the user's key tracking and quota */
  555. if (test_bit(KEY_FLAG_IN_QUOTA, &key->flags)) {
  556. spin_lock_irqsave(&key->user->lock, flags);
  557. key->user->qnkeys--;
  558. key->user->qnbytes -= key->quotalen;
  559. spin_unlock_irqrestore(&key->user->lock, flags);
  560. }
  561. smp_mb(); /* key->user before FINAL_PUT set. */
  562. set_bit(KEY_FLAG_FINAL_PUT, &key->flags);
  563. schedule_work(&key_gc_work);
  564. }
  565. }
  566. }
  567. EXPORT_SYMBOL(key_put);
  568. /*
  569. * Find a key by its serial number.
  570. */
  571. struct key *key_lookup(key_serial_t id)
  572. {
  573. struct rb_node *n;
  574. struct key *key;
  575. spin_lock(&key_serial_lock);
  576. /* search the tree for the specified key */
  577. n = key_serial_tree.rb_node;
  578. while (n) {
  579. key = rb_entry(n, struct key, serial_node);
  580. if (id < key->serial)
  581. n = n->rb_left;
  582. else if (id > key->serial)
  583. n = n->rb_right;
  584. else
  585. goto found;
  586. }
  587. not_found:
  588. key = ERR_PTR(-ENOKEY);
  589. goto error;
  590. found:
  591. /* A key is allowed to be looked up only if someone still owns a
  592. * reference to it - otherwise it's awaiting the gc.
  593. */
  594. if (!refcount_inc_not_zero(&key->usage))
  595. goto not_found;
  596. error:
  597. spin_unlock(&key_serial_lock);
  598. return key;
  599. }
  600. EXPORT_SYMBOL(key_lookup);
  601. /*
  602. * Find and lock the specified key type against removal.
  603. *
  604. * We return with the sem read-locked if successful. If the type wasn't
  605. * available -ENOKEY is returned instead.
  606. */
  607. struct key_type *key_type_lookup(const char *type)
  608. {
  609. struct key_type *ktype;
  610. down_read(&key_types_sem);
  611. /* look up the key type to see if it's one of the registered kernel
  612. * types */
  613. list_for_each_entry(ktype, &key_types_list, link) {
  614. if (strcmp(ktype->name, type) == 0)
  615. goto found_kernel_type;
  616. }
  617. up_read(&key_types_sem);
  618. ktype = ERR_PTR(-ENOKEY);
  619. found_kernel_type:
  620. return ktype;
  621. }
  622. void key_set_timeout(struct key *key, unsigned timeout)
  623. {
  624. time64_t expiry = TIME64_MAX;
  625. /* make the changes with the locks held to prevent races */
  626. down_write(&key->sem);
  627. if (timeout > 0)
  628. expiry = ktime_get_real_seconds() + timeout;
  629. key_set_expiry(key, expiry);
  630. up_write(&key->sem);
  631. }
  632. EXPORT_SYMBOL_GPL(key_set_timeout);
  633. /*
  634. * Unlock a key type locked by key_type_lookup().
  635. */
  636. void key_type_put(struct key_type *ktype)
  637. {
  638. up_read(&key_types_sem);
  639. }
  640. /*
  641. * Attempt to update an existing key.
  642. *
  643. * The key is given to us with an incremented refcount that we need to discard
  644. * if we get an error.
  645. */
  646. static inline key_ref_t __key_update(key_ref_t key_ref,
  647. struct key_preparsed_payload *prep)
  648. {
  649. struct key *key = key_ref_to_ptr(key_ref);
  650. int ret;
  651. /* need write permission on the key to update it */
  652. ret = key_permission(key_ref, KEY_NEED_WRITE);
  653. if (ret < 0)
  654. goto error;
  655. ret = -EEXIST;
  656. if (!key->type->update)
  657. goto error;
  658. down_write(&key->sem);
  659. ret = key->type->update(key, prep);
  660. if (ret == 0) {
  661. /* Updating a negative key positively instantiates it */
  662. mark_key_instantiated(key, 0);
  663. notify_key(key, NOTIFY_KEY_UPDATED, 0);
  664. }
  665. up_write(&key->sem);
  666. if (ret < 0)
  667. goto error;
  668. out:
  669. return key_ref;
  670. error:
  671. key_put(key);
  672. key_ref = ERR_PTR(ret);
  673. goto out;
  674. }
  675. /*
  676. * Create or potentially update a key. The combined logic behind
  677. * key_create_or_update() and key_create()
  678. */
  679. static key_ref_t __key_create_or_update(key_ref_t keyring_ref,
  680. const char *type,
  681. const char *description,
  682. const void *payload,
  683. size_t plen,
  684. key_perm_t perm,
  685. unsigned long flags,
  686. bool allow_update)
  687. {
  688. struct keyring_index_key index_key = {
  689. .description = description,
  690. };
  691. struct key_preparsed_payload prep;
  692. struct assoc_array_edit *edit = NULL;
  693. const struct cred *cred = current_cred();
  694. struct key *keyring, *key = NULL;
  695. key_ref_t key_ref;
  696. int ret;
  697. struct key_restriction *restrict_link = NULL;
  698. /* look up the key type to see if it's one of the registered kernel
  699. * types */
  700. index_key.type = key_type_lookup(type);
  701. if (IS_ERR(index_key.type)) {
  702. key_ref = ERR_PTR(-ENODEV);
  703. goto error;
  704. }
  705. key_ref = ERR_PTR(-EINVAL);
  706. if (!index_key.type->instantiate ||
  707. (!index_key.description && !index_key.type->preparse))
  708. goto error_put_type;
  709. keyring = key_ref_to_ptr(keyring_ref);
  710. key_check(keyring);
  711. if (!(flags & KEY_ALLOC_BYPASS_RESTRICTION))
  712. restrict_link = keyring->restrict_link;
  713. key_ref = ERR_PTR(-ENOTDIR);
  714. if (keyring->type != &key_type_keyring)
  715. goto error_put_type;
  716. memset(&prep, 0, sizeof(prep));
  717. prep.orig_description = description;
  718. prep.data = payload;
  719. prep.datalen = plen;
  720. prep.quotalen = index_key.type->def_datalen;
  721. prep.expiry = TIME64_MAX;
  722. if (index_key.type->preparse) {
  723. ret = index_key.type->preparse(&prep);
  724. if (ret < 0) {
  725. key_ref = ERR_PTR(ret);
  726. goto error_free_prep;
  727. }
  728. if (!index_key.description)
  729. index_key.description = prep.description;
  730. key_ref = ERR_PTR(-EINVAL);
  731. if (!index_key.description)
  732. goto error_free_prep;
  733. }
  734. index_key.desc_len = strlen(index_key.description);
  735. key_set_index_key(&index_key);
  736. ret = __key_link_lock(keyring, &index_key);
  737. if (ret < 0) {
  738. key_ref = ERR_PTR(ret);
  739. goto error_free_prep;
  740. }
  741. ret = __key_link_begin(keyring, &index_key, &edit);
  742. if (ret < 0) {
  743. key_ref = ERR_PTR(ret);
  744. goto error_link_end;
  745. }
  746. if (restrict_link && restrict_link->check) {
  747. ret = restrict_link->check(keyring, index_key.type,
  748. &prep.payload, restrict_link->key);
  749. if (ret < 0) {
  750. key_ref = ERR_PTR(ret);
  751. goto error_link_end;
  752. }
  753. }
  754. /* if we're going to allocate a new key, we're going to have
  755. * to modify the keyring */
  756. ret = key_permission(keyring_ref, KEY_NEED_WRITE);
  757. if (ret < 0) {
  758. key_ref = ERR_PTR(ret);
  759. goto error_link_end;
  760. }
  761. /* if it's requested and possible to update this type of key, search
  762. * for an existing key of the same type and description in the
  763. * destination keyring and update that instead if possible
  764. */
  765. if (allow_update) {
  766. if (index_key.type->update) {
  767. key_ref = find_key_to_update(keyring_ref, &index_key);
  768. if (key_ref)
  769. goto found_matching_key;
  770. }
  771. } else {
  772. key_ref = find_key_to_update(keyring_ref, &index_key);
  773. if (key_ref) {
  774. key_ref_put(key_ref);
  775. key_ref = ERR_PTR(-EEXIST);
  776. goto error_link_end;
  777. }
  778. }
  779. /* if the client doesn't provide, decide on the permissions we want */
  780. if (perm == KEY_PERM_UNDEF) {
  781. perm = KEY_POS_VIEW | KEY_POS_SEARCH | KEY_POS_LINK | KEY_POS_SETATTR;
  782. perm |= KEY_USR_VIEW;
  783. if (index_key.type->read)
  784. perm |= KEY_POS_READ;
  785. if (index_key.type == &key_type_keyring ||
  786. index_key.type->update)
  787. perm |= KEY_POS_WRITE;
  788. }
  789. /* allocate a new key */
  790. key = key_alloc(index_key.type, index_key.description,
  791. cred->fsuid, cred->fsgid, cred, perm, flags, NULL);
  792. if (IS_ERR(key)) {
  793. key_ref = ERR_CAST(key);
  794. goto error_link_end;
  795. }
  796. /* instantiate it and link it into the target keyring */
  797. ret = __key_instantiate_and_link(key, &prep, keyring, NULL, &edit);
  798. if (ret < 0) {
  799. key_put(key);
  800. key_ref = ERR_PTR(ret);
  801. goto error_link_end;
  802. }
  803. security_key_post_create_or_update(keyring, key, payload, plen, flags,
  804. true);
  805. key_ref = make_key_ref(key, is_key_possessed(keyring_ref));
  806. error_link_end:
  807. __key_link_end(keyring, &index_key, edit);
  808. error_free_prep:
  809. if (index_key.type->preparse)
  810. index_key.type->free_preparse(&prep);
  811. error_put_type:
  812. key_type_put(index_key.type);
  813. error:
  814. return key_ref;
  815. found_matching_key:
  816. /* we found a matching key, so we're going to try to update it
  817. * - we can drop the locks first as we have the key pinned
  818. */
  819. __key_link_end(keyring, &index_key, edit);
  820. key = key_ref_to_ptr(key_ref);
  821. if (test_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags)) {
  822. ret = wait_for_key_construction(key, true);
  823. if (ret < 0) {
  824. key_ref_put(key_ref);
  825. key_ref = ERR_PTR(ret);
  826. goto error_free_prep;
  827. }
  828. }
  829. key_ref = __key_update(key_ref, &prep);
  830. if (!IS_ERR(key_ref))
  831. security_key_post_create_or_update(keyring, key, payload, plen,
  832. flags, false);
  833. goto error_free_prep;
  834. }
  835. /**
  836. * key_create_or_update - Update or create and instantiate a key.
  837. * @keyring_ref: A pointer to the destination keyring with possession flag.
  838. * @type: The type of key.
  839. * @description: The searchable description for the key.
  840. * @payload: The data to use to instantiate or update the key.
  841. * @plen: The length of @payload.
  842. * @perm: The permissions mask for a new key.
  843. * @flags: The quota flags for a new key.
  844. *
  845. * Search the destination keyring for a key of the same description and if one
  846. * is found, update it, otherwise create and instantiate a new one and create a
  847. * link to it from that keyring.
  848. *
  849. * If perm is KEY_PERM_UNDEF then an appropriate key permissions mask will be
  850. * concocted.
  851. *
  852. * Returns a pointer to the new key if successful, -ENODEV if the key type
  853. * wasn't available, -ENOTDIR if the keyring wasn't a keyring, -EACCES if the
  854. * caller isn't permitted to modify the keyring or the LSM did not permit
  855. * creation of the key.
  856. *
  857. * On success, the possession flag from the keyring ref will be tacked on to
  858. * the key ref before it is returned.
  859. */
  860. key_ref_t key_create_or_update(key_ref_t keyring_ref,
  861. const char *type,
  862. const char *description,
  863. const void *payload,
  864. size_t plen,
  865. key_perm_t perm,
  866. unsigned long flags)
  867. {
  868. return __key_create_or_update(keyring_ref, type, description, payload,
  869. plen, perm, flags, true);
  870. }
  871. EXPORT_SYMBOL(key_create_or_update);
  872. /**
  873. * key_create - Create and instantiate a key.
  874. * @keyring_ref: A pointer to the destination keyring with possession flag.
  875. * @type: The type of key.
  876. * @description: The searchable description for the key.
  877. * @payload: The data to use to instantiate or update the key.
  878. * @plen: The length of @payload.
  879. * @perm: The permissions mask for a new key.
  880. * @flags: The quota flags for a new key.
  881. *
  882. * Create and instantiate a new key and link to it from the destination keyring.
  883. *
  884. * If perm is KEY_PERM_UNDEF then an appropriate key permissions mask will be
  885. * concocted.
  886. *
  887. * Returns a pointer to the new key if successful, -EEXIST if a key with the
  888. * same description already exists, -ENODEV if the key type wasn't available,
  889. * -ENOTDIR if the keyring wasn't a keyring, -EACCES if the caller isn't
  890. * permitted to modify the keyring or the LSM did not permit creation of the
  891. * key.
  892. *
  893. * On success, the possession flag from the keyring ref will be tacked on to
  894. * the key ref before it is returned.
  895. */
  896. key_ref_t key_create(key_ref_t keyring_ref,
  897. const char *type,
  898. const char *description,
  899. const void *payload,
  900. size_t plen,
  901. key_perm_t perm,
  902. unsigned long flags)
  903. {
  904. return __key_create_or_update(keyring_ref, type, description, payload,
  905. plen, perm, flags, false);
  906. }
  907. EXPORT_SYMBOL(key_create);
  908. /**
  909. * key_update - Update a key's contents.
  910. * @key_ref: The pointer (plus possession flag) to the key.
  911. * @payload: The data to be used to update the key.
  912. * @plen: The length of @payload.
  913. *
  914. * Attempt to update the contents of a key with the given payload data. The
  915. * caller must be granted Write permission on the key. Negative keys can be
  916. * instantiated by this method.
  917. *
  918. * Returns 0 on success, -EACCES if not permitted and -EOPNOTSUPP if the key
  919. * type does not support updating. The key type may return other errors.
  920. */
  921. int key_update(key_ref_t key_ref, const void *payload, size_t plen)
  922. {
  923. struct key_preparsed_payload prep;
  924. struct key *key = key_ref_to_ptr(key_ref);
  925. int ret;
  926. key_check(key);
  927. /* the key must be writable */
  928. ret = key_permission(key_ref, KEY_NEED_WRITE);
  929. if (ret < 0)
  930. return ret;
  931. /* attempt to update it if supported */
  932. if (!key->type->update)
  933. return -EOPNOTSUPP;
  934. memset(&prep, 0, sizeof(prep));
  935. prep.data = payload;
  936. prep.datalen = plen;
  937. prep.quotalen = key->type->def_datalen;
  938. prep.expiry = TIME64_MAX;
  939. if (key->type->preparse) {
  940. ret = key->type->preparse(&prep);
  941. if (ret < 0)
  942. goto error;
  943. }
  944. down_write(&key->sem);
  945. ret = key->type->update(key, &prep);
  946. if (ret == 0) {
  947. /* Updating a negative key positively instantiates it */
  948. mark_key_instantiated(key, 0);
  949. notify_key(key, NOTIFY_KEY_UPDATED, 0);
  950. }
  951. up_write(&key->sem);
  952. error:
  953. if (key->type->preparse)
  954. key->type->free_preparse(&prep);
  955. return ret;
  956. }
  957. EXPORT_SYMBOL(key_update);
  958. /**
  959. * key_revoke - Revoke a key.
  960. * @key: The key to be revoked.
  961. *
  962. * Mark a key as being revoked and ask the type to free up its resources. The
  963. * revocation timeout is set and the key and all its links will be
  964. * automatically garbage collected after key_gc_delay amount of time if they
  965. * are not manually dealt with first.
  966. */
  967. void key_revoke(struct key *key)
  968. {
  969. time64_t time;
  970. key_check(key);
  971. /* make sure no one's trying to change or use the key when we mark it
  972. * - we tell lockdep that we might nest because we might be revoking an
  973. * authorisation key whilst holding the sem on a key we've just
  974. * instantiated
  975. */
  976. down_write_nested(&key->sem, 1);
  977. if (!test_and_set_bit(KEY_FLAG_REVOKED, &key->flags)) {
  978. notify_key(key, NOTIFY_KEY_REVOKED, 0);
  979. if (key->type->revoke)
  980. key->type->revoke(key);
  981. /* set the death time to no more than the expiry time */
  982. time = ktime_get_real_seconds();
  983. if (key->revoked_at == 0 || key->revoked_at > time) {
  984. key->revoked_at = time;
  985. key_schedule_gc(key->revoked_at + key_gc_delay);
  986. }
  987. }
  988. up_write(&key->sem);
  989. }
  990. EXPORT_SYMBOL(key_revoke);
  991. /**
  992. * key_invalidate - Invalidate a key.
  993. * @key: The key to be invalidated.
  994. *
  995. * Mark a key as being invalidated and have it cleaned up immediately. The key
  996. * is ignored by all searches and other operations from this point.
  997. */
  998. void key_invalidate(struct key *key)
  999. {
  1000. kenter("%d", key_serial(key));
  1001. key_check(key);
  1002. if (!test_bit(KEY_FLAG_INVALIDATED, &key->flags)) {
  1003. down_write_nested(&key->sem, 1);
  1004. if (!test_and_set_bit(KEY_FLAG_INVALIDATED, &key->flags)) {
  1005. notify_key(key, NOTIFY_KEY_INVALIDATED, 0);
  1006. key_schedule_gc_links();
  1007. }
  1008. up_write(&key->sem);
  1009. }
  1010. }
  1011. EXPORT_SYMBOL(key_invalidate);
  1012. /**
  1013. * generic_key_instantiate - Simple instantiation of a key from preparsed data
  1014. * @key: The key to be instantiated
  1015. * @prep: The preparsed data to load.
  1016. *
  1017. * Instantiate a key from preparsed data. We assume we can just copy the data
  1018. * in directly and clear the old pointers.
  1019. *
  1020. * This can be pointed to directly by the key type instantiate op pointer.
  1021. */
  1022. int generic_key_instantiate(struct key *key, struct key_preparsed_payload *prep)
  1023. {
  1024. int ret;
  1025. pr_devel("==>%s()\n", __func__);
  1026. ret = key_payload_reserve(key, prep->quotalen);
  1027. if (ret == 0) {
  1028. rcu_assign_keypointer(key, prep->payload.data[0]);
  1029. key->payload.data[1] = prep->payload.data[1];
  1030. key->payload.data[2] = prep->payload.data[2];
  1031. key->payload.data[3] = prep->payload.data[3];
  1032. prep->payload.data[0] = NULL;
  1033. prep->payload.data[1] = NULL;
  1034. prep->payload.data[2] = NULL;
  1035. prep->payload.data[3] = NULL;
  1036. }
  1037. pr_devel("<==%s() = %d\n", __func__, ret);
  1038. return ret;
  1039. }
  1040. EXPORT_SYMBOL(generic_key_instantiate);
  1041. /**
  1042. * register_key_type - Register a type of key.
  1043. * @ktype: The new key type.
  1044. *
  1045. * Register a new key type.
  1046. *
  1047. * Returns 0 on success or -EEXIST if a type of this name already exists.
  1048. */
  1049. int register_key_type(struct key_type *ktype)
  1050. {
  1051. struct key_type *p;
  1052. int ret;
  1053. memset(&ktype->lock_class, 0, sizeof(ktype->lock_class));
  1054. ret = -EEXIST;
  1055. down_write(&key_types_sem);
  1056. /* disallow key types with the same name */
  1057. list_for_each_entry(p, &key_types_list, link) {
  1058. if (strcmp(p->name, ktype->name) == 0)
  1059. goto out;
  1060. }
  1061. /* store the type */
  1062. list_add(&ktype->link, &key_types_list);
  1063. pr_notice("Key type %s registered\n", ktype->name);
  1064. ret = 0;
  1065. out:
  1066. up_write(&key_types_sem);
  1067. return ret;
  1068. }
  1069. EXPORT_SYMBOL(register_key_type);
  1070. /**
  1071. * unregister_key_type - Unregister a type of key.
  1072. * @ktype: The key type.
  1073. *
  1074. * Unregister a key type and mark all the extant keys of this type as dead.
  1075. * Those keys of this type are then destroyed to get rid of their payloads and
  1076. * they and their links will be garbage collected as soon as possible.
  1077. */
  1078. void unregister_key_type(struct key_type *ktype)
  1079. {
  1080. down_write(&key_types_sem);
  1081. list_del_init(&ktype->link);
  1082. downgrade_write(&key_types_sem);
  1083. key_gc_keytype(ktype);
  1084. pr_notice("Key type %s unregistered\n", ktype->name);
  1085. up_read(&key_types_sem);
  1086. }
  1087. EXPORT_SYMBOL(unregister_key_type);
  1088. /*
  1089. * Initialise the key management state.
  1090. */
  1091. void __init key_init(void)
  1092. {
  1093. /* allocate a slab in which we can store keys */
  1094. key_jar = kmem_cache_create("key_jar", sizeof(struct key),
  1095. 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL);
  1096. /* add the special key types */
  1097. list_add_tail(&key_type_keyring.link, &key_types_list);
  1098. list_add_tail(&key_type_dead.link, &key_types_list);
  1099. list_add_tail(&key_type_user.link, &key_types_list);
  1100. list_add_tail(&key_type_logon.link, &key_types_list);
  1101. /* record the root user tracking */
  1102. rb_link_node(&root_key_user.node,
  1103. NULL,
  1104. &key_user_tree.rb_node);
  1105. rb_insert_color(&root_key_user.node,
  1106. &key_user_tree);
  1107. }