xref: /linux/security/keys/key.c (revision 899af9ffd2671351e5402d572934dd59b5e91ae5)
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 	down_write_nested(&key->sem, 2);
445 
446 	/* can't instantiate twice */
447 	if (key->state == KEY_IS_UNINSTANTIATED) {
448 		/* instantiate the key */
449 		ret = key->type->instantiate(key, prep);
450 
451 		if (ret == 0) {
452 			/* mark the key as being instantiated */
453 			atomic_inc(&key->user->nikeys);
454 			mark_key_instantiated(key, 0);
455 			notify_key(key, NOTIFY_KEY_INSTANTIATED, 0);
456 
457 			if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags))
458 				awaken = 1;
459 
460 			/* and link it into the destination keyring */
461 			if (keyring) {
462 				if (test_bit(KEY_FLAG_KEEP, &keyring->flags))
463 					set_bit(KEY_FLAG_KEEP, &key->flags);
464 
465 				__key_link(keyring, key, _edit);
466 			}
467 
468 			/* disable the authorisation key */
469 			if (authkey)
470 				key_invalidate(authkey);
471 
472 			if (prep->expiry != TIME64_MAX)
473 				key_set_expiry(key, prep->expiry);
474 		}
475 	}
476 
477 	up_write(&key->sem);
478 	mutex_unlock(&key_construction_mutex);
479 
480 	/* wake up anyone waiting for a key to be constructed */
481 	if (awaken)
482 		wake_up_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT);
483 
484 	return ret;
485 }
486 
487 /**
488  * key_instantiate_and_link - Instantiate a key and link it into the keyring.
489  * @key: The key to instantiate.
490  * @data: The data to use to instantiate the keyring.
491  * @datalen: The length of @data.
492  * @keyring: Keyring to create a link in on success (or NULL).
493  * @authkey: The authorisation token permitting instantiation.
494  *
495  * Instantiate a key that's in the uninstantiated state using the provided data
496  * and, if successful, link it in to the destination keyring if one is
497  * supplied.
498  *
499  * If successful, 0 is returned, the authorisation token is revoked and anyone
500  * waiting for the key is woken up.  If the key was already instantiated,
501  * -EBUSY will be returned.
502  */
503 int key_instantiate_and_link(struct key *key,
504 			     const void *data,
505 			     size_t datalen,
506 			     struct key *keyring,
507 			     struct key *authkey)
508 {
509 	struct key_preparsed_payload prep;
510 	struct assoc_array_edit *edit = NULL;
511 	int ret;
512 
513 	memset(&prep, 0, sizeof(prep));
514 	prep.orig_description = key->description;
515 	prep.data = data;
516 	prep.datalen = datalen;
517 	prep.quotalen = key->type->def_datalen;
518 	prep.expiry = TIME64_MAX;
519 	if (key->type->preparse) {
520 		ret = key->type->preparse(&prep);
521 		if (ret < 0)
522 			goto error;
523 	}
524 
525 	if (keyring) {
526 		ret = __key_link_lock(keyring, &key->index_key);
527 		if (ret < 0)
528 			goto error;
529 
530 		ret = __key_link_begin(keyring, &key->index_key, &edit);
531 		if (ret < 0)
532 			goto error_link_end;
533 
534 		if (keyring->restrict_link && keyring->restrict_link->check) {
535 			struct key_restriction *keyres = keyring->restrict_link;
536 
537 			ret = keyres->check(keyring, key->type, &prep.payload,
538 					    keyres->key);
539 			if (ret < 0)
540 				goto error_link_end;
541 		}
542 	}
543 
544 	ret = __key_instantiate_and_link(key, &prep, keyring, authkey, &edit);
545 
546 error_link_end:
547 	if (keyring)
548 		__key_link_end(keyring, &key->index_key, edit);
549 
550 error:
551 	if (key->type->preparse)
552 		key->type->free_preparse(&prep);
553 	return ret;
554 }
555 
556 EXPORT_SYMBOL(key_instantiate_and_link);
557 
558 /**
559  * key_reject_and_link - Negatively instantiate a key and link it into the keyring.
560  * @key: The key to instantiate.
561  * @timeout: The timeout on the negative key.
562  * @error: The error to return when the key is hit.
563  * @keyring: Keyring to create a link in on success (or NULL).
564  * @authkey: The authorisation token permitting instantiation.
565  *
566  * Negatively instantiate a key that's in the uninstantiated state and, if
567  * successful, set its timeout and stored error and link it in to the
568  * destination keyring if one is supplied.  The key and any links to the key
569  * will be automatically garbage collected after the timeout expires.
570  *
571  * Negative keys are used to rate limit repeated request_key() calls by causing
572  * them to return the stored error code (typically ENOKEY) until the negative
573  * key expires.
574  *
575  * If successful, 0 is returned, the authorisation token is revoked and anyone
576  * waiting for the key is woken up.  If the key was already instantiated,
577  * -EBUSY will be returned.
578  */
579 int key_reject_and_link(struct key *key,
580 			unsigned timeout,
581 			unsigned error,
582 			struct key *keyring,
583 			struct key *authkey)
584 {
585 	struct assoc_array_edit *edit = NULL;
586 	int ret, awaken, link_ret = 0;
587 
588 	key_check(key);
589 	key_check(keyring);
590 
591 	awaken = 0;
592 	ret = -EBUSY;
593 
594 	if (keyring) {
595 		link_ret = __key_link_lock(keyring, &key->index_key);
596 		if (link_ret == 0) {
597 			/*
598 			 * Check the restriction under the keyring semaphore.
599 			 * keyring_restrict() installs it while holding the
600 			 * semaphore, so testing it beforehand races with a
601 			 * concurrent restriction install.
602 			 */
603 			if (keyring->restrict_link) {
604 				__key_link_end(keyring, &key->index_key, edit);
605 				return -EPERM;
606 			}
607 			link_ret = __key_link_begin(keyring, &key->index_key, &edit);
608 			if (link_ret < 0)
609 				__key_link_end(keyring, &key->index_key, edit);
610 		}
611 	}
612 
613 	mutex_lock(&key_construction_mutex);
614 	down_write_nested(&key->sem, 2);
615 
616 	/* can't instantiate twice */
617 	if (key->state == KEY_IS_UNINSTANTIATED) {
618 		/* mark the key as being negatively instantiated */
619 		atomic_inc(&key->user->nikeys);
620 		mark_key_instantiated(key, -error);
621 		notify_key(key, NOTIFY_KEY_INSTANTIATED, -error);
622 		key_set_expiry(key, ktime_get_real_seconds() + timeout);
623 
624 		if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags))
625 			awaken = 1;
626 
627 		ret = 0;
628 
629 		/* and link it into the destination keyring */
630 		if (keyring && link_ret == 0)
631 			__key_link(keyring, key, &edit);
632 
633 		/* disable the authorisation key */
634 		if (authkey)
635 			key_invalidate(authkey);
636 	}
637 
638 	up_write(&key->sem);
639 	mutex_unlock(&key_construction_mutex);
640 
641 	if (keyring && link_ret == 0)
642 		__key_link_end(keyring, &key->index_key, edit);
643 
644 	/* wake up anyone waiting for a key to be constructed */
645 	if (awaken)
646 		wake_up_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT);
647 
648 	return ret == 0 ? link_ret : ret;
649 }
650 EXPORT_SYMBOL(key_reject_and_link);
651 
652 /**
653  * key_put - Discard a reference to a key.
654  * @key: The key to discard a reference from.
655  *
656  * Discard a reference to a key, and when all the references are gone, we
657  * schedule the cleanup task to come and pull it out of the tree in process
658  * context at some later time.
659  */
660 void key_put(struct key *key)
661 {
662 	if (key) {
663 		key_check(key);
664 
665 		if (refcount_dec_and_test(&key->usage)) {
666 			unsigned long flags;
667 
668 			/* deal with the user's key tracking and quota */
669 			if (test_bit(KEY_FLAG_IN_QUOTA, &key->flags)) {
670 				spin_lock_irqsave(&key->user->lock, flags);
671 				key->user->qnkeys--;
672 				key->user->qnbytes -= key->quotalen;
673 				spin_unlock_irqrestore(&key->user->lock, flags);
674 			}
675 			/* Mark key as safe for GC after key->user done. */
676 			clear_bit_unlock(KEY_FLAG_USER_ALIVE, &key->flags);
677 			schedule_work(&key_gc_work);
678 		}
679 	}
680 }
681 EXPORT_SYMBOL(key_put);
682 
683 /*
684  * Find a key by its serial number.
685  */
686 struct key *key_lookup(key_serial_t id)
687 {
688 	struct rb_node *n;
689 	struct key *key;
690 
691 	spin_lock(&key_serial_lock);
692 
693 	/* search the tree for the specified key */
694 	n = key_serial_tree.rb_node;
695 	while (n) {
696 		key = rb_entry(n, struct key, serial_node);
697 
698 		if (id < key->serial)
699 			n = n->rb_left;
700 		else if (id > key->serial)
701 			n = n->rb_right;
702 		else
703 			goto found;
704 	}
705 
706 not_found:
707 	key = ERR_PTR(-ENOKEY);
708 	goto error;
709 
710 found:
711 	/* A key is allowed to be looked up only if someone still owns a
712 	 * reference to it - otherwise it's awaiting the gc.
713 	 */
714 	if (!refcount_inc_not_zero(&key->usage))
715 		goto not_found;
716 
717 error:
718 	spin_unlock(&key_serial_lock);
719 	return key;
720 }
721 EXPORT_SYMBOL(key_lookup);
722 
723 /*
724  * Find and lock the specified key type against removal.
725  *
726  * We return with the sem read-locked if successful.  If the type wasn't
727  * available -ENOKEY is returned instead.
728  */
729 struct key_type *key_type_lookup(const char *type)
730 {
731 	struct key_type *ktype;
732 
733 	down_read(&key_types_sem);
734 
735 	/* look up the key type to see if it's one of the registered kernel
736 	 * types */
737 	list_for_each_entry(ktype, &key_types_list, link) {
738 		if (strcmp(ktype->name, type) == 0)
739 			goto found_kernel_type;
740 	}
741 
742 	up_read(&key_types_sem);
743 	ktype = ERR_PTR(-ENOKEY);
744 
745 found_kernel_type:
746 	return ktype;
747 }
748 
749 void key_set_timeout(struct key *key, unsigned timeout)
750 {
751 	time64_t expiry = TIME64_MAX;
752 
753 	/* make the changes with the locks held to prevent races */
754 	down_write(&key->sem);
755 
756 	if (timeout > 0)
757 		expiry = ktime_get_real_seconds() + timeout;
758 	key_set_expiry(key, expiry);
759 
760 	up_write(&key->sem);
761 }
762 EXPORT_SYMBOL_GPL(key_set_timeout);
763 
764 /*
765  * Unlock a key type locked by key_type_lookup().
766  */
767 void key_type_put(struct key_type *ktype)
768 {
769 	up_read(&key_types_sem);
770 }
771 
772 /*
773  * Attempt to update an existing key.
774  *
775  * The key is given to us with an incremented refcount that we need to discard
776  * if we get an error.
777  */
778 static inline key_ref_t __key_update(key_ref_t key_ref,
779 				     struct key_preparsed_payload *prep)
780 {
781 	struct key *key = key_ref_to_ptr(key_ref);
782 	int ret;
783 
784 	/* need write permission on the key to update it */
785 	ret = key_permission(key_ref, KEY_NEED_WRITE);
786 	if (ret < 0)
787 		goto error;
788 
789 	ret = -EEXIST;
790 	if (!key->type->update)
791 		goto error;
792 
793 	down_write(&key->sem);
794 
795 	ret = key->type->update(key, prep);
796 	if (ret == 0) {
797 		/* Updating a negative key positively instantiates it */
798 		mark_key_instantiated(key, 0);
799 		notify_key(key, NOTIFY_KEY_UPDATED, 0);
800 	}
801 
802 	up_write(&key->sem);
803 
804 	if (ret < 0)
805 		goto error;
806 out:
807 	return key_ref;
808 
809 error:
810 	key_put(key);
811 	key_ref = ERR_PTR(ret);
812 	goto out;
813 }
814 
815 /*
816  * Create or potentially update a key. The combined logic behind
817  * key_create_or_update() and key_create()
818  */
819 static key_ref_t __key_create_or_update(key_ref_t keyring_ref,
820 					const char *type,
821 					const char *description,
822 					const void *payload,
823 					size_t plen,
824 					key_perm_t perm,
825 					unsigned long flags,
826 					bool allow_update)
827 {
828 	struct keyring_index_key index_key = {
829 		.description	= description,
830 	};
831 	struct key_preparsed_payload prep;
832 	struct assoc_array_edit *edit = NULL;
833 	const struct cred *cred = current_cred();
834 	struct key *keyring, *key = NULL;
835 	key_ref_t key_ref;
836 	int ret;
837 	struct key_restriction *restrict_link = NULL;
838 	size_t desclen;
839 
840 	/* look up the key type to see if it's one of the registered kernel
841 	 * types */
842 	index_key.type = key_type_lookup(type);
843 	if (IS_ERR(index_key.type)) {
844 		key_ref = ERR_PTR(-ENODEV);
845 		goto error;
846 	}
847 
848 	key_ref = ERR_PTR(-EINVAL);
849 	if (!index_key.type->instantiate ||
850 	    (!index_key.description && !index_key.type->preparse))
851 		goto error_put_type;
852 
853 	keyring = key_ref_to_ptr(keyring_ref);
854 
855 	key_check(keyring);
856 
857 	key_ref = ERR_PTR(-ENOTDIR);
858 	if (keyring->type != &key_type_keyring)
859 		goto error_put_type;
860 
861 	memset(&prep, 0, sizeof(prep));
862 	prep.orig_description = description;
863 	prep.data = payload;
864 	prep.datalen = plen;
865 	prep.quotalen = index_key.type->def_datalen;
866 	prep.expiry = TIME64_MAX;
867 	if (index_key.type->preparse) {
868 		ret = index_key.type->preparse(&prep);
869 		if (ret < 0) {
870 			key_ref = ERR_PTR(ret);
871 			goto error_free_prep;
872 		}
873 		if (!index_key.description)
874 			index_key.description = prep.description;
875 		key_ref = ERR_PTR(-EINVAL);
876 		if (!index_key.description)
877 			goto error_free_prep;
878 	}
879 	desclen = strlen(index_key.description);
880 	if (desclen >= KEY_MAX_DESC_SIZE) {
881 		key_ref = ERR_PTR(-EINVAL);
882 		goto error_free_prep;
883 	}
884 	index_key.desc_len = desclen;
885 	key_set_index_key(&index_key);
886 
887 	ret = __key_link_lock(keyring, &index_key);
888 	if (ret < 0) {
889 		key_ref = ERR_PTR(ret);
890 		goto error_free_prep;
891 	}
892 
893 	ret = __key_link_begin(keyring, &index_key, &edit);
894 	if (ret < 0) {
895 		key_ref = ERR_PTR(ret);
896 		goto error_link_end;
897 	}
898 
899 	if (!(flags & KEY_ALLOC_BYPASS_RESTRICTION))
900 		restrict_link = keyring->restrict_link;
901 
902 	if (restrict_link && restrict_link->check) {
903 		ret = restrict_link->check(keyring, index_key.type,
904 					   &prep.payload, restrict_link->key);
905 		if (ret < 0) {
906 			key_ref = ERR_PTR(ret);
907 			goto error_link_end;
908 		}
909 	}
910 
911 	/* if we're going to allocate a new key, we're going to have
912 	 * to modify the keyring */
913 	ret = key_permission(keyring_ref, KEY_NEED_WRITE);
914 	if (ret < 0) {
915 		key_ref = ERR_PTR(ret);
916 		goto error_link_end;
917 	}
918 
919 	/* if it's requested and possible to update this type of key, search
920 	 * for an existing key of the same type and description in the
921 	 * destination keyring and update that instead if possible
922 	 */
923 	if (allow_update) {
924 		if (index_key.type->update) {
925 			key_ref = find_key_to_update(keyring_ref, &index_key);
926 			if (key_ref)
927 				goto found_matching_key;
928 		}
929 	} else {
930 		key_ref = find_key_to_update(keyring_ref, &index_key);
931 		if (key_ref) {
932 			key_ref_put(key_ref);
933 			key_ref = ERR_PTR(-EEXIST);
934 			goto error_link_end;
935 		}
936 	}
937 
938 	/* if the client doesn't provide, decide on the permissions we want */
939 	if (perm == KEY_PERM_UNDEF) {
940 		perm = KEY_POS_VIEW | KEY_POS_SEARCH | KEY_POS_LINK | KEY_POS_SETATTR;
941 		perm |= KEY_USR_VIEW;
942 
943 		if (index_key.type->read)
944 			perm |= KEY_POS_READ;
945 
946 		if (index_key.type == &key_type_keyring ||
947 		    index_key.type->update)
948 			perm |= KEY_POS_WRITE;
949 	}
950 
951 	/* allocate a new key */
952 	key = key_alloc(index_key.type, index_key.description,
953 			cred->fsuid, cred->fsgid, cred, perm, flags, NULL);
954 	if (IS_ERR(key)) {
955 		key_ref = ERR_CAST(key);
956 		goto error_link_end;
957 	}
958 
959 	/* instantiate it and link it into the target keyring */
960 	ret = __key_instantiate_and_link(key, &prep, keyring, NULL, &edit);
961 	if (ret < 0) {
962 		key_put(key);
963 		key_ref = ERR_PTR(ret);
964 		goto error_link_end;
965 	}
966 
967 	security_key_post_create_or_update(keyring, key, payload, plen, flags,
968 					   true);
969 
970 	key_ref = make_key_ref(key, is_key_possessed(keyring_ref));
971 
972 error_link_end:
973 	__key_link_end(keyring, &index_key, edit);
974 error_free_prep:
975 	if (index_key.type->preparse)
976 		index_key.type->free_preparse(&prep);
977 error_put_type:
978 	key_type_put(index_key.type);
979 error:
980 	return key_ref;
981 
982  found_matching_key:
983 	/* we found a matching key, so we're going to try to update it
984 	 * - we can drop the locks first as we have the key pinned
985 	 */
986 	__key_link_end(keyring, &index_key, edit);
987 
988 	key = key_ref_to_ptr(key_ref);
989 	if (test_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags)) {
990 		ret = wait_for_key_construction(key, true);
991 		if (ret < 0) {
992 			key_ref_put(key_ref);
993 			key_ref = ERR_PTR(ret);
994 			goto error_free_prep;
995 		}
996 	}
997 
998 	key_ref = __key_update(key_ref, &prep);
999 
1000 	if (!IS_ERR(key_ref))
1001 		security_key_post_create_or_update(keyring, key, payload, plen,
1002 						   flags, false);
1003 
1004 	goto error_free_prep;
1005 }
1006 
1007 /**
1008  * key_create_or_update - Update or create and instantiate a key.
1009  * @keyring_ref: A pointer to the destination keyring with possession flag.
1010  * @type: The type of key.
1011  * @description: The searchable description for the key.
1012  * @payload: The data to use to instantiate or update the key.
1013  * @plen: The length of @payload.
1014  * @perm: The permissions mask for a new key.
1015  * @flags: The quota flags for a new key.
1016  *
1017  * Search the destination keyring for a key of the same description and if one
1018  * is found, update it, otherwise create and instantiate a new one and create a
1019  * link to it from that keyring.
1020  *
1021  * If perm is KEY_PERM_UNDEF then an appropriate key permissions mask will be
1022  * concocted.
1023  *
1024  * Returns a pointer to the new key if successful, -ENODEV if the key type
1025  * wasn't available, -ENOTDIR if the keyring wasn't a keyring, -EACCES if the
1026  * caller isn't permitted to modify the keyring or the LSM did not permit
1027  * creation of the key.
1028  *
1029  * On success, the possession flag from the keyring ref will be tacked on to
1030  * the key ref before it is returned.
1031  */
1032 key_ref_t key_create_or_update(key_ref_t keyring_ref,
1033 			       const char *type,
1034 			       const char *description,
1035 			       const void *payload,
1036 			       size_t plen,
1037 			       key_perm_t perm,
1038 			       unsigned long flags)
1039 {
1040 	return __key_create_or_update(keyring_ref, type, description, payload,
1041 				      plen, perm, flags, true);
1042 }
1043 EXPORT_SYMBOL(key_create_or_update);
1044 
1045 /**
1046  * key_create - Create and instantiate a key.
1047  * @keyring_ref: A pointer to the destination keyring with possession flag.
1048  * @type: The type of key.
1049  * @description: The searchable description for the key.
1050  * @payload: The data to use to instantiate or update the key.
1051  * @plen: The length of @payload.
1052  * @perm: The permissions mask for a new key.
1053  * @flags: The quota flags for a new key.
1054  *
1055  * Create and instantiate a new key and link to it from the destination keyring.
1056  *
1057  * If perm is KEY_PERM_UNDEF then an appropriate key permissions mask will be
1058  * concocted.
1059  *
1060  * Returns a pointer to the new key if successful, -EEXIST if a key with the
1061  * same description already exists, -ENODEV if the key type wasn't available,
1062  * -ENOTDIR if the keyring wasn't a keyring, -EACCES if the caller isn't
1063  * permitted to modify the keyring or the LSM did not permit creation of the
1064  * key.
1065  *
1066  * On success, the possession flag from the keyring ref will be tacked on to
1067  * the key ref before it is returned.
1068  */
1069 key_ref_t key_create(key_ref_t keyring_ref,
1070 		     const char *type,
1071 		     const char *description,
1072 		     const void *payload,
1073 		     size_t plen,
1074 		     key_perm_t perm,
1075 		     unsigned long flags)
1076 {
1077 	return __key_create_or_update(keyring_ref, type, description, payload,
1078 				      plen, perm, flags, false);
1079 }
1080 EXPORT_SYMBOL(key_create);
1081 
1082 /**
1083  * key_update - Update a key's contents.
1084  * @key_ref: The pointer (plus possession flag) to the key.
1085  * @payload: The data to be used to update the key.
1086  * @plen: The length of @payload.
1087  *
1088  * Attempt to update the contents of a key with the given payload data.  The
1089  * caller must be granted Write permission on the key.  Negative keys can be
1090  * instantiated by this method.
1091  *
1092  * Returns 0 on success, -EACCES if not permitted and -EOPNOTSUPP if the key
1093  * type does not support updating.  The key type may return other errors.
1094  */
1095 int key_update(key_ref_t key_ref, const void *payload, size_t plen)
1096 {
1097 	struct key_preparsed_payload prep;
1098 	struct key *key = key_ref_to_ptr(key_ref);
1099 	int ret;
1100 
1101 	key_check(key);
1102 
1103 	/* the key must be writable */
1104 	ret = key_permission(key_ref, KEY_NEED_WRITE);
1105 	if (ret < 0)
1106 		return ret;
1107 
1108 	down_write(&key->sem);
1109 
1110 	/* attempt to update it if supported */
1111 	ret = -EOPNOTSUPP;
1112 	if (!key->type->update)
1113 		goto out;
1114 
1115 	memset(&prep, 0, sizeof(prep));
1116 	prep.data = payload;
1117 	prep.datalen = plen;
1118 	prep.quotalen = key->type->def_datalen;
1119 	prep.expiry = TIME64_MAX;
1120 	if (key->type->preparse) {
1121 		ret = key->type->preparse(&prep);
1122 		if (ret < 0)
1123 			goto out_free_preparse;
1124 	}
1125 
1126 	ret = key->type->update(key, &prep);
1127 	if (ret == 0) {
1128 		/* Updating a negative key positively instantiates it */
1129 		mark_key_instantiated(key, 0);
1130 		notify_key(key, NOTIFY_KEY_UPDATED, 0);
1131 	}
1132 
1133 out_free_preparse:
1134 	if (key->type->preparse)
1135 		key->type->free_preparse(&prep);
1136 
1137 out:
1138 	up_write(&key->sem);
1139 	return ret;
1140 }
1141 EXPORT_SYMBOL(key_update);
1142 
1143 /**
1144  * key_revoke - Revoke a key.
1145  * @key: The key to be revoked.
1146  *
1147  * Mark a key as being revoked and ask the type to free up its resources.  The
1148  * revocation timeout is set and the key and all its links will be
1149  * automatically garbage collected after key_gc_delay amount of time if they
1150  * are not manually dealt with first.
1151  */
1152 void key_revoke(struct key *key)
1153 {
1154 	time64_t time;
1155 
1156 	key_check(key);
1157 
1158 	/* make sure no one's trying to change or use the key when we mark it
1159 	 * - we tell lockdep that we might nest because we might be revoking an
1160 	 *   authorisation key whilst holding the sem on a key we've just
1161 	 *   instantiated
1162 	 */
1163 	down_write_nested(&key->sem, 1);
1164 	if (!test_and_set_bit(KEY_FLAG_REVOKED, &key->flags)) {
1165 		notify_key(key, NOTIFY_KEY_REVOKED, 0);
1166 		if (key->type->revoke)
1167 			key->type->revoke(key);
1168 
1169 		/* set the death time to no more than the expiry time */
1170 		time = ktime_get_real_seconds();
1171 		if (key->revoked_at == 0 || key->revoked_at > time) {
1172 			key->revoked_at = time;
1173 			key_schedule_gc(key->revoked_at + key_gc_delay);
1174 		}
1175 	}
1176 
1177 	up_write(&key->sem);
1178 }
1179 EXPORT_SYMBOL(key_revoke);
1180 
1181 /**
1182  * key_invalidate - Invalidate a key.
1183  * @key: The key to be invalidated.
1184  *
1185  * Mark a key as being invalidated and have it cleaned up immediately.  The key
1186  * is ignored by all searches and other operations from this point.
1187  */
1188 void key_invalidate(struct key *key)
1189 {
1190 	kenter("%d", key_serial(key));
1191 
1192 	key_check(key);
1193 
1194 	if (!test_bit(KEY_FLAG_INVALIDATED, &key->flags)) {
1195 		down_write_nested(&key->sem, 1);
1196 		if (!test_and_set_bit(KEY_FLAG_INVALIDATED, &key->flags)) {
1197 			notify_key(key, NOTIFY_KEY_INVALIDATED, 0);
1198 			key_schedule_gc_links();
1199 		}
1200 		up_write(&key->sem);
1201 	}
1202 }
1203 EXPORT_SYMBOL(key_invalidate);
1204 
1205 /**
1206  * generic_key_instantiate - Simple instantiation of a key from preparsed data
1207  * @key: The key to be instantiated
1208  * @prep: The preparsed data to load.
1209  *
1210  * Instantiate a key from preparsed data.  We assume we can just copy the data
1211  * in directly and clear the old pointers.
1212  *
1213  * This can be pointed to directly by the key type instantiate op pointer.
1214  */
1215 int generic_key_instantiate(struct key *key, struct key_preparsed_payload *prep)
1216 {
1217 	int ret;
1218 
1219 	pr_devel("==>%s()\n", __func__);
1220 
1221 	ret = key_payload_reserve(key, prep->quotalen);
1222 	if (ret == 0) {
1223 		rcu_assign_keypointer(key, prep->payload.data[0]);
1224 		key->payload.data[1] = prep->payload.data[1];
1225 		key->payload.data[2] = prep->payload.data[2];
1226 		key->payload.data[3] = prep->payload.data[3];
1227 		prep->payload.data[0] = NULL;
1228 		prep->payload.data[1] = NULL;
1229 		prep->payload.data[2] = NULL;
1230 		prep->payload.data[3] = NULL;
1231 	}
1232 	pr_devel("<==%s() = %d\n", __func__, ret);
1233 	return ret;
1234 }
1235 EXPORT_SYMBOL(generic_key_instantiate);
1236 
1237 /**
1238  * register_key_type - Register a type of key.
1239  * @ktype: The new key type.
1240  *
1241  * Register a new key type.
1242  *
1243  * Returns 0 on success or -EEXIST if a type of this name already exists.
1244  */
1245 int register_key_type(struct key_type *ktype)
1246 {
1247 	struct key_type *p;
1248 	int ret;
1249 
1250 	memset(&ktype->lock_class, 0, sizeof(ktype->lock_class));
1251 
1252 	ret = -EEXIST;
1253 	down_write(&key_types_sem);
1254 
1255 	/* disallow key types with the same name */
1256 	list_for_each_entry(p, &key_types_list, link) {
1257 		if (strcmp(p->name, ktype->name) == 0)
1258 			goto out;
1259 	}
1260 
1261 	/* store the type */
1262 	list_add(&ktype->link, &key_types_list);
1263 
1264 	pr_notice("Key type %s registered\n", ktype->name);
1265 	ret = 0;
1266 
1267 out:
1268 	up_write(&key_types_sem);
1269 	return ret;
1270 }
1271 EXPORT_SYMBOL(register_key_type);
1272 
1273 /**
1274  * unregister_key_type - Unregister a type of key.
1275  * @ktype: The key type.
1276  *
1277  * Unregister a key type and mark all the extant keys of this type as dead.
1278  * Those keys of this type are then destroyed to get rid of their payloads and
1279  * they and their links will be garbage collected as soon as possible.
1280  */
1281 void unregister_key_type(struct key_type *ktype)
1282 {
1283 	down_write(&key_types_sem);
1284 	list_del_init(&ktype->link);
1285 	downgrade_write(&key_types_sem);
1286 	key_gc_keytype(ktype);
1287 	pr_notice("Key type %s unregistered\n", ktype->name);
1288 	up_read(&key_types_sem);
1289 }
1290 EXPORT_SYMBOL(unregister_key_type);
1291 
1292 /*
1293  * Initialise the key management state.
1294  */
1295 void __init key_init(void)
1296 {
1297 	/* allocate a slab in which we can store keys */
1298 	key_jar = kmem_cache_create("key_jar", sizeof(struct key),
1299 			0, SLAB_HWCACHE_ALIGN | SLAB_PANIC | SLAB_NO_MERGE, NULL);
1300 
1301 	/* add the special key types */
1302 	list_add_tail(&key_type_keyring.link, &key_types_list);
1303 	list_add_tail(&key_type_dead.link, &key_types_list);
1304 	list_add_tail(&key_type_user.link, &key_types_list);
1305 	list_add_tail(&key_type_logon.link, &key_types_list);
1306 
1307 	/* record the root user tracking */
1308 	rb_link_node(&root_key_user.node,
1309 		     NULL,
1310 		     &key_user_tree.rb_node);
1311 
1312 	rb_insert_color(&root_key_user.node,
1313 			&key_user_tree);
1314 }
1315