]> asedeno.scripts.mit.edu Git - linux.git/blob - security/keys/keyctl.c
keys: Provide KEYCTL_GRANT_PERMISSION
[linux.git] / security / keys / keyctl.c
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                KEYCTL_CAPS1_ACL_ALTERABLE),
46 };
47
48 static int key_get_type_from_user(char *type,
49                                   const char __user *_type,
50                                   unsigned len)
51 {
52         int ret;
53
54         ret = strncpy_from_user(type, _type, len);
55         if (ret < 0)
56                 return ret;
57         if (ret == 0 || ret >= len)
58                 return -EINVAL;
59         if (type[0] == '.')
60                 return -EPERM;
61         type[len - 1] = '\0';
62         return 0;
63 }
64
65 /*
66  * Extract the description of a new key from userspace and either add it as a
67  * new key to the specified keyring or update a matching key in that keyring.
68  *
69  * If the description is NULL or an empty string, the key type is asked to
70  * generate one from the payload.
71  *
72  * The keyring must be writable so that we can attach the key to it.
73  *
74  * If successful, the new key's serial number is returned, otherwise an error
75  * code is returned.
76  */
77 SYSCALL_DEFINE5(add_key, const char __user *, _type,
78                 const char __user *, _description,
79                 const void __user *, _payload,
80                 size_t, plen,
81                 key_serial_t, ringid)
82 {
83         key_ref_t keyring_ref, key_ref;
84         char type[32], *description;
85         void *payload;
86         long ret;
87
88         ret = -EINVAL;
89         if (plen > 1024 * 1024 - 1)
90                 goto error;
91
92         /* draw all the data into kernel space */
93         ret = key_get_type_from_user(type, _type, sizeof(type));
94         if (ret < 0)
95                 goto error;
96
97         description = NULL;
98         if (_description) {
99                 description = strndup_user(_description, KEY_MAX_DESC_SIZE);
100                 if (IS_ERR(description)) {
101                         ret = PTR_ERR(description);
102                         goto error;
103                 }
104                 if (!*description) {
105                         kfree(description);
106                         description = NULL;
107                 } else if ((description[0] == '.') &&
108                            (strncmp(type, "keyring", 7) == 0)) {
109                         ret = -EPERM;
110                         goto error2;
111                 }
112         }
113
114         /* pull the payload in if one was supplied */
115         payload = NULL;
116
117         if (plen) {
118                 ret = -ENOMEM;
119                 payload = kvmalloc(plen, GFP_KERNEL);
120                 if (!payload)
121                         goto error2;
122
123                 ret = -EFAULT;
124                 if (copy_from_user(payload, _payload, plen) != 0)
125                         goto error3;
126         }
127
128         /* find the target keyring (which must be writable) */
129         keyring_ref = lookup_user_key(ringid, KEY_LOOKUP_CREATE, KEY_NEED_WRITE);
130         if (IS_ERR(keyring_ref)) {
131                 ret = PTR_ERR(keyring_ref);
132                 goto error3;
133         }
134
135         /* create or update the requested key and add it to the target
136          * keyring */
137         key_ref = key_create_or_update(keyring_ref, type, description,
138                                        payload, plen, NULL, 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, NULL,
229                                    key_ref_to_ptr(dest_ref),
230                                    KEY_ALLOC_IN_QUOTA);
231         if (IS_ERR(key)) {
232                 ret = PTR_ERR(key);
233                 goto error5;
234         }
235
236         /* wait for the key to finish being constructed */
237         ret = wait_for_key_construction(key, 1);
238         if (ret < 0)
239                 goto error6;
240
241         ret = key->serial;
242
243 error6:
244         key_put(key);
245 error5:
246         key_type_put(ktype);
247 error4:
248         key_ref_put(dest_ref);
249 error3:
250         kfree(callout_info);
251 error2:
252         kfree(description);
253 error:
254         return ret;
255 }
256
257 /*
258  * Get the ID of the specified process keyring.
259  *
260  * The requested keyring must have search permission to be found.
261  *
262  * If successful, the ID of the requested keyring will be returned.
263  */
264 long keyctl_get_keyring_ID(key_serial_t id, int create)
265 {
266         key_ref_t key_ref;
267         unsigned long lflags;
268         long ret;
269
270         lflags = create ? KEY_LOOKUP_CREATE : 0;
271         key_ref = lookup_user_key(id, lflags, KEY_NEED_SEARCH);
272         if (IS_ERR(key_ref)) {
273                 ret = PTR_ERR(key_ref);
274                 goto error;
275         }
276
277         ret = key_ref_to_ptr(key_ref)->serial;
278         key_ref_put(key_ref);
279 error:
280         return ret;
281 }
282
283 /*
284  * Join a (named) session keyring.
285  *
286  * Create and join an anonymous session keyring or join a named session
287  * keyring, creating it if necessary.  A named session keyring must have Search
288  * permission for it to be joined.  Session keyrings without this permit will
289  * be skipped over.  It is not permitted for userspace to create or join
290  * keyrings whose name begin with a dot.
291  *
292  * If successful, the ID of the joined session keyring will be returned.
293  */
294 long keyctl_join_session_keyring(const char __user *_name)
295 {
296         char *name;
297         long ret;
298
299         /* fetch the name from userspace */
300         name = NULL;
301         if (_name) {
302                 name = strndup_user(_name, KEY_MAX_DESC_SIZE);
303                 if (IS_ERR(name)) {
304                         ret = PTR_ERR(name);
305                         goto error;
306                 }
307
308                 ret = -EPERM;
309                 if (name[0] == '.')
310                         goto error_name;
311         }
312
313         /* join the session */
314         ret = join_session_keyring(name);
315 error_name:
316         kfree(name);
317 error:
318         return ret;
319 }
320
321 /*
322  * Update a key's data payload from the given data.
323  *
324  * The key must grant the caller Write permission and the key type must support
325  * updating for this to work.  A negative key can be positively instantiated
326  * with this call.
327  *
328  * If successful, 0 will be returned.  If the key type does not support
329  * updating, then -EOPNOTSUPP will be returned.
330  */
331 long keyctl_update_key(key_serial_t id,
332                        const void __user *_payload,
333                        size_t plen)
334 {
335         key_ref_t key_ref;
336         void *payload;
337         long ret;
338
339         ret = -EINVAL;
340         if (plen > PAGE_SIZE)
341                 goto error;
342
343         /* pull the payload in if one was supplied */
344         payload = NULL;
345         if (plen) {
346                 ret = -ENOMEM;
347                 payload = kmalloc(plen, GFP_KERNEL);
348                 if (!payload)
349                         goto error;
350
351                 ret = -EFAULT;
352                 if (copy_from_user(payload, _payload, plen) != 0)
353                         goto error2;
354         }
355
356         /* find the target key (which must be writable) */
357         key_ref = lookup_user_key(id, 0, KEY_NEED_WRITE);
358         if (IS_ERR(key_ref)) {
359                 ret = PTR_ERR(key_ref);
360                 goto error2;
361         }
362
363         /* update the key */
364         ret = key_update(key_ref, payload, plen);
365
366         key_ref_put(key_ref);
367 error2:
368         kzfree(payload);
369 error:
370         return ret;
371 }
372
373 /*
374  * Revoke a key.
375  *
376  * The key must be grant the caller Write or Setattr permission for this to
377  * work.  The key type should give up its quota claim when revoked.  The key
378  * and any links to the key will be automatically garbage collected after a
379  * certain amount of time (/proc/sys/kernel/keys/gc_delay).
380  *
381  * Keys with KEY_FLAG_KEEP set should not be revoked.
382  *
383  * If successful, 0 is returned.
384  */
385 long keyctl_revoke_key(key_serial_t id)
386 {
387         key_ref_t key_ref;
388         struct key *key;
389         long ret;
390
391         key_ref = lookup_user_key(id, 0, KEY_NEED_REVOKE);
392         if (IS_ERR(key_ref)) {
393                 ret = PTR_ERR(key_ref);
394                 goto error;
395         }
396
397         key = key_ref_to_ptr(key_ref);
398         ret = 0;
399         if (test_bit(KEY_FLAG_KEEP, &key->flags))
400                 ret = -EPERM;
401         else
402                 key_revoke(key);
403
404         key_ref_put(key_ref);
405 error:
406         return ret;
407 }
408
409 /*
410  * Invalidate a key.
411  *
412  * The key must be grant the caller Invalidate permission for this to work.
413  * The key and any links to the key will be automatically garbage collected
414  * immediately.
415  *
416  * Keys with KEY_FLAG_KEEP set should not be invalidated.
417  *
418  * If successful, 0 is returned.
419  */
420 long keyctl_invalidate_key(key_serial_t id)
421 {
422         key_ref_t key_ref;
423         struct key *key;
424         long ret;
425
426         kenter("%d", id);
427
428         key_ref = lookup_user_key(id, 0, KEY_NEED_INVAL);
429         if (IS_ERR(key_ref)) {
430                 ret = PTR_ERR(key_ref);
431
432                 /* Root is permitted to invalidate certain special keys */
433                 if (capable(CAP_SYS_ADMIN)) {
434                         key_ref = lookup_user_key(id, 0, 0);
435                         if (IS_ERR(key_ref))
436                                 goto error;
437                         if (test_bit(KEY_FLAG_ROOT_CAN_INVAL,
438                                      &key_ref_to_ptr(key_ref)->flags))
439                                 goto invalidate;
440                         goto error_put;
441                 }
442
443                 goto error;
444         }
445
446 invalidate:
447         key = key_ref_to_ptr(key_ref);
448         ret = 0;
449         if (test_bit(KEY_FLAG_KEEP, &key->flags))
450                 ret = -EPERM;
451         else
452                 key_invalidate(key);
453 error_put:
454         key_ref_put(key_ref);
455 error:
456         kleave(" = %ld", ret);
457         return ret;
458 }
459
460 /*
461  * Clear the specified keyring, creating an empty process keyring if one of the
462  * special keyring IDs is used.
463  *
464  * The keyring must grant the caller Write permission and not have
465  * KEY_FLAG_KEEP set for this to work.  If successful, 0 will be returned.
466  */
467 long keyctl_keyring_clear(key_serial_t ringid)
468 {
469         key_ref_t keyring_ref;
470         struct key *keyring;
471         long ret;
472
473         keyring_ref = lookup_user_key(ringid, KEY_LOOKUP_CREATE, KEY_NEED_CLEAR);
474         if (IS_ERR(keyring_ref)) {
475                 ret = PTR_ERR(keyring_ref);
476
477                 /* Root is permitted to invalidate certain special keyrings */
478                 if (capable(CAP_SYS_ADMIN)) {
479                         keyring_ref = lookup_user_key(ringid, 0, 0);
480                         if (IS_ERR(keyring_ref))
481                                 goto error;
482                         if (test_bit(KEY_FLAG_ROOT_CAN_CLEAR,
483                                      &key_ref_to_ptr(keyring_ref)->flags))
484                                 goto clear;
485                         goto error_put;
486                 }
487
488                 goto error;
489         }
490
491 clear:
492         keyring = key_ref_to_ptr(keyring_ref);
493         if (test_bit(KEY_FLAG_KEEP, &keyring->flags))
494                 ret = -EPERM;
495         else
496                 ret = keyring_clear(keyring);
497 error_put:
498         key_ref_put(keyring_ref);
499 error:
500         return ret;
501 }
502
503 /*
504  * Create a link from a keyring to a key if there's no matching key in the
505  * keyring, otherwise replace the link to the matching key with a link to the
506  * new key.
507  *
508  * The key must grant the caller Link permission and the the keyring must grant
509  * the caller Write permission.  Furthermore, if an additional link is created,
510  * the keyring's quota will be extended.
511  *
512  * If successful, 0 will be returned.
513  */
514 long keyctl_keyring_link(key_serial_t id, key_serial_t ringid)
515 {
516         key_ref_t keyring_ref, key_ref;
517         long ret;
518
519         keyring_ref = lookup_user_key(ringid, KEY_LOOKUP_CREATE, KEY_NEED_WRITE);
520         if (IS_ERR(keyring_ref)) {
521                 ret = PTR_ERR(keyring_ref);
522                 goto error;
523         }
524
525         key_ref = lookup_user_key(id, KEY_LOOKUP_CREATE, KEY_NEED_LINK);
526         if (IS_ERR(key_ref)) {
527                 ret = PTR_ERR(key_ref);
528                 goto error2;
529         }
530
531         ret = key_link(key_ref_to_ptr(keyring_ref), key_ref_to_ptr(key_ref));
532
533         key_ref_put(key_ref);
534 error2:
535         key_ref_put(keyring_ref);
536 error:
537         return ret;
538 }
539
540 /*
541  * Unlink a key from a keyring.
542  *
543  * The keyring must grant the caller Write permission for this to work; the key
544  * itself need not grant the caller anything.  If the last link to a key is
545  * removed then that key will be scheduled for destruction.
546  *
547  * Keys or keyrings with KEY_FLAG_KEEP set should not be unlinked.
548  *
549  * If successful, 0 will be returned.
550  */
551 long keyctl_keyring_unlink(key_serial_t id, key_serial_t ringid)
552 {
553         key_ref_t keyring_ref, key_ref;
554         struct key *keyring, *key;
555         long ret;
556
557         keyring_ref = lookup_user_key(ringid, 0, KEY_NEED_WRITE);
558         if (IS_ERR(keyring_ref)) {
559                 ret = PTR_ERR(keyring_ref);
560                 goto error;
561         }
562
563         key_ref = lookup_user_key(id, KEY_LOOKUP_FOR_UNLINK, 0);
564         if (IS_ERR(key_ref)) {
565                 ret = PTR_ERR(key_ref);
566                 goto error2;
567         }
568
569         keyring = key_ref_to_ptr(keyring_ref);
570         key = key_ref_to_ptr(key_ref);
571         if (test_bit(KEY_FLAG_KEEP, &keyring->flags) &&
572             test_bit(KEY_FLAG_KEEP, &key->flags))
573                 ret = -EPERM;
574         else
575                 ret = key_unlink(keyring, key);
576
577         key_ref_put(key_ref);
578 error2:
579         key_ref_put(keyring_ref);
580 error:
581         return ret;
582 }
583
584 /*
585  * Move a link to a key from one keyring to another, displacing any matching
586  * key from the destination keyring.
587  *
588  * The key must grant the caller Link permission and both keyrings must grant
589  * the caller Write permission.  There must also be a link in the from keyring
590  * to the key.  If both keyrings are the same, nothing is done.
591  *
592  * If successful, 0 will be returned.
593  */
594 long keyctl_keyring_move(key_serial_t id, key_serial_t from_ringid,
595                          key_serial_t to_ringid, unsigned int flags)
596 {
597         key_ref_t key_ref, from_ref, to_ref;
598         long ret;
599
600         if (flags & ~KEYCTL_MOVE_EXCL)
601                 return -EINVAL;
602
603         key_ref = lookup_user_key(id, KEY_LOOKUP_CREATE, KEY_NEED_LINK);
604         if (IS_ERR(key_ref))
605                 return PTR_ERR(key_ref);
606
607         from_ref = lookup_user_key(from_ringid, 0, KEY_NEED_WRITE);
608         if (IS_ERR(from_ref)) {
609                 ret = PTR_ERR(from_ref);
610                 goto error2;
611         }
612
613         to_ref = lookup_user_key(to_ringid, KEY_LOOKUP_CREATE, KEY_NEED_WRITE);
614         if (IS_ERR(to_ref)) {
615                 ret = PTR_ERR(to_ref);
616                 goto error3;
617         }
618
619         ret = key_move(key_ref_to_ptr(key_ref), key_ref_to_ptr(from_ref),
620                        key_ref_to_ptr(to_ref), flags);
621
622         key_ref_put(to_ref);
623 error3:
624         key_ref_put(from_ref);
625 error2:
626         key_ref_put(key_ref);
627         return ret;
628 }
629
630 /*
631  * Return a description of a key to userspace.
632  *
633  * The key must grant the caller View permission for this to work.
634  *
635  * If there's a buffer, we place up to buflen bytes of data into it formatted
636  * in the following way:
637  *
638  *      type;uid;gid;perm;description<NUL>
639  *
640  * If successful, we return the amount of description available, irrespective
641  * of how much we may have copied into the buffer.
642  */
643 long keyctl_describe_key(key_serial_t keyid,
644                          char __user *buffer,
645                          size_t buflen)
646 {
647         struct key *key, *instkey;
648         unsigned int perm;
649         key_ref_t key_ref;
650         char *infobuf;
651         long ret;
652         int desclen, infolen;
653
654         key_ref = lookup_user_key(keyid, KEY_LOOKUP_PARTIAL, KEY_NEED_VIEW);
655         if (IS_ERR(key_ref)) {
656                 /* viewing a key under construction is permitted if we have the
657                  * authorisation token handy */
658                 if (PTR_ERR(key_ref) == -EACCES) {
659                         instkey = key_get_instantiation_authkey(keyid);
660                         if (!IS_ERR(instkey)) {
661                                 key_put(instkey);
662                                 key_ref = lookup_user_key(keyid,
663                                                           KEY_LOOKUP_PARTIAL,
664                                                           0);
665                                 if (!IS_ERR(key_ref))
666                                         goto okay;
667                         }
668                 }
669
670                 ret = PTR_ERR(key_ref);
671                 goto error;
672         }
673
674 okay:
675         key = key_ref_to_ptr(key_ref);
676         desclen = strlen(key->description);
677
678         rcu_read_lock();
679         perm = key_acl_to_perm(rcu_dereference(key->acl));
680         rcu_read_unlock();
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                             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_SETSEC);
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, unsigned int perm)
1002 {
1003         struct key_acl *acl;
1004         struct key *key;
1005         key_ref_t key_ref;
1006         long ret;
1007         int nr, i, j;
1008
1009         if (perm & ~(KEY_POS_ALL | KEY_USR_ALL | KEY_GRP_ALL | KEY_OTH_ALL))
1010                 return -EINVAL;
1011
1012         nr = 0;
1013         if (perm & KEY_POS_ALL) nr++;
1014         if (perm & KEY_USR_ALL) nr++;
1015         if (perm & KEY_GRP_ALL) nr++;
1016         if (perm & KEY_OTH_ALL) nr++;
1017
1018         key_ref = lookup_user_key(id, KEY_LOOKUP_CREATE | KEY_LOOKUP_PARTIAL,
1019                                   KEY_NEED_SETSEC);
1020         if (IS_ERR(key_ref)) {
1021                 ret = PTR_ERR(key_ref);
1022                 goto error;
1023         }
1024
1025         key = key_ref_to_ptr(key_ref);
1026
1027         ret = -EOPNOTSUPP;
1028         if (test_bit(KEY_FLAG_HAS_ACL, &key->flags))
1029                 goto error_key;
1030
1031         ret = -ENOMEM;
1032         acl = kzalloc(struct_size(acl, aces, nr), GFP_KERNEL);
1033         if (!acl)
1034                 goto error_key;
1035
1036         refcount_set(&acl->usage, 1);
1037         acl->nr_ace = nr;
1038         j = 0;
1039         for (i = 0; i < 4; i++) {
1040                 struct key_ace *ace = &acl->aces[j];
1041                 unsigned int subset = (perm >> (i * 8)) & KEY_OTH_ALL;
1042
1043                 if (!subset)
1044                         continue;
1045                 ace->type = KEY_ACE_SUBJ_STANDARD;
1046                 ace->subject_id = KEY_ACE_EVERYONE + i;
1047                 ace->perm = subset;
1048                 if (subset & (KEY_OTH_WRITE | KEY_OTH_SETATTR))
1049                         ace->perm |= KEY_ACE_REVOKE;
1050                 if (subset & KEY_OTH_SEARCH)
1051                         ace->perm |= KEY_ACE_INVAL;
1052                 if (key->type == &key_type_keyring) {
1053                         if (subset & KEY_OTH_SEARCH)
1054                                 ace->perm |= KEY_ACE_JOIN;
1055                         if (subset & KEY_OTH_WRITE)
1056                                 ace->perm |= KEY_ACE_CLEAR;
1057                 }
1058                 j++;
1059         }
1060
1061         /* make the changes with the locks held to prevent chown/chmod races */
1062         down_write(&key->sem);
1063         ret = key_set_acl(key, acl);
1064         up_write(&key->sem);
1065 error_key:
1066         key_put(key);
1067 error:
1068         return ret;
1069 }
1070
1071 /*
1072  * Get the destination keyring for instantiation and check that the caller has
1073  * Write permission on it.
1074  */
1075 static long get_instantiation_keyring(key_serial_t ringid,
1076                                       struct request_key_auth *rka,
1077                                       struct key **_dest_keyring)
1078 {
1079         key_ref_t dkref;
1080
1081         *_dest_keyring = NULL;
1082
1083         /* just return a NULL pointer if we weren't asked to make a link */
1084         if (ringid == 0)
1085                 return 0;
1086
1087         /* if a specific keyring is nominated by ID, then use that */
1088         if (ringid > 0) {
1089                 dkref = lookup_user_key(ringid, KEY_LOOKUP_CREATE, KEY_NEED_WRITE);
1090                 if (IS_ERR(dkref))
1091                         return PTR_ERR(dkref);
1092                 *_dest_keyring = key_ref_to_ptr(dkref);
1093                 return 0;
1094         }
1095
1096         if (ringid == KEY_SPEC_REQKEY_AUTH_KEY)
1097                 return -EINVAL;
1098
1099         /* otherwise specify the destination keyring recorded in the
1100          * authorisation key (any KEY_SPEC_*_KEYRING) */
1101         if (ringid >= KEY_SPEC_REQUESTOR_KEYRING) {
1102                 *_dest_keyring = key_get(rka->dest_keyring);
1103                 return 0;
1104         }
1105
1106         return -ENOKEY;
1107 }
1108
1109 /*
1110  * Change the request_key authorisation key on the current process.
1111  */
1112 static int keyctl_change_reqkey_auth(struct key *key)
1113 {
1114         struct cred *new;
1115
1116         new = prepare_creds();
1117         if (!new)
1118                 return -ENOMEM;
1119
1120         key_put(new->request_key_auth);
1121         new->request_key_auth = key_get(key);
1122
1123         return commit_creds(new);
1124 }
1125
1126 /*
1127  * Instantiate a key with the specified payload and link the key into the
1128  * destination keyring if one is given.
1129  *
1130  * The caller must have the appropriate instantiation permit set for this to
1131  * work (see keyctl_assume_authority).  No other permissions are required.
1132  *
1133  * If successful, 0 will be returned.
1134  */
1135 long keyctl_instantiate_key_common(key_serial_t id,
1136                                    struct iov_iter *from,
1137                                    key_serial_t ringid)
1138 {
1139         const struct cred *cred = current_cred();
1140         struct request_key_auth *rka;
1141         struct key *instkey, *dest_keyring;
1142         size_t plen = from ? iov_iter_count(from) : 0;
1143         void *payload;
1144         long ret;
1145
1146         kenter("%d,,%zu,%d", id, plen, ringid);
1147
1148         if (!plen)
1149                 from = NULL;
1150
1151         ret = -EINVAL;
1152         if (plen > 1024 * 1024 - 1)
1153                 goto error;
1154
1155         /* the appropriate instantiation authorisation key must have been
1156          * assumed before calling this */
1157         ret = -EPERM;
1158         instkey = cred->request_key_auth;
1159         if (!instkey)
1160                 goto error;
1161
1162         rka = instkey->payload.data[0];
1163         if (rka->target_key->serial != id)
1164                 goto error;
1165
1166         /* pull the payload in if one was supplied */
1167         payload = NULL;
1168
1169         if (from) {
1170                 ret = -ENOMEM;
1171                 payload = kvmalloc(plen, GFP_KERNEL);
1172                 if (!payload)
1173                         goto error;
1174
1175                 ret = -EFAULT;
1176                 if (!copy_from_iter_full(payload, plen, from))
1177                         goto error2;
1178         }
1179
1180         /* find the destination keyring amongst those belonging to the
1181          * requesting task */
1182         ret = get_instantiation_keyring(ringid, rka, &dest_keyring);
1183         if (ret < 0)
1184                 goto error2;
1185
1186         /* instantiate the key and link it into a keyring */
1187         ret = key_instantiate_and_link(rka->target_key, payload, plen,
1188                                        dest_keyring, instkey);
1189
1190         key_put(dest_keyring);
1191
1192         /* discard the assumed authority if it's just been disabled by
1193          * instantiation of the key */
1194         if (ret == 0)
1195                 keyctl_change_reqkey_auth(NULL);
1196
1197 error2:
1198         if (payload) {
1199                 memzero_explicit(payload, plen);
1200                 kvfree(payload);
1201         }
1202 error:
1203         return ret;
1204 }
1205
1206 /*
1207  * Instantiate a key with the specified payload and link the key into the
1208  * destination keyring if one is given.
1209  *
1210  * The caller must have the appropriate instantiation permit set for this to
1211  * work (see keyctl_assume_authority).  No other permissions are required.
1212  *
1213  * If successful, 0 will be returned.
1214  */
1215 long keyctl_instantiate_key(key_serial_t id,
1216                             const void __user *_payload,
1217                             size_t plen,
1218                             key_serial_t ringid)
1219 {
1220         if (_payload && plen) {
1221                 struct iovec iov;
1222                 struct iov_iter from;
1223                 int ret;
1224
1225                 ret = import_single_range(WRITE, (void __user *)_payload, plen,
1226                                           &iov, &from);
1227                 if (unlikely(ret))
1228                         return ret;
1229
1230                 return keyctl_instantiate_key_common(id, &from, ringid);
1231         }
1232
1233         return keyctl_instantiate_key_common(id, NULL, ringid);
1234 }
1235
1236 /*
1237  * Instantiate a key with the specified multipart payload and link the key into
1238  * the destination keyring if one is given.
1239  *
1240  * The caller must have the appropriate instantiation permit set for this to
1241  * work (see keyctl_assume_authority).  No other permissions are required.
1242  *
1243  * If successful, 0 will be returned.
1244  */
1245 long keyctl_instantiate_key_iov(key_serial_t id,
1246                                 const struct iovec __user *_payload_iov,
1247                                 unsigned ioc,
1248                                 key_serial_t ringid)
1249 {
1250         struct iovec iovstack[UIO_FASTIOV], *iov = iovstack;
1251         struct iov_iter from;
1252         long ret;
1253
1254         if (!_payload_iov)
1255                 ioc = 0;
1256
1257         ret = import_iovec(WRITE, _payload_iov, ioc,
1258                                     ARRAY_SIZE(iovstack), &iov, &from);
1259         if (ret < 0)
1260                 return ret;
1261         ret = keyctl_instantiate_key_common(id, &from, ringid);
1262         kfree(iov);
1263         return ret;
1264 }
1265
1266 /*
1267  * Negatively instantiate the key with the given timeout (in seconds) and link
1268  * the key into the destination keyring if one is given.
1269  *
1270  * The caller must have the appropriate instantiation permit set for this to
1271  * work (see keyctl_assume_authority).  No other permissions are required.
1272  *
1273  * The key and any links to the key will be automatically garbage collected
1274  * after the timeout expires.
1275  *
1276  * Negative keys are used to rate limit repeated request_key() calls by causing
1277  * them to return -ENOKEY until the negative key expires.
1278  *
1279  * If successful, 0 will be returned.
1280  */
1281 long keyctl_negate_key(key_serial_t id, unsigned timeout, key_serial_t ringid)
1282 {
1283         return keyctl_reject_key(id, timeout, ENOKEY, ringid);
1284 }
1285
1286 /*
1287  * Negatively instantiate the key with the given timeout (in seconds) and error
1288  * code and link the key into the destination keyring if one is given.
1289  *
1290  * The caller must have the appropriate instantiation permit set for this to
1291  * work (see keyctl_assume_authority).  No other permissions are required.
1292  *
1293  * The key and any links to the key will be automatically garbage collected
1294  * after the timeout expires.
1295  *
1296  * Negative keys are used to rate limit repeated request_key() calls by causing
1297  * them to return the specified error code until the negative key expires.
1298  *
1299  * If successful, 0 will be returned.
1300  */
1301 long keyctl_reject_key(key_serial_t id, unsigned timeout, unsigned error,
1302                        key_serial_t ringid)
1303 {
1304         const struct cred *cred = current_cred();
1305         struct request_key_auth *rka;
1306         struct key *instkey, *dest_keyring;
1307         long ret;
1308
1309         kenter("%d,%u,%u,%d", id, timeout, error, ringid);
1310
1311         /* must be a valid error code and mustn't be a kernel special */
1312         if (error <= 0 ||
1313             error >= MAX_ERRNO ||
1314             error == ERESTARTSYS ||
1315             error == ERESTARTNOINTR ||
1316             error == ERESTARTNOHAND ||
1317             error == ERESTART_RESTARTBLOCK)
1318                 return -EINVAL;
1319
1320         /* the appropriate instantiation authorisation key must have been
1321          * assumed before calling this */
1322         ret = -EPERM;
1323         instkey = cred->request_key_auth;
1324         if (!instkey)
1325                 goto error;
1326
1327         rka = instkey->payload.data[0];
1328         if (rka->target_key->serial != id)
1329                 goto error;
1330
1331         /* find the destination keyring if present (which must also be
1332          * writable) */
1333         ret = get_instantiation_keyring(ringid, rka, &dest_keyring);
1334         if (ret < 0)
1335                 goto error;
1336
1337         /* instantiate the key and link it into a keyring */
1338         ret = key_reject_and_link(rka->target_key, timeout, error,
1339                                   dest_keyring, instkey);
1340
1341         key_put(dest_keyring);
1342
1343         /* discard the assumed authority if it's just been disabled by
1344          * instantiation of the key */
1345         if (ret == 0)
1346                 keyctl_change_reqkey_auth(NULL);
1347
1348 error:
1349         return ret;
1350 }
1351
1352 /*
1353  * Read or set the default keyring in which request_key() will cache keys and
1354  * return the old setting.
1355  *
1356  * If a thread or process keyring is specified then it will be created if it
1357  * doesn't yet exist.  The old setting will be returned if successful.
1358  */
1359 long keyctl_set_reqkey_keyring(int reqkey_defl)
1360 {
1361         struct cred *new;
1362         int ret, old_setting;
1363
1364         old_setting = current_cred_xxx(jit_keyring);
1365
1366         if (reqkey_defl == KEY_REQKEY_DEFL_NO_CHANGE)
1367                 return old_setting;
1368
1369         new = prepare_creds();
1370         if (!new)
1371                 return -ENOMEM;
1372
1373         switch (reqkey_defl) {
1374         case KEY_REQKEY_DEFL_THREAD_KEYRING:
1375                 ret = install_thread_keyring_to_cred(new);
1376                 if (ret < 0)
1377                         goto error;
1378                 goto set;
1379
1380         case KEY_REQKEY_DEFL_PROCESS_KEYRING:
1381                 ret = install_process_keyring_to_cred(new);
1382                 if (ret < 0)
1383                         goto error;
1384                 goto set;
1385
1386         case KEY_REQKEY_DEFL_DEFAULT:
1387         case KEY_REQKEY_DEFL_SESSION_KEYRING:
1388         case KEY_REQKEY_DEFL_USER_KEYRING:
1389         case KEY_REQKEY_DEFL_USER_SESSION_KEYRING:
1390         case KEY_REQKEY_DEFL_REQUESTOR_KEYRING:
1391                 goto set;
1392
1393         case KEY_REQKEY_DEFL_NO_CHANGE:
1394         case KEY_REQKEY_DEFL_GROUP_KEYRING:
1395         default:
1396                 ret = -EINVAL;
1397                 goto error;
1398         }
1399
1400 set:
1401         new->jit_keyring = reqkey_defl;
1402         commit_creds(new);
1403         return old_setting;
1404 error:
1405         abort_creds(new);
1406         return ret;
1407 }
1408
1409 /*
1410  * Set or clear the timeout on a key.
1411  *
1412  * Either the key must grant the caller Setattr permission or else the caller
1413  * must hold an instantiation authorisation token for the key.
1414  *
1415  * The timeout is either 0 to clear the timeout, or a number of seconds from
1416  * the current time.  The key and any links to the key will be automatically
1417  * garbage collected after the timeout expires.
1418  *
1419  * Keys with KEY_FLAG_KEEP set should not be timed out.
1420  *
1421  * If successful, 0 is returned.
1422  */
1423 long keyctl_set_timeout(key_serial_t id, unsigned timeout)
1424 {
1425         struct key *key, *instkey;
1426         key_ref_t key_ref;
1427         long ret;
1428
1429         key_ref = lookup_user_key(id, KEY_LOOKUP_CREATE | KEY_LOOKUP_PARTIAL,
1430                                   KEY_NEED_SETSEC);
1431         if (IS_ERR(key_ref)) {
1432                 /* setting the timeout on a key under construction is permitted
1433                  * if we have the authorisation token handy */
1434                 if (PTR_ERR(key_ref) == -EACCES) {
1435                         instkey = key_get_instantiation_authkey(id);
1436                         if (!IS_ERR(instkey)) {
1437                                 key_put(instkey);
1438                                 key_ref = lookup_user_key(id,
1439                                                           KEY_LOOKUP_PARTIAL,
1440                                                           0);
1441                                 if (!IS_ERR(key_ref))
1442                                         goto okay;
1443                         }
1444                 }
1445
1446                 ret = PTR_ERR(key_ref);
1447                 goto error;
1448         }
1449
1450 okay:
1451         key = key_ref_to_ptr(key_ref);
1452         ret = 0;
1453         if (test_bit(KEY_FLAG_KEEP, &key->flags))
1454                 ret = -EPERM;
1455         else
1456                 key_set_timeout(key, timeout);
1457         key_put(key);
1458
1459 error:
1460         return ret;
1461 }
1462
1463 /*
1464  * Assume (or clear) the authority to instantiate the specified key.
1465  *
1466  * This sets the authoritative token currently in force for key instantiation.
1467  * This must be done for a key to be instantiated.  It has the effect of making
1468  * available all the keys from the caller of the request_key() that created a
1469  * key to request_key() calls made by the caller of this function.
1470  *
1471  * The caller must have the instantiation key in their process keyrings with a
1472  * Search permission grant available to the caller.
1473  *
1474  * If the ID given is 0, then the setting will be cleared and 0 returned.
1475  *
1476  * If the ID given has a matching an authorisation key, then that key will be
1477  * set and its ID will be returned.  The authorisation key can be read to get
1478  * the callout information passed to request_key().
1479  */
1480 long keyctl_assume_authority(key_serial_t id)
1481 {
1482         struct key *authkey;
1483         long ret;
1484
1485         /* special key IDs aren't permitted */
1486         ret = -EINVAL;
1487         if (id < 0)
1488                 goto error;
1489
1490         /* we divest ourselves of authority if given an ID of 0 */
1491         if (id == 0) {
1492                 ret = keyctl_change_reqkey_auth(NULL);
1493                 goto error;
1494         }
1495
1496         /* attempt to assume the authority temporarily granted to us whilst we
1497          * instantiate the specified key
1498          * - the authorisation key must be in the current task's keyrings
1499          *   somewhere
1500          */
1501         authkey = key_get_instantiation_authkey(id);
1502         if (IS_ERR(authkey)) {
1503                 ret = PTR_ERR(authkey);
1504                 goto error;
1505         }
1506
1507         ret = keyctl_change_reqkey_auth(authkey);
1508         if (ret == 0)
1509                 ret = authkey->serial;
1510         key_put(authkey);
1511 error:
1512         return ret;
1513 }
1514
1515 /*
1516  * Get a key's the LSM security label.
1517  *
1518  * The key must grant the caller View permission for this to work.
1519  *
1520  * If there's a buffer, then up to buflen bytes of data will be placed into it.
1521  *
1522  * If successful, the amount of information available will be returned,
1523  * irrespective of how much was copied (including the terminal NUL).
1524  */
1525 long keyctl_get_security(key_serial_t keyid,
1526                          char __user *buffer,
1527                          size_t buflen)
1528 {
1529         struct key *key, *instkey;
1530         key_ref_t key_ref;
1531         char *context;
1532         long ret;
1533
1534         key_ref = lookup_user_key(keyid, KEY_LOOKUP_PARTIAL, KEY_NEED_VIEW);
1535         if (IS_ERR(key_ref)) {
1536                 if (PTR_ERR(key_ref) != -EACCES)
1537                         return PTR_ERR(key_ref);
1538
1539                 /* viewing a key under construction is also permitted if we
1540                  * have the authorisation token handy */
1541                 instkey = key_get_instantiation_authkey(keyid);
1542                 if (IS_ERR(instkey))
1543                         return PTR_ERR(instkey);
1544                 key_put(instkey);
1545
1546                 key_ref = lookup_user_key(keyid, KEY_LOOKUP_PARTIAL, 0);
1547                 if (IS_ERR(key_ref))
1548                         return PTR_ERR(key_ref);
1549         }
1550
1551         key = key_ref_to_ptr(key_ref);
1552         ret = security_key_getsecurity(key, &context);
1553         if (ret == 0) {
1554                 /* if no information was returned, give userspace an empty
1555                  * string */
1556                 ret = 1;
1557                 if (buffer && buflen > 0 &&
1558                     copy_to_user(buffer, "", 1) != 0)
1559                         ret = -EFAULT;
1560         } else if (ret > 0) {
1561                 /* return as much data as there's room for */
1562                 if (buffer && buflen > 0) {
1563                         if (buflen > ret)
1564                                 buflen = ret;
1565
1566                         if (copy_to_user(buffer, context, buflen) != 0)
1567                                 ret = -EFAULT;
1568                 }
1569
1570                 kfree(context);
1571         }
1572
1573         key_ref_put(key_ref);
1574         return ret;
1575 }
1576
1577 /*
1578  * Attempt to install the calling process's session keyring on the process's
1579  * parent process.
1580  *
1581  * The keyring must exist and must grant the caller JOIN permission, and the
1582  * parent process must be single-threaded and must have the same effective
1583  * ownership as this process and mustn't be SUID/SGID.
1584  *
1585  * The keyring will be emplaced on the parent when it next resumes userspace.
1586  *
1587  * If successful, 0 will be returned.
1588  */
1589 long keyctl_session_to_parent(void)
1590 {
1591         struct task_struct *me, *parent;
1592         const struct cred *mycred, *pcred;
1593         struct callback_head *newwork, *oldwork;
1594         key_ref_t keyring_r;
1595         struct cred *cred;
1596         int ret;
1597
1598         keyring_r = lookup_user_key(KEY_SPEC_SESSION_KEYRING, 0, KEY_NEED_JOIN);
1599         if (IS_ERR(keyring_r))
1600                 return PTR_ERR(keyring_r);
1601
1602         ret = -ENOMEM;
1603
1604         /* our parent is going to need a new cred struct, a new tgcred struct
1605          * and new security data, so we allocate them here to prevent ENOMEM in
1606          * our parent */
1607         cred = cred_alloc_blank();
1608         if (!cred)
1609                 goto error_keyring;
1610         newwork = &cred->rcu;
1611
1612         cred->session_keyring = key_ref_to_ptr(keyring_r);
1613         keyring_r = NULL;
1614         init_task_work(newwork, key_change_session_keyring);
1615
1616         me = current;
1617         rcu_read_lock();
1618         write_lock_irq(&tasklist_lock);
1619
1620         ret = -EPERM;
1621         oldwork = NULL;
1622         parent = rcu_dereference_protected(me->real_parent,
1623                                            lockdep_is_held(&tasklist_lock));
1624
1625         /* the parent mustn't be init and mustn't be a kernel thread */
1626         if (parent->pid <= 1 || !parent->mm)
1627                 goto unlock;
1628
1629         /* the parent must be single threaded */
1630         if (!thread_group_empty(parent))
1631                 goto unlock;
1632
1633         /* the parent and the child must have different session keyrings or
1634          * there's no point */
1635         mycred = current_cred();
1636         pcred = __task_cred(parent);
1637         if (mycred == pcred ||
1638             mycred->session_keyring == pcred->session_keyring) {
1639                 ret = 0;
1640                 goto unlock;
1641         }
1642
1643         /* the parent must have the same effective ownership and mustn't be
1644          * SUID/SGID */
1645         if (!uid_eq(pcred->uid,  mycred->euid) ||
1646             !uid_eq(pcred->euid, mycred->euid) ||
1647             !uid_eq(pcred->suid, mycred->euid) ||
1648             !gid_eq(pcred->gid,  mycred->egid) ||
1649             !gid_eq(pcred->egid, mycred->egid) ||
1650             !gid_eq(pcred->sgid, mycred->egid))
1651                 goto unlock;
1652
1653         /* the keyrings must have the same UID */
1654         if ((pcred->session_keyring &&
1655              !uid_eq(pcred->session_keyring->uid, mycred->euid)) ||
1656             !uid_eq(mycred->session_keyring->uid, mycred->euid))
1657                 goto unlock;
1658
1659         /* cancel an already pending keyring replacement */
1660         oldwork = task_work_cancel(parent, key_change_session_keyring);
1661
1662         /* the replacement session keyring is applied just prior to userspace
1663          * restarting */
1664         ret = task_work_add(parent, newwork, true);
1665         if (!ret)
1666                 newwork = NULL;
1667 unlock:
1668         write_unlock_irq(&tasklist_lock);
1669         rcu_read_unlock();
1670         if (oldwork)
1671                 put_cred(container_of(oldwork, struct cred, rcu));
1672         if (newwork)
1673                 put_cred(cred);
1674         return ret;
1675
1676 error_keyring:
1677         key_ref_put(keyring_r);
1678         return ret;
1679 }
1680
1681 /*
1682  * Apply a restriction to a given keyring.
1683  *
1684  * The caller must have Setattr permission to change keyring restrictions.
1685  *
1686  * The requested type name may be a NULL pointer to reject all attempts
1687  * to link to the keyring.  In this case, _restriction must also be NULL.
1688  * Otherwise, both _type and _restriction must be non-NULL.
1689  *
1690  * Returns 0 if successful.
1691  */
1692 long keyctl_restrict_keyring(key_serial_t id, const char __user *_type,
1693                              const char __user *_restriction)
1694 {
1695         key_ref_t key_ref;
1696         char type[32];
1697         char *restriction = NULL;
1698         long ret;
1699
1700         key_ref = lookup_user_key(id, 0, KEY_NEED_SETSEC);
1701         if (IS_ERR(key_ref))
1702                 return PTR_ERR(key_ref);
1703
1704         ret = -EINVAL;
1705         if (_type) {
1706                 if (!_restriction)
1707                         goto error;
1708
1709                 ret = key_get_type_from_user(type, _type, sizeof(type));
1710                 if (ret < 0)
1711                         goto error;
1712
1713                 restriction = strndup_user(_restriction, PAGE_SIZE);
1714                 if (IS_ERR(restriction)) {
1715                         ret = PTR_ERR(restriction);
1716                         goto error;
1717                 }
1718         } else {
1719                 if (_restriction)
1720                         goto error;
1721         }
1722
1723         ret = keyring_restrict(key_ref, _type ? type : NULL, restriction);
1724         kfree(restriction);
1725 error:
1726         key_ref_put(key_ref);
1727         return ret;
1728 }
1729
1730 /*
1731  * Get keyrings subsystem capabilities.
1732  */
1733 long keyctl_capabilities(unsigned char __user *_buffer, size_t buflen)
1734 {
1735         size_t size = buflen;
1736
1737         if (size > 0) {
1738                 if (size > sizeof(keyrings_capabilities))
1739                         size = sizeof(keyrings_capabilities);
1740                 if (copy_to_user(_buffer, keyrings_capabilities, size) != 0)
1741                         return -EFAULT;
1742                 if (size < buflen &&
1743                     clear_user(_buffer + size, buflen - size) != 0)
1744                         return -EFAULT;
1745         }
1746
1747         return sizeof(keyrings_capabilities);
1748 }
1749
1750 /*
1751  * The key control system call
1752  */
1753 SYSCALL_DEFINE5(keyctl, int, option, unsigned long, arg2, unsigned long, arg3,
1754                 unsigned long, arg4, unsigned long, arg5)
1755 {
1756         switch (option) {
1757         case KEYCTL_GET_KEYRING_ID:
1758                 return keyctl_get_keyring_ID((key_serial_t) arg2,
1759                                              (int) arg3);
1760
1761         case KEYCTL_JOIN_SESSION_KEYRING:
1762                 return keyctl_join_session_keyring((const char __user *) arg2);
1763
1764         case KEYCTL_UPDATE:
1765                 return keyctl_update_key((key_serial_t) arg2,
1766                                          (const void __user *) arg3,
1767                                          (size_t) arg4);
1768
1769         case KEYCTL_REVOKE:
1770                 return keyctl_revoke_key((key_serial_t) arg2);
1771
1772         case KEYCTL_DESCRIBE:
1773                 return keyctl_describe_key((key_serial_t) arg2,
1774                                            (char __user *) arg3,
1775                                            (unsigned) arg4);
1776
1777         case KEYCTL_CLEAR:
1778                 return keyctl_keyring_clear((key_serial_t) arg2);
1779
1780         case KEYCTL_LINK:
1781                 return keyctl_keyring_link((key_serial_t) arg2,
1782                                            (key_serial_t) arg3);
1783
1784         case KEYCTL_UNLINK:
1785                 return keyctl_keyring_unlink((key_serial_t) arg2,
1786                                              (key_serial_t) arg3);
1787
1788         case KEYCTL_SEARCH:
1789                 return keyctl_keyring_search((key_serial_t) arg2,
1790                                              (const char __user *) arg3,
1791                                              (const char __user *) arg4,
1792                                              (key_serial_t) arg5);
1793
1794         case KEYCTL_READ:
1795                 return keyctl_read_key((key_serial_t) arg2,
1796                                        (char __user *) arg3,
1797                                        (size_t) arg4);
1798
1799         case KEYCTL_CHOWN:
1800                 return keyctl_chown_key((key_serial_t) arg2,
1801                                         (uid_t) arg3,
1802                                         (gid_t) arg4);
1803
1804         case KEYCTL_SETPERM:
1805                 return keyctl_setperm_key((key_serial_t) arg2,
1806                                           (unsigned int)arg3);
1807
1808         case KEYCTL_INSTANTIATE:
1809                 return keyctl_instantiate_key((key_serial_t) arg2,
1810                                               (const void __user *) arg3,
1811                                               (size_t) arg4,
1812                                               (key_serial_t) arg5);
1813
1814         case KEYCTL_NEGATE:
1815                 return keyctl_negate_key((key_serial_t) arg2,
1816                                          (unsigned) arg3,
1817                                          (key_serial_t) arg4);
1818
1819         case KEYCTL_SET_REQKEY_KEYRING:
1820                 return keyctl_set_reqkey_keyring(arg2);
1821
1822         case KEYCTL_SET_TIMEOUT:
1823                 return keyctl_set_timeout((key_serial_t) arg2,
1824                                           (unsigned) arg3);
1825
1826         case KEYCTL_ASSUME_AUTHORITY:
1827                 return keyctl_assume_authority((key_serial_t) arg2);
1828
1829         case KEYCTL_GET_SECURITY:
1830                 return keyctl_get_security((key_serial_t) arg2,
1831                                            (char __user *) arg3,
1832                                            (size_t) arg4);
1833
1834         case KEYCTL_SESSION_TO_PARENT:
1835                 return keyctl_session_to_parent();
1836
1837         case KEYCTL_REJECT:
1838                 return keyctl_reject_key((key_serial_t) arg2,
1839                                          (unsigned) arg3,
1840                                          (unsigned) arg4,
1841                                          (key_serial_t) arg5);
1842
1843         case KEYCTL_INSTANTIATE_IOV:
1844                 return keyctl_instantiate_key_iov(
1845                         (key_serial_t) arg2,
1846                         (const struct iovec __user *) arg3,
1847                         (unsigned) arg4,
1848                         (key_serial_t) arg5);
1849
1850         case KEYCTL_INVALIDATE:
1851                 return keyctl_invalidate_key((key_serial_t) arg2);
1852
1853         case KEYCTL_GET_PERSISTENT:
1854                 return keyctl_get_persistent((uid_t)arg2, (key_serial_t)arg3);
1855
1856         case KEYCTL_DH_COMPUTE:
1857                 return keyctl_dh_compute((struct keyctl_dh_params __user *) arg2,
1858                                          (char __user *) arg3, (size_t) arg4,
1859                                          (struct keyctl_kdf_params __user *) arg5);
1860
1861         case KEYCTL_RESTRICT_KEYRING:
1862                 return keyctl_restrict_keyring((key_serial_t) arg2,
1863                                                (const char __user *) arg3,
1864                                                (const char __user *) arg4);
1865
1866         case KEYCTL_PKEY_QUERY:
1867                 if (arg3 != 0)
1868                         return -EINVAL;
1869                 return keyctl_pkey_query((key_serial_t)arg2,
1870                                          (const char __user *)arg4,
1871                                          (struct keyctl_pkey_query __user *)arg5);
1872
1873         case KEYCTL_PKEY_ENCRYPT:
1874         case KEYCTL_PKEY_DECRYPT:
1875         case KEYCTL_PKEY_SIGN:
1876                 return keyctl_pkey_e_d_s(
1877                         option,
1878                         (const struct keyctl_pkey_params __user *)arg2,
1879                         (const char __user *)arg3,
1880                         (const void __user *)arg4,
1881                         (void __user *)arg5);
1882
1883         case KEYCTL_PKEY_VERIFY:
1884                 return keyctl_pkey_verify(
1885                         (const struct keyctl_pkey_params __user *)arg2,
1886                         (const char __user *)arg3,
1887                         (const void __user *)arg4,
1888                         (const void __user *)arg5);
1889
1890         case KEYCTL_MOVE:
1891                 return keyctl_keyring_move((key_serial_t)arg2,
1892                                            (key_serial_t)arg3,
1893                                            (key_serial_t)arg4,
1894                                            (unsigned int)arg5);
1895         case KEYCTL_GRANT_PERMISSION:
1896                 return keyctl_grant_permission((key_serial_t)arg2,
1897                                                (enum key_ace_subject_type)arg3,
1898                                                (unsigned int)arg4,
1899                                                (unsigned int)arg5);
1900
1901         case KEYCTL_CAPABILITIES:
1902                 return keyctl_capabilities((unsigned char __user *)arg2, (size_t)arg3);
1903
1904         default:
1905                 return -EOPNOTSUPP;
1906         }
1907 }