key.c 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293
  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_obj(struct key_user);
  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. key->flags |= 1 << KEY_FLAG_USER_ALIVE;
  259. if (!(flags & KEY_ALLOC_NOT_IN_QUOTA))
  260. key->flags |= 1 << KEY_FLAG_IN_QUOTA;
  261. if (flags & KEY_ALLOC_BUILT_IN)
  262. key->flags |= 1 << KEY_FLAG_BUILTIN;
  263. if (flags & KEY_ALLOC_UID_KEYRING)
  264. key->flags |= 1 << KEY_FLAG_UID_KEYRING;
  265. if (flags & KEY_ALLOC_SET_KEEP)
  266. key->flags |= 1 << KEY_FLAG_KEEP;
  267. #ifdef KEY_DEBUGGING
  268. key->magic = KEY_DEBUG_MAGIC;
  269. #endif
  270. /* let the security module know about the key */
  271. ret = security_key_alloc(key, cred, flags);
  272. if (ret < 0)
  273. goto security_error;
  274. /* publish the key by giving it a serial number */
  275. refcount_inc(&key->domain_tag->usage);
  276. atomic_inc(&user->nkeys);
  277. key_alloc_serial(key);
  278. error:
  279. return key;
  280. security_error:
  281. kfree(key->description);
  282. kmem_cache_free(key_jar, key);
  283. if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) {
  284. spin_lock_irqsave(&user->lock, irqflags);
  285. user->qnkeys--;
  286. user->qnbytes -= quotalen;
  287. spin_unlock_irqrestore(&user->lock, irqflags);
  288. }
  289. key_user_put(user);
  290. key = ERR_PTR(ret);
  291. goto error;
  292. no_memory_3:
  293. kmem_cache_free(key_jar, key);
  294. no_memory_2:
  295. if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) {
  296. spin_lock_irqsave(&user->lock, irqflags);
  297. user->qnkeys--;
  298. user->qnbytes -= quotalen;
  299. spin_unlock_irqrestore(&user->lock, irqflags);
  300. }
  301. key_user_put(user);
  302. no_memory_1:
  303. key = ERR_PTR(-ENOMEM);
  304. goto error;
  305. no_quota:
  306. spin_unlock_irqrestore(&user->lock, irqflags);
  307. key_user_put(user);
  308. key = ERR_PTR(-EDQUOT);
  309. goto error;
  310. }
  311. EXPORT_SYMBOL(key_alloc);
  312. /**
  313. * key_payload_reserve - Adjust data quota reservation for the key's payload
  314. * @key: The key to make the reservation for.
  315. * @datalen: The amount of data payload the caller now wants.
  316. *
  317. * Adjust the amount of the owning user's key data quota that a key reserves.
  318. * If the amount is increased, then -EDQUOT may be returned if there isn't
  319. * enough free quota available.
  320. *
  321. * If successful, 0 is returned.
  322. */
  323. int key_payload_reserve(struct key *key, size_t datalen)
  324. {
  325. int delta = (int)datalen - key->datalen;
  326. int ret = 0;
  327. key_check(key);
  328. /* contemplate the quota adjustment */
  329. if (delta != 0 && test_bit(KEY_FLAG_IN_QUOTA, &key->flags)) {
  330. unsigned maxbytes = uid_eq(key->user->uid, GLOBAL_ROOT_UID) ?
  331. key_quota_root_maxbytes : key_quota_maxbytes;
  332. unsigned long flags;
  333. spin_lock_irqsave(&key->user->lock, flags);
  334. if (delta > 0 &&
  335. (key->user->qnbytes + delta > maxbytes ||
  336. key->user->qnbytes + delta < key->user->qnbytes)) {
  337. ret = -EDQUOT;
  338. }
  339. else {
  340. key->user->qnbytes += delta;
  341. key->quotalen += delta;
  342. }
  343. spin_unlock_irqrestore(&key->user->lock, flags);
  344. }
  345. /* change the recorded data length if that didn't generate an error */
  346. if (ret == 0)
  347. key->datalen = datalen;
  348. return ret;
  349. }
  350. EXPORT_SYMBOL(key_payload_reserve);
  351. /*
  352. * Change the key state to being instantiated.
  353. */
  354. static void mark_key_instantiated(struct key *key, int reject_error)
  355. {
  356. /* Commit the payload before setting the state; barrier versus
  357. * key_read_state().
  358. */
  359. smp_store_release(&key->state,
  360. (reject_error < 0) ? reject_error : KEY_IS_POSITIVE);
  361. }
  362. /*
  363. * Instantiate a key and link it into the target keyring atomically. Must be
  364. * called with the target keyring's semaphore writelocked. The target key's
  365. * semaphore need not be locked as instantiation is serialised by
  366. * key_construction_mutex.
  367. */
  368. static int __key_instantiate_and_link(struct key *key,
  369. struct key_preparsed_payload *prep,
  370. struct key *keyring,
  371. struct key *authkey,
  372. struct assoc_array_edit **_edit)
  373. {
  374. int ret, awaken;
  375. key_check(key);
  376. key_check(keyring);
  377. awaken = 0;
  378. ret = -EBUSY;
  379. mutex_lock(&key_construction_mutex);
  380. /* can't instantiate twice */
  381. if (key->state == KEY_IS_UNINSTANTIATED) {
  382. /* instantiate the key */
  383. ret = key->type->instantiate(key, prep);
  384. if (ret == 0) {
  385. /* mark the key as being instantiated */
  386. atomic_inc(&key->user->nikeys);
  387. mark_key_instantiated(key, 0);
  388. notify_key(key, NOTIFY_KEY_INSTANTIATED, 0);
  389. if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags))
  390. awaken = 1;
  391. /* and link it into the destination keyring */
  392. if (keyring) {
  393. if (test_bit(KEY_FLAG_KEEP, &keyring->flags))
  394. set_bit(KEY_FLAG_KEEP, &key->flags);
  395. __key_link(keyring, key, _edit);
  396. }
  397. /* disable the authorisation key */
  398. if (authkey)
  399. key_invalidate(authkey);
  400. if (prep->expiry != TIME64_MAX)
  401. key_set_expiry(key, prep->expiry);
  402. }
  403. }
  404. mutex_unlock(&key_construction_mutex);
  405. /* wake up anyone waiting for a key to be constructed */
  406. if (awaken)
  407. wake_up_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT);
  408. return ret;
  409. }
  410. /**
  411. * key_instantiate_and_link - Instantiate a key and link it into the keyring.
  412. * @key: The key to instantiate.
  413. * @data: The data to use to instantiate the keyring.
  414. * @datalen: The length of @data.
  415. * @keyring: Keyring to create a link in on success (or NULL).
  416. * @authkey: The authorisation token permitting instantiation.
  417. *
  418. * Instantiate a key that's in the uninstantiated state using the provided data
  419. * and, if successful, link it in to the destination keyring if one is
  420. * supplied.
  421. *
  422. * If successful, 0 is returned, the authorisation token is revoked and anyone
  423. * waiting for the key is woken up. If the key was already instantiated,
  424. * -EBUSY will be returned.
  425. */
  426. int key_instantiate_and_link(struct key *key,
  427. const void *data,
  428. size_t datalen,
  429. struct key *keyring,
  430. struct key *authkey)
  431. {
  432. struct key_preparsed_payload prep;
  433. struct assoc_array_edit *edit = NULL;
  434. int ret;
  435. memset(&prep, 0, sizeof(prep));
  436. prep.orig_description = key->description;
  437. prep.data = data;
  438. prep.datalen = datalen;
  439. prep.quotalen = key->type->def_datalen;
  440. prep.expiry = TIME64_MAX;
  441. if (key->type->preparse) {
  442. ret = key->type->preparse(&prep);
  443. if (ret < 0)
  444. goto error;
  445. }
  446. if (keyring) {
  447. ret = __key_link_lock(keyring, &key->index_key);
  448. if (ret < 0)
  449. goto error;
  450. ret = __key_link_begin(keyring, &key->index_key, &edit);
  451. if (ret < 0)
  452. goto error_link_end;
  453. if (keyring->restrict_link && keyring->restrict_link->check) {
  454. struct key_restriction *keyres = keyring->restrict_link;
  455. ret = keyres->check(keyring, key->type, &prep.payload,
  456. keyres->key);
  457. if (ret < 0)
  458. goto error_link_end;
  459. }
  460. }
  461. ret = __key_instantiate_and_link(key, &prep, keyring, authkey, &edit);
  462. error_link_end:
  463. if (keyring)
  464. __key_link_end(keyring, &key->index_key, edit);
  465. error:
  466. if (key->type->preparse)
  467. key->type->free_preparse(&prep);
  468. return ret;
  469. }
  470. EXPORT_SYMBOL(key_instantiate_and_link);
  471. /**
  472. * key_reject_and_link - Negatively instantiate a key and link it into the keyring.
  473. * @key: The key to instantiate.
  474. * @timeout: The timeout on the negative key.
  475. * @error: The error to return when the key is hit.
  476. * @keyring: Keyring to create a link in on success (or NULL).
  477. * @authkey: The authorisation token permitting instantiation.
  478. *
  479. * Negatively instantiate a key that's in the uninstantiated state and, if
  480. * successful, set its timeout and stored error and link it in to the
  481. * destination keyring if one is supplied. The key and any links to the key
  482. * will be automatically garbage collected after the timeout expires.
  483. *
  484. * Negative keys are used to rate limit repeated request_key() calls by causing
  485. * them to return the stored error code (typically ENOKEY) until the negative
  486. * key expires.
  487. *
  488. * If successful, 0 is returned, the authorisation token is revoked and anyone
  489. * waiting for the key is woken up. If the key was already instantiated,
  490. * -EBUSY will be returned.
  491. */
  492. int key_reject_and_link(struct key *key,
  493. unsigned timeout,
  494. unsigned error,
  495. struct key *keyring,
  496. struct key *authkey)
  497. {
  498. struct assoc_array_edit *edit = NULL;
  499. int ret, awaken, link_ret = 0;
  500. key_check(key);
  501. key_check(keyring);
  502. awaken = 0;
  503. ret = -EBUSY;
  504. if (keyring) {
  505. if (keyring->restrict_link)
  506. return -EPERM;
  507. link_ret = __key_link_lock(keyring, &key->index_key);
  508. if (link_ret == 0) {
  509. link_ret = __key_link_begin(keyring, &key->index_key, &edit);
  510. if (link_ret < 0)
  511. __key_link_end(keyring, &key->index_key, edit);
  512. }
  513. }
  514. mutex_lock(&key_construction_mutex);
  515. /* can't instantiate twice */
  516. if (key->state == KEY_IS_UNINSTANTIATED) {
  517. /* mark the key as being negatively instantiated */
  518. atomic_inc(&key->user->nikeys);
  519. mark_key_instantiated(key, -error);
  520. notify_key(key, NOTIFY_KEY_INSTANTIATED, -error);
  521. key_set_expiry(key, ktime_get_real_seconds() + timeout);
  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. unsigned long flags;
  555. /* deal with the user's key tracking and quota */
  556. if (test_bit(KEY_FLAG_IN_QUOTA, &key->flags)) {
  557. spin_lock_irqsave(&key->user->lock, flags);
  558. key->user->qnkeys--;
  559. key->user->qnbytes -= key->quotalen;
  560. spin_unlock_irqrestore(&key->user->lock, flags);
  561. }
  562. /* Mark key as safe for GC after key->user done. */
  563. clear_bit_unlock(KEY_FLAG_USER_ALIVE, &key->flags);
  564. schedule_work(&key_gc_work);
  565. }
  566. }
  567. }
  568. EXPORT_SYMBOL(key_put);
  569. /*
  570. * Find a key by its serial number.
  571. */
  572. struct key *key_lookup(key_serial_t id)
  573. {
  574. struct rb_node *n;
  575. struct key *key;
  576. spin_lock(&key_serial_lock);
  577. /* search the tree for the specified key */
  578. n = key_serial_tree.rb_node;
  579. while (n) {
  580. key = rb_entry(n, struct key, serial_node);
  581. if (id < key->serial)
  582. n = n->rb_left;
  583. else if (id > key->serial)
  584. n = n->rb_right;
  585. else
  586. goto found;
  587. }
  588. not_found:
  589. key = ERR_PTR(-ENOKEY);
  590. goto error;
  591. found:
  592. /* A key is allowed to be looked up only if someone still owns a
  593. * reference to it - otherwise it's awaiting the gc.
  594. */
  595. if (!refcount_inc_not_zero(&key->usage))
  596. goto not_found;
  597. error:
  598. spin_unlock(&key_serial_lock);
  599. return key;
  600. }
  601. EXPORT_SYMBOL(key_lookup);
  602. /*
  603. * Find and lock the specified key type against removal.
  604. *
  605. * We return with the sem read-locked if successful. If the type wasn't
  606. * available -ENOKEY is returned instead.
  607. */
  608. struct key_type *key_type_lookup(const char *type)
  609. {
  610. struct key_type *ktype;
  611. down_read(&key_types_sem);
  612. /* look up the key type to see if it's one of the registered kernel
  613. * types */
  614. list_for_each_entry(ktype, &key_types_list, link) {
  615. if (strcmp(ktype->name, type) == 0)
  616. goto found_kernel_type;
  617. }
  618. up_read(&key_types_sem);
  619. ktype = ERR_PTR(-ENOKEY);
  620. found_kernel_type:
  621. return ktype;
  622. }
  623. void key_set_timeout(struct key *key, unsigned timeout)
  624. {
  625. time64_t expiry = TIME64_MAX;
  626. /* make the changes with the locks held to prevent races */
  627. down_write(&key->sem);
  628. if (timeout > 0)
  629. expiry = ktime_get_real_seconds() + timeout;
  630. key_set_expiry(key, expiry);
  631. up_write(&key->sem);
  632. }
  633. EXPORT_SYMBOL_GPL(key_set_timeout);
  634. /*
  635. * Unlock a key type locked by key_type_lookup().
  636. */
  637. void key_type_put(struct key_type *ktype)
  638. {
  639. up_read(&key_types_sem);
  640. }
  641. /*
  642. * Attempt to update an existing key.
  643. *
  644. * The key is given to us with an incremented refcount that we need to discard
  645. * if we get an error.
  646. */
  647. static inline key_ref_t __key_update(key_ref_t key_ref,
  648. struct key_preparsed_payload *prep)
  649. {
  650. struct key *key = key_ref_to_ptr(key_ref);
  651. int ret;
  652. /* need write permission on the key to update it */
  653. ret = key_permission(key_ref, KEY_NEED_WRITE);
  654. if (ret < 0)
  655. goto error;
  656. ret = -EEXIST;
  657. if (!key->type->update)
  658. goto error;
  659. down_write(&key->sem);
  660. ret = key->type->update(key, prep);
  661. if (ret == 0) {
  662. /* Updating a negative key positively instantiates it */
  663. mark_key_instantiated(key, 0);
  664. notify_key(key, NOTIFY_KEY_UPDATED, 0);
  665. }
  666. up_write(&key->sem);
  667. if (ret < 0)
  668. goto error;
  669. out:
  670. return key_ref;
  671. error:
  672. key_put(key);
  673. key_ref = ERR_PTR(ret);
  674. goto out;
  675. }
  676. /*
  677. * Create or potentially update a key. The combined logic behind
  678. * key_create_or_update() and key_create()
  679. */
  680. static key_ref_t __key_create_or_update(key_ref_t keyring_ref,
  681. const char *type,
  682. const char *description,
  683. const void *payload,
  684. size_t plen,
  685. key_perm_t perm,
  686. unsigned long flags,
  687. bool allow_update)
  688. {
  689. struct keyring_index_key index_key = {
  690. .description = description,
  691. };
  692. struct key_preparsed_payload prep;
  693. struct assoc_array_edit *edit = NULL;
  694. const struct cred *cred = current_cred();
  695. struct key *keyring, *key = NULL;
  696. key_ref_t key_ref;
  697. int ret;
  698. struct key_restriction *restrict_link = NULL;
  699. /* look up the key type to see if it's one of the registered kernel
  700. * types */
  701. index_key.type = key_type_lookup(type);
  702. if (IS_ERR(index_key.type)) {
  703. key_ref = ERR_PTR(-ENODEV);
  704. goto error;
  705. }
  706. key_ref = ERR_PTR(-EINVAL);
  707. if (!index_key.type->instantiate ||
  708. (!index_key.description && !index_key.type->preparse))
  709. goto error_put_type;
  710. keyring = key_ref_to_ptr(keyring_ref);
  711. key_check(keyring);
  712. if (!(flags & KEY_ALLOC_BYPASS_RESTRICTION))
  713. restrict_link = keyring->restrict_link;
  714. key_ref = ERR_PTR(-ENOTDIR);
  715. if (keyring->type != &key_type_keyring)
  716. goto error_put_type;
  717. memset(&prep, 0, sizeof(prep));
  718. prep.orig_description = description;
  719. prep.data = payload;
  720. prep.datalen = plen;
  721. prep.quotalen = index_key.type->def_datalen;
  722. prep.expiry = TIME64_MAX;
  723. if (index_key.type->preparse) {
  724. ret = index_key.type->preparse(&prep);
  725. if (ret < 0) {
  726. key_ref = ERR_PTR(ret);
  727. goto error_free_prep;
  728. }
  729. if (!index_key.description)
  730. index_key.description = prep.description;
  731. key_ref = ERR_PTR(-EINVAL);
  732. if (!index_key.description)
  733. goto error_free_prep;
  734. }
  735. index_key.desc_len = strlen(index_key.description);
  736. key_set_index_key(&index_key);
  737. ret = __key_link_lock(keyring, &index_key);
  738. if (ret < 0) {
  739. key_ref = ERR_PTR(ret);
  740. goto error_free_prep;
  741. }
  742. ret = __key_link_begin(keyring, &index_key, &edit);
  743. if (ret < 0) {
  744. key_ref = ERR_PTR(ret);
  745. goto error_link_end;
  746. }
  747. if (restrict_link && restrict_link->check) {
  748. ret = restrict_link->check(keyring, index_key.type,
  749. &prep.payload, restrict_link->key);
  750. if (ret < 0) {
  751. key_ref = ERR_PTR(ret);
  752. goto error_link_end;
  753. }
  754. }
  755. /* if we're going to allocate a new key, we're going to have
  756. * to modify the keyring */
  757. ret = key_permission(keyring_ref, KEY_NEED_WRITE);
  758. if (ret < 0) {
  759. key_ref = ERR_PTR(ret);
  760. goto error_link_end;
  761. }
  762. /* if it's requested and possible to update this type of key, search
  763. * for an existing key of the same type and description in the
  764. * destination keyring and update that instead if possible
  765. */
  766. if (allow_update) {
  767. if (index_key.type->update) {
  768. key_ref = find_key_to_update(keyring_ref, &index_key);
  769. if (key_ref)
  770. goto found_matching_key;
  771. }
  772. } else {
  773. key_ref = find_key_to_update(keyring_ref, &index_key);
  774. if (key_ref) {
  775. key_ref_put(key_ref);
  776. key_ref = ERR_PTR(-EEXIST);
  777. goto error_link_end;
  778. }
  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. security_key_post_create_or_update(keyring, key, payload, plen, flags,
  805. 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. security_key_post_create_or_update(keyring, key, payload, plen,
  833. flags, false);
  834. goto error_free_prep;
  835. }
  836. /**
  837. * key_create_or_update - Update or create and instantiate a key.
  838. * @keyring_ref: A pointer to the destination keyring with possession flag.
  839. * @type: The type of key.
  840. * @description: The searchable description for the key.
  841. * @payload: The data to use to instantiate or update the key.
  842. * @plen: The length of @payload.
  843. * @perm: The permissions mask for a new key.
  844. * @flags: The quota flags for a new key.
  845. *
  846. * Search the destination keyring for a key of the same description and if one
  847. * is found, update it, otherwise create and instantiate a new one and create a
  848. * link to it from that keyring.
  849. *
  850. * If perm is KEY_PERM_UNDEF then an appropriate key permissions mask will be
  851. * concocted.
  852. *
  853. * Returns a pointer to the new key if successful, -ENODEV if the key type
  854. * wasn't available, -ENOTDIR if the keyring wasn't a keyring, -EACCES if the
  855. * caller isn't permitted to modify the keyring or the LSM did not permit
  856. * creation of the key.
  857. *
  858. * On success, the possession flag from the keyring ref will be tacked on to
  859. * the key ref before it is returned.
  860. */
  861. key_ref_t key_create_or_update(key_ref_t keyring_ref,
  862. const char *type,
  863. const char *description,
  864. const void *payload,
  865. size_t plen,
  866. key_perm_t perm,
  867. unsigned long flags)
  868. {
  869. return __key_create_or_update(keyring_ref, type, description, payload,
  870. plen, perm, flags, true);
  871. }
  872. EXPORT_SYMBOL(key_create_or_update);
  873. /**
  874. * key_create - Create and instantiate a key.
  875. * @keyring_ref: A pointer to the destination keyring with possession flag.
  876. * @type: The type of key.
  877. * @description: The searchable description for the key.
  878. * @payload: The data to use to instantiate or update the key.
  879. * @plen: The length of @payload.
  880. * @perm: The permissions mask for a new key.
  881. * @flags: The quota flags for a new key.
  882. *
  883. * Create and instantiate a new key and link to it from the destination keyring.
  884. *
  885. * If perm is KEY_PERM_UNDEF then an appropriate key permissions mask will be
  886. * concocted.
  887. *
  888. * Returns a pointer to the new key if successful, -EEXIST if a key with the
  889. * same description already exists, -ENODEV if the key type wasn't available,
  890. * -ENOTDIR if the keyring wasn't a keyring, -EACCES if the caller isn't
  891. * permitted to modify the keyring or the LSM did not permit creation of the
  892. * key.
  893. *
  894. * On success, the possession flag from the keyring ref will be tacked on to
  895. * the key ref before it is returned.
  896. */
  897. key_ref_t key_create(key_ref_t keyring_ref,
  898. const char *type,
  899. const char *description,
  900. const void *payload,
  901. size_t plen,
  902. key_perm_t perm,
  903. unsigned long flags)
  904. {
  905. return __key_create_or_update(keyring_ref, type, description, payload,
  906. plen, perm, flags, false);
  907. }
  908. EXPORT_SYMBOL(key_create);
  909. /**
  910. * key_update - Update a key's contents.
  911. * @key_ref: The pointer (plus possession flag) to the key.
  912. * @payload: The data to be used to update the key.
  913. * @plen: The length of @payload.
  914. *
  915. * Attempt to update the contents of a key with the given payload data. The
  916. * caller must be granted Write permission on the key. Negative keys can be
  917. * instantiated by this method.
  918. *
  919. * Returns 0 on success, -EACCES if not permitted and -EOPNOTSUPP if the key
  920. * type does not support updating. The key type may return other errors.
  921. */
  922. int key_update(key_ref_t key_ref, const void *payload, size_t plen)
  923. {
  924. struct key_preparsed_payload prep;
  925. struct key *key = key_ref_to_ptr(key_ref);
  926. int ret;
  927. key_check(key);
  928. /* the key must be writable */
  929. ret = key_permission(key_ref, KEY_NEED_WRITE);
  930. if (ret < 0)
  931. return ret;
  932. /* attempt to update it if supported */
  933. if (!key->type->update)
  934. return -EOPNOTSUPP;
  935. memset(&prep, 0, sizeof(prep));
  936. prep.data = payload;
  937. prep.datalen = plen;
  938. prep.quotalen = key->type->def_datalen;
  939. prep.expiry = TIME64_MAX;
  940. if (key->type->preparse) {
  941. ret = key->type->preparse(&prep);
  942. if (ret < 0)
  943. goto error;
  944. }
  945. down_write(&key->sem);
  946. ret = key->type->update(key, &prep);
  947. if (ret == 0) {
  948. /* Updating a negative key positively instantiates it */
  949. mark_key_instantiated(key, 0);
  950. notify_key(key, NOTIFY_KEY_UPDATED, 0);
  951. }
  952. up_write(&key->sem);
  953. error:
  954. if (key->type->preparse)
  955. key->type->free_preparse(&prep);
  956. return ret;
  957. }
  958. EXPORT_SYMBOL(key_update);
  959. /**
  960. * key_revoke - Revoke a key.
  961. * @key: The key to be revoked.
  962. *
  963. * Mark a key as being revoked and ask the type to free up its resources. The
  964. * revocation timeout is set and the key and all its links will be
  965. * automatically garbage collected after key_gc_delay amount of time if they
  966. * are not manually dealt with first.
  967. */
  968. void key_revoke(struct key *key)
  969. {
  970. time64_t time;
  971. key_check(key);
  972. /* make sure no one's trying to change or use the key when we mark it
  973. * - we tell lockdep that we might nest because we might be revoking an
  974. * authorisation key whilst holding the sem on a key we've just
  975. * instantiated
  976. */
  977. down_write_nested(&key->sem, 1);
  978. if (!test_and_set_bit(KEY_FLAG_REVOKED, &key->flags)) {
  979. notify_key(key, NOTIFY_KEY_REVOKED, 0);
  980. if (key->type->revoke)
  981. key->type->revoke(key);
  982. /* set the death time to no more than the expiry time */
  983. time = ktime_get_real_seconds();
  984. if (key->revoked_at == 0 || key->revoked_at > time) {
  985. key->revoked_at = time;
  986. key_schedule_gc(key->revoked_at + key_gc_delay);
  987. }
  988. }
  989. up_write(&key->sem);
  990. }
  991. EXPORT_SYMBOL(key_revoke);
  992. /**
  993. * key_invalidate - Invalidate a key.
  994. * @key: The key to be invalidated.
  995. *
  996. * Mark a key as being invalidated and have it cleaned up immediately. The key
  997. * is ignored by all searches and other operations from this point.
  998. */
  999. void key_invalidate(struct key *key)
  1000. {
  1001. kenter("%d", key_serial(key));
  1002. key_check(key);
  1003. if (!test_bit(KEY_FLAG_INVALIDATED, &key->flags)) {
  1004. down_write_nested(&key->sem, 1);
  1005. if (!test_and_set_bit(KEY_FLAG_INVALIDATED, &key->flags)) {
  1006. notify_key(key, NOTIFY_KEY_INVALIDATED, 0);
  1007. key_schedule_gc_links();
  1008. }
  1009. up_write(&key->sem);
  1010. }
  1011. }
  1012. EXPORT_SYMBOL(key_invalidate);
  1013. /**
  1014. * generic_key_instantiate - Simple instantiation of a key from preparsed data
  1015. * @key: The key to be instantiated
  1016. * @prep: The preparsed data to load.
  1017. *
  1018. * Instantiate a key from preparsed data. We assume we can just copy the data
  1019. * in directly and clear the old pointers.
  1020. *
  1021. * This can be pointed to directly by the key type instantiate op pointer.
  1022. */
  1023. int generic_key_instantiate(struct key *key, struct key_preparsed_payload *prep)
  1024. {
  1025. int ret;
  1026. pr_devel("==>%s()\n", __func__);
  1027. ret = key_payload_reserve(key, prep->quotalen);
  1028. if (ret == 0) {
  1029. rcu_assign_keypointer(key, prep->payload.data[0]);
  1030. key->payload.data[1] = prep->payload.data[1];
  1031. key->payload.data[2] = prep->payload.data[2];
  1032. key->payload.data[3] = prep->payload.data[3];
  1033. prep->payload.data[0] = NULL;
  1034. prep->payload.data[1] = NULL;
  1035. prep->payload.data[2] = NULL;
  1036. prep->payload.data[3] = NULL;
  1037. }
  1038. pr_devel("<==%s() = %d\n", __func__, ret);
  1039. return ret;
  1040. }
  1041. EXPORT_SYMBOL(generic_key_instantiate);
  1042. /**
  1043. * register_key_type - Register a type of key.
  1044. * @ktype: The new key type.
  1045. *
  1046. * Register a new key type.
  1047. *
  1048. * Returns 0 on success or -EEXIST if a type of this name already exists.
  1049. */
  1050. int register_key_type(struct key_type *ktype)
  1051. {
  1052. struct key_type *p;
  1053. int ret;
  1054. memset(&ktype->lock_class, 0, sizeof(ktype->lock_class));
  1055. ret = -EEXIST;
  1056. down_write(&key_types_sem);
  1057. /* disallow key types with the same name */
  1058. list_for_each_entry(p, &key_types_list, link) {
  1059. if (strcmp(p->name, ktype->name) == 0)
  1060. goto out;
  1061. }
  1062. /* store the type */
  1063. list_add(&ktype->link, &key_types_list);
  1064. pr_notice("Key type %s registered\n", ktype->name);
  1065. ret = 0;
  1066. out:
  1067. up_write(&key_types_sem);
  1068. return ret;
  1069. }
  1070. EXPORT_SYMBOL(register_key_type);
  1071. /**
  1072. * unregister_key_type - Unregister a type of key.
  1073. * @ktype: The key type.
  1074. *
  1075. * Unregister a key type and mark all the extant keys of this type as dead.
  1076. * Those keys of this type are then destroyed to get rid of their payloads and
  1077. * they and their links will be garbage collected as soon as possible.
  1078. */
  1079. void unregister_key_type(struct key_type *ktype)
  1080. {
  1081. down_write(&key_types_sem);
  1082. list_del_init(&ktype->link);
  1083. downgrade_write(&key_types_sem);
  1084. key_gc_keytype(ktype);
  1085. pr_notice("Key type %s unregistered\n", ktype->name);
  1086. up_read(&key_types_sem);
  1087. }
  1088. EXPORT_SYMBOL(unregister_key_type);
  1089. /*
  1090. * Initialise the key management state.
  1091. */
  1092. void __init key_init(void)
  1093. {
  1094. /* allocate a slab in which we can store keys */
  1095. key_jar = kmem_cache_create("key_jar", sizeof(struct key),
  1096. 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL);
  1097. /* add the special key types */
  1098. list_add_tail(&key_type_keyring.link, &key_types_list);
  1099. list_add_tail(&key_type_dead.link, &key_types_list);
  1100. list_add_tail(&key_type_user.link, &key_types_list);
  1101. list_add_tail(&key_type_logon.link, &key_types_list);
  1102. /* record the root user tracking */
  1103. rb_link_node(&root_key_user.node,
  1104. NULL,
  1105. &key_user_tree.rb_node);
  1106. rb_insert_color(&root_key_user.node,
  1107. &key_user_tree);
  1108. }