1/* Request a key from userspace
2 *
3 * Copyright (C) 2004-2007 Red Hat, Inc. All Rights Reserved.
4 * Written by David Howells (dhowells@redhat.com)
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 * See Documentation/security/keys-request-key.txt
12 */
13
14#include <linux/module.h>
15#include <linux/sched.h>
16#include <linux/kmod.h>
17#include <linux/err.h>
18#include <linux/keyctl.h>
19#include <linux/slab.h>
20#include "internal.h"
21
22#define key_negative_timeout	60	/* default timeout on a negative key's existence */
23
24/**
25 * complete_request_key - Complete the construction of a key.
26 * @cons: The key construction record.
27 * @error: The success or failute of the construction.
28 *
29 * Complete the attempt to construct a key.  The key will be negated
30 * if an error is indicated.  The authorisation key will be revoked
31 * unconditionally.
32 */
33void complete_request_key(struct key_construction *cons, int error)
34{
35	kenter("{%d,%d},%d", cons->key->serial, cons->authkey->serial, error);
36
37	if (error < 0)
38		key_negate_and_link(cons->key, key_negative_timeout, NULL,
39				    cons->authkey);
40	else
41		key_revoke(cons->authkey);
42
43	key_put(cons->key);
44	key_put(cons->authkey);
45	kfree(cons);
46}
47EXPORT_SYMBOL(complete_request_key);
48
49/*
50 * Initialise a usermode helper that is going to have a specific session
51 * keyring.
52 *
53 * This is called in context of freshly forked kthread before kernel_execve(),
54 * so we can simply install the desired session_keyring at this point.
55 */
56static int umh_keys_init(struct subprocess_info *info, struct cred *cred)
57{
58	struct key *keyring = info->data;
59
60	return install_session_keyring_to_cred(cred, keyring);
61}
62
63/*
64 * Clean up a usermode helper with session keyring.
65 */
66static void umh_keys_cleanup(struct subprocess_info *info)
67{
68	struct key *keyring = info->data;
69	key_put(keyring);
70}
71
72/*
73 * Call a usermode helper with a specific session keyring.
74 */
75static int call_usermodehelper_keys(char *path, char **argv, char **envp,
76					struct key *session_keyring, int wait)
77{
78	struct subprocess_info *info;
79
80	info = call_usermodehelper_setup(path, argv, envp, GFP_KERNEL,
81					  umh_keys_init, umh_keys_cleanup,
82					  session_keyring);
83	if (!info)
84		return -ENOMEM;
85
86	key_get(session_keyring);
87	return call_usermodehelper_exec(info, wait);
88}
89
90/*
91 * Request userspace finish the construction of a key
92 * - execute "/sbin/request-key <op> <key> <uid> <gid> <keyring> <keyring> <keyring>"
93 */
94static int call_sbin_request_key(struct key_construction *cons,
95				 const char *op,
96				 void *aux)
97{
98	const struct cred *cred = current_cred();
99	key_serial_t prkey, sskey;
100	struct key *key = cons->key, *authkey = cons->authkey, *keyring,
101		*session;
102	char *argv[9], *envp[3], uid_str[12], gid_str[12];
103	char key_str[12], keyring_str[3][12];
104	char desc[20];
105	int ret, i;
106
107	kenter("{%d},{%d},%s", key->serial, authkey->serial, op);
108
109	ret = install_user_keyrings();
110	if (ret < 0)
111		goto error_alloc;
112
113	/* allocate a new session keyring */
114	sprintf(desc, "_req.%u", key->serial);
115
116	cred = get_current_cred();
117	keyring = keyring_alloc(desc, cred->fsuid, cred->fsgid, cred,
118				KEY_POS_ALL | KEY_USR_VIEW | KEY_USR_READ,
119				KEY_ALLOC_QUOTA_OVERRUN, NULL);
120	put_cred(cred);
121	if (IS_ERR(keyring)) {
122		ret = PTR_ERR(keyring);
123		goto error_alloc;
124	}
125
126	/* attach the auth key to the session keyring */
127	ret = key_link(keyring, authkey);
128	if (ret < 0)
129		goto error_link;
130
131	/* record the UID and GID */
132	sprintf(uid_str, "%d", from_kuid(&init_user_ns, cred->fsuid));
133	sprintf(gid_str, "%d", from_kgid(&init_user_ns, cred->fsgid));
134
135	/* we say which key is under construction */
136	sprintf(key_str, "%d", key->serial);
137
138	/* we specify the process's default keyrings */
139	sprintf(keyring_str[0], "%d",
140		cred->thread_keyring ? cred->thread_keyring->serial : 0);
141
142	prkey = 0;
143	if (cred->process_keyring)
144		prkey = cred->process_keyring->serial;
145	sprintf(keyring_str[1], "%d", prkey);
146
147	rcu_read_lock();
148	session = rcu_dereference(cred->session_keyring);
149	if (!session)
150		session = cred->user->session_keyring;
151	sskey = session->serial;
152	rcu_read_unlock();
153
154	sprintf(keyring_str[2], "%d", sskey);
155
156	/* set up a minimal environment */
157	i = 0;
158	envp[i++] = "HOME=/";
159	envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
160	envp[i] = NULL;
161
162	/* set up the argument list */
163	i = 0;
164	argv[i++] = "/sbin/request-key";
165	argv[i++] = (char *) op;
166	argv[i++] = key_str;
167	argv[i++] = uid_str;
168	argv[i++] = gid_str;
169	argv[i++] = keyring_str[0];
170	argv[i++] = keyring_str[1];
171	argv[i++] = keyring_str[2];
172	argv[i] = NULL;
173
174	/* do it */
175	ret = call_usermodehelper_keys(argv[0], argv, envp, keyring,
176				       UMH_WAIT_PROC);
177	kdebug("usermode -> 0x%x", ret);
178	if (ret >= 0) {
179		/* ret is the exit/wait code */
180		if (test_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags) ||
181		    key_validate(key) < 0)
182			ret = -ENOKEY;
183		else
184			/* ignore any errors from userspace if the key was
185			 * instantiated */
186			ret = 0;
187	}
188
189error_link:
190	key_put(keyring);
191
192error_alloc:
193	complete_request_key(cons, ret);
194	kleave(" = %d", ret);
195	return ret;
196}
197
198/*
199 * Call out to userspace for key construction.
200 *
201 * Program failure is ignored in favour of key status.
202 */
203static int construct_key(struct key *key, const void *callout_info,
204			 size_t callout_len, void *aux,
205			 struct key *dest_keyring)
206{
207	struct key_construction *cons;
208	request_key_actor_t actor;
209	struct key *authkey;
210	int ret;
211
212	kenter("%d,%p,%zu,%p", key->serial, callout_info, callout_len, aux);
213
214	cons = kmalloc(sizeof(*cons), GFP_KERNEL);
215	if (!cons)
216		return -ENOMEM;
217
218	/* allocate an authorisation key */
219	authkey = request_key_auth_new(key, callout_info, callout_len,
220				       dest_keyring);
221	if (IS_ERR(authkey)) {
222		kfree(cons);
223		ret = PTR_ERR(authkey);
224		authkey = NULL;
225	} else {
226		cons->authkey = key_get(authkey);
227		cons->key = key_get(key);
228
229		/* make the call */
230		actor = call_sbin_request_key;
231		if (key->type->request_key)
232			actor = key->type->request_key;
233
234		ret = actor(cons, "create", aux);
235
236		/* check that the actor called complete_request_key() prior to
237		 * returning an error */
238		WARN_ON(ret < 0 &&
239			!test_bit(KEY_FLAG_REVOKED, &authkey->flags));
240		key_put(authkey);
241	}
242
243	kleave(" = %d", ret);
244	return ret;
245}
246
247/*
248 * Get the appropriate destination keyring for the request.
249 *
250 * The keyring selected is returned with an extra reference upon it which the
251 * caller must release.
252 */
253static void construct_get_dest_keyring(struct key **_dest_keyring)
254{
255	struct request_key_auth *rka;
256	const struct cred *cred = current_cred();
257	struct key *dest_keyring = *_dest_keyring, *authkey;
258
259	kenter("%p", dest_keyring);
260
261	/* find the appropriate keyring */
262	if (dest_keyring) {
263		/* the caller supplied one */
264		key_get(dest_keyring);
265	} else {
266		/* use a default keyring; falling through the cases until we
267		 * find one that we actually have */
268		switch (cred->jit_keyring) {
269		case KEY_REQKEY_DEFL_DEFAULT:
270		case KEY_REQKEY_DEFL_REQUESTOR_KEYRING:
271			if (cred->request_key_auth) {
272				authkey = cred->request_key_auth;
273				down_read(&authkey->sem);
274				rka = authkey->payload.data[0];
275				if (!test_bit(KEY_FLAG_REVOKED,
276					      &authkey->flags))
277					dest_keyring =
278						key_get(rka->dest_keyring);
279				up_read(&authkey->sem);
280				if (dest_keyring)
281					break;
282			}
283
284		case KEY_REQKEY_DEFL_THREAD_KEYRING:
285			dest_keyring = key_get(cred->thread_keyring);
286			if (dest_keyring)
287				break;
288
289		case KEY_REQKEY_DEFL_PROCESS_KEYRING:
290			dest_keyring = key_get(cred->process_keyring);
291			if (dest_keyring)
292				break;
293
294		case KEY_REQKEY_DEFL_SESSION_KEYRING:
295			rcu_read_lock();
296			dest_keyring = key_get(
297				rcu_dereference(cred->session_keyring));
298			rcu_read_unlock();
299
300			if (dest_keyring)
301				break;
302
303		case KEY_REQKEY_DEFL_USER_SESSION_KEYRING:
304			dest_keyring =
305				key_get(cred->user->session_keyring);
306			break;
307
308		case KEY_REQKEY_DEFL_USER_KEYRING:
309			dest_keyring = key_get(cred->user->uid_keyring);
310			break;
311
312		case KEY_REQKEY_DEFL_GROUP_KEYRING:
313		default:
314			BUG();
315		}
316	}
317
318	*_dest_keyring = dest_keyring;
319	kleave(" [dk %d]", key_serial(dest_keyring));
320	return;
321}
322
323/*
324 * Allocate a new key in under-construction state and attempt to link it in to
325 * the requested keyring.
326 *
327 * May return a key that's already under construction instead if there was a
328 * race between two thread calling request_key().
329 */
330static int construct_alloc_key(struct keyring_search_context *ctx,
331			       struct key *dest_keyring,
332			       unsigned long flags,
333			       struct key_user *user,
334			       struct key **_key)
335{
336	struct assoc_array_edit *edit;
337	struct key *key;
338	key_perm_t perm;
339	key_ref_t key_ref;
340	int ret;
341
342	kenter("%s,%s,,,",
343	       ctx->index_key.type->name, ctx->index_key.description);
344
345	*_key = NULL;
346	mutex_lock(&user->cons_lock);
347
348	perm = KEY_POS_VIEW | KEY_POS_SEARCH | KEY_POS_LINK | KEY_POS_SETATTR;
349	perm |= KEY_USR_VIEW;
350	if (ctx->index_key.type->read)
351		perm |= KEY_POS_READ;
352	if (ctx->index_key.type == &key_type_keyring ||
353	    ctx->index_key.type->update)
354		perm |= KEY_POS_WRITE;
355
356	key = key_alloc(ctx->index_key.type, ctx->index_key.description,
357			ctx->cred->fsuid, ctx->cred->fsgid, ctx->cred,
358			perm, flags);
359	if (IS_ERR(key))
360		goto alloc_failed;
361
362	set_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags);
363
364	if (dest_keyring) {
365		ret = __key_link_begin(dest_keyring, &ctx->index_key, &edit);
366		if (ret < 0)
367			goto link_prealloc_failed;
368	}
369
370	/* attach the key to the destination keyring under lock, but we do need
371	 * to do another check just in case someone beat us to it whilst we
372	 * waited for locks */
373	mutex_lock(&key_construction_mutex);
374
375	key_ref = search_process_keyrings(ctx);
376	if (!IS_ERR(key_ref))
377		goto key_already_present;
378
379	if (dest_keyring)
380		__key_link(key, &edit);
381
382	mutex_unlock(&key_construction_mutex);
383	if (dest_keyring)
384		__key_link_end(dest_keyring, &ctx->index_key, edit);
385	mutex_unlock(&user->cons_lock);
386	*_key = key;
387	kleave(" = 0 [%d]", key_serial(key));
388	return 0;
389
390	/* the key is now present - we tell the caller that we found it by
391	 * returning -EINPROGRESS  */
392key_already_present:
393	key_put(key);
394	mutex_unlock(&key_construction_mutex);
395	key = key_ref_to_ptr(key_ref);
396	if (dest_keyring) {
397		ret = __key_link_check_live_key(dest_keyring, key);
398		if (ret == 0)
399			__key_link(key, &edit);
400		__key_link_end(dest_keyring, &ctx->index_key, edit);
401		if (ret < 0)
402			goto link_check_failed;
403	}
404	mutex_unlock(&user->cons_lock);
405	*_key = key;
406	kleave(" = -EINPROGRESS [%d]", key_serial(key));
407	return -EINPROGRESS;
408
409link_check_failed:
410	mutex_unlock(&user->cons_lock);
411	key_put(key);
412	kleave(" = %d [linkcheck]", ret);
413	return ret;
414
415link_prealloc_failed:
416	mutex_unlock(&user->cons_lock);
417	key_put(key);
418	kleave(" = %d [prelink]", ret);
419	return ret;
420
421alloc_failed:
422	mutex_unlock(&user->cons_lock);
423	kleave(" = %ld", PTR_ERR(key));
424	return PTR_ERR(key);
425}
426
427/*
428 * Commence key construction.
429 */
430static struct key *construct_key_and_link(struct keyring_search_context *ctx,
431					  const char *callout_info,
432					  size_t callout_len,
433					  void *aux,
434					  struct key *dest_keyring,
435					  unsigned long flags)
436{
437	struct key_user *user;
438	struct key *key;
439	int ret;
440
441	kenter("");
442
443	if (ctx->index_key.type == &key_type_keyring)
444		return ERR_PTR(-EPERM);
445
446	user = key_user_lookup(current_fsuid());
447	if (!user)
448		return ERR_PTR(-ENOMEM);
449
450	construct_get_dest_keyring(&dest_keyring);
451
452	ret = construct_alloc_key(ctx, dest_keyring, flags, user, &key);
453	key_user_put(user);
454
455	if (ret == 0) {
456		ret = construct_key(key, callout_info, callout_len, aux,
457				    dest_keyring);
458		if (ret < 0) {
459			kdebug("cons failed");
460			goto construction_failed;
461		}
462	} else if (ret == -EINPROGRESS) {
463		ret = 0;
464	} else {
465		goto couldnt_alloc_key;
466	}
467
468	key_put(dest_keyring);
469	kleave(" = key %d", key_serial(key));
470	return key;
471
472construction_failed:
473	key_negate_and_link(key, key_negative_timeout, NULL, NULL);
474	key_put(key);
475couldnt_alloc_key:
476	key_put(dest_keyring);
477	kleave(" = %d", ret);
478	return ERR_PTR(ret);
479}
480
481/**
482 * request_key_and_link - Request a key and cache it in a keyring.
483 * @type: The type of key we want.
484 * @description: The searchable description of the key.
485 * @callout_info: The data to pass to the instantiation upcall (or NULL).
486 * @callout_len: The length of callout_info.
487 * @aux: Auxiliary data for the upcall.
488 * @dest_keyring: Where to cache the key.
489 * @flags: Flags to key_alloc().
490 *
491 * A key matching the specified criteria is searched for in the process's
492 * keyrings and returned with its usage count incremented if found.  Otherwise,
493 * if callout_info is not NULL, a key will be allocated and some service
494 * (probably in userspace) will be asked to instantiate it.
495 *
496 * If successfully found or created, the key will be linked to the destination
497 * keyring if one is provided.
498 *
499 * Returns a pointer to the key if successful; -EACCES, -ENOKEY, -EKEYREVOKED
500 * or -EKEYEXPIRED if an inaccessible, negative, revoked or expired key was
501 * found; -ENOKEY if no key was found and no @callout_info was given; -EDQUOT
502 * if insufficient key quota was available to create a new key; or -ENOMEM if
503 * insufficient memory was available.
504 *
505 * If the returned key was created, then it may still be under construction,
506 * and wait_for_key_construction() should be used to wait for that to complete.
507 */
508struct key *request_key_and_link(struct key_type *type,
509				 const char *description,
510				 const void *callout_info,
511				 size_t callout_len,
512				 void *aux,
513				 struct key *dest_keyring,
514				 unsigned long flags)
515{
516	struct keyring_search_context ctx = {
517		.index_key.type		= type,
518		.index_key.description	= description,
519		.cred			= current_cred(),
520		.match_data.cmp		= key_default_cmp,
521		.match_data.raw_data	= description,
522		.match_data.lookup_type	= KEYRING_SEARCH_LOOKUP_DIRECT,
523		.flags			= (KEYRING_SEARCH_DO_STATE_CHECK |
524					   KEYRING_SEARCH_SKIP_EXPIRED),
525	};
526	struct key *key;
527	key_ref_t key_ref;
528	int ret;
529
530	kenter("%s,%s,%p,%zu,%p,%p,%lx",
531	       ctx.index_key.type->name, ctx.index_key.description,
532	       callout_info, callout_len, aux, dest_keyring, flags);
533
534	if (type->match_preparse) {
535		ret = type->match_preparse(&ctx.match_data);
536		if (ret < 0) {
537			key = ERR_PTR(ret);
538			goto error;
539		}
540	}
541
542	/* search all the process keyrings for a key */
543	key_ref = search_process_keyrings(&ctx);
544
545	if (!IS_ERR(key_ref)) {
546		key = key_ref_to_ptr(key_ref);
547		if (dest_keyring) {
548			construct_get_dest_keyring(&dest_keyring);
549			ret = key_link(dest_keyring, key);
550			key_put(dest_keyring);
551			if (ret < 0) {
552				key_put(key);
553				key = ERR_PTR(ret);
554				goto error_free;
555			}
556		}
557	} else if (PTR_ERR(key_ref) != -EAGAIN) {
558		key = ERR_CAST(key_ref);
559	} else  {
560		/* the search failed, but the keyrings were searchable, so we
561		 * should consult userspace if we can */
562		key = ERR_PTR(-ENOKEY);
563		if (!callout_info)
564			goto error_free;
565
566		key = construct_key_and_link(&ctx, callout_info, callout_len,
567					     aux, dest_keyring, flags);
568	}
569
570error_free:
571	if (type->match_free)
572		type->match_free(&ctx.match_data);
573error:
574	kleave(" = %p", key);
575	return key;
576}
577
578/**
579 * wait_for_key_construction - Wait for construction of a key to complete
580 * @key: The key being waited for.
581 * @intr: Whether to wait interruptibly.
582 *
583 * Wait for a key to finish being constructed.
584 *
585 * Returns 0 if successful; -ERESTARTSYS if the wait was interrupted; -ENOKEY
586 * if the key was negated; or -EKEYREVOKED or -EKEYEXPIRED if the key was
587 * revoked or expired.
588 */
589int wait_for_key_construction(struct key *key, bool intr)
590{
591	int ret;
592
593	ret = wait_on_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT,
594			  intr ? TASK_INTERRUPTIBLE : TASK_UNINTERRUPTIBLE);
595	if (ret)
596		return -ERESTARTSYS;
597	if (test_bit(KEY_FLAG_NEGATIVE, &key->flags)) {
598		smp_rmb();
599		return key->reject_error;
600	}
601	return key_validate(key);
602}
603EXPORT_SYMBOL(wait_for_key_construction);
604
605/**
606 * request_key - Request a key and wait for construction
607 * @type: Type of key.
608 * @description: The searchable description of the key.
609 * @callout_info: The data to pass to the instantiation upcall (or NULL).
610 *
611 * As for request_key_and_link() except that it does not add the returned key
612 * to a keyring if found, new keys are always allocated in the user's quota,
613 * the callout_info must be a NUL-terminated string and no auxiliary data can
614 * be passed.
615 *
616 * Furthermore, it then works as wait_for_key_construction() to wait for the
617 * completion of keys undergoing construction with a non-interruptible wait.
618 */
619struct key *request_key(struct key_type *type,
620			const char *description,
621			const char *callout_info)
622{
623	struct key *key;
624	size_t callout_len = 0;
625	int ret;
626
627	if (callout_info)
628		callout_len = strlen(callout_info);
629	key = request_key_and_link(type, description, callout_info, callout_len,
630				   NULL, NULL, KEY_ALLOC_IN_QUOTA);
631	if (!IS_ERR(key)) {
632		ret = wait_for_key_construction(key, false);
633		if (ret < 0) {
634			key_put(key);
635			return ERR_PTR(ret);
636		}
637	}
638	return key;
639}
640EXPORT_SYMBOL(request_key);
641
642/**
643 * request_key_with_auxdata - Request a key with auxiliary data for the upcaller
644 * @type: The type of key we want.
645 * @description: The searchable description of the key.
646 * @callout_info: The data to pass to the instantiation upcall (or NULL).
647 * @callout_len: The length of callout_info.
648 * @aux: Auxiliary data for the upcall.
649 *
650 * As for request_key_and_link() except that it does not add the returned key
651 * to a keyring if found and new keys are always allocated in the user's quota.
652 *
653 * Furthermore, it then works as wait_for_key_construction() to wait for the
654 * completion of keys undergoing construction with a non-interruptible wait.
655 */
656struct key *request_key_with_auxdata(struct key_type *type,
657				     const char *description,
658				     const void *callout_info,
659				     size_t callout_len,
660				     void *aux)
661{
662	struct key *key;
663	int ret;
664
665	key = request_key_and_link(type, description, callout_info, callout_len,
666				   aux, NULL, KEY_ALLOC_IN_QUOTA);
667	if (!IS_ERR(key)) {
668		ret = wait_for_key_construction(key, false);
669		if (ret < 0) {
670			key_put(key);
671			return ERR_PTR(ret);
672		}
673	}
674	return key;
675}
676EXPORT_SYMBOL(request_key_with_auxdata);
677
678/*
679 * request_key_async - Request a key (allow async construction)
680 * @type: Type of key.
681 * @description: The searchable description of the key.
682 * @callout_info: The data to pass to the instantiation upcall (or NULL).
683 * @callout_len: The length of callout_info.
684 *
685 * As for request_key_and_link() except that it does not add the returned key
686 * to a keyring if found, new keys are always allocated in the user's quota and
687 * no auxiliary data can be passed.
688 *
689 * The caller should call wait_for_key_construction() to wait for the
690 * completion of the returned key if it is still undergoing construction.
691 */
692struct key *request_key_async(struct key_type *type,
693			      const char *description,
694			      const void *callout_info,
695			      size_t callout_len)
696{
697	return request_key_and_link(type, description, callout_info,
698				    callout_len, NULL, NULL,
699				    KEY_ALLOC_IN_QUOTA);
700}
701EXPORT_SYMBOL(request_key_async);
702
703/*
704 * request a key with auxiliary data for the upcaller (allow async construction)
705 * @type: Type of key.
706 * @description: The searchable description of the key.
707 * @callout_info: The data to pass to the instantiation upcall (or NULL).
708 * @callout_len: The length of callout_info.
709 * @aux: Auxiliary data for the upcall.
710 *
711 * As for request_key_and_link() except that it does not add the returned key
712 * to a keyring if found and new keys are always allocated in the user's quota.
713 *
714 * The caller should call wait_for_key_construction() to wait for the
715 * completion of the returned key if it is still undergoing construction.
716 */
717struct key *request_key_async_with_auxdata(struct key_type *type,
718					   const char *description,
719					   const void *callout_info,
720					   size_t callout_len,
721					   void *aux)
722{
723	return request_key_and_link(type, description, callout_info,
724				    callout_len, aux, NULL, KEY_ALLOC_IN_QUOTA);
725}
726EXPORT_SYMBOL(request_key_async_with_auxdata);
727