1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /* Manage a process's keyrings
4 * Copyright (C) 2004-2005, 2008 Red Hat, Inc. All Rights Reserved.
5 * Written by David Howells (dhowells@redhat.com)
8 #include <linux/init.h>
9 #include <linux/sched.h>
10 #include <linux/sched/user.h>
11 #include <linux/keyctl.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>
22 /* Session keyring create vs join semaphore */
23 static DEFINE_MUTEX(key_session_mutex);
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,
36 * Get or create a user register keyring.
38 static struct key *get_user_register(struct user_namespace *user_ns)
40 struct key *reg_keyring = READ_ONCE(user_ns->user_keyring_register);
45 down_write(&user_ns->keyring_sem);
47 /* Make sure there's a register keyring. It gets owned by the
48 * user_namespace's owner.
50 reg_keyring = user_ns->user_keyring_register;
52 reg_keyring = keyring_alloc(".user_reg",
53 user_ns->owner, INVALID_GID,
55 KEY_POS_WRITE | KEY_POS_SEARCH |
56 KEY_USR_VIEW | KEY_USR_READ,
59 if (!IS_ERR(reg_keyring))
60 smp_store_release(&user_ns->user_keyring_register,
64 up_write(&user_ns->keyring_sem);
66 /* We don't return a ref since the keyring is pinned by the user_ns */
71 * Look up the user and user session keyrings for the current process's UID,
72 * creating them if they don't exist.
74 int look_up_user_keyrings(struct key **_user_keyring,
75 struct key **_user_session_keyring)
77 const struct cred *cred = current_cred();
78 struct user_namespace *user_ns = current_user_ns();
79 struct key *reg_keyring, *uid_keyring, *session_keyring;
80 key_perm_t user_keyring_perm;
81 key_ref_t uid_keyring_r, session_keyring_r;
82 uid_t uid = from_kuid(user_ns, cred->user->uid);
86 user_keyring_perm = (KEY_POS_ALL & ~KEY_POS_SETATTR) | KEY_USR_ALL;
90 reg_keyring = get_user_register(user_ns);
91 if (IS_ERR(reg_keyring))
92 return PTR_ERR(reg_keyring);
94 down_write(&user_ns->keyring_sem);
97 /* Get the user keyring. Note that there may be one in existence
98 * already as it may have been pinned by a session, but the user_struct
99 * pointing to it may have been destroyed by setuid.
101 snprintf(buf, sizeof(buf), "_uid.%u", uid);
102 uid_keyring_r = keyring_search(make_key_ref(reg_keyring, true),
103 &key_type_keyring, buf, false);
104 kdebug("_uid %p", uid_keyring_r);
105 if (uid_keyring_r == ERR_PTR(-EAGAIN)) {
106 uid_keyring = keyring_alloc(buf, cred->user->uid, INVALID_GID,
107 cred, user_keyring_perm,
108 KEY_ALLOC_UID_KEYRING |
111 if (IS_ERR(uid_keyring)) {
112 ret = PTR_ERR(uid_keyring);
115 } else if (IS_ERR(uid_keyring_r)) {
116 ret = PTR_ERR(uid_keyring_r);
119 uid_keyring = key_ref_to_ptr(uid_keyring_r);
122 /* Get a default session keyring (which might also exist already) */
123 snprintf(buf, sizeof(buf), "_uid_ses.%u", uid);
124 session_keyring_r = keyring_search(make_key_ref(reg_keyring, true),
125 &key_type_keyring, buf, false);
126 kdebug("_uid_ses %p", session_keyring_r);
127 if (session_keyring_r == ERR_PTR(-EAGAIN)) {
128 session_keyring = keyring_alloc(buf, cred->user->uid, INVALID_GID,
129 cred, user_keyring_perm,
130 KEY_ALLOC_UID_KEYRING |
133 if (IS_ERR(session_keyring)) {
134 ret = PTR_ERR(session_keyring);
138 /* We install a link from the user session keyring to
141 ret = key_link(session_keyring, uid_keyring);
143 goto error_release_session;
145 /* And only then link the user-session keyring to the
148 ret = key_link(reg_keyring, session_keyring);
150 goto error_release_session;
151 } else if (IS_ERR(session_keyring_r)) {
152 ret = PTR_ERR(session_keyring_r);
155 session_keyring = key_ref_to_ptr(session_keyring_r);
158 up_write(&user_ns->keyring_sem);
160 if (_user_session_keyring)
161 *_user_session_keyring = session_keyring;
163 key_put(session_keyring);
165 *_user_keyring = uid_keyring;
167 key_put(uid_keyring);
171 error_release_session:
172 key_put(session_keyring);
174 key_put(uid_keyring);
176 up_write(&user_ns->keyring_sem);
177 kleave(" = %d", ret);
182 * Get the user session keyring if it exists, but don't create it if it
185 struct key *get_user_session_keyring_rcu(const struct cred *cred)
187 struct key *reg_keyring = READ_ONCE(cred->user_ns->user_keyring_register);
188 key_ref_t session_keyring_r;
191 struct keyring_search_context ctx = {
192 .index_key.type = &key_type_keyring,
193 .index_key.description = buf,
195 .match_data.cmp = key_default_cmp,
196 .match_data.raw_data = buf,
197 .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT,
198 .flags = KEYRING_SEARCH_DO_STATE_CHECK,
204 ctx.index_key.desc_len = snprintf(buf, sizeof(buf), "_uid_ses.%u",
205 from_kuid(cred->user_ns,
208 session_keyring_r = keyring_search_rcu(make_key_ref(reg_keyring, true),
210 if (IS_ERR(session_keyring_r))
212 return key_ref_to_ptr(session_keyring_r);
216 * Install a thread keyring to the given credentials struct if it didn't have
217 * one already. This is allowed to overrun the quota.
219 * Return: 0 if a thread keyring is now present; -errno on failure.
221 int install_thread_keyring_to_cred(struct cred *new)
225 if (new->thread_keyring)
228 keyring = keyring_alloc("_tid", new->uid, new->gid, new,
229 KEY_POS_ALL | KEY_USR_VIEW,
230 KEY_ALLOC_QUOTA_OVERRUN,
233 return PTR_ERR(keyring);
235 new->thread_keyring = keyring;
240 * Install a thread keyring to the current task if it didn't have one already.
242 * Return: 0 if a thread keyring is now present; -errno on failure.
244 static int install_thread_keyring(void)
249 new = prepare_creds();
253 ret = install_thread_keyring_to_cred(new);
259 return commit_creds(new);
263 * Install a process keyring to the given credentials struct if it didn't have
264 * one already. This is allowed to overrun the quota.
266 * Return: 0 if a process keyring is now present; -errno on failure.
268 int install_process_keyring_to_cred(struct cred *new)
272 if (new->process_keyring)
275 keyring = keyring_alloc("_pid", new->uid, new->gid, new,
276 KEY_POS_ALL | KEY_USR_VIEW,
277 KEY_ALLOC_QUOTA_OVERRUN,
280 return PTR_ERR(keyring);
282 new->process_keyring = keyring;
287 * Install a process keyring to the current task if it didn't have one already.
289 * Return: 0 if a process keyring is now present; -errno on failure.
291 static int install_process_keyring(void)
296 new = prepare_creds();
300 ret = install_process_keyring_to_cred(new);
306 return commit_creds(new);
310 * Install the given keyring as the session keyring of the given credentials
311 * struct, replacing the existing one if any. If the given keyring is NULL,
312 * then install a new anonymous session keyring.
313 * @cred can not be in use by any task yet.
315 * Return: 0 on success; -errno on failure.
317 int install_session_keyring_to_cred(struct cred *cred, struct key *keyring)
324 /* create an empty session keyring */
326 flags = KEY_ALLOC_QUOTA_OVERRUN;
327 if (cred->session_keyring)
328 flags = KEY_ALLOC_IN_QUOTA;
330 keyring = keyring_alloc("_ses", cred->uid, cred->gid, cred,
331 KEY_POS_ALL | KEY_USR_VIEW | KEY_USR_READ,
334 return PTR_ERR(keyring);
339 /* install the keyring */
340 old = cred->session_keyring;
341 cred->session_keyring = keyring;
350 * Install the given keyring as the session keyring of the current task,
351 * replacing the existing one if any. If the given keyring is NULL, then
352 * install a new anonymous session keyring.
354 * Return: 0 on success; -errno on failure.
356 static int install_session_keyring(struct key *keyring)
361 new = prepare_creds();
365 ret = install_session_keyring_to_cred(new, keyring);
371 return commit_creds(new);
375 * Handle the fsuid changing.
377 void key_fsuid_changed(struct cred *new_cred)
379 /* update the ownership of the thread keyring */
380 if (new_cred->thread_keyring) {
381 down_write(&new_cred->thread_keyring->sem);
382 new_cred->thread_keyring->uid = new_cred->fsuid;
383 up_write(&new_cred->thread_keyring->sem);
388 * Handle the fsgid changing.
390 void key_fsgid_changed(struct cred *new_cred)
392 /* update the ownership of the thread keyring */
393 if (new_cred->thread_keyring) {
394 down_write(&new_cred->thread_keyring->sem);
395 new_cred->thread_keyring->gid = new_cred->fsgid;
396 up_write(&new_cred->thread_keyring->sem);
401 * Search the process keyrings attached to the supplied cred for the first
402 * matching key under RCU conditions (the caller must be holding the RCU read
405 * The search criteria are the type and the match function. The description is
406 * given to the match function as a parameter, but doesn't otherwise influence
407 * the search. Typically the match function will compare the description
408 * parameter to the key's description.
410 * This can only search keyrings that grant Search permission to the supplied
411 * credentials. Keyrings linked to searched keyrings will also be searched if
412 * they grant Search permission too. Keys can only be found if they grant
413 * Search permission to the credentials.
415 * Returns a pointer to the key with the key usage count incremented if
416 * successful, -EAGAIN if we didn't find any matching key or -ENOKEY if we only
417 * matched negative keys.
419 * In the case of a successful return, the possession attribute is set on the
420 * returned key reference.
422 key_ref_t search_cred_keyrings_rcu(struct keyring_search_context *ctx)
424 struct key *user_session;
425 key_ref_t key_ref, ret, err;
426 const struct cred *cred = ctx->cred;
428 /* we want to return -EAGAIN or -ENOKEY if any of the keyrings were
429 * searchable, but we failed to find a key or we found a negative key;
430 * otherwise we want to return a sample error (probably -EACCES) if
431 * none of the keyrings were searchable
433 * in terms of priority: success > -ENOKEY > -EAGAIN > other error
437 err = ERR_PTR(-EAGAIN);
439 /* search the thread keyring first */
440 if (cred->thread_keyring) {
441 key_ref = keyring_search_rcu(
442 make_key_ref(cred->thread_keyring, 1), ctx);
443 if (!IS_ERR(key_ref))
446 switch (PTR_ERR(key_ref)) {
447 case -EAGAIN: /* no key */
448 case -ENOKEY: /* negative key */
457 /* search the process keyring second */
458 if (cred->process_keyring) {
459 key_ref = keyring_search_rcu(
460 make_key_ref(cred->process_keyring, 1), ctx);
461 if (!IS_ERR(key_ref))
464 switch (PTR_ERR(key_ref)) {
465 case -EAGAIN: /* no key */
469 case -ENOKEY: /* negative key */
478 /* search the session keyring */
479 if (cred->session_keyring) {
480 key_ref = keyring_search_rcu(
481 make_key_ref(cred->session_keyring, 1), ctx);
483 if (!IS_ERR(key_ref))
486 switch (PTR_ERR(key_ref)) {
487 case -EAGAIN: /* no key */
491 case -ENOKEY: /* negative key */
499 /* or search the user-session keyring */
500 else if ((user_session = get_user_session_keyring_rcu(cred))) {
501 key_ref = keyring_search_rcu(make_key_ref(user_session, 1),
503 key_put(user_session);
505 if (!IS_ERR(key_ref))
508 switch (PTR_ERR(key_ref)) {
509 case -EAGAIN: /* no key */
513 case -ENOKEY: /* negative key */
522 /* no key - decide on the error we're going to go for */
523 key_ref = ret ? ret : err;
530 * Search the process keyrings attached to the supplied cred for the first
531 * matching key in the manner of search_my_process_keyrings(), but also search
532 * the keys attached to the assumed authorisation key using its credentials if
535 * The caller must be holding the RCU read lock.
537 * Return same as search_cred_keyrings_rcu().
539 key_ref_t search_process_keyrings_rcu(struct keyring_search_context *ctx)
541 struct request_key_auth *rka;
542 key_ref_t key_ref, ret = ERR_PTR(-EACCES), err;
544 key_ref = search_cred_keyrings_rcu(ctx);
545 if (!IS_ERR(key_ref))
549 /* if this process has an instantiation authorisation key, then we also
550 * search the keyrings of the process mentioned there
551 * - we don't permit access to request_key auth keys via this method
553 if (ctx->cred->request_key_auth &&
554 ctx->cred == current_cred() &&
555 ctx->index_key.type != &key_type_request_key_auth
557 const struct cred *cred = ctx->cred;
559 if (key_validate(cred->request_key_auth) == 0) {
560 rka = ctx->cred->request_key_auth->payload.data[0];
562 //// was search_process_keyrings() [ie. recursive]
563 ctx->cred = rka->cred;
564 key_ref = search_cred_keyrings_rcu(ctx);
567 if (!IS_ERR(key_ref))
573 /* no key - decide on the error we're going to go for */
574 if (err == ERR_PTR(-ENOKEY) || ret == ERR_PTR(-ENOKEY))
575 key_ref = ERR_PTR(-ENOKEY);
576 else if (err == ERR_PTR(-EACCES))
585 * See if the key we're looking at is the target key.
587 bool lookup_user_key_possessed(const struct key *key,
588 const struct key_match_data *match_data)
590 return key == match_data->raw_data;
594 * Look up a key ID given us by userspace with a given permissions mask to get
595 * the key it refers to.
597 * Flags can be passed to request that special keyrings be created if referred
598 * to directly, to permit partially constructed keys to be found and to skip
599 * validity and permission checks on the found key.
601 * Returns a pointer to the key with an incremented usage count if successful;
602 * -EINVAL if the key ID is invalid; -ENOKEY if the key ID does not correspond
603 * to a key or the best found key was a negative key; -EKEYREVOKED or
604 * -EKEYEXPIRED if the best found key was revoked or expired; -EACCES if the
605 * found key doesn't grant the requested permit or the LSM denied access to it;
606 * or -ENOMEM if a special keyring couldn't be created.
608 * In the case of a successful return, the possession attribute is set on the
609 * returned key reference.
611 key_ref_t lookup_user_key(key_serial_t id, unsigned long lflags,
612 enum key_need_perm need_perm)
614 struct keyring_search_context ctx = {
615 .match_data.cmp = lookup_user_key_possessed,
616 .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT,
617 .flags = (KEYRING_SEARCH_NO_STATE_CHECK |
618 KEYRING_SEARCH_RECURSE),
620 struct request_key_auth *rka;
621 struct key *key, *user_session;
622 key_ref_t key_ref, skey_ref;
626 ctx.cred = get_current_cred();
627 key_ref = ERR_PTR(-ENOKEY);
630 case KEY_SPEC_THREAD_KEYRING:
631 if (!ctx.cred->thread_keyring) {
632 if (!(lflags & KEY_LOOKUP_CREATE))
635 ret = install_thread_keyring();
637 key_ref = ERR_PTR(ret);
643 key = ctx.cred->thread_keyring;
645 key_ref = make_key_ref(key, 1);
648 case KEY_SPEC_PROCESS_KEYRING:
649 if (!ctx.cred->process_keyring) {
650 if (!(lflags & KEY_LOOKUP_CREATE))
653 ret = install_process_keyring();
655 key_ref = ERR_PTR(ret);
661 key = ctx.cred->process_keyring;
663 key_ref = make_key_ref(key, 1);
666 case KEY_SPEC_SESSION_KEYRING:
667 if (!ctx.cred->session_keyring) {
668 /* always install a session keyring upon access if one
669 * doesn't exist yet */
670 ret = look_up_user_keyrings(NULL, &user_session);
673 if (lflags & KEY_LOOKUP_CREATE)
674 ret = join_session_keyring(NULL);
676 ret = install_session_keyring(user_session);
678 key_put(user_session);
682 } else if (test_bit(KEY_FLAG_UID_KEYRING,
683 &ctx.cred->session_keyring->flags) &&
684 lflags & KEY_LOOKUP_CREATE) {
685 ret = join_session_keyring(NULL);
691 key = ctx.cred->session_keyring;
693 key_ref = make_key_ref(key, 1);
696 case KEY_SPEC_USER_KEYRING:
697 ret = look_up_user_keyrings(&key, NULL);
700 key_ref = make_key_ref(key, 1);
703 case KEY_SPEC_USER_SESSION_KEYRING:
704 ret = look_up_user_keyrings(NULL, &key);
707 key_ref = make_key_ref(key, 1);
710 case KEY_SPEC_GROUP_KEYRING:
711 /* group keyrings are not yet supported */
712 key_ref = ERR_PTR(-EINVAL);
715 case KEY_SPEC_REQKEY_AUTH_KEY:
716 key = ctx.cred->request_key_auth;
721 key_ref = make_key_ref(key, 1);
724 case KEY_SPEC_REQUESTOR_KEYRING:
725 if (!ctx.cred->request_key_auth)
728 down_read(&ctx.cred->request_key_auth->sem);
729 if (test_bit(KEY_FLAG_REVOKED,
730 &ctx.cred->request_key_auth->flags)) {
731 key_ref = ERR_PTR(-EKEYREVOKED);
734 rka = ctx.cred->request_key_auth->payload.data[0];
735 key = rka->dest_keyring;
738 up_read(&ctx.cred->request_key_auth->sem);
741 key_ref = make_key_ref(key, 1);
745 key_ref = ERR_PTR(-EINVAL);
749 key = key_lookup(id);
751 key_ref = ERR_CAST(key);
755 key_ref = make_key_ref(key, 0);
757 /* check to see if we possess the key */
758 ctx.index_key = key->index_key;
759 ctx.match_data.raw_data = key;
760 kdebug("check possessed");
762 skey_ref = search_process_keyrings_rcu(&ctx);
764 kdebug("possessed=%p", skey_ref);
766 if (!IS_ERR(skey_ref)) {
774 /* unlink does not use the nominated key in any way, so can skip all
775 * the permission checks as it is only concerned with the keyring */
776 if (need_perm != KEY_NEED_UNLINK) {
777 if (!(lflags & KEY_LOOKUP_PARTIAL)) {
778 ret = wait_for_key_construction(key, true);
783 if (need_perm != KEY_AUTHTOKEN_OVERRIDE &&
784 need_perm != KEY_DEFER_PERM_CHECK)
790 } else if (need_perm != KEY_DEFER_PERM_CHECK) {
791 ret = key_validate(key);
797 if (!(lflags & KEY_LOOKUP_PARTIAL) &&
798 key_read_state(key) == KEY_IS_UNINSTANTIATED)
802 /* check the permissions */
803 ret = key_task_permission(key_ref, ctx.cred, need_perm);
807 key->last_used_at = ktime_get_real_seconds();
814 key_ref_put(key_ref);
815 key_ref = ERR_PTR(ret);
818 /* if we attempted to install a keyring, then it may have caused new
819 * creds to be installed */
824 EXPORT_SYMBOL(lookup_user_key);
827 * Join the named keyring as the session keyring if possible else attempt to
828 * create a new one of that name and join that.
830 * If the name is NULL, an empty anonymous keyring will be installed as the
833 * Named session keyrings are joined with a semaphore held to prevent the
834 * keyrings from going away whilst the attempt is made to going them and also
835 * to prevent a race in creating compatible session keyrings.
837 long join_session_keyring(const char *name)
839 const struct cred *old;
844 new = prepare_creds();
847 old = current_cred();
849 /* if no name is provided, install an anonymous keyring */
851 ret = install_session_keyring_to_cred(new, NULL);
855 serial = new->session_keyring->serial;
856 ret = commit_creds(new);
862 /* allow the user to join or create a named keyring */
863 mutex_lock(&key_session_mutex);
865 /* look for an existing keyring of this name */
866 keyring = find_keyring_by_name(name, false);
867 if (PTR_ERR(keyring) == -ENOKEY) {
868 /* not found - try and create a new one */
869 keyring = keyring_alloc(
870 name, old->uid, old->gid, old,
871 KEY_POS_ALL | KEY_USR_VIEW | KEY_USR_READ | KEY_USR_LINK,
872 KEY_ALLOC_IN_QUOTA, NULL, NULL);
873 if (IS_ERR(keyring)) {
874 ret = PTR_ERR(keyring);
877 } else if (IS_ERR(keyring)) {
878 ret = PTR_ERR(keyring);
880 } else if (keyring == new->session_keyring) {
885 /* we've got a keyring - now to install it */
886 ret = install_session_keyring_to_cred(new, keyring);
891 mutex_unlock(&key_session_mutex);
893 ret = keyring->serial;
901 mutex_unlock(&key_session_mutex);
908 * Replace a process's session keyring on behalf of one of its children when
909 * the target process is about to resume userspace execution.
911 void key_change_session_keyring(struct callback_head *twork)
913 const struct cred *old = current_cred();
914 struct cred *new = container_of(twork, struct cred, rcu);
916 if (unlikely(current->flags & PF_EXITING)) {
921 /* If get_ucounts fails more bits are needed in the refcount */
922 if (unlikely(!get_ucounts(old->ucounts))) {
923 WARN_ONCE(1, "In %s get_ucounts failed\n", __func__);
928 new-> uid = old-> uid;
929 new-> euid = old-> euid;
930 new-> suid = old-> suid;
931 new->fsuid = old->fsuid;
932 new-> gid = old-> gid;
933 new-> egid = old-> egid;
934 new-> sgid = old-> sgid;
935 new->fsgid = old->fsgid;
936 new->user = get_uid(old->user);
937 new->ucounts = old->ucounts;
938 new->user_ns = get_user_ns(old->user_ns);
939 new->group_info = get_group_info(old->group_info);
941 new->securebits = old->securebits;
942 new->cap_inheritable = old->cap_inheritable;
943 new->cap_permitted = old->cap_permitted;
944 new->cap_effective = old->cap_effective;
945 new->cap_ambient = old->cap_ambient;
946 new->cap_bset = old->cap_bset;
948 new->jit_keyring = old->jit_keyring;
949 new->thread_keyring = key_get(old->thread_keyring);
950 new->process_keyring = key_get(old->process_keyring);
952 security_transfer_creds(new, old);
958 * Make sure that root's user and user-session keyrings exist.
960 static int __init init_root_keyring(void)
962 return look_up_user_keyrings(NULL, NULL);
965 late_initcall(init_root_keyring);