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