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