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