xref: /openbmc/linux/security/keys/keyctl.c (revision a2818ee4)
1 /* Userspace key control operations
2  *
3  * Copyright (C) 2004-5 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 
12 #include <linux/init.h>
13 #include <linux/sched.h>
14 #include <linux/sched/task.h>
15 #include <linux/slab.h>
16 #include <linux/syscalls.h>
17 #include <linux/key.h>
18 #include <linux/keyctl.h>
19 #include <linux/fs.h>
20 #include <linux/capability.h>
21 #include <linux/cred.h>
22 #include <linux/string.h>
23 #include <linux/err.h>
24 #include <linux/vmalloc.h>
25 #include <linux/security.h>
26 #include <linux/uio.h>
27 #include <linux/uaccess.h>
28 #include "internal.h"
29 
30 #define KEY_MAX_DESC_SIZE 4096
31 
32 static int key_get_type_from_user(char *type,
33 				  const char __user *_type,
34 				  unsigned len)
35 {
36 	int ret;
37 
38 	ret = strncpy_from_user(type, _type, len);
39 	if (ret < 0)
40 		return ret;
41 	if (ret == 0 || ret >= len)
42 		return -EINVAL;
43 	if (type[0] == '.')
44 		return -EPERM;
45 	type[len - 1] = '\0';
46 	return 0;
47 }
48 
49 /*
50  * Extract the description of a new key from userspace and either add it as a
51  * new key to the specified keyring or update a matching key in that keyring.
52  *
53  * If the description is NULL or an empty string, the key type is asked to
54  * generate one from the payload.
55  *
56  * The keyring must be writable so that we can attach the key to it.
57  *
58  * If successful, the new key's serial number is returned, otherwise an error
59  * code is returned.
60  */
61 SYSCALL_DEFINE5(add_key, const char __user *, _type,
62 		const char __user *, _description,
63 		const void __user *, _payload,
64 		size_t, plen,
65 		key_serial_t, ringid)
66 {
67 	key_ref_t keyring_ref, key_ref;
68 	char type[32], *description;
69 	void *payload;
70 	long ret;
71 
72 	ret = -EINVAL;
73 	if (plen > 1024 * 1024 - 1)
74 		goto error;
75 
76 	/* draw all the data into kernel space */
77 	ret = key_get_type_from_user(type, _type, sizeof(type));
78 	if (ret < 0)
79 		goto error;
80 
81 	description = NULL;
82 	if (_description) {
83 		description = strndup_user(_description, KEY_MAX_DESC_SIZE);
84 		if (IS_ERR(description)) {
85 			ret = PTR_ERR(description);
86 			goto error;
87 		}
88 		if (!*description) {
89 			kfree(description);
90 			description = NULL;
91 		} else if ((description[0] == '.') &&
92 			   (strncmp(type, "keyring", 7) == 0)) {
93 			ret = -EPERM;
94 			goto error2;
95 		}
96 	}
97 
98 	/* pull the payload in if one was supplied */
99 	payload = NULL;
100 
101 	if (plen) {
102 		ret = -ENOMEM;
103 		payload = kvmalloc(plen, GFP_KERNEL);
104 		if (!payload)
105 			goto error2;
106 
107 		ret = -EFAULT;
108 		if (copy_from_user(payload, _payload, plen) != 0)
109 			goto error3;
110 	}
111 
112 	/* find the target keyring (which must be writable) */
113 	keyring_ref = lookup_user_key(ringid, KEY_LOOKUP_CREATE, KEY_NEED_WRITE);
114 	if (IS_ERR(keyring_ref)) {
115 		ret = PTR_ERR(keyring_ref);
116 		goto error3;
117 	}
118 
119 	/* create or update the requested key and add it to the target
120 	 * keyring */
121 	key_ref = key_create_or_update(keyring_ref, type, description,
122 				       payload, plen, KEY_PERM_UNDEF,
123 				       KEY_ALLOC_IN_QUOTA);
124 	if (!IS_ERR(key_ref)) {
125 		ret = key_ref_to_ptr(key_ref)->serial;
126 		key_ref_put(key_ref);
127 	}
128 	else {
129 		ret = PTR_ERR(key_ref);
130 	}
131 
132 	key_ref_put(keyring_ref);
133  error3:
134 	if (payload) {
135 		memzero_explicit(payload, plen);
136 		kvfree(payload);
137 	}
138  error2:
139 	kfree(description);
140  error:
141 	return ret;
142 }
143 
144 /*
145  * Search the process keyrings and keyring trees linked from those for a
146  * matching key.  Keyrings must have appropriate Search permission to be
147  * searched.
148  *
149  * If a key is found, it will be attached to the destination keyring if there's
150  * one specified and the serial number of the key will be returned.
151  *
152  * If no key is found, /sbin/request-key will be invoked if _callout_info is
153  * non-NULL in an attempt to create a key.  The _callout_info string will be
154  * passed to /sbin/request-key to aid with completing the request.  If the
155  * _callout_info string is "" then it will be changed to "-".
156  */
157 SYSCALL_DEFINE4(request_key, const char __user *, _type,
158 		const char __user *, _description,
159 		const char __user *, _callout_info,
160 		key_serial_t, destringid)
161 {
162 	struct key_type *ktype;
163 	struct key *key;
164 	key_ref_t dest_ref;
165 	size_t callout_len;
166 	char type[32], *description, *callout_info;
167 	long ret;
168 
169 	/* pull the type into kernel space */
170 	ret = key_get_type_from_user(type, _type, sizeof(type));
171 	if (ret < 0)
172 		goto error;
173 
174 	/* pull the description into kernel space */
175 	description = strndup_user(_description, KEY_MAX_DESC_SIZE);
176 	if (IS_ERR(description)) {
177 		ret = PTR_ERR(description);
178 		goto error;
179 	}
180 
181 	/* pull the callout info into kernel space */
182 	callout_info = NULL;
183 	callout_len = 0;
184 	if (_callout_info) {
185 		callout_info = strndup_user(_callout_info, PAGE_SIZE);
186 		if (IS_ERR(callout_info)) {
187 			ret = PTR_ERR(callout_info);
188 			goto error2;
189 		}
190 		callout_len = strlen(callout_info);
191 	}
192 
193 	/* get the destination keyring if specified */
194 	dest_ref = NULL;
195 	if (destringid) {
196 		dest_ref = lookup_user_key(destringid, KEY_LOOKUP_CREATE,
197 					   KEY_NEED_WRITE);
198 		if (IS_ERR(dest_ref)) {
199 			ret = PTR_ERR(dest_ref);
200 			goto error3;
201 		}
202 	}
203 
204 	/* find the key type */
205 	ktype = key_type_lookup(type);
206 	if (IS_ERR(ktype)) {
207 		ret = PTR_ERR(ktype);
208 		goto error4;
209 	}
210 
211 	/* do the search */
212 	key = request_key_and_link(ktype, description, callout_info,
213 				   callout_len, NULL, key_ref_to_ptr(dest_ref),
214 				   KEY_ALLOC_IN_QUOTA);
215 	if (IS_ERR(key)) {
216 		ret = PTR_ERR(key);
217 		goto error5;
218 	}
219 
220 	/* wait for the key to finish being constructed */
221 	ret = wait_for_key_construction(key, 1);
222 	if (ret < 0)
223 		goto error6;
224 
225 	ret = key->serial;
226 
227 error6:
228  	key_put(key);
229 error5:
230 	key_type_put(ktype);
231 error4:
232 	key_ref_put(dest_ref);
233 error3:
234 	kfree(callout_info);
235 error2:
236 	kfree(description);
237 error:
238 	return ret;
239 }
240 
241 /*
242  * Get the ID of the specified process keyring.
243  *
244  * The requested keyring must have search permission to be found.
245  *
246  * If successful, the ID of the requested keyring will be returned.
247  */
248 long keyctl_get_keyring_ID(key_serial_t id, int create)
249 {
250 	key_ref_t key_ref;
251 	unsigned long lflags;
252 	long ret;
253 
254 	lflags = create ? KEY_LOOKUP_CREATE : 0;
255 	key_ref = lookup_user_key(id, lflags, KEY_NEED_SEARCH);
256 	if (IS_ERR(key_ref)) {
257 		ret = PTR_ERR(key_ref);
258 		goto error;
259 	}
260 
261 	ret = key_ref_to_ptr(key_ref)->serial;
262 	key_ref_put(key_ref);
263 error:
264 	return ret;
265 }
266 
267 /*
268  * Join a (named) session keyring.
269  *
270  * Create and join an anonymous session keyring or join a named session
271  * keyring, creating it if necessary.  A named session keyring must have Search
272  * permission for it to be joined.  Session keyrings without this permit will
273  * be skipped over.  It is not permitted for userspace to create or join
274  * keyrings whose name begin with a dot.
275  *
276  * If successful, the ID of the joined session keyring will be returned.
277  */
278 long keyctl_join_session_keyring(const char __user *_name)
279 {
280 	char *name;
281 	long ret;
282 
283 	/* fetch the name from userspace */
284 	name = NULL;
285 	if (_name) {
286 		name = strndup_user(_name, KEY_MAX_DESC_SIZE);
287 		if (IS_ERR(name)) {
288 			ret = PTR_ERR(name);
289 			goto error;
290 		}
291 
292 		ret = -EPERM;
293 		if (name[0] == '.')
294 			goto error_name;
295 	}
296 
297 	/* join the session */
298 	ret = join_session_keyring(name);
299 error_name:
300 	kfree(name);
301 error:
302 	return ret;
303 }
304 
305 /*
306  * Update a key's data payload from the given data.
307  *
308  * The key must grant the caller Write permission and the key type must support
309  * updating for this to work.  A negative key can be positively instantiated
310  * with this call.
311  *
312  * If successful, 0 will be returned.  If the key type does not support
313  * updating, then -EOPNOTSUPP will be returned.
314  */
315 long keyctl_update_key(key_serial_t id,
316 		       const void __user *_payload,
317 		       size_t plen)
318 {
319 	key_ref_t key_ref;
320 	void *payload;
321 	long ret;
322 
323 	ret = -EINVAL;
324 	if (plen > PAGE_SIZE)
325 		goto error;
326 
327 	/* pull the payload in if one was supplied */
328 	payload = NULL;
329 	if (plen) {
330 		ret = -ENOMEM;
331 		payload = kmalloc(plen, GFP_KERNEL);
332 		if (!payload)
333 			goto error;
334 
335 		ret = -EFAULT;
336 		if (copy_from_user(payload, _payload, plen) != 0)
337 			goto error2;
338 	}
339 
340 	/* find the target key (which must be writable) */
341 	key_ref = lookup_user_key(id, 0, KEY_NEED_WRITE);
342 	if (IS_ERR(key_ref)) {
343 		ret = PTR_ERR(key_ref);
344 		goto error2;
345 	}
346 
347 	/* update the key */
348 	ret = key_update(key_ref, payload, plen);
349 
350 	key_ref_put(key_ref);
351 error2:
352 	kzfree(payload);
353 error:
354 	return ret;
355 }
356 
357 /*
358  * Revoke a key.
359  *
360  * The key must be grant the caller Write or Setattr permission for this to
361  * work.  The key type should give up its quota claim when revoked.  The key
362  * and any links to the key will be automatically garbage collected after a
363  * certain amount of time (/proc/sys/kernel/keys/gc_delay).
364  *
365  * Keys with KEY_FLAG_KEEP set should not be revoked.
366  *
367  * If successful, 0 is returned.
368  */
369 long keyctl_revoke_key(key_serial_t id)
370 {
371 	key_ref_t key_ref;
372 	struct key *key;
373 	long ret;
374 
375 	key_ref = lookup_user_key(id, 0, KEY_NEED_WRITE);
376 	if (IS_ERR(key_ref)) {
377 		ret = PTR_ERR(key_ref);
378 		if (ret != -EACCES)
379 			goto error;
380 		key_ref = lookup_user_key(id, 0, KEY_NEED_SETATTR);
381 		if (IS_ERR(key_ref)) {
382 			ret = PTR_ERR(key_ref);
383 			goto error;
384 		}
385 	}
386 
387 	key = key_ref_to_ptr(key_ref);
388 	ret = 0;
389 	if (test_bit(KEY_FLAG_KEEP, &key->flags))
390 		ret = -EPERM;
391 	else
392 		key_revoke(key);
393 
394 	key_ref_put(key_ref);
395 error:
396 	return ret;
397 }
398 
399 /*
400  * Invalidate a key.
401  *
402  * The key must be grant the caller Invalidate permission for this to work.
403  * The key and any links to the key will be automatically garbage collected
404  * immediately.
405  *
406  * Keys with KEY_FLAG_KEEP set should not be invalidated.
407  *
408  * If successful, 0 is returned.
409  */
410 long keyctl_invalidate_key(key_serial_t id)
411 {
412 	key_ref_t key_ref;
413 	struct key *key;
414 	long ret;
415 
416 	kenter("%d", id);
417 
418 	key_ref = lookup_user_key(id, 0, KEY_NEED_SEARCH);
419 	if (IS_ERR(key_ref)) {
420 		ret = PTR_ERR(key_ref);
421 
422 		/* Root is permitted to invalidate certain special keys */
423 		if (capable(CAP_SYS_ADMIN)) {
424 			key_ref = lookup_user_key(id, 0, 0);
425 			if (IS_ERR(key_ref))
426 				goto error;
427 			if (test_bit(KEY_FLAG_ROOT_CAN_INVAL,
428 				     &key_ref_to_ptr(key_ref)->flags))
429 				goto invalidate;
430 			goto error_put;
431 		}
432 
433 		goto error;
434 	}
435 
436 invalidate:
437 	key = key_ref_to_ptr(key_ref);
438 	ret = 0;
439 	if (test_bit(KEY_FLAG_KEEP, &key->flags))
440 		ret = -EPERM;
441 	else
442 		key_invalidate(key);
443 error_put:
444 	key_ref_put(key_ref);
445 error:
446 	kleave(" = %ld", ret);
447 	return ret;
448 }
449 
450 /*
451  * Clear the specified keyring, creating an empty process keyring if one of the
452  * special keyring IDs is used.
453  *
454  * The keyring must grant the caller Write permission and not have
455  * KEY_FLAG_KEEP set for this to work.  If successful, 0 will be returned.
456  */
457 long keyctl_keyring_clear(key_serial_t ringid)
458 {
459 	key_ref_t keyring_ref;
460 	struct key *keyring;
461 	long ret;
462 
463 	keyring_ref = lookup_user_key(ringid, KEY_LOOKUP_CREATE, KEY_NEED_WRITE);
464 	if (IS_ERR(keyring_ref)) {
465 		ret = PTR_ERR(keyring_ref);
466 
467 		/* Root is permitted to invalidate certain special keyrings */
468 		if (capable(CAP_SYS_ADMIN)) {
469 			keyring_ref = lookup_user_key(ringid, 0, 0);
470 			if (IS_ERR(keyring_ref))
471 				goto error;
472 			if (test_bit(KEY_FLAG_ROOT_CAN_CLEAR,
473 				     &key_ref_to_ptr(keyring_ref)->flags))
474 				goto clear;
475 			goto error_put;
476 		}
477 
478 		goto error;
479 	}
480 
481 clear:
482 	keyring = key_ref_to_ptr(keyring_ref);
483 	if (test_bit(KEY_FLAG_KEEP, &keyring->flags))
484 		ret = -EPERM;
485 	else
486 		ret = keyring_clear(keyring);
487 error_put:
488 	key_ref_put(keyring_ref);
489 error:
490 	return ret;
491 }
492 
493 /*
494  * Create a link from a keyring to a key if there's no matching key in the
495  * keyring, otherwise replace the link to the matching key with a link to the
496  * new key.
497  *
498  * The key must grant the caller Link permission and the the keyring must grant
499  * the caller Write permission.  Furthermore, if an additional link is created,
500  * the keyring's quota will be extended.
501  *
502  * If successful, 0 will be returned.
503  */
504 long keyctl_keyring_link(key_serial_t id, key_serial_t ringid)
505 {
506 	key_ref_t keyring_ref, key_ref;
507 	long ret;
508 
509 	keyring_ref = lookup_user_key(ringid, KEY_LOOKUP_CREATE, KEY_NEED_WRITE);
510 	if (IS_ERR(keyring_ref)) {
511 		ret = PTR_ERR(keyring_ref);
512 		goto error;
513 	}
514 
515 	key_ref = lookup_user_key(id, KEY_LOOKUP_CREATE, KEY_NEED_LINK);
516 	if (IS_ERR(key_ref)) {
517 		ret = PTR_ERR(key_ref);
518 		goto error2;
519 	}
520 
521 	ret = key_link(key_ref_to_ptr(keyring_ref), key_ref_to_ptr(key_ref));
522 
523 	key_ref_put(key_ref);
524 error2:
525 	key_ref_put(keyring_ref);
526 error:
527 	return ret;
528 }
529 
530 /*
531  * Unlink a key from a keyring.
532  *
533  * The keyring must grant the caller Write permission for this to work; the key
534  * itself need not grant the caller anything.  If the last link to a key is
535  * removed then that key will be scheduled for destruction.
536  *
537  * Keys or keyrings with KEY_FLAG_KEEP set should not be unlinked.
538  *
539  * If successful, 0 will be returned.
540  */
541 long keyctl_keyring_unlink(key_serial_t id, key_serial_t ringid)
542 {
543 	key_ref_t keyring_ref, key_ref;
544 	struct key *keyring, *key;
545 	long ret;
546 
547 	keyring_ref = lookup_user_key(ringid, 0, KEY_NEED_WRITE);
548 	if (IS_ERR(keyring_ref)) {
549 		ret = PTR_ERR(keyring_ref);
550 		goto error;
551 	}
552 
553 	key_ref = lookup_user_key(id, KEY_LOOKUP_FOR_UNLINK, 0);
554 	if (IS_ERR(key_ref)) {
555 		ret = PTR_ERR(key_ref);
556 		goto error2;
557 	}
558 
559 	keyring = key_ref_to_ptr(keyring_ref);
560 	key = key_ref_to_ptr(key_ref);
561 	if (test_bit(KEY_FLAG_KEEP, &keyring->flags) &&
562 	    test_bit(KEY_FLAG_KEEP, &key->flags))
563 		ret = -EPERM;
564 	else
565 		ret = key_unlink(keyring, key);
566 
567 	key_ref_put(key_ref);
568 error2:
569 	key_ref_put(keyring_ref);
570 error:
571 	return ret;
572 }
573 
574 /*
575  * Return a description of a key to userspace.
576  *
577  * The key must grant the caller View permission for this to work.
578  *
579  * If there's a buffer, we place up to buflen bytes of data into it formatted
580  * in the following way:
581  *
582  *	type;uid;gid;perm;description<NUL>
583  *
584  * If successful, we return the amount of description available, irrespective
585  * of how much we may have copied into the buffer.
586  */
587 long keyctl_describe_key(key_serial_t keyid,
588 			 char __user *buffer,
589 			 size_t buflen)
590 {
591 	struct key *key, *instkey;
592 	key_ref_t key_ref;
593 	char *infobuf;
594 	long ret;
595 	int desclen, infolen;
596 
597 	key_ref = lookup_user_key(keyid, KEY_LOOKUP_PARTIAL, KEY_NEED_VIEW);
598 	if (IS_ERR(key_ref)) {
599 		/* viewing a key under construction is permitted if we have the
600 		 * authorisation token handy */
601 		if (PTR_ERR(key_ref) == -EACCES) {
602 			instkey = key_get_instantiation_authkey(keyid);
603 			if (!IS_ERR(instkey)) {
604 				key_put(instkey);
605 				key_ref = lookup_user_key(keyid,
606 							  KEY_LOOKUP_PARTIAL,
607 							  0);
608 				if (!IS_ERR(key_ref))
609 					goto okay;
610 			}
611 		}
612 
613 		ret = PTR_ERR(key_ref);
614 		goto error;
615 	}
616 
617 okay:
618 	key = key_ref_to_ptr(key_ref);
619 	desclen = strlen(key->description);
620 
621 	/* calculate how much information we're going to return */
622 	ret = -ENOMEM;
623 	infobuf = kasprintf(GFP_KERNEL,
624 			    "%s;%d;%d;%08x;",
625 			    key->type->name,
626 			    from_kuid_munged(current_user_ns(), key->uid),
627 			    from_kgid_munged(current_user_ns(), key->gid),
628 			    key->perm);
629 	if (!infobuf)
630 		goto error2;
631 	infolen = strlen(infobuf);
632 	ret = infolen + desclen + 1;
633 
634 	/* consider returning the data */
635 	if (buffer && buflen >= ret) {
636 		if (copy_to_user(buffer, infobuf, infolen) != 0 ||
637 		    copy_to_user(buffer + infolen, key->description,
638 				 desclen + 1) != 0)
639 			ret = -EFAULT;
640 	}
641 
642 	kfree(infobuf);
643 error2:
644 	key_ref_put(key_ref);
645 error:
646 	return ret;
647 }
648 
649 /*
650  * Search the specified keyring and any keyrings it links to for a matching
651  * key.  Only keyrings that grant the caller Search permission will be searched
652  * (this includes the starting keyring).  Only keys with Search permission can
653  * be found.
654  *
655  * If successful, the found key will be linked to the destination keyring if
656  * supplied and the key has Link permission, and the found key ID will be
657  * returned.
658  */
659 long keyctl_keyring_search(key_serial_t ringid,
660 			   const char __user *_type,
661 			   const char __user *_description,
662 			   key_serial_t destringid)
663 {
664 	struct key_type *ktype;
665 	key_ref_t keyring_ref, key_ref, dest_ref;
666 	char type[32], *description;
667 	long ret;
668 
669 	/* pull the type and description into kernel space */
670 	ret = key_get_type_from_user(type, _type, sizeof(type));
671 	if (ret < 0)
672 		goto error;
673 
674 	description = strndup_user(_description, KEY_MAX_DESC_SIZE);
675 	if (IS_ERR(description)) {
676 		ret = PTR_ERR(description);
677 		goto error;
678 	}
679 
680 	/* get the keyring at which to begin the search */
681 	keyring_ref = lookup_user_key(ringid, 0, KEY_NEED_SEARCH);
682 	if (IS_ERR(keyring_ref)) {
683 		ret = PTR_ERR(keyring_ref);
684 		goto error2;
685 	}
686 
687 	/* get the destination keyring if specified */
688 	dest_ref = NULL;
689 	if (destringid) {
690 		dest_ref = lookup_user_key(destringid, KEY_LOOKUP_CREATE,
691 					   KEY_NEED_WRITE);
692 		if (IS_ERR(dest_ref)) {
693 			ret = PTR_ERR(dest_ref);
694 			goto error3;
695 		}
696 	}
697 
698 	/* find the key type */
699 	ktype = key_type_lookup(type);
700 	if (IS_ERR(ktype)) {
701 		ret = PTR_ERR(ktype);
702 		goto error4;
703 	}
704 
705 	/* do the search */
706 	key_ref = keyring_search(keyring_ref, ktype, description);
707 	if (IS_ERR(key_ref)) {
708 		ret = PTR_ERR(key_ref);
709 
710 		/* treat lack or presence of a negative key the same */
711 		if (ret == -EAGAIN)
712 			ret = -ENOKEY;
713 		goto error5;
714 	}
715 
716 	/* link the resulting key to the destination keyring if we can */
717 	if (dest_ref) {
718 		ret = key_permission(key_ref, KEY_NEED_LINK);
719 		if (ret < 0)
720 			goto error6;
721 
722 		ret = key_link(key_ref_to_ptr(dest_ref), key_ref_to_ptr(key_ref));
723 		if (ret < 0)
724 			goto error6;
725 	}
726 
727 	ret = key_ref_to_ptr(key_ref)->serial;
728 
729 error6:
730 	key_ref_put(key_ref);
731 error5:
732 	key_type_put(ktype);
733 error4:
734 	key_ref_put(dest_ref);
735 error3:
736 	key_ref_put(keyring_ref);
737 error2:
738 	kfree(description);
739 error:
740 	return ret;
741 }
742 
743 /*
744  * Read a key's payload.
745  *
746  * The key must either grant the caller Read permission, or it must grant the
747  * caller Search permission when searched for from the process keyrings.
748  *
749  * If successful, we place up to buflen bytes of data into the buffer, if one
750  * is provided, and return the amount of data that is available in the key,
751  * irrespective of how much we copied into the buffer.
752  */
753 long keyctl_read_key(key_serial_t keyid, char __user *buffer, size_t buflen)
754 {
755 	struct key *key;
756 	key_ref_t key_ref;
757 	long ret;
758 
759 	/* find the key first */
760 	key_ref = lookup_user_key(keyid, 0, 0);
761 	if (IS_ERR(key_ref)) {
762 		ret = -ENOKEY;
763 		goto error;
764 	}
765 
766 	key = key_ref_to_ptr(key_ref);
767 
768 	ret = key_read_state(key);
769 	if (ret < 0)
770 		goto error2; /* Negatively instantiated */
771 
772 	/* see if we can read it directly */
773 	ret = key_permission(key_ref, KEY_NEED_READ);
774 	if (ret == 0)
775 		goto can_read_key;
776 	if (ret != -EACCES)
777 		goto error2;
778 
779 	/* we can't; see if it's searchable from this process's keyrings
780 	 * - we automatically take account of the fact that it may be
781 	 *   dangling off an instantiation key
782 	 */
783 	if (!is_key_possessed(key_ref)) {
784 		ret = -EACCES;
785 		goto error2;
786 	}
787 
788 	/* the key is probably readable - now try to read it */
789 can_read_key:
790 	ret = -EOPNOTSUPP;
791 	if (key->type->read) {
792 		/* Read the data with the semaphore held (since we might sleep)
793 		 * to protect against the key being updated or revoked.
794 		 */
795 		down_read(&key->sem);
796 		ret = key_validate(key);
797 		if (ret == 0)
798 			ret = key->type->read(key, buffer, buflen);
799 		up_read(&key->sem);
800 	}
801 
802 error2:
803 	key_put(key);
804 error:
805 	return ret;
806 }
807 
808 /*
809  * Change the ownership of a key
810  *
811  * The key must grant the caller Setattr permission for this to work, though
812  * the key need not be fully instantiated yet.  For the UID to be changed, or
813  * for the GID to be changed to a group the caller is not a member of, the
814  * caller must have sysadmin capability.  If either uid or gid is -1 then that
815  * attribute is not changed.
816  *
817  * If the UID is to be changed, the new user must have sufficient quota to
818  * accept the key.  The quota deduction will be removed from the old user to
819  * the new user should the attribute be changed.
820  *
821  * If successful, 0 will be returned.
822  */
823 long keyctl_chown_key(key_serial_t id, uid_t user, gid_t group)
824 {
825 	struct key_user *newowner, *zapowner = NULL;
826 	struct key *key;
827 	key_ref_t key_ref;
828 	long ret;
829 	kuid_t uid;
830 	kgid_t gid;
831 
832 	uid = make_kuid(current_user_ns(), user);
833 	gid = make_kgid(current_user_ns(), group);
834 	ret = -EINVAL;
835 	if ((user != (uid_t) -1) && !uid_valid(uid))
836 		goto error;
837 	if ((group != (gid_t) -1) && !gid_valid(gid))
838 		goto error;
839 
840 	ret = 0;
841 	if (user == (uid_t) -1 && group == (gid_t) -1)
842 		goto error;
843 
844 	key_ref = lookup_user_key(id, KEY_LOOKUP_CREATE | KEY_LOOKUP_PARTIAL,
845 				  KEY_NEED_SETATTR);
846 	if (IS_ERR(key_ref)) {
847 		ret = PTR_ERR(key_ref);
848 		goto error;
849 	}
850 
851 	key = key_ref_to_ptr(key_ref);
852 
853 	/* make the changes with the locks held to prevent chown/chown races */
854 	ret = -EACCES;
855 	down_write(&key->sem);
856 
857 	if (!capable(CAP_SYS_ADMIN)) {
858 		/* only the sysadmin can chown a key to some other UID */
859 		if (user != (uid_t) -1 && !uid_eq(key->uid, uid))
860 			goto error_put;
861 
862 		/* only the sysadmin can set the key's GID to a group other
863 		 * than one of those that the current process subscribes to */
864 		if (group != (gid_t) -1 && !gid_eq(gid, key->gid) && !in_group_p(gid))
865 			goto error_put;
866 	}
867 
868 	/* change the UID */
869 	if (user != (uid_t) -1 && !uid_eq(uid, key->uid)) {
870 		ret = -ENOMEM;
871 		newowner = key_user_lookup(uid);
872 		if (!newowner)
873 			goto error_put;
874 
875 		/* transfer the quota burden to the new user */
876 		if (test_bit(KEY_FLAG_IN_QUOTA, &key->flags)) {
877 			unsigned maxkeys = uid_eq(uid, GLOBAL_ROOT_UID) ?
878 				key_quota_root_maxkeys : key_quota_maxkeys;
879 			unsigned maxbytes = uid_eq(uid, GLOBAL_ROOT_UID) ?
880 				key_quota_root_maxbytes : key_quota_maxbytes;
881 
882 			spin_lock(&newowner->lock);
883 			if (newowner->qnkeys + 1 >= maxkeys ||
884 			    newowner->qnbytes + key->quotalen >= maxbytes ||
885 			    newowner->qnbytes + key->quotalen <
886 			    newowner->qnbytes)
887 				goto quota_overrun;
888 
889 			newowner->qnkeys++;
890 			newowner->qnbytes += key->quotalen;
891 			spin_unlock(&newowner->lock);
892 
893 			spin_lock(&key->user->lock);
894 			key->user->qnkeys--;
895 			key->user->qnbytes -= key->quotalen;
896 			spin_unlock(&key->user->lock);
897 		}
898 
899 		atomic_dec(&key->user->nkeys);
900 		atomic_inc(&newowner->nkeys);
901 
902 		if (key->state != KEY_IS_UNINSTANTIATED) {
903 			atomic_dec(&key->user->nikeys);
904 			atomic_inc(&newowner->nikeys);
905 		}
906 
907 		zapowner = key->user;
908 		key->user = newowner;
909 		key->uid = uid;
910 	}
911 
912 	/* change the GID */
913 	if (group != (gid_t) -1)
914 		key->gid = gid;
915 
916 	ret = 0;
917 
918 error_put:
919 	up_write(&key->sem);
920 	key_put(key);
921 	if (zapowner)
922 		key_user_put(zapowner);
923 error:
924 	return ret;
925 
926 quota_overrun:
927 	spin_unlock(&newowner->lock);
928 	zapowner = newowner;
929 	ret = -EDQUOT;
930 	goto error_put;
931 }
932 
933 /*
934  * Change the permission mask on a key.
935  *
936  * The key must grant the caller Setattr permission for this to work, though
937  * the key need not be fully instantiated yet.  If the caller does not have
938  * sysadmin capability, it may only change the permission on keys that it owns.
939  */
940 long keyctl_setperm_key(key_serial_t id, key_perm_t perm)
941 {
942 	struct key *key;
943 	key_ref_t key_ref;
944 	long ret;
945 
946 	ret = -EINVAL;
947 	if (perm & ~(KEY_POS_ALL | KEY_USR_ALL | KEY_GRP_ALL | KEY_OTH_ALL))
948 		goto error;
949 
950 	key_ref = lookup_user_key(id, KEY_LOOKUP_CREATE | KEY_LOOKUP_PARTIAL,
951 				  KEY_NEED_SETATTR);
952 	if (IS_ERR(key_ref)) {
953 		ret = PTR_ERR(key_ref);
954 		goto error;
955 	}
956 
957 	key = key_ref_to_ptr(key_ref);
958 
959 	/* make the changes with the locks held to prevent chown/chmod races */
960 	ret = -EACCES;
961 	down_write(&key->sem);
962 
963 	/* if we're not the sysadmin, we can only change a key that we own */
964 	if (capable(CAP_SYS_ADMIN) || uid_eq(key->uid, current_fsuid())) {
965 		key->perm = perm;
966 		ret = 0;
967 	}
968 
969 	up_write(&key->sem);
970 	key_put(key);
971 error:
972 	return ret;
973 }
974 
975 /*
976  * Get the destination keyring for instantiation and check that the caller has
977  * Write permission on it.
978  */
979 static long get_instantiation_keyring(key_serial_t ringid,
980 				      struct request_key_auth *rka,
981 				      struct key **_dest_keyring)
982 {
983 	key_ref_t dkref;
984 
985 	*_dest_keyring = NULL;
986 
987 	/* just return a NULL pointer if we weren't asked to make a link */
988 	if (ringid == 0)
989 		return 0;
990 
991 	/* if a specific keyring is nominated by ID, then use that */
992 	if (ringid > 0) {
993 		dkref = lookup_user_key(ringid, KEY_LOOKUP_CREATE, KEY_NEED_WRITE);
994 		if (IS_ERR(dkref))
995 			return PTR_ERR(dkref);
996 		*_dest_keyring = key_ref_to_ptr(dkref);
997 		return 0;
998 	}
999 
1000 	if (ringid == KEY_SPEC_REQKEY_AUTH_KEY)
1001 		return -EINVAL;
1002 
1003 	/* otherwise specify the destination keyring recorded in the
1004 	 * authorisation key (any KEY_SPEC_*_KEYRING) */
1005 	if (ringid >= KEY_SPEC_REQUESTOR_KEYRING) {
1006 		*_dest_keyring = key_get(rka->dest_keyring);
1007 		return 0;
1008 	}
1009 
1010 	return -ENOKEY;
1011 }
1012 
1013 /*
1014  * Change the request_key authorisation key on the current process.
1015  */
1016 static int keyctl_change_reqkey_auth(struct key *key)
1017 {
1018 	struct cred *new;
1019 
1020 	new = prepare_creds();
1021 	if (!new)
1022 		return -ENOMEM;
1023 
1024 	key_put(new->request_key_auth);
1025 	new->request_key_auth = key_get(key);
1026 
1027 	return commit_creds(new);
1028 }
1029 
1030 /*
1031  * Instantiate a key with the specified payload and link the key into the
1032  * destination keyring if one is given.
1033  *
1034  * The caller must have the appropriate instantiation permit set for this to
1035  * work (see keyctl_assume_authority).  No other permissions are required.
1036  *
1037  * If successful, 0 will be returned.
1038  */
1039 long keyctl_instantiate_key_common(key_serial_t id,
1040 				   struct iov_iter *from,
1041 				   key_serial_t ringid)
1042 {
1043 	const struct cred *cred = current_cred();
1044 	struct request_key_auth *rka;
1045 	struct key *instkey, *dest_keyring;
1046 	size_t plen = from ? iov_iter_count(from) : 0;
1047 	void *payload;
1048 	long ret;
1049 
1050 	kenter("%d,,%zu,%d", id, plen, ringid);
1051 
1052 	if (!plen)
1053 		from = NULL;
1054 
1055 	ret = -EINVAL;
1056 	if (plen > 1024 * 1024 - 1)
1057 		goto error;
1058 
1059 	/* the appropriate instantiation authorisation key must have been
1060 	 * assumed before calling this */
1061 	ret = -EPERM;
1062 	instkey = cred->request_key_auth;
1063 	if (!instkey)
1064 		goto error;
1065 
1066 	rka = instkey->payload.data[0];
1067 	if (rka->target_key->serial != id)
1068 		goto error;
1069 
1070 	/* pull the payload in if one was supplied */
1071 	payload = NULL;
1072 
1073 	if (from) {
1074 		ret = -ENOMEM;
1075 		payload = kvmalloc(plen, GFP_KERNEL);
1076 		if (!payload)
1077 			goto error;
1078 
1079 		ret = -EFAULT;
1080 		if (!copy_from_iter_full(payload, plen, from))
1081 			goto error2;
1082 	}
1083 
1084 	/* find the destination keyring amongst those belonging to the
1085 	 * requesting task */
1086 	ret = get_instantiation_keyring(ringid, rka, &dest_keyring);
1087 	if (ret < 0)
1088 		goto error2;
1089 
1090 	/* instantiate the key and link it into a keyring */
1091 	ret = key_instantiate_and_link(rka->target_key, payload, plen,
1092 				       dest_keyring, instkey);
1093 
1094 	key_put(dest_keyring);
1095 
1096 	/* discard the assumed authority if it's just been disabled by
1097 	 * instantiation of the key */
1098 	if (ret == 0)
1099 		keyctl_change_reqkey_auth(NULL);
1100 
1101 error2:
1102 	if (payload) {
1103 		memzero_explicit(payload, plen);
1104 		kvfree(payload);
1105 	}
1106 error:
1107 	return ret;
1108 }
1109 
1110 /*
1111  * Instantiate a key with the specified payload and link the key into the
1112  * destination keyring if one is given.
1113  *
1114  * The caller must have the appropriate instantiation permit set for this to
1115  * work (see keyctl_assume_authority).  No other permissions are required.
1116  *
1117  * If successful, 0 will be returned.
1118  */
1119 long keyctl_instantiate_key(key_serial_t id,
1120 			    const void __user *_payload,
1121 			    size_t plen,
1122 			    key_serial_t ringid)
1123 {
1124 	if (_payload && plen) {
1125 		struct iovec iov;
1126 		struct iov_iter from;
1127 		int ret;
1128 
1129 		ret = import_single_range(WRITE, (void __user *)_payload, plen,
1130 					  &iov, &from);
1131 		if (unlikely(ret))
1132 			return ret;
1133 
1134 		return keyctl_instantiate_key_common(id, &from, ringid);
1135 	}
1136 
1137 	return keyctl_instantiate_key_common(id, NULL, ringid);
1138 }
1139 
1140 /*
1141  * Instantiate a key with the specified multipart payload and link the key into
1142  * the destination keyring if one is given.
1143  *
1144  * The caller must have the appropriate instantiation permit set for this to
1145  * work (see keyctl_assume_authority).  No other permissions are required.
1146  *
1147  * If successful, 0 will be returned.
1148  */
1149 long keyctl_instantiate_key_iov(key_serial_t id,
1150 				const struct iovec __user *_payload_iov,
1151 				unsigned ioc,
1152 				key_serial_t ringid)
1153 {
1154 	struct iovec iovstack[UIO_FASTIOV], *iov = iovstack;
1155 	struct iov_iter from;
1156 	long ret;
1157 
1158 	if (!_payload_iov)
1159 		ioc = 0;
1160 
1161 	ret = import_iovec(WRITE, _payload_iov, ioc,
1162 				    ARRAY_SIZE(iovstack), &iov, &from);
1163 	if (ret < 0)
1164 		return ret;
1165 	ret = keyctl_instantiate_key_common(id, &from, ringid);
1166 	kfree(iov);
1167 	return ret;
1168 }
1169 
1170 /*
1171  * Negatively instantiate the key with the given timeout (in seconds) and link
1172  * the key into the destination keyring if one is given.
1173  *
1174  * The caller must have the appropriate instantiation permit set for this to
1175  * work (see keyctl_assume_authority).  No other permissions are required.
1176  *
1177  * The key and any links to the key will be automatically garbage collected
1178  * after the timeout expires.
1179  *
1180  * Negative keys are used to rate limit repeated request_key() calls by causing
1181  * them to return -ENOKEY until the negative key expires.
1182  *
1183  * If successful, 0 will be returned.
1184  */
1185 long keyctl_negate_key(key_serial_t id, unsigned timeout, key_serial_t ringid)
1186 {
1187 	return keyctl_reject_key(id, timeout, ENOKEY, ringid);
1188 }
1189 
1190 /*
1191  * Negatively instantiate the key with the given timeout (in seconds) and error
1192  * code and link the key into the destination keyring if one is given.
1193  *
1194  * The caller must have the appropriate instantiation permit set for this to
1195  * work (see keyctl_assume_authority).  No other permissions are required.
1196  *
1197  * The key and any links to the key will be automatically garbage collected
1198  * after the timeout expires.
1199  *
1200  * Negative keys are used to rate limit repeated request_key() calls by causing
1201  * them to return the specified error code until the negative key expires.
1202  *
1203  * If successful, 0 will be returned.
1204  */
1205 long keyctl_reject_key(key_serial_t id, unsigned timeout, unsigned error,
1206 		       key_serial_t ringid)
1207 {
1208 	const struct cred *cred = current_cred();
1209 	struct request_key_auth *rka;
1210 	struct key *instkey, *dest_keyring;
1211 	long ret;
1212 
1213 	kenter("%d,%u,%u,%d", id, timeout, error, ringid);
1214 
1215 	/* must be a valid error code and mustn't be a kernel special */
1216 	if (error <= 0 ||
1217 	    error >= MAX_ERRNO ||
1218 	    error == ERESTARTSYS ||
1219 	    error == ERESTARTNOINTR ||
1220 	    error == ERESTARTNOHAND ||
1221 	    error == ERESTART_RESTARTBLOCK)
1222 		return -EINVAL;
1223 
1224 	/* the appropriate instantiation authorisation key must have been
1225 	 * assumed before calling this */
1226 	ret = -EPERM;
1227 	instkey = cred->request_key_auth;
1228 	if (!instkey)
1229 		goto error;
1230 
1231 	rka = instkey->payload.data[0];
1232 	if (rka->target_key->serial != id)
1233 		goto error;
1234 
1235 	/* find the destination keyring if present (which must also be
1236 	 * writable) */
1237 	ret = get_instantiation_keyring(ringid, rka, &dest_keyring);
1238 	if (ret < 0)
1239 		goto error;
1240 
1241 	/* instantiate the key and link it into a keyring */
1242 	ret = key_reject_and_link(rka->target_key, timeout, error,
1243 				  dest_keyring, instkey);
1244 
1245 	key_put(dest_keyring);
1246 
1247 	/* discard the assumed authority if it's just been disabled by
1248 	 * instantiation of the key */
1249 	if (ret == 0)
1250 		keyctl_change_reqkey_auth(NULL);
1251 
1252 error:
1253 	return ret;
1254 }
1255 
1256 /*
1257  * Read or set the default keyring in which request_key() will cache keys and
1258  * return the old setting.
1259  *
1260  * If a thread or process keyring is specified then it will be created if it
1261  * doesn't yet exist.  The old setting will be returned if successful.
1262  */
1263 long keyctl_set_reqkey_keyring(int reqkey_defl)
1264 {
1265 	struct cred *new;
1266 	int ret, old_setting;
1267 
1268 	old_setting = current_cred_xxx(jit_keyring);
1269 
1270 	if (reqkey_defl == KEY_REQKEY_DEFL_NO_CHANGE)
1271 		return old_setting;
1272 
1273 	new = prepare_creds();
1274 	if (!new)
1275 		return -ENOMEM;
1276 
1277 	switch (reqkey_defl) {
1278 	case KEY_REQKEY_DEFL_THREAD_KEYRING:
1279 		ret = install_thread_keyring_to_cred(new);
1280 		if (ret < 0)
1281 			goto error;
1282 		goto set;
1283 
1284 	case KEY_REQKEY_DEFL_PROCESS_KEYRING:
1285 		ret = install_process_keyring_to_cred(new);
1286 		if (ret < 0)
1287 			goto error;
1288 		goto set;
1289 
1290 	case KEY_REQKEY_DEFL_DEFAULT:
1291 	case KEY_REQKEY_DEFL_SESSION_KEYRING:
1292 	case KEY_REQKEY_DEFL_USER_KEYRING:
1293 	case KEY_REQKEY_DEFL_USER_SESSION_KEYRING:
1294 	case KEY_REQKEY_DEFL_REQUESTOR_KEYRING:
1295 		goto set;
1296 
1297 	case KEY_REQKEY_DEFL_NO_CHANGE:
1298 	case KEY_REQKEY_DEFL_GROUP_KEYRING:
1299 	default:
1300 		ret = -EINVAL;
1301 		goto error;
1302 	}
1303 
1304 set:
1305 	new->jit_keyring = reqkey_defl;
1306 	commit_creds(new);
1307 	return old_setting;
1308 error:
1309 	abort_creds(new);
1310 	return ret;
1311 }
1312 
1313 /*
1314  * Set or clear the timeout on a key.
1315  *
1316  * Either the key must grant the caller Setattr permission or else the caller
1317  * must hold an instantiation authorisation token for the key.
1318  *
1319  * The timeout is either 0 to clear the timeout, or a number of seconds from
1320  * the current time.  The key and any links to the key will be automatically
1321  * garbage collected after the timeout expires.
1322  *
1323  * Keys with KEY_FLAG_KEEP set should not be timed out.
1324  *
1325  * If successful, 0 is returned.
1326  */
1327 long keyctl_set_timeout(key_serial_t id, unsigned timeout)
1328 {
1329 	struct key *key, *instkey;
1330 	key_ref_t key_ref;
1331 	long ret;
1332 
1333 	key_ref = lookup_user_key(id, KEY_LOOKUP_CREATE | KEY_LOOKUP_PARTIAL,
1334 				  KEY_NEED_SETATTR);
1335 	if (IS_ERR(key_ref)) {
1336 		/* setting the timeout on a key under construction is permitted
1337 		 * if we have the authorisation token handy */
1338 		if (PTR_ERR(key_ref) == -EACCES) {
1339 			instkey = key_get_instantiation_authkey(id);
1340 			if (!IS_ERR(instkey)) {
1341 				key_put(instkey);
1342 				key_ref = lookup_user_key(id,
1343 							  KEY_LOOKUP_PARTIAL,
1344 							  0);
1345 				if (!IS_ERR(key_ref))
1346 					goto okay;
1347 			}
1348 		}
1349 
1350 		ret = PTR_ERR(key_ref);
1351 		goto error;
1352 	}
1353 
1354 okay:
1355 	key = key_ref_to_ptr(key_ref);
1356 	ret = 0;
1357 	if (test_bit(KEY_FLAG_KEEP, &key->flags))
1358 		ret = -EPERM;
1359 	else
1360 		key_set_timeout(key, timeout);
1361 	key_put(key);
1362 
1363 error:
1364 	return ret;
1365 }
1366 
1367 /*
1368  * Assume (or clear) the authority to instantiate the specified key.
1369  *
1370  * This sets the authoritative token currently in force for key instantiation.
1371  * This must be done for a key to be instantiated.  It has the effect of making
1372  * available all the keys from the caller of the request_key() that created a
1373  * key to request_key() calls made by the caller of this function.
1374  *
1375  * The caller must have the instantiation key in their process keyrings with a
1376  * Search permission grant available to the caller.
1377  *
1378  * If the ID given is 0, then the setting will be cleared and 0 returned.
1379  *
1380  * If the ID given has a matching an authorisation key, then that key will be
1381  * set and its ID will be returned.  The authorisation key can be read to get
1382  * the callout information passed to request_key().
1383  */
1384 long keyctl_assume_authority(key_serial_t id)
1385 {
1386 	struct key *authkey;
1387 	long ret;
1388 
1389 	/* special key IDs aren't permitted */
1390 	ret = -EINVAL;
1391 	if (id < 0)
1392 		goto error;
1393 
1394 	/* we divest ourselves of authority if given an ID of 0 */
1395 	if (id == 0) {
1396 		ret = keyctl_change_reqkey_auth(NULL);
1397 		goto error;
1398 	}
1399 
1400 	/* attempt to assume the authority temporarily granted to us whilst we
1401 	 * instantiate the specified key
1402 	 * - the authorisation key must be in the current task's keyrings
1403 	 *   somewhere
1404 	 */
1405 	authkey = key_get_instantiation_authkey(id);
1406 	if (IS_ERR(authkey)) {
1407 		ret = PTR_ERR(authkey);
1408 		goto error;
1409 	}
1410 
1411 	ret = keyctl_change_reqkey_auth(authkey);
1412 	if (ret == 0)
1413 		ret = authkey->serial;
1414 	key_put(authkey);
1415 error:
1416 	return ret;
1417 }
1418 
1419 /*
1420  * Get a key's the LSM security label.
1421  *
1422  * The key must grant the caller View permission for this to work.
1423  *
1424  * If there's a buffer, then up to buflen bytes of data will be placed into it.
1425  *
1426  * If successful, the amount of information available will be returned,
1427  * irrespective of how much was copied (including the terminal NUL).
1428  */
1429 long keyctl_get_security(key_serial_t keyid,
1430 			 char __user *buffer,
1431 			 size_t buflen)
1432 {
1433 	struct key *key, *instkey;
1434 	key_ref_t key_ref;
1435 	char *context;
1436 	long ret;
1437 
1438 	key_ref = lookup_user_key(keyid, KEY_LOOKUP_PARTIAL, KEY_NEED_VIEW);
1439 	if (IS_ERR(key_ref)) {
1440 		if (PTR_ERR(key_ref) != -EACCES)
1441 			return PTR_ERR(key_ref);
1442 
1443 		/* viewing a key under construction is also permitted if we
1444 		 * have the authorisation token handy */
1445 		instkey = key_get_instantiation_authkey(keyid);
1446 		if (IS_ERR(instkey))
1447 			return PTR_ERR(instkey);
1448 		key_put(instkey);
1449 
1450 		key_ref = lookup_user_key(keyid, KEY_LOOKUP_PARTIAL, 0);
1451 		if (IS_ERR(key_ref))
1452 			return PTR_ERR(key_ref);
1453 	}
1454 
1455 	key = key_ref_to_ptr(key_ref);
1456 	ret = security_key_getsecurity(key, &context);
1457 	if (ret == 0) {
1458 		/* if no information was returned, give userspace an empty
1459 		 * string */
1460 		ret = 1;
1461 		if (buffer && buflen > 0 &&
1462 		    copy_to_user(buffer, "", 1) != 0)
1463 			ret = -EFAULT;
1464 	} else if (ret > 0) {
1465 		/* return as much data as there's room for */
1466 		if (buffer && buflen > 0) {
1467 			if (buflen > ret)
1468 				buflen = ret;
1469 
1470 			if (copy_to_user(buffer, context, buflen) != 0)
1471 				ret = -EFAULT;
1472 		}
1473 
1474 		kfree(context);
1475 	}
1476 
1477 	key_ref_put(key_ref);
1478 	return ret;
1479 }
1480 
1481 /*
1482  * Attempt to install the calling process's session keyring on the process's
1483  * parent process.
1484  *
1485  * The keyring must exist and must grant the caller LINK permission, and the
1486  * parent process must be single-threaded and must have the same effective
1487  * ownership as this process and mustn't be SUID/SGID.
1488  *
1489  * The keyring will be emplaced on the parent when it next resumes userspace.
1490  *
1491  * If successful, 0 will be returned.
1492  */
1493 long keyctl_session_to_parent(void)
1494 {
1495 	struct task_struct *me, *parent;
1496 	const struct cred *mycred, *pcred;
1497 	struct callback_head *newwork, *oldwork;
1498 	key_ref_t keyring_r;
1499 	struct cred *cred;
1500 	int ret;
1501 
1502 	keyring_r = lookup_user_key(KEY_SPEC_SESSION_KEYRING, 0, KEY_NEED_LINK);
1503 	if (IS_ERR(keyring_r))
1504 		return PTR_ERR(keyring_r);
1505 
1506 	ret = -ENOMEM;
1507 
1508 	/* our parent is going to need a new cred struct, a new tgcred struct
1509 	 * and new security data, so we allocate them here to prevent ENOMEM in
1510 	 * our parent */
1511 	cred = cred_alloc_blank();
1512 	if (!cred)
1513 		goto error_keyring;
1514 	newwork = &cred->rcu;
1515 
1516 	cred->session_keyring = key_ref_to_ptr(keyring_r);
1517 	keyring_r = NULL;
1518 	init_task_work(newwork, key_change_session_keyring);
1519 
1520 	me = current;
1521 	rcu_read_lock();
1522 	write_lock_irq(&tasklist_lock);
1523 
1524 	ret = -EPERM;
1525 	oldwork = NULL;
1526 	parent = me->real_parent;
1527 
1528 	/* the parent mustn't be init and mustn't be a kernel thread */
1529 	if (parent->pid <= 1 || !parent->mm)
1530 		goto unlock;
1531 
1532 	/* the parent must be single threaded */
1533 	if (!thread_group_empty(parent))
1534 		goto unlock;
1535 
1536 	/* the parent and the child must have different session keyrings or
1537 	 * there's no point */
1538 	mycred = current_cred();
1539 	pcred = __task_cred(parent);
1540 	if (mycred == pcred ||
1541 	    mycred->session_keyring == pcred->session_keyring) {
1542 		ret = 0;
1543 		goto unlock;
1544 	}
1545 
1546 	/* the parent must have the same effective ownership and mustn't be
1547 	 * SUID/SGID */
1548 	if (!uid_eq(pcred->uid,	 mycred->euid) ||
1549 	    !uid_eq(pcred->euid, mycred->euid) ||
1550 	    !uid_eq(pcred->suid, mycred->euid) ||
1551 	    !gid_eq(pcred->gid,	 mycred->egid) ||
1552 	    !gid_eq(pcred->egid, mycred->egid) ||
1553 	    !gid_eq(pcred->sgid, mycred->egid))
1554 		goto unlock;
1555 
1556 	/* the keyrings must have the same UID */
1557 	if ((pcred->session_keyring &&
1558 	     !uid_eq(pcred->session_keyring->uid, mycred->euid)) ||
1559 	    !uid_eq(mycred->session_keyring->uid, mycred->euid))
1560 		goto unlock;
1561 
1562 	/* cancel an already pending keyring replacement */
1563 	oldwork = task_work_cancel(parent, key_change_session_keyring);
1564 
1565 	/* the replacement session keyring is applied just prior to userspace
1566 	 * restarting */
1567 	ret = task_work_add(parent, newwork, true);
1568 	if (!ret)
1569 		newwork = NULL;
1570 unlock:
1571 	write_unlock_irq(&tasklist_lock);
1572 	rcu_read_unlock();
1573 	if (oldwork)
1574 		put_cred(container_of(oldwork, struct cred, rcu));
1575 	if (newwork)
1576 		put_cred(cred);
1577 	return ret;
1578 
1579 error_keyring:
1580 	key_ref_put(keyring_r);
1581 	return ret;
1582 }
1583 
1584 /*
1585  * Apply a restriction to a given keyring.
1586  *
1587  * The caller must have Setattr permission to change keyring restrictions.
1588  *
1589  * The requested type name may be a NULL pointer to reject all attempts
1590  * to link to the keyring.  In this case, _restriction must also be NULL.
1591  * Otherwise, both _type and _restriction must be non-NULL.
1592  *
1593  * Returns 0 if successful.
1594  */
1595 long keyctl_restrict_keyring(key_serial_t id, const char __user *_type,
1596 			     const char __user *_restriction)
1597 {
1598 	key_ref_t key_ref;
1599 	char type[32];
1600 	char *restriction = NULL;
1601 	long ret;
1602 
1603 	key_ref = lookup_user_key(id, 0, KEY_NEED_SETATTR);
1604 	if (IS_ERR(key_ref))
1605 		return PTR_ERR(key_ref);
1606 
1607 	ret = -EINVAL;
1608 	if (_type) {
1609 		if (!_restriction)
1610 			goto error;
1611 
1612 		ret = key_get_type_from_user(type, _type, sizeof(type));
1613 		if (ret < 0)
1614 			goto error;
1615 
1616 		restriction = strndup_user(_restriction, PAGE_SIZE);
1617 		if (IS_ERR(restriction)) {
1618 			ret = PTR_ERR(restriction);
1619 			goto error;
1620 		}
1621 	} else {
1622 		if (_restriction)
1623 			goto error;
1624 	}
1625 
1626 	ret = keyring_restrict(key_ref, _type ? type : NULL, restriction);
1627 	kfree(restriction);
1628 error:
1629 	key_ref_put(key_ref);
1630 	return ret;
1631 }
1632 
1633 /*
1634  * The key control system call
1635  */
1636 SYSCALL_DEFINE5(keyctl, int, option, unsigned long, arg2, unsigned long, arg3,
1637 		unsigned long, arg4, unsigned long, arg5)
1638 {
1639 	switch (option) {
1640 	case KEYCTL_GET_KEYRING_ID:
1641 		return keyctl_get_keyring_ID((key_serial_t) arg2,
1642 					     (int) arg3);
1643 
1644 	case KEYCTL_JOIN_SESSION_KEYRING:
1645 		return keyctl_join_session_keyring((const char __user *) arg2);
1646 
1647 	case KEYCTL_UPDATE:
1648 		return keyctl_update_key((key_serial_t) arg2,
1649 					 (const void __user *) arg3,
1650 					 (size_t) arg4);
1651 
1652 	case KEYCTL_REVOKE:
1653 		return keyctl_revoke_key((key_serial_t) arg2);
1654 
1655 	case KEYCTL_DESCRIBE:
1656 		return keyctl_describe_key((key_serial_t) arg2,
1657 					   (char __user *) arg3,
1658 					   (unsigned) arg4);
1659 
1660 	case KEYCTL_CLEAR:
1661 		return keyctl_keyring_clear((key_serial_t) arg2);
1662 
1663 	case KEYCTL_LINK:
1664 		return keyctl_keyring_link((key_serial_t) arg2,
1665 					   (key_serial_t) arg3);
1666 
1667 	case KEYCTL_UNLINK:
1668 		return keyctl_keyring_unlink((key_serial_t) arg2,
1669 					     (key_serial_t) arg3);
1670 
1671 	case KEYCTL_SEARCH:
1672 		return keyctl_keyring_search((key_serial_t) arg2,
1673 					     (const char __user *) arg3,
1674 					     (const char __user *) arg4,
1675 					     (key_serial_t) arg5);
1676 
1677 	case KEYCTL_READ:
1678 		return keyctl_read_key((key_serial_t) arg2,
1679 				       (char __user *) arg3,
1680 				       (size_t) arg4);
1681 
1682 	case KEYCTL_CHOWN:
1683 		return keyctl_chown_key((key_serial_t) arg2,
1684 					(uid_t) arg3,
1685 					(gid_t) arg4);
1686 
1687 	case KEYCTL_SETPERM:
1688 		return keyctl_setperm_key((key_serial_t) arg2,
1689 					  (key_perm_t) arg3);
1690 
1691 	case KEYCTL_INSTANTIATE:
1692 		return keyctl_instantiate_key((key_serial_t) arg2,
1693 					      (const void __user *) arg3,
1694 					      (size_t) arg4,
1695 					      (key_serial_t) arg5);
1696 
1697 	case KEYCTL_NEGATE:
1698 		return keyctl_negate_key((key_serial_t) arg2,
1699 					 (unsigned) arg3,
1700 					 (key_serial_t) arg4);
1701 
1702 	case KEYCTL_SET_REQKEY_KEYRING:
1703 		return keyctl_set_reqkey_keyring(arg2);
1704 
1705 	case KEYCTL_SET_TIMEOUT:
1706 		return keyctl_set_timeout((key_serial_t) arg2,
1707 					  (unsigned) arg3);
1708 
1709 	case KEYCTL_ASSUME_AUTHORITY:
1710 		return keyctl_assume_authority((key_serial_t) arg2);
1711 
1712 	case KEYCTL_GET_SECURITY:
1713 		return keyctl_get_security((key_serial_t) arg2,
1714 					   (char __user *) arg3,
1715 					   (size_t) arg4);
1716 
1717 	case KEYCTL_SESSION_TO_PARENT:
1718 		return keyctl_session_to_parent();
1719 
1720 	case KEYCTL_REJECT:
1721 		return keyctl_reject_key((key_serial_t) arg2,
1722 					 (unsigned) arg3,
1723 					 (unsigned) arg4,
1724 					 (key_serial_t) arg5);
1725 
1726 	case KEYCTL_INSTANTIATE_IOV:
1727 		return keyctl_instantiate_key_iov(
1728 			(key_serial_t) arg2,
1729 			(const struct iovec __user *) arg3,
1730 			(unsigned) arg4,
1731 			(key_serial_t) arg5);
1732 
1733 	case KEYCTL_INVALIDATE:
1734 		return keyctl_invalidate_key((key_serial_t) arg2);
1735 
1736 	case KEYCTL_GET_PERSISTENT:
1737 		return keyctl_get_persistent((uid_t)arg2, (key_serial_t)arg3);
1738 
1739 	case KEYCTL_DH_COMPUTE:
1740 		return keyctl_dh_compute((struct keyctl_dh_params __user *) arg2,
1741 					 (char __user *) arg3, (size_t) arg4,
1742 					 (struct keyctl_kdf_params __user *) arg5);
1743 
1744 	case KEYCTL_RESTRICT_KEYRING:
1745 		return keyctl_restrict_keyring((key_serial_t) arg2,
1746 					       (const char __user *) arg3,
1747 					       (const char __user *) arg4);
1748 
1749 	case KEYCTL_PKEY_QUERY:
1750 		if (arg3 != 0)
1751 			return -EINVAL;
1752 		return keyctl_pkey_query((key_serial_t)arg2,
1753 					 (const char __user *)arg4,
1754 					 (struct keyctl_pkey_query *)arg5);
1755 
1756 	case KEYCTL_PKEY_ENCRYPT:
1757 	case KEYCTL_PKEY_DECRYPT:
1758 	case KEYCTL_PKEY_SIGN:
1759 		return keyctl_pkey_e_d_s(
1760 			option,
1761 			(const struct keyctl_pkey_params __user *)arg2,
1762 			(const char __user *)arg3,
1763 			(const void __user *)arg4,
1764 			(void __user *)arg5);
1765 
1766 	case KEYCTL_PKEY_VERIFY:
1767 		return keyctl_pkey_verify(
1768 			(const struct keyctl_pkey_params __user *)arg2,
1769 			(const char __user *)arg3,
1770 			(const void __user *)arg4,
1771 			(const void __user *)arg5);
1772 
1773 	default:
1774 		return -EOPNOTSUPP;
1775 	}
1776 }
1777