key.c 34 KB

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