key.c 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218
  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/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.data = data;
  436. prep.datalen = datalen;
  437. prep.quotalen = key->type->def_datalen;
  438. prep.expiry = TIME64_MAX;
  439. if (key->type->preparse) {
  440. ret = key->type->preparse(&prep);
  441. if (ret < 0)
  442. goto error;
  443. }
  444. if (keyring) {
  445. ret = __key_link_lock(keyring, &key->index_key);
  446. if (ret < 0)
  447. goto error;
  448. ret = __key_link_begin(keyring, &key->index_key, &edit);
  449. if (ret < 0)
  450. goto error_link_end;
  451. if (keyring->restrict_link && keyring->restrict_link->check) {
  452. struct key_restriction *keyres = keyring->restrict_link;
  453. ret = keyres->check(keyring, key->type, &prep.payload,
  454. keyres->key);
  455. if (ret < 0)
  456. goto error_link_end;
  457. }
  458. }
  459. ret = __key_instantiate_and_link(key, &prep, keyring, authkey, &edit);
  460. error_link_end:
  461. if (keyring)
  462. __key_link_end(keyring, &key->index_key, edit);
  463. error:
  464. if (key->type->preparse)
  465. key->type->free_preparse(&prep);
  466. return ret;
  467. }
  468. EXPORT_SYMBOL(key_instantiate_and_link);
  469. /**
  470. * key_reject_and_link - Negatively instantiate a key and link it into the keyring.
  471. * @key: The key to instantiate.
  472. * @timeout: The timeout on the negative key.
  473. * @error: The error to return when the key is hit.
  474. * @keyring: Keyring to create a link in on success (or NULL).
  475. * @authkey: The authorisation token permitting instantiation.
  476. *
  477. * Negatively instantiate a key that's in the uninstantiated state and, if
  478. * successful, set its timeout and stored error and link it in to the
  479. * destination keyring if one is supplied. The key and any links to the key
  480. * will be automatically garbage collected after the timeout expires.
  481. *
  482. * Negative keys are used to rate limit repeated request_key() calls by causing
  483. * them to return the stored error code (typically ENOKEY) until the negative
  484. * key expires.
  485. *
  486. * If successful, 0 is returned, the authorisation token is revoked and anyone
  487. * waiting for the key is woken up. If the key was already instantiated,
  488. * -EBUSY will be returned.
  489. */
  490. int key_reject_and_link(struct key *key,
  491. unsigned timeout,
  492. unsigned error,
  493. struct key *keyring,
  494. struct key *authkey)
  495. {
  496. struct assoc_array_edit *edit = NULL;
  497. int ret, awaken, link_ret = 0;
  498. key_check(key);
  499. key_check(keyring);
  500. awaken = 0;
  501. ret = -EBUSY;
  502. if (keyring) {
  503. if (keyring->restrict_link)
  504. return -EPERM;
  505. link_ret = __key_link_lock(keyring, &key->index_key);
  506. if (link_ret == 0) {
  507. link_ret = __key_link_begin(keyring, &key->index_key, &edit);
  508. if (link_ret < 0)
  509. __key_link_end(keyring, &key->index_key, edit);
  510. }
  511. }
  512. mutex_lock(&key_construction_mutex);
  513. /* can't instantiate twice */
  514. if (key->state == KEY_IS_UNINSTANTIATED) {
  515. /* mark the key as being negatively instantiated */
  516. atomic_inc(&key->user->nikeys);
  517. mark_key_instantiated(key, -error);
  518. notify_key(key, NOTIFY_KEY_INSTANTIATED, -error);
  519. key->expiry = ktime_get_real_seconds() + timeout;
  520. key_schedule_gc(key->expiry + key_gc_delay);
  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. schedule_work(&key_gc_work);
  554. }
  555. }
  556. EXPORT_SYMBOL(key_put);
  557. /*
  558. * Find a key by its serial number.
  559. */
  560. struct key *key_lookup(key_serial_t id)
  561. {
  562. struct rb_node *n;
  563. struct key *key;
  564. spin_lock(&key_serial_lock);
  565. /* search the tree for the specified key */
  566. n = key_serial_tree.rb_node;
  567. while (n) {
  568. key = rb_entry(n, struct key, serial_node);
  569. if (id < key->serial)
  570. n = n->rb_left;
  571. else if (id > key->serial)
  572. n = n->rb_right;
  573. else
  574. goto found;
  575. }
  576. not_found:
  577. key = ERR_PTR(-ENOKEY);
  578. goto error;
  579. found:
  580. /* A key is allowed to be looked up only if someone still owns a
  581. * reference to it - otherwise it's awaiting the gc.
  582. */
  583. if (!refcount_inc_not_zero(&key->usage))
  584. goto not_found;
  585. error:
  586. spin_unlock(&key_serial_lock);
  587. return key;
  588. }
  589. /*
  590. * Find and lock the specified key type against removal.
  591. *
  592. * We return with the sem read-locked if successful. If the type wasn't
  593. * available -ENOKEY is returned instead.
  594. */
  595. struct key_type *key_type_lookup(const char *type)
  596. {
  597. struct key_type *ktype;
  598. down_read(&key_types_sem);
  599. /* look up the key type to see if it's one of the registered kernel
  600. * types */
  601. list_for_each_entry(ktype, &key_types_list, link) {
  602. if (strcmp(ktype->name, type) == 0)
  603. goto found_kernel_type;
  604. }
  605. up_read(&key_types_sem);
  606. ktype = ERR_PTR(-ENOKEY);
  607. found_kernel_type:
  608. return ktype;
  609. }
  610. void key_set_timeout(struct key *key, unsigned timeout)
  611. {
  612. time64_t expiry = 0;
  613. /* make the changes with the locks held to prevent races */
  614. down_write(&key->sem);
  615. if (timeout > 0)
  616. expiry = ktime_get_real_seconds() + timeout;
  617. key->expiry = expiry;
  618. key_schedule_gc(key->expiry + key_gc_delay);
  619. up_write(&key->sem);
  620. }
  621. EXPORT_SYMBOL_GPL(key_set_timeout);
  622. /*
  623. * Unlock a key type locked by key_type_lookup().
  624. */
  625. void key_type_put(struct key_type *ktype)
  626. {
  627. up_read(&key_types_sem);
  628. }
  629. /*
  630. * Attempt to update an existing key.
  631. *
  632. * The key is given to us with an incremented refcount that we need to discard
  633. * if we get an error.
  634. */
  635. static inline key_ref_t __key_update(key_ref_t key_ref,
  636. struct key_preparsed_payload *prep)
  637. {
  638. struct key *key = key_ref_to_ptr(key_ref);
  639. int ret;
  640. /* need write permission on the key to update it */
  641. ret = key_permission(key_ref, KEY_NEED_WRITE);
  642. if (ret < 0)
  643. goto error;
  644. ret = -EEXIST;
  645. if (!key->type->update)
  646. goto error;
  647. down_write(&key->sem);
  648. ret = key->type->update(key, prep);
  649. if (ret == 0) {
  650. /* Updating a negative key positively instantiates it */
  651. mark_key_instantiated(key, 0);
  652. notify_key(key, NOTIFY_KEY_UPDATED, 0);
  653. }
  654. up_write(&key->sem);
  655. if (ret < 0)
  656. goto error;
  657. out:
  658. return key_ref;
  659. error:
  660. key_put(key);
  661. key_ref = ERR_PTR(ret);
  662. goto out;
  663. }
  664. /**
  665. * key_create_or_update - Update or create and instantiate a key.
  666. * @keyring_ref: A pointer to the destination keyring with possession flag.
  667. * @type: The type of key.
  668. * @description: The searchable description for the key.
  669. * @payload: The data to use to instantiate or update the key.
  670. * @plen: The length of @payload.
  671. * @perm: The permissions mask for a new key.
  672. * @flags: The quota flags for a new key.
  673. *
  674. * Search the destination keyring for a key of the same description and if one
  675. * is found, update it, otherwise create and instantiate a new one and create a
  676. * link to it from that keyring.
  677. *
  678. * If perm is KEY_PERM_UNDEF then an appropriate key permissions mask will be
  679. * concocted.
  680. *
  681. * Returns a pointer to the new key if successful, -ENODEV if the key type
  682. * wasn't available, -ENOTDIR if the keyring wasn't a keyring, -EACCES if the
  683. * caller isn't permitted to modify the keyring or the LSM did not permit
  684. * creation of the key.
  685. *
  686. * On success, the possession flag from the keyring ref will be tacked on to
  687. * the key ref before it is returned.
  688. */
  689. key_ref_t key_create_or_update(key_ref_t keyring_ref,
  690. const char *type,
  691. const char *description,
  692. const void *payload,
  693. size_t plen,
  694. key_perm_t perm,
  695. unsigned long flags)
  696. {
  697. struct keyring_index_key index_key = {
  698. .description = description,
  699. };
  700. struct key_preparsed_payload prep;
  701. struct assoc_array_edit *edit = NULL;
  702. const struct cred *cred = current_cred();
  703. struct key *keyring, *key = NULL;
  704. key_ref_t key_ref;
  705. int ret;
  706. struct key_restriction *restrict_link = NULL;
  707. /* look up the key type to see if it's one of the registered kernel
  708. * types */
  709. index_key.type = key_type_lookup(type);
  710. if (IS_ERR(index_key.type)) {
  711. key_ref = ERR_PTR(-ENODEV);
  712. goto error;
  713. }
  714. key_ref = ERR_PTR(-EINVAL);
  715. if (!index_key.type->instantiate ||
  716. (!index_key.description && !index_key.type->preparse))
  717. goto error_put_type;
  718. keyring = key_ref_to_ptr(keyring_ref);
  719. key_check(keyring);
  720. if (!(flags & KEY_ALLOC_BYPASS_RESTRICTION))
  721. restrict_link = keyring->restrict_link;
  722. key_ref = ERR_PTR(-ENOTDIR);
  723. if (keyring->type != &key_type_keyring)
  724. goto error_put_type;
  725. memset(&prep, 0, sizeof(prep));
  726. prep.data = payload;
  727. prep.datalen = plen;
  728. prep.quotalen = index_key.type->def_datalen;
  729. prep.expiry = TIME64_MAX;
  730. if (index_key.type->preparse) {
  731. ret = index_key.type->preparse(&prep);
  732. if (ret < 0) {
  733. key_ref = ERR_PTR(ret);
  734. goto error_free_prep;
  735. }
  736. if (!index_key.description)
  737. index_key.description = prep.description;
  738. key_ref = ERR_PTR(-EINVAL);
  739. if (!index_key.description)
  740. goto error_free_prep;
  741. }
  742. index_key.desc_len = strlen(index_key.description);
  743. key_set_index_key(&index_key);
  744. ret = __key_link_lock(keyring, &index_key);
  745. if (ret < 0) {
  746. key_ref = ERR_PTR(ret);
  747. goto error_free_prep;
  748. }
  749. ret = __key_link_begin(keyring, &index_key, &edit);
  750. if (ret < 0) {
  751. key_ref = ERR_PTR(ret);
  752. goto error_link_end;
  753. }
  754. if (restrict_link && restrict_link->check) {
  755. ret = restrict_link->check(keyring, index_key.type,
  756. &prep.payload, restrict_link->key);
  757. if (ret < 0) {
  758. key_ref = ERR_PTR(ret);
  759. goto error_link_end;
  760. }
  761. }
  762. /* if we're going to allocate a new key, we're going to have
  763. * to modify the keyring */
  764. ret = key_permission(keyring_ref, KEY_NEED_WRITE);
  765. if (ret < 0) {
  766. key_ref = ERR_PTR(ret);
  767. goto error_link_end;
  768. }
  769. /* if it's possible to update this type of key, search for an existing
  770. * key of the same type and description in the destination keyring and
  771. * update that instead if possible
  772. */
  773. if (index_key.type->update) {
  774. key_ref = find_key_to_update(keyring_ref, &index_key);
  775. if (key_ref)
  776. goto found_matching_key;
  777. }
  778. /* if the client doesn't provide, decide on the permissions we want */
  779. if (perm == KEY_PERM_UNDEF) {
  780. perm = KEY_POS_VIEW | KEY_POS_SEARCH | KEY_POS_LINK | KEY_POS_SETATTR;
  781. perm |= KEY_USR_VIEW;
  782. if (index_key.type->read)
  783. perm |= KEY_POS_READ;
  784. if (index_key.type == &key_type_keyring ||
  785. index_key.type->update)
  786. perm |= KEY_POS_WRITE;
  787. }
  788. /* allocate a new key */
  789. key = key_alloc(index_key.type, index_key.description,
  790. cred->fsuid, cred->fsgid, cred, perm, flags, NULL);
  791. if (IS_ERR(key)) {
  792. key_ref = ERR_CAST(key);
  793. goto error_link_end;
  794. }
  795. /* instantiate it and link it into the target keyring */
  796. ret = __key_instantiate_and_link(key, &prep, keyring, NULL, &edit);
  797. if (ret < 0) {
  798. key_put(key);
  799. key_ref = ERR_PTR(ret);
  800. goto error_link_end;
  801. }
  802. ima_post_key_create_or_update(keyring, key, payload, plen,
  803. flags, true);
  804. key_ref = make_key_ref(key, is_key_possessed(keyring_ref));
  805. error_link_end:
  806. __key_link_end(keyring, &index_key, edit);
  807. error_free_prep:
  808. if (index_key.type->preparse)
  809. index_key.type->free_preparse(&prep);
  810. error_put_type:
  811. key_type_put(index_key.type);
  812. error:
  813. return key_ref;
  814. found_matching_key:
  815. /* we found a matching key, so we're going to try to update it
  816. * - we can drop the locks first as we have the key pinned
  817. */
  818. __key_link_end(keyring, &index_key, edit);
  819. key = key_ref_to_ptr(key_ref);
  820. if (test_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags)) {
  821. ret = wait_for_key_construction(key, true);
  822. if (ret < 0) {
  823. key_ref_put(key_ref);
  824. key_ref = ERR_PTR(ret);
  825. goto error_free_prep;
  826. }
  827. }
  828. key_ref = __key_update(key_ref, &prep);
  829. if (!IS_ERR(key_ref))
  830. ima_post_key_create_or_update(keyring, key,
  831. payload, plen,
  832. flags, false);
  833. goto error_free_prep;
  834. }
  835. EXPORT_SYMBOL(key_create_or_update);
  836. /**
  837. * key_update - Update a key's contents.
  838. * @key_ref: The pointer (plus possession flag) to the key.
  839. * @payload: The data to be used to update the key.
  840. * @plen: The length of @payload.
  841. *
  842. * Attempt to update the contents of a key with the given payload data. The
  843. * caller must be granted Write permission on the key. Negative keys can be
  844. * instantiated by this method.
  845. *
  846. * Returns 0 on success, -EACCES if not permitted and -EOPNOTSUPP if the key
  847. * type does not support updating. The key type may return other errors.
  848. */
  849. int key_update(key_ref_t key_ref, const void *payload, size_t plen)
  850. {
  851. struct key_preparsed_payload prep;
  852. struct key *key = key_ref_to_ptr(key_ref);
  853. int ret;
  854. key_check(key);
  855. /* the key must be writable */
  856. ret = key_permission(key_ref, KEY_NEED_WRITE);
  857. if (ret < 0)
  858. return ret;
  859. /* attempt to update it if supported */
  860. if (!key->type->update)
  861. return -EOPNOTSUPP;
  862. memset(&prep, 0, sizeof(prep));
  863. prep.data = payload;
  864. prep.datalen = plen;
  865. prep.quotalen = key->type->def_datalen;
  866. prep.expiry = TIME64_MAX;
  867. if (key->type->preparse) {
  868. ret = key->type->preparse(&prep);
  869. if (ret < 0)
  870. goto error;
  871. }
  872. down_write(&key->sem);
  873. ret = key->type->update(key, &prep);
  874. if (ret == 0) {
  875. /* Updating a negative key positively instantiates it */
  876. mark_key_instantiated(key, 0);
  877. notify_key(key, NOTIFY_KEY_UPDATED, 0);
  878. }
  879. up_write(&key->sem);
  880. error:
  881. if (key->type->preparse)
  882. key->type->free_preparse(&prep);
  883. return ret;
  884. }
  885. EXPORT_SYMBOL(key_update);
  886. /**
  887. * key_revoke - Revoke a key.
  888. * @key: The key to be revoked.
  889. *
  890. * Mark a key as being revoked and ask the type to free up its resources. The
  891. * revocation timeout is set and the key and all its links will be
  892. * automatically garbage collected after key_gc_delay amount of time if they
  893. * are not manually dealt with first.
  894. */
  895. void key_revoke(struct key *key)
  896. {
  897. time64_t time;
  898. key_check(key);
  899. /* make sure no one's trying to change or use the key when we mark it
  900. * - we tell lockdep that we might nest because we might be revoking an
  901. * authorisation key whilst holding the sem on a key we've just
  902. * instantiated
  903. */
  904. down_write_nested(&key->sem, 1);
  905. if (!test_and_set_bit(KEY_FLAG_REVOKED, &key->flags)) {
  906. notify_key(key, NOTIFY_KEY_REVOKED, 0);
  907. if (key->type->revoke)
  908. key->type->revoke(key);
  909. /* set the death time to no more than the expiry time */
  910. time = ktime_get_real_seconds();
  911. if (key->revoked_at == 0 || key->revoked_at > time) {
  912. key->revoked_at = time;
  913. key_schedule_gc(key->revoked_at + key_gc_delay);
  914. }
  915. }
  916. up_write(&key->sem);
  917. }
  918. EXPORT_SYMBOL(key_revoke);
  919. /**
  920. * key_invalidate - Invalidate a key.
  921. * @key: The key to be invalidated.
  922. *
  923. * Mark a key as being invalidated and have it cleaned up immediately. The key
  924. * is ignored by all searches and other operations from this point.
  925. */
  926. void key_invalidate(struct key *key)
  927. {
  928. kenter("%d", key_serial(key));
  929. key_check(key);
  930. if (!test_bit(KEY_FLAG_INVALIDATED, &key->flags)) {
  931. down_write_nested(&key->sem, 1);
  932. if (!test_and_set_bit(KEY_FLAG_INVALIDATED, &key->flags)) {
  933. notify_key(key, NOTIFY_KEY_INVALIDATED, 0);
  934. key_schedule_gc_links();
  935. }
  936. up_write(&key->sem);
  937. }
  938. }
  939. EXPORT_SYMBOL(key_invalidate);
  940. /**
  941. * generic_key_instantiate - Simple instantiation of a key from preparsed data
  942. * @key: The key to be instantiated
  943. * @prep: The preparsed data to load.
  944. *
  945. * Instantiate a key from preparsed data. We assume we can just copy the data
  946. * in directly and clear the old pointers.
  947. *
  948. * This can be pointed to directly by the key type instantiate op pointer.
  949. */
  950. int generic_key_instantiate(struct key *key, struct key_preparsed_payload *prep)
  951. {
  952. int ret;
  953. pr_devel("==>%s()\n", __func__);
  954. ret = key_payload_reserve(key, prep->quotalen);
  955. if (ret == 0) {
  956. rcu_assign_keypointer(key, prep->payload.data[0]);
  957. key->payload.data[1] = prep->payload.data[1];
  958. key->payload.data[2] = prep->payload.data[2];
  959. key->payload.data[3] = prep->payload.data[3];
  960. prep->payload.data[0] = NULL;
  961. prep->payload.data[1] = NULL;
  962. prep->payload.data[2] = NULL;
  963. prep->payload.data[3] = NULL;
  964. }
  965. pr_devel("<==%s() = %d\n", __func__, ret);
  966. return ret;
  967. }
  968. EXPORT_SYMBOL(generic_key_instantiate);
  969. /**
  970. * register_key_type - Register a type of key.
  971. * @ktype: The new key type.
  972. *
  973. * Register a new key type.
  974. *
  975. * Returns 0 on success or -EEXIST if a type of this name already exists.
  976. */
  977. int register_key_type(struct key_type *ktype)
  978. {
  979. struct key_type *p;
  980. int ret;
  981. memset(&ktype->lock_class, 0, sizeof(ktype->lock_class));
  982. ret = -EEXIST;
  983. down_write(&key_types_sem);
  984. /* disallow key types with the same name */
  985. list_for_each_entry(p, &key_types_list, link) {
  986. if (strcmp(p->name, ktype->name) == 0)
  987. goto out;
  988. }
  989. /* store the type */
  990. list_add(&ktype->link, &key_types_list);
  991. pr_notice("Key type %s registered\n", ktype->name);
  992. ret = 0;
  993. out:
  994. up_write(&key_types_sem);
  995. return ret;
  996. }
  997. EXPORT_SYMBOL(register_key_type);
  998. /**
  999. * unregister_key_type - Unregister a type of key.
  1000. * @ktype: The key type.
  1001. *
  1002. * Unregister a key type and mark all the extant keys of this type as dead.
  1003. * Those keys of this type are then destroyed to get rid of their payloads and
  1004. * they and their links will be garbage collected as soon as possible.
  1005. */
  1006. void unregister_key_type(struct key_type *ktype)
  1007. {
  1008. down_write(&key_types_sem);
  1009. list_del_init(&ktype->link);
  1010. downgrade_write(&key_types_sem);
  1011. key_gc_keytype(ktype);
  1012. pr_notice("Key type %s unregistered\n", ktype->name);
  1013. up_read(&key_types_sem);
  1014. }
  1015. EXPORT_SYMBOL(unregister_key_type);
  1016. /*
  1017. * Initialise the key management state.
  1018. */
  1019. void __init key_init(void)
  1020. {
  1021. /* allocate a slab in which we can store keys */
  1022. key_jar = kmem_cache_create("key_jar", sizeof(struct key),
  1023. 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL);
  1024. /* add the special key types */
  1025. list_add_tail(&key_type_keyring.link, &key_types_list);
  1026. list_add_tail(&key_type_dead.link, &key_types_list);
  1027. list_add_tail(&key_type_user.link, &key_types_list);
  1028. list_add_tail(&key_type_logon.link, &key_types_list);
  1029. /* record the root user tracking */
  1030. rb_link_node(&root_key_user.node,
  1031. NULL,
  1032. &key_user_tree.rb_node);
  1033. rb_insert_color(&root_key_user.node,
  1034. &key_user_tree);
  1035. }