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