Linux kernel mirror (for testing)
git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel
os
linux
1// SPDX-License-Identifier: GPL-2.0-or-later
2/* Request a key from userspace
3 *
4 * Copyright (C) 2004-2007 Red Hat, Inc. All Rights Reserved.
5 * Written by David Howells (dhowells@redhat.com)
6 *
7 * See Documentation/security/keys/request-key.rst
8 */
9
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>
16#include "internal.h"
17#include <keys/request_key_auth-type.h>
18
19#define key_negative_timeout 60 /* default timeout on a negative key's existence */
20
21/**
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.
25 *
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
28 * unconditionally.
29 */
30void complete_request_key(struct key *authkey, int error)
31{
32 struct request_key_auth *rka = get_request_key_auth(authkey);
33 struct key *key = rka->target_key;
34
35 kenter("%d{%d},%d", authkey->serial, key->serial, error);
36
37 if (error < 0)
38 key_negate_and_link(key, key_negative_timeout, NULL, authkey);
39 else
40 key_revoke(authkey);
41}
42EXPORT_SYMBOL(complete_request_key);
43
44/*
45 * Initialise a usermode helper that is going to have a specific session
46 * keyring.
47 *
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.
50 */
51static int umh_keys_init(struct subprocess_info *info, struct cred *cred)
52{
53 struct key *keyring = info->data;
54
55 return install_session_keyring_to_cred(cred, keyring);
56}
57
58/*
59 * Clean up a usermode helper with session keyring.
60 */
61static void umh_keys_cleanup(struct subprocess_info *info)
62{
63 struct key *keyring = info->data;
64 key_put(keyring);
65}
66
67/*
68 * Call a usermode helper with a specific session keyring.
69 */
70static int call_usermodehelper_keys(const char *path, char **argv, char **envp,
71 struct key *session_keyring, int wait)
72{
73 struct subprocess_info *info;
74
75 info = call_usermodehelper_setup(path, argv, envp, GFP_KERNEL,
76 umh_keys_init, umh_keys_cleanup,
77 session_keyring);
78 if (!info)
79 return -ENOMEM;
80
81 key_get(session_keyring);
82 return call_usermodehelper_exec(info, wait);
83}
84
85/*
86 * Request userspace finish the construction of a key
87 * - execute "/sbin/request-key <op> <key> <uid> <gid> <keyring> <keyring> <keyring>"
88 */
89static int call_sbin_request_key(struct key *authkey, void *aux)
90{
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];
98 char desc[20];
99 int ret, i;
100
101 kenter("{%d},{%d},%s", key->serial, authkey->serial, rka->op);
102
103 ret = install_user_keyrings();
104 if (ret < 0)
105 goto error_alloc;
106
107 /* allocate a new session keyring */
108 sprintf(desc, "_req.%u", key->serial);
109
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);
114 put_cred(cred);
115 if (IS_ERR(keyring)) {
116 ret = PTR_ERR(keyring);
117 goto error_alloc;
118 }
119
120 /* attach the auth key to the session keyring */
121 ret = key_link(keyring, authkey);
122 if (ret < 0)
123 goto error_link;
124
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));
128
129 /* we say which key is under construction */
130 sprintf(key_str, "%d", key->serial);
131
132 /* we specify the process's default keyrings */
133 sprintf(keyring_str[0], "%d",
134 cred->thread_keyring ? cred->thread_keyring->serial : 0);
135
136 prkey = 0;
137 if (cred->process_keyring)
138 prkey = cred->process_keyring->serial;
139 sprintf(keyring_str[1], "%d", prkey);
140
141 session = cred->session_keyring;
142 if (!session)
143 session = cred->user->session_keyring;
144 sskey = session->serial;
145
146 sprintf(keyring_str[2], "%d", sskey);
147
148 /* set up a minimal environment */
149 i = 0;
150 envp[i++] = "HOME=/";
151 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
152 envp[i] = NULL;
153
154 /* set up the argument list */
155 i = 0;
156 argv[i++] = (char *)request_key;
157 argv[i++] = (char *)rka->op;
158 argv[i++] = key_str;
159 argv[i++] = uid_str;
160 argv[i++] = gid_str;
161 argv[i++] = keyring_str[0];
162 argv[i++] = keyring_str[1];
163 argv[i++] = keyring_str[2];
164 argv[i] = NULL;
165
166 /* do it */
167 ret = call_usermodehelper_keys(request_key, argv, envp, keyring,
168 UMH_WAIT_PROC);
169 kdebug("usermode -> 0x%x", ret);
170 if (ret >= 0) {
171 /* ret is the exit/wait code */
172 if (test_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags) ||
173 key_validate(key) < 0)
174 ret = -ENOKEY;
175 else
176 /* ignore any errors from userspace if the key was
177 * instantiated */
178 ret = 0;
179 }
180
181error_link:
182 key_put(keyring);
183
184error_alloc:
185 complete_request_key(authkey, ret);
186 kleave(" = %d", ret);
187 return ret;
188}
189
190/*
191 * Call out to userspace for key construction.
192 *
193 * Program failure is ignored in favour of key status.
194 */
195static int construct_key(struct key *key, const void *callout_info,
196 size_t callout_len, void *aux,
197 struct key *dest_keyring)
198{
199 request_key_actor_t actor;
200 struct key *authkey;
201 int ret;
202
203 kenter("%d,%p,%zu,%p", key->serial, callout_info, callout_len, aux);
204
205 /* allocate an authorisation key */
206 authkey = request_key_auth_new(key, "create", callout_info, callout_len,
207 dest_keyring);
208 if (IS_ERR(authkey))
209 return PTR_ERR(authkey);
210
211 /* Make the call */
212 actor = call_sbin_request_key;
213 if (key->type->request_key)
214 actor = key->type->request_key;
215
216 ret = actor(authkey, aux);
217
218 /* check that the actor called complete_request_key() prior to
219 * returning an error */
220 WARN_ON(ret < 0 &&
221 !test_bit(KEY_FLAG_REVOKED, &authkey->flags));
222
223 key_put(authkey);
224 kleave(" = %d", ret);
225 return ret;
226}
227
228/*
229 * Get the appropriate destination keyring for the request.
230 *
231 * The keyring selected is returned with an extra reference upon it which the
232 * caller must release.
233 */
234static int construct_get_dest_keyring(struct key **_dest_keyring)
235{
236 struct request_key_auth *rka;
237 const struct cred *cred = current_cred();
238 struct key *dest_keyring = *_dest_keyring, *authkey;
239 int ret;
240
241 kenter("%p", dest_keyring);
242
243 /* find the appropriate keyring */
244 if (dest_keyring) {
245 /* the caller supplied one */
246 key_get(dest_keyring);
247 } else {
248 bool do_perm_check = true;
249
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,
260 &authkey->flags))
261 dest_keyring =
262 key_get(rka->dest_keyring);
263 up_read(&authkey->sem);
264 if (dest_keyring) {
265 do_perm_check = false;
266 break;
267 }
268 }
269
270 /* fall through */
271 case KEY_REQKEY_DEFL_THREAD_KEYRING:
272 dest_keyring = key_get(cred->thread_keyring);
273 if (dest_keyring)
274 break;
275
276 /* fall through */
277 case KEY_REQKEY_DEFL_PROCESS_KEYRING:
278 dest_keyring = key_get(cred->process_keyring);
279 if (dest_keyring)
280 break;
281
282 /* fall through */
283 case KEY_REQKEY_DEFL_SESSION_KEYRING:
284 dest_keyring = key_get(cred->session_keyring);
285
286 if (dest_keyring)
287 break;
288
289 /* fall through */
290 case KEY_REQKEY_DEFL_USER_SESSION_KEYRING:
291 dest_keyring =
292 key_get(READ_ONCE(cred->user->session_keyring));
293 break;
294
295 case KEY_REQKEY_DEFL_USER_KEYRING:
296 dest_keyring =
297 key_get(READ_ONCE(cred->user->uid_keyring));
298 break;
299
300 case KEY_REQKEY_DEFL_GROUP_KEYRING:
301 default:
302 BUG();
303 }
304
305 /*
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.
309 *
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.
313 */
314 if (dest_keyring && do_perm_check) {
315 ret = key_permission(make_key_ref(dest_keyring, 1),
316 KEY_NEED_WRITE);
317 if (ret) {
318 key_put(dest_keyring);
319 return ret;
320 }
321 }
322 }
323
324 *_dest_keyring = dest_keyring;
325 kleave(" [dk %d]", key_serial(dest_keyring));
326 return 0;
327}
328
329/*
330 * Allocate a new key in under-construction state and attempt to link it in to
331 * the requested keyring.
332 *
333 * May return a key that's already under construction instead if there was a
334 * race between two thread calling request_key().
335 */
336static int construct_alloc_key(struct keyring_search_context *ctx,
337 struct key *dest_keyring,
338 unsigned long flags,
339 struct key_user *user,
340 struct key **_key)
341{
342 struct assoc_array_edit *edit;
343 struct key *key;
344 key_perm_t perm;
345 key_ref_t key_ref;
346 int ret;
347
348 kenter("%s,%s,,,",
349 ctx->index_key.type->name, ctx->index_key.description);
350
351 *_key = NULL;
352 mutex_lock(&user->cons_lock);
353
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;
361
362 key = key_alloc(ctx->index_key.type, ctx->index_key.description,
363 ctx->cred->fsuid, ctx->cred->fsgid, ctx->cred,
364 perm, flags, NULL);
365 if (IS_ERR(key))
366 goto alloc_failed;
367
368 set_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags);
369
370 if (dest_keyring) {
371 ret = __key_link_begin(dest_keyring, &ctx->index_key, &edit);
372 if (ret < 0)
373 goto link_prealloc_failed;
374 }
375
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);
380
381 key_ref = search_process_keyrings(ctx);
382 if (!IS_ERR(key_ref))
383 goto key_already_present;
384
385 if (dest_keyring)
386 __key_link(key, &edit);
387
388 mutex_unlock(&key_construction_mutex);
389 if (dest_keyring)
390 __key_link_end(dest_keyring, &ctx->index_key, edit);
391 mutex_unlock(&user->cons_lock);
392 *_key = key;
393 kleave(" = 0 [%d]", key_serial(key));
394 return 0;
395
396 /* the key is now present - we tell the caller that we found it by
397 * returning -EINPROGRESS */
398key_already_present:
399 key_put(key);
400 mutex_unlock(&key_construction_mutex);
401 key = key_ref_to_ptr(key_ref);
402 if (dest_keyring) {
403 ret = __key_link_check_live_key(dest_keyring, key);
404 if (ret == 0)
405 __key_link(key, &edit);
406 __key_link_end(dest_keyring, &ctx->index_key, edit);
407 if (ret < 0)
408 goto link_check_failed;
409 }
410 mutex_unlock(&user->cons_lock);
411 *_key = key;
412 kleave(" = -EINPROGRESS [%d]", key_serial(key));
413 return -EINPROGRESS;
414
415link_check_failed:
416 mutex_unlock(&user->cons_lock);
417 key_put(key);
418 kleave(" = %d [linkcheck]", ret);
419 return ret;
420
421link_prealloc_failed:
422 mutex_unlock(&user->cons_lock);
423 key_put(key);
424 kleave(" = %d [prelink]", ret);
425 return ret;
426
427alloc_failed:
428 mutex_unlock(&user->cons_lock);
429 kleave(" = %ld", PTR_ERR(key));
430 return PTR_ERR(key);
431}
432
433/*
434 * Commence key construction.
435 */
436static struct key *construct_key_and_link(struct keyring_search_context *ctx,
437 const char *callout_info,
438 size_t callout_len,
439 void *aux,
440 struct key *dest_keyring,
441 unsigned long flags)
442{
443 struct key_user *user;
444 struct key *key;
445 int ret;
446
447 kenter("");
448
449 if (ctx->index_key.type == &key_type_keyring)
450 return ERR_PTR(-EPERM);
451
452 ret = construct_get_dest_keyring(&dest_keyring);
453 if (ret)
454 goto error;
455
456 user = key_user_lookup(current_fsuid());
457 if (!user) {
458 ret = -ENOMEM;
459 goto error_put_dest_keyring;
460 }
461
462 ret = construct_alloc_key(ctx, dest_keyring, flags, user, &key);
463 key_user_put(user);
464
465 if (ret == 0) {
466 ret = construct_key(key, callout_info, callout_len, aux,
467 dest_keyring);
468 if (ret < 0) {
469 kdebug("cons failed");
470 goto construction_failed;
471 }
472 } else if (ret == -EINPROGRESS) {
473 ret = 0;
474 } else {
475 goto error_put_dest_keyring;
476 }
477
478 key_put(dest_keyring);
479 kleave(" = key %d", key_serial(key));
480 return key;
481
482construction_failed:
483 key_negate_and_link(key, key_negative_timeout, NULL, NULL);
484 key_put(key);
485error_put_dest_keyring:
486 key_put(dest_keyring);
487error:
488 kleave(" = %d", ret);
489 return ERR_PTR(ret);
490}
491
492/**
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().
501 *
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.
506 *
507 * If successfully found or created, the key will be linked to the destination
508 * keyring if one is provided.
509 *
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.
515 *
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.
518 */
519struct key *request_key_and_link(struct key_type *type,
520 const char *description,
521 const void *callout_info,
522 size_t callout_len,
523 void *aux,
524 struct key *dest_keyring,
525 unsigned long flags)
526{
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),
537 };
538 struct key *key;
539 key_ref_t key_ref;
540 int ret;
541
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);
545
546 if (type->match_preparse) {
547 ret = type->match_preparse(&ctx.match_data);
548 if (ret < 0) {
549 key = ERR_PTR(ret);
550 goto error;
551 }
552 }
553
554 /* search all the process keyrings for a key */
555 key_ref = search_process_keyrings(&ctx);
556
557 if (!IS_ERR(key_ref)) {
558 key = key_ref_to_ptr(key_ref);
559 if (dest_keyring) {
560 ret = key_link(dest_keyring, key);
561 if (ret < 0) {
562 key_put(key);
563 key = ERR_PTR(ret);
564 goto error_free;
565 }
566 }
567 } else if (PTR_ERR(key_ref) != -EAGAIN) {
568 key = ERR_CAST(key_ref);
569 } else {
570 /* the search failed, but the keyrings were searchable, so we
571 * should consult userspace if we can */
572 key = ERR_PTR(-ENOKEY);
573 if (!callout_info)
574 goto error_free;
575
576 key = construct_key_and_link(&ctx, callout_info, callout_len,
577 aux, dest_keyring, flags);
578 }
579
580error_free:
581 if (type->match_free)
582 type->match_free(&ctx.match_data);
583error:
584 kleave(" = %p", key);
585 return key;
586}
587
588/**
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.
592 *
593 * Wait for a key to finish being constructed.
594 *
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.
598 */
599int wait_for_key_construction(struct key *key, bool intr)
600{
601 int ret;
602
603 ret = wait_on_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT,
604 intr ? TASK_INTERRUPTIBLE : TASK_UNINTERRUPTIBLE);
605 if (ret)
606 return -ERESTARTSYS;
607 ret = key_read_state(key);
608 if (ret < 0)
609 return ret;
610 return key_validate(key);
611}
612EXPORT_SYMBOL(wait_for_key_construction);
613
614/**
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).
619 *
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
623 * be passed.
624 *
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.
627 */
628struct key *request_key(struct key_type *type,
629 const char *description,
630 const char *callout_info)
631{
632 struct key *key;
633 size_t callout_len = 0;
634 int ret;
635
636 if (callout_info)
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);
640 if (!IS_ERR(key)) {
641 ret = wait_for_key_construction(key, false);
642 if (ret < 0) {
643 key_put(key);
644 return ERR_PTR(ret);
645 }
646 }
647 return key;
648}
649EXPORT_SYMBOL(request_key);
650
651/**
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.
658 *
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.
661 *
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.
664 */
665struct key *request_key_with_auxdata(struct key_type *type,
666 const char *description,
667 const void *callout_info,
668 size_t callout_len,
669 void *aux)
670{
671 struct key *key;
672 int ret;
673
674 key = request_key_and_link(type, description, callout_info, callout_len,
675 aux, NULL, KEY_ALLOC_IN_QUOTA);
676 if (!IS_ERR(key)) {
677 ret = wait_for_key_construction(key, false);
678 if (ret < 0) {
679 key_put(key);
680 return ERR_PTR(ret);
681 }
682 }
683 return key;
684}
685EXPORT_SYMBOL(request_key_with_auxdata);
686
687/*
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.
693 *
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.
697 *
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.
700 */
701struct key *request_key_async(struct key_type *type,
702 const char *description,
703 const void *callout_info,
704 size_t callout_len)
705{
706 return request_key_and_link(type, description, callout_info,
707 callout_len, NULL, NULL,
708 KEY_ALLOC_IN_QUOTA);
709}
710EXPORT_SYMBOL(request_key_async);
711
712/*
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.
719 *
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.
722 *
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.
725 */
726struct key *request_key_async_with_auxdata(struct key_type *type,
727 const char *description,
728 const void *callout_info,
729 size_t callout_len,
730 void *aux)
731{
732 return request_key_and_link(type, description, callout_info,
733 callout_len, aux, NULL, KEY_ALLOC_IN_QUOTA);
734}
735EXPORT_SYMBOL(request_key_async_with_auxdata);