xref: /linux/security/keys/process_keys.c (revision 62c457528529cdcfa32bc52b331ceca10f3937b6)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /* Manage a process's keyrings
3  *
4  * Copyright (C) 2004-2005, 2008 Red Hat, Inc. All Rights Reserved.
5  * Written by David Howells (dhowells@redhat.com)
6  */
7 
8 #include <linux/init.h>
9 #include <linux/sched.h>
10 #include <linux/sched/user.h>
11 #include <linux/keyctl.h>
12 #include <linux/fs.h>
13 #include <linux/err.h>
14 #include <linux/mutex.h>
15 #include <linux/security.h>
16 #include <linux/user_namespace.h>
17 #include <linux/uaccess.h>
18 #include <linux/init_task.h>
19 #include <keys/request_key_auth-type.h>
20 #include "internal.h"
21 
22 /* Session keyring create vs join semaphore */
23 static DEFINE_MUTEX(key_session_mutex);
24 
25 /* BPF keyring reachable through KEY_SPEC_BPF_KEYRING */
26 static struct key *bpf_keyring __ro_after_init;
27 
28 /* dm-verity keyring reachable through KEY_SPEC_DM_VERITY_KEYRING */
29 static struct key *dm_verity_keyring;
30 static DEFINE_SPINLOCK(dm_verity_keyring_lock);
31 
32 /* fs-verity keyring reachable through KEY_SPEC_FS_VERITY_KEYRING */
33 static struct key *fs_verity_keyring __ro_after_init;
34 
35 /* The root user's tracking struct */
36 struct key_user root_key_user = {
37 	.usage		= REFCOUNT_INIT(3),
38 	.cons_lock	= __MUTEX_INITIALIZER(root_key_user.cons_lock),
39 	.lock		= __SPIN_LOCK_UNLOCKED(root_key_user.lock),
40 	.nkeys		= ATOMIC_INIT(2),
41 	.nikeys		= ATOMIC_INIT(2),
42 	.uid		= GLOBAL_ROOT_UID,
43 };
44 
45 /*
46  * Get or create a user register keyring.
47  */
48 static struct key *get_user_register(struct user_namespace *user_ns)
49 {
50 	struct key *reg_keyring = READ_ONCE(user_ns->user_keyring_register);
51 
52 	if (reg_keyring)
53 		return reg_keyring;
54 
55 	down_write(&user_ns->keyring_sem);
56 
57 	/* Make sure there's a register keyring.  It gets owned by the
58 	 * user_namespace's owner.
59 	 */
60 	reg_keyring = user_ns->user_keyring_register;
61 	if (!reg_keyring) {
62 		reg_keyring = keyring_alloc(".user_reg",
63 					    user_ns->owner, INVALID_GID,
64 					    kernel_cred(),
65 					    KEY_POS_WRITE | KEY_POS_SEARCH |
66 					    KEY_USR_VIEW | KEY_USR_READ,
67 					    0,
68 					    NULL, NULL);
69 		if (!IS_ERR(reg_keyring))
70 			smp_store_release(&user_ns->user_keyring_register,
71 					  reg_keyring);
72 	}
73 
74 	up_write(&user_ns->keyring_sem);
75 
76 	/* We don't return a ref since the keyring is pinned by the user_ns */
77 	return reg_keyring;
78 }
79 
80 /*
81  * Look up the user and user session keyrings for the current process's UID,
82  * creating them if they don't exist.
83  */
84 int look_up_user_keyrings(struct key **_user_keyring,
85 			  struct key **_user_session_keyring)
86 {
87 	const struct cred *cred = current_cred();
88 	struct user_namespace *user_ns = current_user_ns();
89 	struct key *reg_keyring, *uid_keyring, *session_keyring;
90 	key_perm_t user_keyring_perm;
91 	key_ref_t uid_keyring_r, session_keyring_r;
92 	uid_t uid = from_kuid(user_ns, cred->user->uid);
93 	char buf[20];
94 	int ret;
95 
96 	user_keyring_perm = (KEY_POS_ALL & ~KEY_POS_SETATTR) | KEY_USR_ALL;
97 
98 	kenter("%u", uid);
99 
100 	reg_keyring = get_user_register(user_ns);
101 	if (IS_ERR(reg_keyring))
102 		return PTR_ERR(reg_keyring);
103 
104 	down_write(&user_ns->keyring_sem);
105 	ret = 0;
106 
107 	/* Get the user keyring.  Note that there may be one in existence
108 	 * already as it may have been pinned by a session, but the user_struct
109 	 * pointing to it may have been destroyed by setuid.
110 	 */
111 	snprintf(buf, sizeof(buf), "_uid.%u", uid);
112 	uid_keyring_r = keyring_search(make_key_ref(reg_keyring, true),
113 				       &key_type_keyring, buf, false);
114 	kdebug("_uid %p", uid_keyring_r);
115 	if (uid_keyring_r == ERR_PTR(-EAGAIN)) {
116 		uid_keyring = keyring_alloc(buf, cred->user->uid, INVALID_GID,
117 					    cred, user_keyring_perm,
118 					    KEY_ALLOC_UID_KEYRING |
119 					    KEY_ALLOC_IN_QUOTA,
120 					    NULL, reg_keyring);
121 		if (IS_ERR(uid_keyring)) {
122 			ret = PTR_ERR(uid_keyring);
123 			goto error;
124 		}
125 	} else if (IS_ERR(uid_keyring_r)) {
126 		ret = PTR_ERR(uid_keyring_r);
127 		goto error;
128 	} else {
129 		uid_keyring = key_ref_to_ptr(uid_keyring_r);
130 	}
131 
132 	/* Get a default session keyring (which might also exist already) */
133 	snprintf(buf, sizeof(buf), "_uid_ses.%u", uid);
134 	session_keyring_r = keyring_search(make_key_ref(reg_keyring, true),
135 					   &key_type_keyring, buf, false);
136 	kdebug("_uid_ses %p", session_keyring_r);
137 	if (session_keyring_r == ERR_PTR(-EAGAIN)) {
138 		session_keyring = keyring_alloc(buf, cred->user->uid, INVALID_GID,
139 						cred, user_keyring_perm,
140 						KEY_ALLOC_UID_KEYRING |
141 						KEY_ALLOC_IN_QUOTA,
142 						NULL, NULL);
143 		if (IS_ERR(session_keyring)) {
144 			ret = PTR_ERR(session_keyring);
145 			goto error_release;
146 		}
147 
148 		/* We install a link from the user session keyring to
149 		 * the user keyring.
150 		 */
151 		ret = key_link(session_keyring, uid_keyring);
152 		if (ret < 0)
153 			goto error_release_session;
154 
155 		/* And only then link the user-session keyring to the
156 		 * register.
157 		 */
158 		ret = key_link(reg_keyring, session_keyring);
159 		if (ret < 0)
160 			goto error_release_session;
161 	} else if (IS_ERR(session_keyring_r)) {
162 		ret = PTR_ERR(session_keyring_r);
163 		goto error_release;
164 	} else {
165 		session_keyring = key_ref_to_ptr(session_keyring_r);
166 	}
167 
168 	up_write(&user_ns->keyring_sem);
169 
170 	if (_user_session_keyring)
171 		*_user_session_keyring = session_keyring;
172 	else
173 		key_put(session_keyring);
174 	if (_user_keyring)
175 		*_user_keyring = uid_keyring;
176 	else
177 		key_put(uid_keyring);
178 	kleave(" = 0");
179 	return 0;
180 
181 error_release_session:
182 	key_put(session_keyring);
183 error_release:
184 	key_put(uid_keyring);
185 error:
186 	up_write(&user_ns->keyring_sem);
187 	kleave(" = %d", ret);
188 	return ret;
189 }
190 
191 /*
192  * Get the user session keyring if it exists, but don't create it if it
193  * doesn't.
194  */
195 struct key *get_user_session_keyring_rcu(const struct cred *cred)
196 {
197 	struct key *reg_keyring = READ_ONCE(cred->user_ns->user_keyring_register);
198 	key_ref_t session_keyring_r;
199 	char buf[20];
200 
201 	struct keyring_search_context ctx = {
202 		.index_key.type		= &key_type_keyring,
203 		.index_key.description	= buf,
204 		.cred			= cred,
205 		.match_data.cmp		= key_default_cmp,
206 		.match_data.raw_data	= buf,
207 		.match_data.lookup_type	= KEYRING_SEARCH_LOOKUP_DIRECT,
208 		.flags			= KEYRING_SEARCH_DO_STATE_CHECK,
209 	};
210 
211 	if (!reg_keyring)
212 		return NULL;
213 
214 	ctx.index_key.desc_len = snprintf(buf, sizeof(buf), "_uid_ses.%u",
215 					  from_kuid(cred->user_ns,
216 						    cred->user->uid));
217 
218 	session_keyring_r = keyring_search_rcu(make_key_ref(reg_keyring, true),
219 					       &ctx);
220 	if (IS_ERR(session_keyring_r))
221 		return NULL;
222 	return key_ref_to_ptr(session_keyring_r);
223 }
224 
225 /*
226  * Install a thread keyring to the given credentials struct if it didn't have
227  * one already.  This is allowed to overrun the quota.
228  *
229  * Return: 0 if a thread keyring is now present; -errno on failure.
230  */
231 int install_thread_keyring_to_cred(struct cred *new)
232 {
233 	struct key *keyring;
234 
235 	if (new->thread_keyring)
236 		return 0;
237 
238 	keyring = keyring_alloc("_tid", new->uid, new->gid, new,
239 				KEY_POS_ALL | KEY_USR_VIEW,
240 				KEY_ALLOC_QUOTA_OVERRUN,
241 				NULL, NULL);
242 	if (IS_ERR(keyring))
243 		return PTR_ERR(keyring);
244 
245 	new->thread_keyring = keyring;
246 	return 0;
247 }
248 
249 /*
250  * Install a thread keyring to the current task if it didn't have one already.
251  *
252  * Return: 0 if a thread keyring is now present; -errno on failure.
253  */
254 static int install_thread_keyring(void)
255 {
256 	struct cred *new;
257 	int ret;
258 
259 	new = prepare_creds();
260 	if (!new)
261 		return -ENOMEM;
262 
263 	ret = install_thread_keyring_to_cred(new);
264 	if (ret < 0) {
265 		abort_creds(new);
266 		return ret;
267 	}
268 
269 	return commit_creds(new);
270 }
271 
272 /*
273  * Install a process keyring to the given credentials struct if it didn't have
274  * one already.  This is allowed to overrun the quota.
275  *
276  * Return: 0 if a process keyring is now present; -errno on failure.
277  */
278 int install_process_keyring_to_cred(struct cred *new)
279 {
280 	struct key *keyring;
281 
282 	if (new->process_keyring)
283 		return 0;
284 
285 	keyring = keyring_alloc("_pid", new->uid, new->gid, new,
286 				KEY_POS_ALL | KEY_USR_VIEW,
287 				KEY_ALLOC_QUOTA_OVERRUN,
288 				NULL, NULL);
289 	if (IS_ERR(keyring))
290 		return PTR_ERR(keyring);
291 
292 	new->process_keyring = keyring;
293 	return 0;
294 }
295 
296 /*
297  * Install a process keyring to the current task if it didn't have one already.
298  *
299  * Return: 0 if a process keyring is now present; -errno on failure.
300  */
301 static int install_process_keyring(void)
302 {
303 	struct cred *new;
304 	int ret;
305 
306 	new = prepare_creds();
307 	if (!new)
308 		return -ENOMEM;
309 
310 	ret = install_process_keyring_to_cred(new);
311 	if (ret < 0) {
312 		abort_creds(new);
313 		return ret;
314 	}
315 
316 	return commit_creds(new);
317 }
318 
319 /*
320  * Install the given keyring as the session keyring of the given credentials
321  * struct, replacing the existing one if any.  If the given keyring is NULL,
322  * then install a new anonymous session keyring.
323  * @cred can not be in use by any task yet.
324  *
325  * Return: 0 on success; -errno on failure.
326  */
327 int install_session_keyring_to_cred(struct cred *cred, struct key *keyring)
328 {
329 	unsigned long flags;
330 	struct key *old;
331 
332 	might_sleep();
333 
334 	/* create an empty session keyring */
335 	if (!keyring) {
336 		flags = KEY_ALLOC_QUOTA_OVERRUN;
337 		if (cred->session_keyring)
338 			flags = KEY_ALLOC_IN_QUOTA;
339 
340 		keyring = keyring_alloc("_ses", cred->uid, cred->gid, cred,
341 					KEY_POS_ALL | KEY_USR_VIEW | KEY_USR_READ,
342 					flags, NULL, NULL);
343 		if (IS_ERR(keyring))
344 			return PTR_ERR(keyring);
345 	} else {
346 		__key_get(keyring);
347 	}
348 
349 	/* install the keyring */
350 	old = cred->session_keyring;
351 	cred->session_keyring = keyring;
352 
353 	if (old)
354 		key_put(old);
355 
356 	return 0;
357 }
358 
359 /*
360  * Install the given keyring as the session keyring of the current task,
361  * replacing the existing one if any.  If the given keyring is NULL, then
362  * install a new anonymous session keyring.
363  *
364  * Return: 0 on success; -errno on failure.
365  */
366 static int install_session_keyring(struct key *keyring)
367 {
368 	struct cred *new;
369 	int ret;
370 
371 	new = prepare_creds();
372 	if (!new)
373 		return -ENOMEM;
374 
375 	ret = install_session_keyring_to_cred(new, keyring);
376 	if (ret < 0) {
377 		abort_creds(new);
378 		return ret;
379 	}
380 
381 	return commit_creds(new);
382 }
383 
384 /*
385  * Handle the fsuid changing.
386  */
387 void key_fsuid_changed(struct cred *new_cred)
388 {
389 	/* update the ownership of the thread keyring */
390 	if (new_cred->thread_keyring) {
391 		down_write(&new_cred->thread_keyring->sem);
392 		new_cred->thread_keyring->uid = new_cred->fsuid;
393 		up_write(&new_cred->thread_keyring->sem);
394 	}
395 }
396 
397 /*
398  * Handle the fsgid changing.
399  */
400 void key_fsgid_changed(struct cred *new_cred)
401 {
402 	/* update the ownership of the thread keyring */
403 	if (new_cred->thread_keyring) {
404 		down_write(&new_cred->thread_keyring->sem);
405 		new_cred->thread_keyring->gid = new_cred->fsgid;
406 		up_write(&new_cred->thread_keyring->sem);
407 	}
408 }
409 
410 /*
411  * Search the process keyrings attached to the supplied cred for the first
412  * matching key under RCU conditions (the caller must be holding the RCU read
413  * lock).
414  *
415  * The search criteria are the type and the match function.  The description is
416  * given to the match function as a parameter, but doesn't otherwise influence
417  * the search.  Typically the match function will compare the description
418  * parameter to the key's description.
419  *
420  * This can only search keyrings that grant Search permission to the supplied
421  * credentials.  Keyrings linked to searched keyrings will also be searched if
422  * they grant Search permission too.  Keys can only be found if they grant
423  * Search permission to the credentials.
424  *
425  * Returns a pointer to the key with the key usage count incremented if
426  * successful, -EAGAIN if we didn't find any matching key or -ENOKEY if we only
427  * matched negative keys.
428  *
429  * In the case of a successful return, the possession attribute is set on the
430  * returned key reference.
431  */
432 key_ref_t search_cred_keyrings_rcu(struct keyring_search_context *ctx)
433 {
434 	struct key *user_session;
435 	key_ref_t key_ref, ret, err;
436 	const struct cred *cred = ctx->cred;
437 
438 	/* we want to return -EAGAIN or -ENOKEY if any of the keyrings were
439 	 * searchable, but we failed to find a key or we found a negative key;
440 	 * otherwise we want to return a sample error (probably -EACCES) if
441 	 * none of the keyrings were searchable
442 	 *
443 	 * in terms of priority: success > -ENOKEY > -EAGAIN > other error
444 	 */
445 	key_ref = NULL;
446 	ret = NULL;
447 	err = ERR_PTR(-EAGAIN);
448 
449 	/* search the thread keyring first */
450 	if (cred->thread_keyring) {
451 		key_ref = keyring_search_rcu(
452 			make_key_ref(cred->thread_keyring, 1), ctx);
453 		if (!IS_ERR(key_ref))
454 			goto found;
455 
456 		switch (PTR_ERR(key_ref)) {
457 		case -EAGAIN: /* no key */
458 		case -ENOKEY: /* negative key */
459 			ret = key_ref;
460 			break;
461 		default:
462 			err = key_ref;
463 			break;
464 		}
465 	}
466 
467 	/* search the process keyring second */
468 	if (cred->process_keyring) {
469 		key_ref = keyring_search_rcu(
470 			make_key_ref(cred->process_keyring, 1), ctx);
471 		if (!IS_ERR(key_ref))
472 			goto found;
473 
474 		switch (PTR_ERR(key_ref)) {
475 		case -EAGAIN: /* no key */
476 			if (ret)
477 				break;
478 			fallthrough;
479 		case -ENOKEY: /* negative key */
480 			ret = key_ref;
481 			break;
482 		default:
483 			err = key_ref;
484 			break;
485 		}
486 	}
487 
488 	/* search the session keyring */
489 	if (cred->session_keyring) {
490 		key_ref = keyring_search_rcu(
491 			make_key_ref(cred->session_keyring, 1), ctx);
492 
493 		if (!IS_ERR(key_ref))
494 			goto found;
495 
496 		switch (PTR_ERR(key_ref)) {
497 		case -EAGAIN: /* no key */
498 			if (ret)
499 				break;
500 			fallthrough;
501 		case -ENOKEY: /* negative key */
502 			ret = key_ref;
503 			break;
504 		default:
505 			err = key_ref;
506 			break;
507 		}
508 	}
509 	/* or search the user-session keyring */
510 	else if ((user_session = get_user_session_keyring_rcu(cred))) {
511 		key_ref = keyring_search_rcu(make_key_ref(user_session, 1),
512 					     ctx);
513 		key_put(user_session);
514 
515 		if (!IS_ERR(key_ref))
516 			goto found;
517 
518 		switch (PTR_ERR(key_ref)) {
519 		case -EAGAIN: /* no key */
520 			if (ret)
521 				break;
522 			fallthrough;
523 		case -ENOKEY: /* negative key */
524 			ret = key_ref;
525 			break;
526 		default:
527 			err = key_ref;
528 			break;
529 		}
530 	}
531 
532 	/* no key - decide on the error we're going to go for */
533 	key_ref = ret ? ret : err;
534 
535 found:
536 	return key_ref;
537 }
538 
539 /*
540  * Search the process keyrings attached to the supplied cred for the first
541  * matching key in the manner of search_cred_keyrings_rcu(), but also search
542  * the keys attached to the assumed authorisation key using its credentials if
543  * one is available.
544  *
545  * The caller must be holding the RCU read lock.
546  *
547  * Return same as search_cred_keyrings_rcu().
548  */
549 key_ref_t search_process_keyrings_rcu(struct keyring_search_context *ctx)
550 {
551 	struct request_key_auth *rka;
552 	key_ref_t key_ref, ret = ERR_PTR(-EACCES), err;
553 
554 	key_ref = search_cred_keyrings_rcu(ctx);
555 	if (!IS_ERR(key_ref))
556 		goto found;
557 	err = key_ref;
558 
559 	/* if this process has an instantiation authorisation key, then we also
560 	 * search the keyrings of the process mentioned there
561 	 * - we don't permit access to request_key auth keys via this method
562 	 */
563 	if (ctx->cred->request_key_auth &&
564 	    ctx->cred == current_cred() &&
565 	    ctx->index_key.type != &key_type_request_key_auth
566 	    ) {
567 		const struct cred *cred = ctx->cred;
568 
569 		rka = dereference_key_rcu(cred->request_key_auth);
570 		if (rka && key_validate(cred->request_key_auth) == 0) {
571 			//// was search_process_keyrings() [ie. recursive]
572 			ctx->cred = rka->cred;
573 			key_ref = search_cred_keyrings_rcu(ctx);
574 			ctx->cred = cred;
575 
576 			if (!IS_ERR(key_ref))
577 				goto found;
578 			ret = key_ref;
579 		}
580 	}
581 
582 	/* no key - decide on the error we're going to go for */
583 	if (err == ERR_PTR(-ENOKEY) || ret == ERR_PTR(-ENOKEY))
584 		key_ref = ERR_PTR(-ENOKEY);
585 	else if (err == ERR_PTR(-EACCES))
586 		key_ref = ret;
587 	else
588 		key_ref = err;
589 
590 found:
591 	return key_ref;
592 }
593 /*
594  * See if the key we're looking at is the target key.
595  */
596 bool lookup_user_key_possessed(const struct key *key,
597 			       const struct key_match_data *match_data)
598 {
599 	return key == match_data->raw_data;
600 }
601 
602 /**
603  * key_register_bpf_keyring - Publish the BPF keyring for KEY_SPEC_BPF_KEYRING
604  * @keyring: The keyring to publish
605  *
606  * Make @keyring reachable by userspace through the KEY_SPEC_BPF_KEYRING
607  * special key ID, so that provisioning it does not require scraping its
608  * serial out of /proc/keys first. Called once, from an initcall, and never
609  * undone.
610  */
611 void key_register_bpf_keyring(struct key *keyring)
612 {
613 	bpf_keyring = keyring;
614 }
615 
616 /**
617  * key_register_dm_verity_keyring - Publish the keyring for KEY_SPEC_DM_VERITY_KEYRING
618  * @keyring: The keyring to publish, or NULL to withdraw it
619  *
620  * Make @keyring reachable by userspace through the KEY_SPEC_DM_VERITY_KEYRING
621  * special key ID, so that provisioning it does not require scraping its
622  * serial out of /proc/keys first. dm-verity can be unloaded as a module
623  * and the keyring deregistered, as such serialize access with
624  * dm_verity_keyring_lock.
625  */
626 void key_register_dm_verity_keyring(struct key *keyring)
627 {
628 	spin_lock(&dm_verity_keyring_lock);
629 	dm_verity_keyring = keyring;
630 	spin_unlock(&dm_verity_keyring_lock);
631 }
632 EXPORT_SYMBOL_GPL(key_register_dm_verity_keyring);
633 
634 /**
635  * key_register_fs_verity_keyring - Publish the keyring for KEY_SPEC_FS_VERITY_KEYRING
636  * @keyring: The keyring to publish
637  *
638  * Make @keyring reachable by userspace through the KEY_SPEC_FS_VERITY_KEYRING
639  * special key ID, so that provisioning it does not require scraping its
640  * serial out of /proc/keys first. Called once, from an initcall, and never
641  * undone.
642  */
643 void key_register_fs_verity_keyring(struct key *keyring)
644 {
645 	fs_verity_keyring = keyring;
646 }
647 
648 /*
649  * Look up a key ID given us by userspace with a given permissions mask to get
650  * the key it refers to.
651  *
652  * Flags can be passed to request that special keyrings be created if referred
653  * to directly, to permit partially constructed keys to be found and to skip
654  * validity and permission checks on the found key.
655  *
656  * Returns a pointer to the key with an incremented usage count if successful;
657  * -EINVAL if the key ID is invalid; -ENOKEY if the key ID does not correspond
658  * to a key or the best found key was a negative key; -EKEYREVOKED or
659  * -EKEYEXPIRED if the best found key was revoked or expired; -EACCES if the
660  * found key doesn't grant the requested permit or the LSM denied access to it;
661  * or -ENOMEM if a special keyring couldn't be created.
662  *
663  * In the case of a successful return, the possession attribute is set on the
664  * returned key reference.
665  */
666 key_ref_t lookup_user_key(key_serial_t id, unsigned long lflags,
667 			  enum key_need_perm need_perm)
668 {
669 	struct keyring_search_context ctx = {
670 		.match_data.cmp		= lookup_user_key_possessed,
671 		.match_data.lookup_type	= KEYRING_SEARCH_LOOKUP_DIRECT,
672 		.flags			= (KEYRING_SEARCH_NO_STATE_CHECK |
673 					   KEYRING_SEARCH_RECURSE),
674 	};
675 	struct request_key_auth *rka;
676 	struct key *key, *user_session;
677 	key_ref_t key_ref, skey_ref;
678 	int ret;
679 
680 try_again:
681 	ctx.cred = get_current_cred();
682 	key_ref = ERR_PTR(-ENOKEY);
683 
684 	switch (id) {
685 	case KEY_SPEC_THREAD_KEYRING:
686 		if (!ctx.cred->thread_keyring) {
687 			if (!(lflags & KEY_LOOKUP_CREATE))
688 				goto error;
689 
690 			ret = install_thread_keyring();
691 			if (ret < 0) {
692 				key_ref = ERR_PTR(ret);
693 				goto error;
694 			}
695 			goto reget_creds;
696 		}
697 
698 		key = ctx.cred->thread_keyring;
699 		__key_get(key);
700 		key_ref = make_key_ref(key, 1);
701 		break;
702 
703 	case KEY_SPEC_PROCESS_KEYRING:
704 		if (!ctx.cred->process_keyring) {
705 			if (!(lflags & KEY_LOOKUP_CREATE))
706 				goto error;
707 
708 			ret = install_process_keyring();
709 			if (ret < 0) {
710 				key_ref = ERR_PTR(ret);
711 				goto error;
712 			}
713 			goto reget_creds;
714 		}
715 
716 		key = ctx.cred->process_keyring;
717 		__key_get(key);
718 		key_ref = make_key_ref(key, 1);
719 		break;
720 
721 	case KEY_SPEC_SESSION_KEYRING:
722 		if (!ctx.cred->session_keyring) {
723 			/* always install a session keyring upon access if one
724 			 * doesn't exist yet */
725 			ret = look_up_user_keyrings(NULL, &user_session);
726 			if (ret < 0)
727 				goto error;
728 			if (lflags & KEY_LOOKUP_CREATE)
729 				ret = join_session_keyring(NULL);
730 			else
731 				ret = install_session_keyring(user_session);
732 
733 			key_put(user_session);
734 			if (ret < 0)
735 				goto error;
736 			goto reget_creds;
737 		} else if (test_bit(KEY_FLAG_UID_KEYRING,
738 				    &ctx.cred->session_keyring->flags) &&
739 			   lflags & KEY_LOOKUP_CREATE) {
740 			ret = join_session_keyring(NULL);
741 			if (ret < 0)
742 				goto error;
743 			goto reget_creds;
744 		}
745 
746 		key = ctx.cred->session_keyring;
747 		__key_get(key);
748 		key_ref = make_key_ref(key, 1);
749 		break;
750 
751 	case KEY_SPEC_USER_KEYRING:
752 		ret = look_up_user_keyrings(&key, NULL);
753 		if (ret < 0)
754 			goto error;
755 		key_ref = make_key_ref(key, 1);
756 		break;
757 
758 	case KEY_SPEC_USER_SESSION_KEYRING:
759 		ret = look_up_user_keyrings(NULL, &key);
760 		if (ret < 0)
761 			goto error;
762 		key_ref = make_key_ref(key, 1);
763 		break;
764 
765 	case KEY_SPEC_GROUP_KEYRING:
766 		/* group keyrings are not yet supported */
767 		key_ref = ERR_PTR(-EINVAL);
768 		goto error;
769 
770 	case KEY_SPEC_REQKEY_AUTH_KEY:
771 		key = ctx.cred->request_key_auth;
772 		if (!key)
773 			goto error;
774 
775 		__key_get(key);
776 		key_ref = make_key_ref(key, 1);
777 		break;
778 
779 	case KEY_SPEC_REQUESTOR_KEYRING:
780 		if (!ctx.cred->request_key_auth)
781 			goto error;
782 
783 		down_read(&ctx.cred->request_key_auth->sem);
784 		if (test_bit(KEY_FLAG_REVOKED,
785 			     &ctx.cred->request_key_auth->flags)) {
786 			key_ref = ERR_PTR(-EKEYREVOKED);
787 			key = NULL;
788 		} else {
789 			rka = ctx.cred->request_key_auth->payload.data[0];
790 			key = rka->dest_keyring;
791 			__key_get(key);
792 		}
793 		up_read(&ctx.cred->request_key_auth->sem);
794 		if (!key)
795 			goto error;
796 		key_ref = make_key_ref(key, 1);
797 		break;
798 
799 	case KEY_SPEC_BPF_KEYRING:
800 		key = bpf_keyring;
801 		if (!key)
802 			goto error;
803 		__key_get(key);
804 		key_ref = make_key_ref(key, 0);
805 		break;
806 
807 	case KEY_SPEC_DM_VERITY_KEYRING:
808 		spin_lock(&dm_verity_keyring_lock);
809 		key = dm_verity_keyring;
810 		if (key)
811 			__key_get(key);
812 		spin_unlock(&dm_verity_keyring_lock);
813 		if (!key)
814 			goto error;
815 		key_ref = make_key_ref(key, 0);
816 		break;
817 
818 	case KEY_SPEC_FS_VERITY_KEYRING:
819 		key = fs_verity_keyring;
820 		if (!key)
821 			goto error;
822 		__key_get(key);
823 		key_ref = make_key_ref(key, 0);
824 		break;
825 
826 	default:
827 		key_ref = ERR_PTR(-EINVAL);
828 		if (id < 1)
829 			goto error;
830 
831 		key = key_lookup(id);
832 		if (IS_ERR(key)) {
833 			key_ref = ERR_CAST(key);
834 			goto error;
835 		}
836 
837 		key_ref = make_key_ref(key, 0);
838 
839 		/* check to see if we possess the key */
840 		ctx.index_key			= key->index_key;
841 		ctx.match_data.raw_data		= key;
842 		kdebug("check possessed");
843 		rcu_read_lock();
844 		skey_ref = search_process_keyrings_rcu(&ctx);
845 		rcu_read_unlock();
846 		kdebug("possessed=%p", skey_ref);
847 
848 		if (!IS_ERR(skey_ref)) {
849 			key_put(key);
850 			key_ref = skey_ref;
851 		}
852 
853 		break;
854 	}
855 
856 	/* unlink does not use the nominated key in any way, so can skip all
857 	 * the permission checks as it is only concerned with the keyring */
858 	if (need_perm != KEY_NEED_UNLINK) {
859 		if (!(lflags & KEY_LOOKUP_PARTIAL)) {
860 			ret = wait_for_key_construction(key, true);
861 			switch (ret) {
862 			case -ERESTARTSYS:
863 				goto invalid_key;
864 			default:
865 				if (need_perm != KEY_AUTHTOKEN_OVERRIDE &&
866 				    need_perm != KEY_DEFER_PERM_CHECK)
867 					goto invalid_key;
868 				break;
869 			case 0:
870 				break;
871 			}
872 		} else if (need_perm != KEY_DEFER_PERM_CHECK) {
873 			ret = key_validate(key);
874 			if (ret < 0)
875 				goto invalid_key;
876 		}
877 
878 		ret = -EIO;
879 		if (!(lflags & KEY_LOOKUP_PARTIAL) &&
880 		    key_read_state(key) == KEY_IS_UNINSTANTIATED)
881 			goto invalid_key;
882 	}
883 
884 	/* check the permissions */
885 	ret = key_task_permission(key_ref, ctx.cred, need_perm);
886 	if (ret < 0)
887 		goto invalid_key;
888 
889 	key->last_used_at = ktime_get_real_seconds();
890 
891 error:
892 	put_cred(ctx.cred);
893 	return key_ref;
894 
895 invalid_key:
896 	key_ref_put(key_ref);
897 	key_ref = ERR_PTR(ret);
898 	goto error;
899 
900 	/* if we attempted to install a keyring, then it may have caused new
901 	 * creds to be installed */
902 reget_creds:
903 	put_cred(ctx.cred);
904 	goto try_again;
905 }
906 EXPORT_SYMBOL(lookup_user_key);
907 
908 /*
909  * Join the named keyring as the session keyring if possible else attempt to
910  * create a new one of that name and join that.
911  *
912  * If the name is NULL, an empty anonymous keyring will be installed as the
913  * session keyring.
914  *
915  * Named session keyrings are joined with a semaphore held to prevent the
916  * keyrings from going away whilst the attempt is made to going them and also
917  * to prevent a race in creating compatible session keyrings.
918  */
919 long join_session_keyring(const char *name)
920 {
921 	const struct cred *old;
922 	struct cred *new;
923 	struct key *keyring;
924 	long ret, serial;
925 
926 	new = prepare_creds();
927 	if (!new)
928 		return -ENOMEM;
929 	old = current_cred();
930 
931 	/* if no name is provided, install an anonymous keyring */
932 	if (!name) {
933 		ret = install_session_keyring_to_cred(new, NULL);
934 		if (ret < 0)
935 			goto error;
936 
937 		serial = new->session_keyring->serial;
938 		ret = commit_creds(new);
939 		if (ret == 0)
940 			ret = serial;
941 		goto okay;
942 	}
943 
944 	/* allow the user to join or create a named keyring */
945 	mutex_lock(&key_session_mutex);
946 
947 	/* look for an existing keyring of this name */
948 	keyring = find_keyring_by_name(name, false);
949 	if (PTR_ERR(keyring) == -ENOKEY) {
950 		/* not found - try and create a new one */
951 		keyring = keyring_alloc(
952 			name, old->uid, old->gid, old,
953 			KEY_POS_ALL | KEY_USR_VIEW | KEY_USR_READ | KEY_USR_LINK,
954 			KEY_ALLOC_IN_QUOTA, NULL, NULL);
955 		if (IS_ERR(keyring)) {
956 			ret = PTR_ERR(keyring);
957 			goto error2;
958 		}
959 	} else if (IS_ERR(keyring)) {
960 		ret = PTR_ERR(keyring);
961 		goto error2;
962 	} else if (keyring == new->session_keyring) {
963 		ret = 0;
964 		goto error3;
965 	}
966 
967 	/* we've got a keyring - now to install it */
968 	ret = install_session_keyring_to_cred(new, keyring);
969 	if (ret < 0)
970 		goto error3;
971 
972 	commit_creds(new);
973 	mutex_unlock(&key_session_mutex);
974 
975 	ret = keyring->serial;
976 	key_put(keyring);
977 okay:
978 	return ret;
979 
980 error3:
981 	key_put(keyring);
982 error2:
983 	mutex_unlock(&key_session_mutex);
984 error:
985 	abort_creds(new);
986 	return ret;
987 }
988 
989 /*
990  * Replace a process's session keyring on behalf of one of its children when
991  * the target  process is about to resume userspace execution.
992  */
993 void key_change_session_keyring(struct callback_head *twork)
994 {
995 	const struct cred *old = current_cred();
996 	struct cred *new = container_of(twork, struct cred, rcu);
997 
998 	if (unlikely(current->flags & PF_EXITING)) {
999 		put_cred(new);
1000 		return;
1001 	}
1002 
1003 	/* If get_ucounts fails more bits are needed in the refcount */
1004 	if (unlikely(!get_ucounts(old->ucounts))) {
1005 		WARN_ONCE(1, "In %s get_ucounts failed\n", __func__);
1006 		put_cred(new);
1007 		return;
1008 	}
1009 
1010 	new->  uid	= old->  uid;
1011 	new-> euid	= old-> euid;
1012 	new-> suid	= old-> suid;
1013 	new->fsuid	= old->fsuid;
1014 	new->  gid	= old->  gid;
1015 	new-> egid	= old-> egid;
1016 	new-> sgid	= old-> sgid;
1017 	new->fsgid	= old->fsgid;
1018 	new->user	= get_uid(old->user);
1019 	new->ucounts	= old->ucounts;
1020 	new->user_ns	= get_user_ns(old->user_ns);
1021 	new->group_info	= get_group_info(old->group_info);
1022 
1023 	new->securebits	= old->securebits;
1024 	new->cap_inheritable	= old->cap_inheritable;
1025 	new->cap_permitted	= old->cap_permitted;
1026 	new->cap_effective	= old->cap_effective;
1027 	new->cap_ambient	= old->cap_ambient;
1028 	new->cap_bset		= old->cap_bset;
1029 
1030 	new->jit_keyring	= old->jit_keyring;
1031 	new->thread_keyring	= key_get(old->thread_keyring);
1032 	new->process_keyring	= key_get(old->process_keyring);
1033 
1034 	security_transfer_creds(new, old);
1035 
1036 	commit_creds(new);
1037 }
1038 
1039 /*
1040  * Make sure that root's user and user-session keyrings exist.
1041  */
1042 static int __init init_root_keyring(void)
1043 {
1044 	return look_up_user_keyrings(NULL, NULL);
1045 }
1046 
1047 late_initcall(init_root_keyring);
1048