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