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