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