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 */
22 * complete_request_key - Complete the construction of a key.
23 * @auth_key: The authorisation key.
24 * @error: The success or failute of the construction.
26 * Complete the attempt to construct a key. The key will be negated
27 * if an error is indicated. The authorisation key will be revoked
30 void complete_request_key(struct key *authkey, int error)
32 struct request_key_auth *rka = get_request_key_auth(authkey);
33 struct key *key = rka->target_key;
35 kenter("%d{%d},%d", authkey->serial, key->serial, error);
38 key_negate_and_link(key, key_negative_timeout, NULL, authkey);
42 EXPORT_SYMBOL(complete_request_key);
45 * Initialise a usermode helper that is going to have a specific session
48 * This is called in context of freshly forked kthread before kernel_execve(),
49 * so we can simply install the desired session_keyring at this point.
51 static int umh_keys_init(struct subprocess_info *info, struct cred *cred)
53 struct key *keyring = info->data;
55 return install_session_keyring_to_cred(cred, keyring);
59 * Clean up a usermode helper with session keyring.
61 static void umh_keys_cleanup(struct subprocess_info *info)
63 struct key *keyring = info->data;
68 * Call a usermode helper with a specific session keyring.
70 static int call_usermodehelper_keys(const char *path, char **argv, char **envp,
71 struct key *session_keyring, int wait)
73 struct subprocess_info *info;
75 info = call_usermodehelper_setup(path, argv, envp, GFP_KERNEL,
76 umh_keys_init, umh_keys_cleanup,
81 key_get(session_keyring);
82 return call_usermodehelper_exec(info, wait);
86 * Request userspace finish the construction of a key
87 * - execute "/sbin/request-key <op> <key> <uid> <gid> <keyring> <keyring> <keyring>"
89 static int call_sbin_request_key(struct key *authkey, void *aux)
91 static char const request_key[] = "/sbin/request-key";
92 struct request_key_auth *rka = get_request_key_auth(authkey);
93 const struct cred *cred = current_cred();
94 key_serial_t prkey, sskey;
95 struct key *key = rka->target_key, *keyring, *session;
96 char *argv[9], *envp[3], uid_str[12], gid_str[12];
97 char key_str[12], keyring_str[3][12];
101 kenter("{%d},{%d},%s", key->serial, authkey->serial, rka->op);
103 ret = install_user_keyrings();
107 /* allocate a new session keyring */
108 sprintf(desc, "_req.%u", key->serial);
110 cred = get_current_cred();
111 keyring = keyring_alloc(desc, cred->fsuid, cred->fsgid, cred,
112 KEY_POS_ALL | KEY_USR_VIEW | KEY_USR_READ,
113 KEY_ALLOC_QUOTA_OVERRUN, NULL, NULL);
115 if (IS_ERR(keyring)) {
116 ret = PTR_ERR(keyring);
120 /* attach the auth key to the session keyring */
121 ret = key_link(keyring, authkey);
125 /* record the UID and GID */
126 sprintf(uid_str, "%d", from_kuid(&init_user_ns, cred->fsuid));
127 sprintf(gid_str, "%d", from_kgid(&init_user_ns, cred->fsgid));
129 /* we say which key is under construction */
130 sprintf(key_str, "%d", key->serial);
132 /* we specify the process's default keyrings */
133 sprintf(keyring_str[0], "%d",
134 cred->thread_keyring ? cred->thread_keyring->serial : 0);
137 if (cred->process_keyring)
138 prkey = cred->process_keyring->serial;
139 sprintf(keyring_str[1], "%d", prkey);
141 session = cred->session_keyring;
143 session = cred->user->session_keyring;
144 sskey = session->serial;
146 sprintf(keyring_str[2], "%d", sskey);
148 /* set up a minimal environment */
150 envp[i++] = "HOME=/";
151 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
154 /* set up the argument list */
156 argv[i++] = (char *)request_key;
157 argv[i++] = (char *)rka->op;
161 argv[i++] = keyring_str[0];
162 argv[i++] = keyring_str[1];
163 argv[i++] = keyring_str[2];
167 ret = call_usermodehelper_keys(request_key, argv, envp, keyring,
169 kdebug("usermode -> 0x%x", ret);
171 /* ret is the exit/wait code */
172 if (test_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags) ||
173 key_validate(key) < 0)
176 /* ignore any errors from userspace if the key was
185 complete_request_key(authkey, ret);
186 kleave(" = %d", ret);
191 * Call out to userspace for key construction.
193 * Program failure is ignored in favour of key status.
195 static int construct_key(struct key *key, const void *callout_info,
196 size_t callout_len, void *aux,
197 struct key *dest_keyring)
199 request_key_actor_t actor;
203 kenter("%d,%p,%zu,%p", key->serial, callout_info, callout_len, aux);
205 /* allocate an authorisation key */
206 authkey = request_key_auth_new(key, "create", callout_info, callout_len,
209 return PTR_ERR(authkey);
212 actor = call_sbin_request_key;
213 if (key->type->request_key)
214 actor = key->type->request_key;
216 ret = actor(authkey, aux);
218 /* check that the actor called complete_request_key() prior to
219 * returning an error */
221 !test_bit(KEY_FLAG_REVOKED, &authkey->flags));
224 kleave(" = %d", ret);
229 * Get the appropriate destination keyring for the request.
231 * The keyring selected is returned with an extra reference upon it which the
232 * caller must release.
234 static int construct_get_dest_keyring(struct key **_dest_keyring)
236 struct request_key_auth *rka;
237 const struct cred *cred = current_cred();
238 struct key *dest_keyring = *_dest_keyring, *authkey;
241 kenter("%p", dest_keyring);
243 /* find the appropriate keyring */
245 /* the caller supplied one */
246 key_get(dest_keyring);
248 bool do_perm_check = true;
250 /* use a default keyring; falling through the cases until we
251 * find one that we actually have */
252 switch (cred->jit_keyring) {
253 case KEY_REQKEY_DEFL_DEFAULT:
254 case KEY_REQKEY_DEFL_REQUESTOR_KEYRING:
255 if (cred->request_key_auth) {
256 authkey = cred->request_key_auth;
257 down_read(&authkey->sem);
258 rka = get_request_key_auth(authkey);
259 if (!test_bit(KEY_FLAG_REVOKED,
262 key_get(rka->dest_keyring);
263 up_read(&authkey->sem);
265 do_perm_check = false;
271 case KEY_REQKEY_DEFL_THREAD_KEYRING:
272 dest_keyring = key_get(cred->thread_keyring);
277 case KEY_REQKEY_DEFL_PROCESS_KEYRING:
278 dest_keyring = key_get(cred->process_keyring);
283 case KEY_REQKEY_DEFL_SESSION_KEYRING:
284 dest_keyring = key_get(cred->session_keyring);
290 case KEY_REQKEY_DEFL_USER_SESSION_KEYRING:
292 key_get(READ_ONCE(cred->user->session_keyring));
295 case KEY_REQKEY_DEFL_USER_KEYRING:
297 key_get(READ_ONCE(cred->user->uid_keyring));
300 case KEY_REQKEY_DEFL_GROUP_KEYRING:
306 * Require Write permission on the keyring. This is essential
307 * because the default keyring may be the session keyring, and
308 * joining a keyring only requires Search permission.
310 * However, this check is skipped for the "requestor keyring" so
311 * that /sbin/request-key can itself use request_key() to add
312 * keys to the original requestor's destination keyring.
314 if (dest_keyring && do_perm_check) {
315 ret = key_permission(make_key_ref(dest_keyring, 1),
318 key_put(dest_keyring);
324 *_dest_keyring = dest_keyring;
325 kleave(" [dk %d]", key_serial(dest_keyring));
330 * Allocate a new key in under-construction state and attempt to link it in to
331 * the requested keyring.
333 * May return a key that's already under construction instead if there was a
334 * race between two thread calling request_key().
336 static int construct_alloc_key(struct keyring_search_context *ctx,
337 struct key *dest_keyring,
339 struct key_user *user,
342 struct assoc_array_edit *edit;
349 ctx->index_key.type->name, ctx->index_key.description);
352 mutex_lock(&user->cons_lock);
354 perm = KEY_POS_VIEW | KEY_POS_SEARCH | KEY_POS_LINK | KEY_POS_SETATTR;
355 perm |= KEY_USR_VIEW;
356 if (ctx->index_key.type->read)
357 perm |= KEY_POS_READ;
358 if (ctx->index_key.type == &key_type_keyring ||
359 ctx->index_key.type->update)
360 perm |= KEY_POS_WRITE;
362 key = key_alloc(ctx->index_key.type, ctx->index_key.description,
363 ctx->cred->fsuid, ctx->cred->fsgid, ctx->cred,
368 set_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags);
371 ret = __key_link_begin(dest_keyring, &ctx->index_key, &edit);
373 goto link_prealloc_failed;
376 /* attach the key to the destination keyring under lock, but we do need
377 * to do another check just in case someone beat us to it whilst we
378 * waited for locks */
379 mutex_lock(&key_construction_mutex);
381 key_ref = search_process_keyrings(ctx);
382 if (!IS_ERR(key_ref))
383 goto key_already_present;
386 __key_link(key, &edit);
388 mutex_unlock(&key_construction_mutex);
390 __key_link_end(dest_keyring, &ctx->index_key, edit);
391 mutex_unlock(&user->cons_lock);
393 kleave(" = 0 [%d]", key_serial(key));
396 /* the key is now present - we tell the caller that we found it by
397 * returning -EINPROGRESS */
400 mutex_unlock(&key_construction_mutex);
401 key = key_ref_to_ptr(key_ref);
403 ret = __key_link_check_live_key(dest_keyring, key);
405 __key_link(key, &edit);
406 __key_link_end(dest_keyring, &ctx->index_key, edit);
408 goto link_check_failed;
410 mutex_unlock(&user->cons_lock);
412 kleave(" = -EINPROGRESS [%d]", key_serial(key));
416 mutex_unlock(&user->cons_lock);
418 kleave(" = %d [linkcheck]", ret);
421 link_prealloc_failed:
422 mutex_unlock(&user->cons_lock);
424 kleave(" = %d [prelink]", ret);
428 mutex_unlock(&user->cons_lock);
429 kleave(" = %ld", PTR_ERR(key));
434 * Commence key construction.
436 static struct key *construct_key_and_link(struct keyring_search_context *ctx,
437 const char *callout_info,
440 struct key *dest_keyring,
443 struct key_user *user;
449 if (ctx->index_key.type == &key_type_keyring)
450 return ERR_PTR(-EPERM);
452 ret = construct_get_dest_keyring(&dest_keyring);
456 user = key_user_lookup(current_fsuid());
459 goto error_put_dest_keyring;
462 ret = construct_alloc_key(ctx, dest_keyring, flags, user, &key);
466 ret = construct_key(key, callout_info, callout_len, aux,
469 kdebug("cons failed");
470 goto construction_failed;
472 } else if (ret == -EINPROGRESS) {
475 goto error_put_dest_keyring;
478 key_put(dest_keyring);
479 kleave(" = key %d", key_serial(key));
483 key_negate_and_link(key, key_negative_timeout, NULL, NULL);
485 error_put_dest_keyring:
486 key_put(dest_keyring);
488 kleave(" = %d", ret);
493 * request_key_and_link - Request a key and cache it in a keyring.
494 * @type: The type of key we want.
495 * @description: The searchable description of the key.
496 * @callout_info: The data to pass to the instantiation upcall (or NULL).
497 * @callout_len: The length of callout_info.
498 * @aux: Auxiliary data for the upcall.
499 * @dest_keyring: Where to cache the key.
500 * @flags: Flags to key_alloc().
502 * A key matching the specified criteria is searched for in the process's
503 * keyrings and returned with its usage count incremented if found. Otherwise,
504 * if callout_info is not NULL, a key will be allocated and some service
505 * (probably in userspace) will be asked to instantiate it.
507 * If successfully found or created, the key will be linked to the destination
508 * keyring if one is provided.
510 * Returns a pointer to the key if successful; -EACCES, -ENOKEY, -EKEYREVOKED
511 * or -EKEYEXPIRED if an inaccessible, negative, revoked or expired key was
512 * found; -ENOKEY if no key was found and no @callout_info was given; -EDQUOT
513 * if insufficient key quota was available to create a new key; or -ENOMEM if
514 * insufficient memory was available.
516 * If the returned key was created, then it may still be under construction,
517 * and wait_for_key_construction() should be used to wait for that to complete.
519 struct key *request_key_and_link(struct key_type *type,
520 const char *description,
521 const void *callout_info,
524 struct key *dest_keyring,
527 struct keyring_search_context ctx = {
528 .index_key.type = type,
529 .index_key.description = description,
530 .index_key.desc_len = strlen(description),
531 .cred = current_cred(),
532 .match_data.cmp = key_default_cmp,
533 .match_data.raw_data = description,
534 .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT,
535 .flags = (KEYRING_SEARCH_DO_STATE_CHECK |
536 KEYRING_SEARCH_SKIP_EXPIRED),
542 kenter("%s,%s,%p,%zu,%p,%p,%lx",
543 ctx.index_key.type->name, ctx.index_key.description,
544 callout_info, callout_len, aux, dest_keyring, flags);
546 if (type->match_preparse) {
547 ret = type->match_preparse(&ctx.match_data);
554 /* search all the process keyrings for a key */
555 key_ref = search_process_keyrings(&ctx);
557 if (!IS_ERR(key_ref)) {
558 key = key_ref_to_ptr(key_ref);
560 ret = key_link(dest_keyring, key);
567 } else if (PTR_ERR(key_ref) != -EAGAIN) {
568 key = ERR_CAST(key_ref);
570 /* the search failed, but the keyrings were searchable, so we
571 * should consult userspace if we can */
572 key = ERR_PTR(-ENOKEY);
576 key = construct_key_and_link(&ctx, callout_info, callout_len,
577 aux, dest_keyring, flags);
581 if (type->match_free)
582 type->match_free(&ctx.match_data);
584 kleave(" = %p", key);
589 * wait_for_key_construction - Wait for construction of a key to complete
590 * @key: The key being waited for.
591 * @intr: Whether to wait interruptibly.
593 * Wait for a key to finish being constructed.
595 * Returns 0 if successful; -ERESTARTSYS if the wait was interrupted; -ENOKEY
596 * if the key was negated; or -EKEYREVOKED or -EKEYEXPIRED if the key was
597 * revoked or expired.
599 int wait_for_key_construction(struct key *key, bool intr)
603 ret = wait_on_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT,
604 intr ? TASK_INTERRUPTIBLE : TASK_UNINTERRUPTIBLE);
607 ret = key_read_state(key);
610 return key_validate(key);
612 EXPORT_SYMBOL(wait_for_key_construction);
615 * request_key - Request a key and wait for construction
616 * @type: Type of key.
617 * @description: The searchable description of the key.
618 * @callout_info: The data to pass to the instantiation upcall (or NULL).
620 * As for request_key_and_link() except that it does not add the returned key
621 * to a keyring if found, new keys are always allocated in the user's quota,
622 * the callout_info must be a NUL-terminated string and no auxiliary data can
625 * Furthermore, it then works as wait_for_key_construction() to wait for the
626 * completion of keys undergoing construction with a non-interruptible wait.
628 struct key *request_key(struct key_type *type,
629 const char *description,
630 const char *callout_info)
633 size_t callout_len = 0;
637 callout_len = strlen(callout_info);
638 key = request_key_and_link(type, description, callout_info, callout_len,
639 NULL, NULL, KEY_ALLOC_IN_QUOTA);
641 ret = wait_for_key_construction(key, false);
649 EXPORT_SYMBOL(request_key);
652 * request_key_with_auxdata - Request a key with auxiliary data for the upcaller
653 * @type: The type of key we want.
654 * @description: The searchable description of the key.
655 * @callout_info: The data to pass to the instantiation upcall (or NULL).
656 * @callout_len: The length of callout_info.
657 * @aux: Auxiliary data for the upcall.
659 * As for request_key_and_link() except that it does not add the returned key
660 * to a keyring if found and new keys are always allocated in the user's quota.
662 * Furthermore, it then works as wait_for_key_construction() to wait for the
663 * completion of keys undergoing construction with a non-interruptible wait.
665 struct key *request_key_with_auxdata(struct key_type *type,
666 const char *description,
667 const void *callout_info,
674 key = request_key_and_link(type, description, callout_info, callout_len,
675 aux, NULL, KEY_ALLOC_IN_QUOTA);
677 ret = wait_for_key_construction(key, false);
685 EXPORT_SYMBOL(request_key_with_auxdata);
688 * request_key_async - Request a key (allow async construction)
689 * @type: Type of key.
690 * @description: The searchable description of the key.
691 * @callout_info: The data to pass to the instantiation upcall (or NULL).
692 * @callout_len: The length of callout_info.
694 * As for request_key_and_link() except that it does not add the returned key
695 * to a keyring if found, new keys are always allocated in the user's quota and
696 * no auxiliary data can be passed.
698 * The caller should call wait_for_key_construction() to wait for the
699 * completion of the returned key if it is still undergoing construction.
701 struct key *request_key_async(struct key_type *type,
702 const char *description,
703 const void *callout_info,
706 return request_key_and_link(type, description, callout_info,
707 callout_len, NULL, NULL,
710 EXPORT_SYMBOL(request_key_async);
713 * request a key with auxiliary data for the upcaller (allow async construction)
714 * @type: Type of key.
715 * @description: The searchable description of the key.
716 * @callout_info: The data to pass to the instantiation upcall (or NULL).
717 * @callout_len: The length of callout_info.
718 * @aux: Auxiliary data for the upcall.
720 * As for request_key_and_link() except that it does not add the returned key
721 * to a keyring if found and new keys are always allocated in the user's quota.
723 * The caller should call wait_for_key_construction() to wait for the
724 * completion of the returned key if it is still undergoing construction.
726 struct key *request_key_async_with_auxdata(struct key_type *type,
727 const char *description,
728 const void *callout_info,
732 return request_key_and_link(type, description, callout_info,
733 callout_len, aux, NULL, KEY_ALLOC_IN_QUOTA);
735 EXPORT_SYMBOL(request_key_async_with_auxdata);