1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /* Request a key from userspace
4 * Copyright (C) 2004-2007 Red Hat, Inc. All Rights Reserved.
5 * Written by David Howells (dhowells@redhat.com)
7 * See Documentation/security/keys/request-key.rst
10 #include <linux/export.h>
11 #include <linux/sched.h>
12 #include <linux/kmod.h>
13 #include <linux/err.h>
14 #include <linux/keyctl.h>
15 #include <linux/slab.h>
17 #include <keys/request_key_auth-type.h>
19 #define key_negative_timeout 60 /* default timeout on a negative key's existence */
21 static struct key *check_cached_key(struct keyring_search_context *ctx)
23 #ifdef CONFIG_KEYS_REQUEST_CACHE
24 struct key *key = current->cached_requested_key;
27 ctx->match_data.cmp(key, &ctx->match_data) &&
28 !(key->flags & ((1 << KEY_FLAG_INVALIDATED) |
29 (1 << KEY_FLAG_REVOKED))))
35 static void cache_requested_key(struct key *key)
37 #ifdef CONFIG_KEYS_REQUEST_CACHE
38 struct task_struct *t = current;
40 key_put(t->cached_requested_key);
41 t->cached_requested_key = key_get(key);
42 set_tsk_thread_flag(t, TIF_NOTIFY_RESUME);
47 * complete_request_key - Complete the construction of a key.
48 * @authkey: The authorisation key.
49 * @error: The success or failute of the construction.
51 * Complete the attempt to construct a key. The key will be negated
52 * if an error is indicated. The authorisation key will be revoked
55 void complete_request_key(struct key *authkey, int error)
57 struct request_key_auth *rka = get_request_key_auth(authkey);
58 struct key *key = rka->target_key;
60 kenter("%d{%d},%d", authkey->serial, key->serial, error);
63 key_negate_and_link(key, key_negative_timeout, NULL, authkey);
67 EXPORT_SYMBOL(complete_request_key);
70 * Initialise a usermode helper that is going to have a specific session
73 * This is called in context of freshly forked kthread before kernel_execve(),
74 * so we can simply install the desired session_keyring at this point.
76 static int umh_keys_init(struct subprocess_info *info, struct cred *cred)
78 struct key *keyring = info->data;
80 return install_session_keyring_to_cred(cred, keyring);
84 * Clean up a usermode helper with session keyring.
86 static void umh_keys_cleanup(struct subprocess_info *info)
88 struct key *keyring = info->data;
93 * Call a usermode helper with a specific session keyring.
95 static int call_usermodehelper_keys(const char *path, char **argv, char **envp,
96 struct key *session_keyring, int wait)
98 struct subprocess_info *info;
100 info = call_usermodehelper_setup(path, argv, envp, GFP_KERNEL,
101 umh_keys_init, umh_keys_cleanup,
106 key_get(session_keyring);
107 return call_usermodehelper_exec(info, wait);
111 * Request userspace finish the construction of a key
112 * - execute "/sbin/request-key <op> <key> <uid> <gid> <keyring> <keyring> <keyring>"
114 static int call_sbin_request_key(struct key *authkey, void *aux)
116 static char const request_key[] = "/sbin/request-key";
117 struct request_key_auth *rka = get_request_key_auth(authkey);
118 const struct cred *cred = current_cred();
119 key_serial_t prkey, sskey;
120 struct key *key = rka->target_key, *keyring, *session;
121 char *argv[9], *envp[3], uid_str[12], gid_str[12];
122 char key_str[12], keyring_str[3][12];
126 kenter("{%d},{%d},%s", key->serial, authkey->serial, rka->op);
128 ret = install_user_keyrings();
132 /* allocate a new session keyring */
133 sprintf(desc, "_req.%u", key->serial);
135 cred = get_current_cred();
136 keyring = keyring_alloc(desc, cred->fsuid, cred->fsgid, cred,
137 KEY_POS_ALL | KEY_USR_VIEW | KEY_USR_READ,
138 KEY_ALLOC_QUOTA_OVERRUN, NULL, NULL);
140 if (IS_ERR(keyring)) {
141 ret = PTR_ERR(keyring);
145 /* attach the auth key to the session keyring */
146 ret = key_link(keyring, authkey);
150 /* record the UID and GID */
151 sprintf(uid_str, "%d", from_kuid(&init_user_ns, cred->fsuid));
152 sprintf(gid_str, "%d", from_kgid(&init_user_ns, cred->fsgid));
154 /* we say which key is under construction */
155 sprintf(key_str, "%d", key->serial);
157 /* we specify the process's default keyrings */
158 sprintf(keyring_str[0], "%d",
159 cred->thread_keyring ? cred->thread_keyring->serial : 0);
162 if (cred->process_keyring)
163 prkey = cred->process_keyring->serial;
164 sprintf(keyring_str[1], "%d", prkey);
166 session = cred->session_keyring;
168 session = cred->user->session_keyring;
169 sskey = session->serial;
171 sprintf(keyring_str[2], "%d", sskey);
173 /* set up a minimal environment */
175 envp[i++] = "HOME=/";
176 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
179 /* set up the argument list */
181 argv[i++] = (char *)request_key;
182 argv[i++] = (char *)rka->op;
186 argv[i++] = keyring_str[0];
187 argv[i++] = keyring_str[1];
188 argv[i++] = keyring_str[2];
192 ret = call_usermodehelper_keys(request_key, argv, envp, keyring,
194 kdebug("usermode -> 0x%x", ret);
196 /* ret is the exit/wait code */
197 if (test_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags) ||
198 key_validate(key) < 0)
201 /* ignore any errors from userspace if the key was
210 complete_request_key(authkey, ret);
211 kleave(" = %d", ret);
216 * Call out to userspace for key construction.
218 * Program failure is ignored in favour of key status.
220 static int construct_key(struct key *key, const void *callout_info,
221 size_t callout_len, void *aux,
222 struct key *dest_keyring)
224 request_key_actor_t actor;
228 kenter("%d,%p,%zu,%p", key->serial, callout_info, callout_len, aux);
230 /* allocate an authorisation key */
231 authkey = request_key_auth_new(key, "create", callout_info, callout_len,
234 return PTR_ERR(authkey);
237 actor = call_sbin_request_key;
238 if (key->type->request_key)
239 actor = key->type->request_key;
241 ret = actor(authkey, aux);
243 /* check that the actor called complete_request_key() prior to
244 * returning an error */
246 !test_bit(KEY_FLAG_INVALIDATED, &authkey->flags));
249 kleave(" = %d", ret);
254 * Get the appropriate destination keyring for the request.
256 * The keyring selected is returned with an extra reference upon it which the
257 * caller must release.
259 static int construct_get_dest_keyring(struct key **_dest_keyring)
261 struct request_key_auth *rka;
262 const struct cred *cred = current_cred();
263 struct key *dest_keyring = *_dest_keyring, *authkey;
266 kenter("%p", dest_keyring);
268 /* find the appropriate keyring */
270 /* the caller supplied one */
271 key_get(dest_keyring);
273 bool do_perm_check = true;
275 /* use a default keyring; falling through the cases until we
276 * find one that we actually have */
277 switch (cred->jit_keyring) {
278 case KEY_REQKEY_DEFL_DEFAULT:
279 case KEY_REQKEY_DEFL_REQUESTOR_KEYRING:
280 if (cred->request_key_auth) {
281 authkey = cred->request_key_auth;
282 down_read(&authkey->sem);
283 rka = get_request_key_auth(authkey);
284 if (!test_bit(KEY_FLAG_REVOKED,
287 key_get(rka->dest_keyring);
288 up_read(&authkey->sem);
290 do_perm_check = false;
296 case KEY_REQKEY_DEFL_THREAD_KEYRING:
297 dest_keyring = key_get(cred->thread_keyring);
302 case KEY_REQKEY_DEFL_PROCESS_KEYRING:
303 dest_keyring = key_get(cred->process_keyring);
308 case KEY_REQKEY_DEFL_SESSION_KEYRING:
309 dest_keyring = key_get(cred->session_keyring);
315 case KEY_REQKEY_DEFL_USER_SESSION_KEYRING:
317 key_get(READ_ONCE(cred->user->session_keyring));
320 case KEY_REQKEY_DEFL_USER_KEYRING:
322 key_get(READ_ONCE(cred->user->uid_keyring));
325 case KEY_REQKEY_DEFL_GROUP_KEYRING:
331 * Require Write permission on the keyring. This is essential
332 * because the default keyring may be the session keyring, and
333 * joining a keyring only requires Search permission.
335 * However, this check is skipped for the "requestor keyring" so
336 * that /sbin/request-key can itself use request_key() to add
337 * keys to the original requestor's destination keyring.
339 if (dest_keyring && do_perm_check) {
340 ret = key_permission(make_key_ref(dest_keyring, 1),
343 key_put(dest_keyring);
349 *_dest_keyring = dest_keyring;
350 kleave(" [dk %d]", key_serial(dest_keyring));
355 * Allocate a new key in under-construction state and attempt to link it in to
356 * the requested keyring.
358 * May return a key that's already under construction instead if there was a
359 * race between two thread calling request_key().
361 static int construct_alloc_key(struct keyring_search_context *ctx,
362 struct key *dest_keyring,
364 struct key_user *user,
367 struct assoc_array_edit *edit = NULL;
374 ctx->index_key.type->name, ctx->index_key.description);
377 mutex_lock(&user->cons_lock);
379 perm = KEY_POS_VIEW | KEY_POS_SEARCH | KEY_POS_LINK | KEY_POS_SETATTR;
380 perm |= KEY_USR_VIEW;
381 if (ctx->index_key.type->read)
382 perm |= KEY_POS_READ;
383 if (ctx->index_key.type == &key_type_keyring ||
384 ctx->index_key.type->update)
385 perm |= KEY_POS_WRITE;
387 key = key_alloc(ctx->index_key.type, ctx->index_key.description,
388 ctx->cred->fsuid, ctx->cred->fsgid, ctx->cred,
393 set_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags);
396 ret = __key_link_lock(dest_keyring, &ctx->index_key);
398 goto link_lock_failed;
399 ret = __key_link_begin(dest_keyring, &ctx->index_key, &edit);
401 goto link_prealloc_failed;
404 /* attach the key to the destination keyring under lock, but we do need
405 * to do another check just in case someone beat us to it whilst we
406 * waited for locks */
407 mutex_lock(&key_construction_mutex);
410 key_ref = search_process_keyrings_rcu(ctx);
412 if (!IS_ERR(key_ref))
413 goto key_already_present;
416 __key_link(key, &edit);
418 mutex_unlock(&key_construction_mutex);
420 __key_link_end(dest_keyring, &ctx->index_key, edit);
421 mutex_unlock(&user->cons_lock);
423 kleave(" = 0 [%d]", key_serial(key));
426 /* the key is now present - we tell the caller that we found it by
427 * returning -EINPROGRESS */
430 mutex_unlock(&key_construction_mutex);
431 key = key_ref_to_ptr(key_ref);
433 ret = __key_link_check_live_key(dest_keyring, key);
435 __key_link(key, &edit);
436 __key_link_end(dest_keyring, &ctx->index_key, edit);
438 goto link_check_failed;
440 mutex_unlock(&user->cons_lock);
442 kleave(" = -EINPROGRESS [%d]", key_serial(key));
446 mutex_unlock(&user->cons_lock);
448 kleave(" = %d [linkcheck]", ret);
451 link_prealloc_failed:
452 __key_link_end(dest_keyring, &ctx->index_key, edit);
454 mutex_unlock(&user->cons_lock);
456 kleave(" = %d [prelink]", ret);
460 mutex_unlock(&user->cons_lock);
461 kleave(" = %ld", PTR_ERR(key));
466 * Commence key construction.
468 static struct key *construct_key_and_link(struct keyring_search_context *ctx,
469 const char *callout_info,
472 struct key *dest_keyring,
475 struct key_user *user;
481 if (ctx->index_key.type == &key_type_keyring)
482 return ERR_PTR(-EPERM);
484 ret = construct_get_dest_keyring(&dest_keyring);
488 user = key_user_lookup(current_fsuid());
491 goto error_put_dest_keyring;
494 ret = construct_alloc_key(ctx, dest_keyring, flags, user, &key);
498 ret = construct_key(key, callout_info, callout_len, aux,
501 kdebug("cons failed");
502 goto construction_failed;
504 } else if (ret == -EINPROGRESS) {
507 goto error_put_dest_keyring;
510 key_put(dest_keyring);
511 kleave(" = key %d", key_serial(key));
515 key_negate_and_link(key, key_negative_timeout, NULL, NULL);
517 error_put_dest_keyring:
518 key_put(dest_keyring);
520 kleave(" = %d", ret);
525 * request_key_and_link - Request a key and cache it in a keyring.
526 * @type: The type of key we want.
527 * @description: The searchable description of the key.
528 * @callout_info: The data to pass to the instantiation upcall (or NULL).
529 * @callout_len: The length of callout_info.
530 * @aux: Auxiliary data for the upcall.
531 * @dest_keyring: Where to cache the key.
532 * @flags: Flags to key_alloc().
534 * A key matching the specified criteria is searched for in the process's
535 * keyrings and returned with its usage count incremented if found. Otherwise,
536 * if callout_info is not NULL, a key will be allocated and some service
537 * (probably in userspace) will be asked to instantiate it.
539 * If successfully found or created, the key will be linked to the destination
540 * keyring if one is provided.
542 * Returns a pointer to the key if successful; -EACCES, -ENOKEY, -EKEYREVOKED
543 * or -EKEYEXPIRED if an inaccessible, negative, revoked or expired key was
544 * found; -ENOKEY if no key was found and no @callout_info was given; -EDQUOT
545 * if insufficient key quota was available to create a new key; or -ENOMEM if
546 * insufficient memory was available.
548 * If the returned key was created, then it may still be under construction,
549 * and wait_for_key_construction() should be used to wait for that to complete.
551 struct key *request_key_and_link(struct key_type *type,
552 const char *description,
553 const void *callout_info,
556 struct key *dest_keyring,
559 struct keyring_search_context ctx = {
560 .index_key.type = type,
561 .index_key.description = description,
562 .index_key.desc_len = strlen(description),
563 .cred = current_cred(),
564 .match_data.cmp = key_default_cmp,
565 .match_data.raw_data = description,
566 .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT,
567 .flags = (KEYRING_SEARCH_DO_STATE_CHECK |
568 KEYRING_SEARCH_SKIP_EXPIRED),
574 kenter("%s,%s,%p,%zu,%p,%p,%lx",
575 ctx.index_key.type->name, ctx.index_key.description,
576 callout_info, callout_len, aux, dest_keyring, flags);
578 if (type->match_preparse) {
579 ret = type->match_preparse(&ctx.match_data);
586 key = check_cached_key(&ctx);
590 /* search all the process keyrings for a key */
592 key_ref = search_process_keyrings_rcu(&ctx);
595 if (!IS_ERR(key_ref)) {
597 ret = key_task_permission(key_ref, current_cred(),
600 key_ref_put(key_ref);
606 key = key_ref_to_ptr(key_ref);
608 ret = key_link(dest_keyring, key);
616 /* Only cache the key on immediate success */
617 cache_requested_key(key);
618 } else if (PTR_ERR(key_ref) != -EAGAIN) {
619 key = ERR_CAST(key_ref);
621 /* the search failed, but the keyrings were searchable, so we
622 * should consult userspace if we can */
623 key = ERR_PTR(-ENOKEY);
627 key = construct_key_and_link(&ctx, callout_info, callout_len,
628 aux, dest_keyring, flags);
632 if (type->match_free)
633 type->match_free(&ctx.match_data);
635 kleave(" = %p", key);
640 * wait_for_key_construction - Wait for construction of a key to complete
641 * @key: The key being waited for.
642 * @intr: Whether to wait interruptibly.
644 * Wait for a key to finish being constructed.
646 * Returns 0 if successful; -ERESTARTSYS if the wait was interrupted; -ENOKEY
647 * if the key was negated; or -EKEYREVOKED or -EKEYEXPIRED if the key was
648 * revoked or expired.
650 int wait_for_key_construction(struct key *key, bool intr)
654 ret = wait_on_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT,
655 intr ? TASK_INTERRUPTIBLE : TASK_UNINTERRUPTIBLE);
658 ret = key_read_state(key);
661 return key_validate(key);
663 EXPORT_SYMBOL(wait_for_key_construction);
666 * request_key - Request a key and wait for construction
667 * @type: Type of key.
668 * @description: The searchable description of the key.
669 * @callout_info: The data to pass to the instantiation upcall (or NULL).
671 * As for request_key_and_link() except that it does not add the returned key
672 * to a keyring if found, new keys are always allocated in the user's quota,
673 * the callout_info must be a NUL-terminated string and no auxiliary data can
676 * Furthermore, it then works as wait_for_key_construction() to wait for the
677 * completion of keys undergoing construction with a non-interruptible wait.
679 struct key *request_key(struct key_type *type,
680 const char *description,
681 const char *callout_info)
684 size_t callout_len = 0;
688 callout_len = strlen(callout_info);
689 key = request_key_and_link(type, description, callout_info, callout_len,
690 NULL, NULL, KEY_ALLOC_IN_QUOTA);
692 ret = wait_for_key_construction(key, false);
700 EXPORT_SYMBOL(request_key);
703 * request_key_with_auxdata - Request a key with auxiliary data for the upcaller
704 * @type: The type of key we want.
705 * @description: The searchable description of the key.
706 * @callout_info: The data to pass to the instantiation upcall (or NULL).
707 * @callout_len: The length of callout_info.
708 * @aux: Auxiliary data for the upcall.
710 * As for request_key_and_link() except that it does not add the returned key
711 * to a keyring if found and new keys are always allocated in the user's quota.
713 * Furthermore, it then works as wait_for_key_construction() to wait for the
714 * completion of keys undergoing construction with a non-interruptible wait.
716 struct key *request_key_with_auxdata(struct key_type *type,
717 const char *description,
718 const void *callout_info,
725 key = request_key_and_link(type, description, callout_info, callout_len,
726 aux, NULL, KEY_ALLOC_IN_QUOTA);
728 ret = wait_for_key_construction(key, false);
736 EXPORT_SYMBOL(request_key_with_auxdata);
739 * request_key_rcu - Request key from RCU-read-locked context
740 * @type: The type of key we want.
741 * @description: The name of the key we want.
743 * Request a key from a context that we may not sleep in (such as RCU-mode
744 * pathwalk). Keys under construction are ignored.
746 * Return a pointer to the found key if successful, -ENOKEY if we couldn't find
747 * a key or some other error if the key found was unsuitable or inaccessible.
749 struct key *request_key_rcu(struct key_type *type, const char *description)
751 struct keyring_search_context ctx = {
752 .index_key.type = type,
753 .index_key.description = description,
754 .index_key.desc_len = strlen(description),
755 .cred = current_cred(),
756 .match_data.cmp = key_default_cmp,
757 .match_data.raw_data = description,
758 .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT,
759 .flags = (KEYRING_SEARCH_DO_STATE_CHECK |
760 KEYRING_SEARCH_SKIP_EXPIRED),
765 kenter("%s,%s", type->name, description);
767 key = check_cached_key(&ctx);
771 /* search all the process keyrings for a key */
772 key_ref = search_process_keyrings_rcu(&ctx);
773 if (IS_ERR(key_ref)) {
774 key = ERR_CAST(key_ref);
775 if (PTR_ERR(key_ref) == -EAGAIN)
776 key = ERR_PTR(-ENOKEY);
778 key = key_ref_to_ptr(key_ref);
779 cache_requested_key(key);
782 kleave(" = %p", key);
785 EXPORT_SYMBOL(request_key_rcu);