keys: Replace uid/gid/perm permissions checking with an ACL
[sfrench/cifs-2.6.git] / security / keys / keyring.c
1 /* Keyring handling
2  *
3  * Copyright (C) 2004-2005, 2008, 2013 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/export.h>
13 #include <linux/init.h>
14 #include <linux/sched.h>
15 #include <linux/slab.h>
16 #include <linux/security.h>
17 #include <linux/seq_file.h>
18 #include <linux/err.h>
19 #include <linux/user_namespace.h>
20 #include <linux/nsproxy.h>
21 #include <keys/keyring-type.h>
22 #include <keys/user-type.h>
23 #include <linux/assoc_array_priv.h>
24 #include <linux/uaccess.h>
25 #include <net/net_namespace.h>
26 #include "internal.h"
27
28 /*
29  * When plumbing the depths of the key tree, this sets a hard limit
30  * set on how deep we're willing to go.
31  */
32 #define KEYRING_SEARCH_MAX_DEPTH 6
33
34 /*
35  * We mark pointers we pass to the associative array with bit 1 set if
36  * they're keyrings and clear otherwise.
37  */
38 #define KEYRING_PTR_SUBTYPE     0x2UL
39
40 static inline bool keyring_ptr_is_keyring(const struct assoc_array_ptr *x)
41 {
42         return (unsigned long)x & KEYRING_PTR_SUBTYPE;
43 }
44 static inline struct key *keyring_ptr_to_key(const struct assoc_array_ptr *x)
45 {
46         void *object = assoc_array_ptr_to_leaf(x);
47         return (struct key *)((unsigned long)object & ~KEYRING_PTR_SUBTYPE);
48 }
49 static inline void *keyring_key_to_ptr(struct key *key)
50 {
51         if (key->type == &key_type_keyring)
52                 return (void *)((unsigned long)key | KEYRING_PTR_SUBTYPE);
53         return key;
54 }
55
56 static DEFINE_RWLOCK(keyring_name_lock);
57
58 /*
59  * Clean up the bits of user_namespace that belong to us.
60  */
61 void key_free_user_ns(struct user_namespace *ns)
62 {
63         write_lock(&keyring_name_lock);
64         list_del_init(&ns->keyring_name_list);
65         write_unlock(&keyring_name_lock);
66
67         key_put(ns->user_keyring_register);
68 #ifdef CONFIG_PERSISTENT_KEYRINGS
69         key_put(ns->persistent_keyring_register);
70 #endif
71 }
72
73 /*
74  * The keyring key type definition.  Keyrings are simply keys of this type and
75  * can be treated as ordinary keys in addition to having their own special
76  * operations.
77  */
78 static int keyring_preparse(struct key_preparsed_payload *prep);
79 static void keyring_free_preparse(struct key_preparsed_payload *prep);
80 static int keyring_instantiate(struct key *keyring,
81                                struct key_preparsed_payload *prep);
82 static void keyring_revoke(struct key *keyring);
83 static void keyring_destroy(struct key *keyring);
84 static void keyring_describe(const struct key *keyring, struct seq_file *m);
85 static long keyring_read(const struct key *keyring,
86                          char __user *buffer, size_t buflen);
87
88 struct key_type key_type_keyring = {
89         .name           = "keyring",
90         .def_datalen    = 0,
91         .preparse       = keyring_preparse,
92         .free_preparse  = keyring_free_preparse,
93         .instantiate    = keyring_instantiate,
94         .revoke         = keyring_revoke,
95         .destroy        = keyring_destroy,
96         .describe       = keyring_describe,
97         .read           = keyring_read,
98 };
99 EXPORT_SYMBOL(key_type_keyring);
100
101 /*
102  * Semaphore to serialise link/link calls to prevent two link calls in parallel
103  * introducing a cycle.
104  */
105 static DEFINE_MUTEX(keyring_serialise_link_lock);
106
107 /*
108  * Publish the name of a keyring so that it can be found by name (if it has
109  * one and it doesn't begin with a dot).
110  */
111 static void keyring_publish_name(struct key *keyring)
112 {
113         struct user_namespace *ns = current_user_ns();
114
115         if (keyring->description &&
116             keyring->description[0] &&
117             keyring->description[0] != '.') {
118                 write_lock(&keyring_name_lock);
119                 list_add_tail(&keyring->name_link, &ns->keyring_name_list);
120                 write_unlock(&keyring_name_lock);
121         }
122 }
123
124 /*
125  * Preparse a keyring payload
126  */
127 static int keyring_preparse(struct key_preparsed_payload *prep)
128 {
129         return prep->datalen != 0 ? -EINVAL : 0;
130 }
131
132 /*
133  * Free a preparse of a user defined key payload
134  */
135 static void keyring_free_preparse(struct key_preparsed_payload *prep)
136 {
137 }
138
139 /*
140  * Initialise a keyring.
141  *
142  * Returns 0 on success, -EINVAL if given any data.
143  */
144 static int keyring_instantiate(struct key *keyring,
145                                struct key_preparsed_payload *prep)
146 {
147         assoc_array_init(&keyring->keys);
148         /* make the keyring available by name if it has one */
149         keyring_publish_name(keyring);
150         return 0;
151 }
152
153 /*
154  * Multiply 64-bits by 32-bits to 96-bits and fold back to 64-bit.  Ideally we'd
155  * fold the carry back too, but that requires inline asm.
156  */
157 static u64 mult_64x32_and_fold(u64 x, u32 y)
158 {
159         u64 hi = (u64)(u32)(x >> 32) * y;
160         u64 lo = (u64)(u32)(x) * y;
161         return lo + ((u64)(u32)hi << 32) + (u32)(hi >> 32);
162 }
163
164 /*
165  * Hash a key type and description.
166  */
167 static void hash_key_type_and_desc(struct keyring_index_key *index_key)
168 {
169         const unsigned level_shift = ASSOC_ARRAY_LEVEL_STEP;
170         const unsigned long fan_mask = ASSOC_ARRAY_FAN_MASK;
171         const char *description = index_key->description;
172         unsigned long hash, type;
173         u32 piece;
174         u64 acc;
175         int n, desc_len = index_key->desc_len;
176
177         type = (unsigned long)index_key->type;
178         acc = mult_64x32_and_fold(type, desc_len + 13);
179         acc = mult_64x32_and_fold(acc, 9207);
180         piece = (unsigned long)index_key->domain_tag;
181         acc = mult_64x32_and_fold(acc, piece);
182         acc = mult_64x32_and_fold(acc, 9207);
183
184         for (;;) {
185                 n = desc_len;
186                 if (n <= 0)
187                         break;
188                 if (n > 4)
189                         n = 4;
190                 piece = 0;
191                 memcpy(&piece, description, n);
192                 description += n;
193                 desc_len -= n;
194                 acc = mult_64x32_and_fold(acc, piece);
195                 acc = mult_64x32_and_fold(acc, 9207);
196         }
197
198         /* Fold the hash down to 32 bits if need be. */
199         hash = acc;
200         if (ASSOC_ARRAY_KEY_CHUNK_SIZE == 32)
201                 hash ^= acc >> 32;
202
203         /* Squidge all the keyrings into a separate part of the tree to
204          * ordinary keys by making sure the lowest level segment in the hash is
205          * zero for keyrings and non-zero otherwise.
206          */
207         if (index_key->type != &key_type_keyring && (hash & fan_mask) == 0)
208                 hash |= (hash >> (ASSOC_ARRAY_KEY_CHUNK_SIZE - level_shift)) | 1;
209         else if (index_key->type == &key_type_keyring && (hash & fan_mask) != 0)
210                 hash = (hash + (hash << level_shift)) & ~fan_mask;
211         index_key->hash = hash;
212 }
213
214 /*
215  * Finalise an index key to include a part of the description actually in the
216  * index key, to set the domain tag and to calculate the hash.
217  */
218 void key_set_index_key(struct keyring_index_key *index_key)
219 {
220         static struct key_tag default_domain_tag = { .usage = REFCOUNT_INIT(1), };
221         size_t n = min_t(size_t, index_key->desc_len, sizeof(index_key->desc));
222
223         memcpy(index_key->desc, index_key->description, n);
224
225         if (!index_key->domain_tag) {
226                 if (index_key->type->flags & KEY_TYPE_NET_DOMAIN)
227                         index_key->domain_tag = current->nsproxy->net_ns->key_domain;
228                 else
229                         index_key->domain_tag = &default_domain_tag;
230         }
231
232         hash_key_type_and_desc(index_key);
233 }
234
235 /**
236  * key_put_tag - Release a ref on a tag.
237  * @tag: The tag to release.
238  *
239  * This releases a reference the given tag and returns true if that ref was the
240  * last one.
241  */
242 bool key_put_tag(struct key_tag *tag)
243 {
244         if (refcount_dec_and_test(&tag->usage)) {
245                 kfree_rcu(tag, rcu);
246                 return true;
247         }
248
249         return false;
250 }
251
252 /**
253  * key_remove_domain - Kill off a key domain and gc its keys
254  * @domain_tag: The domain tag to release.
255  *
256  * This marks a domain tag as being dead and releases a ref on it.  If that
257  * wasn't the last reference, the garbage collector is poked to try and delete
258  * all keys that were in the domain.
259  */
260 void key_remove_domain(struct key_tag *domain_tag)
261 {
262         domain_tag->removed = true;
263         if (!key_put_tag(domain_tag))
264                 key_schedule_gc_links();
265 }
266
267 /*
268  * Build the next index key chunk.
269  *
270  * We return it one word-sized chunk at a time.
271  */
272 static unsigned long keyring_get_key_chunk(const void *data, int level)
273 {
274         const struct keyring_index_key *index_key = data;
275         unsigned long chunk = 0;
276         const u8 *d;
277         int desc_len = index_key->desc_len, n = sizeof(chunk);
278
279         level /= ASSOC_ARRAY_KEY_CHUNK_SIZE;
280         switch (level) {
281         case 0:
282                 return index_key->hash;
283         case 1:
284                 return index_key->x;
285         case 2:
286                 return (unsigned long)index_key->type;
287         case 3:
288                 return (unsigned long)index_key->domain_tag;
289         default:
290                 level -= 4;
291                 if (desc_len <= sizeof(index_key->desc))
292                         return 0;
293
294                 d = index_key->description + sizeof(index_key->desc);
295                 d += level * sizeof(long);
296                 desc_len -= sizeof(index_key->desc);
297                 if (desc_len > n)
298                         desc_len = n;
299                 do {
300                         chunk <<= 8;
301                         chunk |= *d++;
302                 } while (--desc_len > 0);
303                 return chunk;
304         }
305 }
306
307 static unsigned long keyring_get_object_key_chunk(const void *object, int level)
308 {
309         const struct key *key = keyring_ptr_to_key(object);
310         return keyring_get_key_chunk(&key->index_key, level);
311 }
312
313 static bool keyring_compare_object(const void *object, const void *data)
314 {
315         const struct keyring_index_key *index_key = data;
316         const struct key *key = keyring_ptr_to_key(object);
317
318         return key->index_key.type == index_key->type &&
319                 key->index_key.domain_tag == index_key->domain_tag &&
320                 key->index_key.desc_len == index_key->desc_len &&
321                 memcmp(key->index_key.description, index_key->description,
322                        index_key->desc_len) == 0;
323 }
324
325 /*
326  * Compare the index keys of a pair of objects and determine the bit position
327  * at which they differ - if they differ.
328  */
329 static int keyring_diff_objects(const void *object, const void *data)
330 {
331         const struct key *key_a = keyring_ptr_to_key(object);
332         const struct keyring_index_key *a = &key_a->index_key;
333         const struct keyring_index_key *b = data;
334         unsigned long seg_a, seg_b;
335         int level, i;
336
337         level = 0;
338         seg_a = a->hash;
339         seg_b = b->hash;
340         if ((seg_a ^ seg_b) != 0)
341                 goto differ;
342         level += ASSOC_ARRAY_KEY_CHUNK_SIZE / 8;
343
344         /* The number of bits contributed by the hash is controlled by a
345          * constant in the assoc_array headers.  Everything else thereafter we
346          * can deal with as being machine word-size dependent.
347          */
348         seg_a = a->x;
349         seg_b = b->x;
350         if ((seg_a ^ seg_b) != 0)
351                 goto differ;
352         level += sizeof(unsigned long);
353
354         /* The next bit may not work on big endian */
355         seg_a = (unsigned long)a->type;
356         seg_b = (unsigned long)b->type;
357         if ((seg_a ^ seg_b) != 0)
358                 goto differ;
359         level += sizeof(unsigned long);
360
361         seg_a = (unsigned long)a->domain_tag;
362         seg_b = (unsigned long)b->domain_tag;
363         if ((seg_a ^ seg_b) != 0)
364                 goto differ;
365         level += sizeof(unsigned long);
366
367         i = sizeof(a->desc);
368         if (a->desc_len <= i)
369                 goto same;
370
371         for (; i < a->desc_len; i++) {
372                 seg_a = *(unsigned char *)(a->description + i);
373                 seg_b = *(unsigned char *)(b->description + i);
374                 if ((seg_a ^ seg_b) != 0)
375                         goto differ_plus_i;
376         }
377
378 same:
379         return -1;
380
381 differ_plus_i:
382         level += i;
383 differ:
384         i = level * 8 + __ffs(seg_a ^ seg_b);
385         return i;
386 }
387
388 /*
389  * Free an object after stripping the keyring flag off of the pointer.
390  */
391 static void keyring_free_object(void *object)
392 {
393         key_put(keyring_ptr_to_key(object));
394 }
395
396 /*
397  * Operations for keyring management by the index-tree routines.
398  */
399 static const struct assoc_array_ops keyring_assoc_array_ops = {
400         .get_key_chunk          = keyring_get_key_chunk,
401         .get_object_key_chunk   = keyring_get_object_key_chunk,
402         .compare_object         = keyring_compare_object,
403         .diff_objects           = keyring_diff_objects,
404         .free_object            = keyring_free_object,
405 };
406
407 /*
408  * Clean up a keyring when it is destroyed.  Unpublish its name if it had one
409  * and dispose of its data.
410  *
411  * The garbage collector detects the final key_put(), removes the keyring from
412  * the serial number tree and then does RCU synchronisation before coming here,
413  * so we shouldn't need to worry about code poking around here with the RCU
414  * readlock held by this time.
415  */
416 static void keyring_destroy(struct key *keyring)
417 {
418         if (keyring->description) {
419                 write_lock(&keyring_name_lock);
420
421                 if (keyring->name_link.next != NULL &&
422                     !list_empty(&keyring->name_link))
423                         list_del(&keyring->name_link);
424
425                 write_unlock(&keyring_name_lock);
426         }
427
428         if (keyring->restrict_link) {
429                 struct key_restriction *keyres = keyring->restrict_link;
430
431                 key_put(keyres->key);
432                 kfree(keyres);
433         }
434
435         assoc_array_destroy(&keyring->keys, &keyring_assoc_array_ops);
436 }
437
438 /*
439  * Describe a keyring for /proc.
440  */
441 static void keyring_describe(const struct key *keyring, struct seq_file *m)
442 {
443         if (keyring->description)
444                 seq_puts(m, keyring->description);
445         else
446                 seq_puts(m, "[anon]");
447
448         if (key_is_positive(keyring)) {
449                 if (keyring->keys.nr_leaves_on_tree != 0)
450                         seq_printf(m, ": %lu", keyring->keys.nr_leaves_on_tree);
451                 else
452                         seq_puts(m, ": empty");
453         }
454 }
455
456 struct keyring_read_iterator_context {
457         size_t                  buflen;
458         size_t                  count;
459         key_serial_t __user     *buffer;
460 };
461
462 static int keyring_read_iterator(const void *object, void *data)
463 {
464         struct keyring_read_iterator_context *ctx = data;
465         const struct key *key = keyring_ptr_to_key(object);
466         int ret;
467
468         kenter("{%s,%d},,{%zu/%zu}",
469                key->type->name, key->serial, ctx->count, ctx->buflen);
470
471         if (ctx->count >= ctx->buflen)
472                 return 1;
473
474         ret = put_user(key->serial, ctx->buffer);
475         if (ret < 0)
476                 return ret;
477         ctx->buffer++;
478         ctx->count += sizeof(key->serial);
479         return 0;
480 }
481
482 /*
483  * Read a list of key IDs from the keyring's contents in binary form
484  *
485  * The keyring's semaphore is read-locked by the caller.  This prevents someone
486  * from modifying it under us - which could cause us to read key IDs multiple
487  * times.
488  */
489 static long keyring_read(const struct key *keyring,
490                          char __user *buffer, size_t buflen)
491 {
492         struct keyring_read_iterator_context ctx;
493         long ret;
494
495         kenter("{%d},,%zu", key_serial(keyring), buflen);
496
497         if (buflen & (sizeof(key_serial_t) - 1))
498                 return -EINVAL;
499
500         /* Copy as many key IDs as fit into the buffer */
501         if (buffer && buflen) {
502                 ctx.buffer = (key_serial_t __user *)buffer;
503                 ctx.buflen = buflen;
504                 ctx.count = 0;
505                 ret = assoc_array_iterate(&keyring->keys,
506                                           keyring_read_iterator, &ctx);
507                 if (ret < 0) {
508                         kleave(" = %ld [iterate]", ret);
509                         return ret;
510                 }
511         }
512
513         /* Return the size of the buffer needed */
514         ret = keyring->keys.nr_leaves_on_tree * sizeof(key_serial_t);
515         if (ret <= buflen)
516                 kleave("= %ld [ok]", ret);
517         else
518                 kleave("= %ld [buffer too small]", ret);
519         return ret;
520 }
521
522 /**
523  * keyring_alloc - Allocate a keyring and link into the destination
524  * @description: The key description to allow the key to be searched out.
525  * @uid: The owner of the new key.
526  * @gid: The group ID for the new key's group permissions.
527  * @cred: The credentials specifying UID namespace.
528  * @acl: The ACL to attach to the new key.
529  * @flags: Flags specifying quota properties.
530  * @restrict_link: Optional link restriction for new keyrings.
531  * @dest: Destination keyring.
532  */
533 struct key *keyring_alloc(const char *description, kuid_t uid, kgid_t gid,
534                           const struct cred *cred, struct key_acl *acl,
535                           unsigned long flags,
536                           struct key_restriction *restrict_link,
537                           struct key *dest)
538 {
539         struct key *keyring;
540         int ret;
541
542         keyring = key_alloc(&key_type_keyring, description,
543                             uid, gid, cred, acl, flags, restrict_link);
544         if (!IS_ERR(keyring)) {
545                 ret = key_instantiate_and_link(keyring, NULL, 0, dest, NULL);
546                 if (ret < 0) {
547                         key_put(keyring);
548                         keyring = ERR_PTR(ret);
549                 }
550         }
551
552         return keyring;
553 }
554 EXPORT_SYMBOL(keyring_alloc);
555
556 /**
557  * restrict_link_reject - Give -EPERM to restrict link
558  * @keyring: The keyring being added to.
559  * @type: The type of key being added.
560  * @payload: The payload of the key intended to be added.
561  * @restriction_key: Keys providing additional data for evaluating restriction.
562  *
563  * Reject the addition of any links to a keyring.  It can be overridden by
564  * passing KEY_ALLOC_BYPASS_RESTRICTION to key_instantiate_and_link() when
565  * adding a key to a keyring.
566  *
567  * This is meant to be stored in a key_restriction structure which is passed
568  * in the restrict_link parameter to keyring_alloc().
569  */
570 int restrict_link_reject(struct key *keyring,
571                          const struct key_type *type,
572                          const union key_payload *payload,
573                          struct key *restriction_key)
574 {
575         return -EPERM;
576 }
577
578 /*
579  * By default, we keys found by getting an exact match on their descriptions.
580  */
581 bool key_default_cmp(const struct key *key,
582                      const struct key_match_data *match_data)
583 {
584         return strcmp(key->description, match_data->raw_data) == 0;
585 }
586
587 /*
588  * Iteration function to consider each key found.
589  */
590 static int keyring_search_iterator(const void *object, void *iterator_data)
591 {
592         struct keyring_search_context *ctx = iterator_data;
593         const struct key *key = keyring_ptr_to_key(object);
594         unsigned long kflags = READ_ONCE(key->flags);
595         short state = READ_ONCE(key->state);
596
597         kenter("{%d}", key->serial);
598
599         /* ignore keys not of this type */
600         if (key->type != ctx->index_key.type) {
601                 kleave(" = 0 [!type]");
602                 return 0;
603         }
604
605         /* skip invalidated, revoked and expired keys */
606         if (ctx->flags & KEYRING_SEARCH_DO_STATE_CHECK) {
607                 time64_t expiry = READ_ONCE(key->expiry);
608
609                 if (kflags & ((1 << KEY_FLAG_INVALIDATED) |
610                               (1 << KEY_FLAG_REVOKED))) {
611                         ctx->result = ERR_PTR(-EKEYREVOKED);
612                         kleave(" = %d [invrev]", ctx->skipped_ret);
613                         goto skipped;
614                 }
615
616                 if (expiry && ctx->now >= expiry) {
617                         if (!(ctx->flags & KEYRING_SEARCH_SKIP_EXPIRED))
618                                 ctx->result = ERR_PTR(-EKEYEXPIRED);
619                         kleave(" = %d [expire]", ctx->skipped_ret);
620                         goto skipped;
621                 }
622         }
623
624         /* keys that don't match */
625         if (!ctx->match_data.cmp(key, &ctx->match_data)) {
626                 kleave(" = 0 [!match]");
627                 return 0;
628         }
629
630         /* key must have search permissions */
631         if (!(ctx->flags & KEYRING_SEARCH_NO_CHECK_PERM) &&
632             key_task_permission(make_key_ref(key, ctx->possessed),
633                                 ctx->cred, KEY_NEED_SEARCH) < 0) {
634                 ctx->result = ERR_PTR(-EACCES);
635                 kleave(" = %d [!perm]", ctx->skipped_ret);
636                 goto skipped;
637         }
638
639         if (ctx->flags & KEYRING_SEARCH_DO_STATE_CHECK) {
640                 /* we set a different error code if we pass a negative key */
641                 if (state < 0) {
642                         ctx->result = ERR_PTR(state);
643                         kleave(" = %d [neg]", ctx->skipped_ret);
644                         goto skipped;
645                 }
646         }
647
648         /* Found */
649         ctx->result = make_key_ref(key, ctx->possessed);
650         kleave(" = 1 [found]");
651         return 1;
652
653 skipped:
654         return ctx->skipped_ret;
655 }
656
657 /*
658  * Search inside a keyring for a key.  We can search by walking to it
659  * directly based on its index-key or we can iterate over the entire
660  * tree looking for it, based on the match function.
661  */
662 static int search_keyring(struct key *keyring, struct keyring_search_context *ctx)
663 {
664         if (ctx->match_data.lookup_type == KEYRING_SEARCH_LOOKUP_DIRECT) {
665                 const void *object;
666
667                 object = assoc_array_find(&keyring->keys,
668                                           &keyring_assoc_array_ops,
669                                           &ctx->index_key);
670                 return object ? ctx->iterator(object, ctx) : 0;
671         }
672         return assoc_array_iterate(&keyring->keys, ctx->iterator, ctx);
673 }
674
675 /*
676  * Search a tree of keyrings that point to other keyrings up to the maximum
677  * depth.
678  */
679 static bool search_nested_keyrings(struct key *keyring,
680                                    struct keyring_search_context *ctx)
681 {
682         struct {
683                 struct key *keyring;
684                 struct assoc_array_node *node;
685                 int slot;
686         } stack[KEYRING_SEARCH_MAX_DEPTH];
687
688         struct assoc_array_shortcut *shortcut;
689         struct assoc_array_node *node;
690         struct assoc_array_ptr *ptr;
691         struct key *key;
692         int sp = 0, slot;
693
694         kenter("{%d},{%s,%s}",
695                keyring->serial,
696                ctx->index_key.type->name,
697                ctx->index_key.description);
698
699 #define STATE_CHECKS (KEYRING_SEARCH_NO_STATE_CHECK | KEYRING_SEARCH_DO_STATE_CHECK)
700         BUG_ON((ctx->flags & STATE_CHECKS) == 0 ||
701                (ctx->flags & STATE_CHECKS) == STATE_CHECKS);
702
703         if (ctx->index_key.description)
704                 key_set_index_key(&ctx->index_key);
705
706         /* Check to see if this top-level keyring is what we are looking for
707          * and whether it is valid or not.
708          */
709         if (ctx->match_data.lookup_type == KEYRING_SEARCH_LOOKUP_ITERATE ||
710             keyring_compare_object(keyring, &ctx->index_key)) {
711                 ctx->skipped_ret = 2;
712                 switch (ctx->iterator(keyring_key_to_ptr(keyring), ctx)) {
713                 case 1:
714                         goto found;
715                 case 2:
716                         return false;
717                 default:
718                         break;
719                 }
720         }
721
722         ctx->skipped_ret = 0;
723
724         /* Start processing a new keyring */
725 descend_to_keyring:
726         kdebug("descend to %d", keyring->serial);
727         if (keyring->flags & ((1 << KEY_FLAG_INVALIDATED) |
728                               (1 << KEY_FLAG_REVOKED)))
729                 goto not_this_keyring;
730
731         /* Search through the keys in this keyring before its searching its
732          * subtrees.
733          */
734         if (search_keyring(keyring, ctx))
735                 goto found;
736
737         /* Then manually iterate through the keyrings nested in this one.
738          *
739          * Start from the root node of the index tree.  Because of the way the
740          * hash function has been set up, keyrings cluster on the leftmost
741          * branch of the root node (root slot 0) or in the root node itself.
742          * Non-keyrings avoid the leftmost branch of the root entirely (root
743          * slots 1-15).
744          */
745         if (!(ctx->flags & KEYRING_SEARCH_RECURSE))
746                 goto not_this_keyring;
747
748         ptr = READ_ONCE(keyring->keys.root);
749         if (!ptr)
750                 goto not_this_keyring;
751
752         if (assoc_array_ptr_is_shortcut(ptr)) {
753                 /* If the root is a shortcut, either the keyring only contains
754                  * keyring pointers (everything clusters behind root slot 0) or
755                  * doesn't contain any keyring pointers.
756                  */
757                 shortcut = assoc_array_ptr_to_shortcut(ptr);
758                 if ((shortcut->index_key[0] & ASSOC_ARRAY_FAN_MASK) != 0)
759                         goto not_this_keyring;
760
761                 ptr = READ_ONCE(shortcut->next_node);
762                 node = assoc_array_ptr_to_node(ptr);
763                 goto begin_node;
764         }
765
766         node = assoc_array_ptr_to_node(ptr);
767         ptr = node->slots[0];
768         if (!assoc_array_ptr_is_meta(ptr))
769                 goto begin_node;
770
771 descend_to_node:
772         /* Descend to a more distal node in this keyring's content tree and go
773          * through that.
774          */
775         kdebug("descend");
776         if (assoc_array_ptr_is_shortcut(ptr)) {
777                 shortcut = assoc_array_ptr_to_shortcut(ptr);
778                 ptr = READ_ONCE(shortcut->next_node);
779                 BUG_ON(!assoc_array_ptr_is_node(ptr));
780         }
781         node = assoc_array_ptr_to_node(ptr);
782
783 begin_node:
784         kdebug("begin_node");
785         slot = 0;
786 ascend_to_node:
787         /* Go through the slots in a node */
788         for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
789                 ptr = READ_ONCE(node->slots[slot]);
790
791                 if (assoc_array_ptr_is_meta(ptr) && node->back_pointer)
792                         goto descend_to_node;
793
794                 if (!keyring_ptr_is_keyring(ptr))
795                         continue;
796
797                 key = keyring_ptr_to_key(ptr);
798
799                 if (sp >= KEYRING_SEARCH_MAX_DEPTH) {
800                         if (ctx->flags & KEYRING_SEARCH_DETECT_TOO_DEEP) {
801                                 ctx->result = ERR_PTR(-ELOOP);
802                                 return false;
803                         }
804                         goto not_this_keyring;
805                 }
806
807                 /* Search a nested keyring */
808                 if (!(ctx->flags & KEYRING_SEARCH_NO_CHECK_PERM) &&
809                     key_task_permission(make_key_ref(key, ctx->possessed),
810                                         ctx->cred, KEY_NEED_SEARCH) < 0)
811                         continue;
812
813                 /* stack the current position */
814                 stack[sp].keyring = keyring;
815                 stack[sp].node = node;
816                 stack[sp].slot = slot;
817                 sp++;
818
819                 /* begin again with the new keyring */
820                 keyring = key;
821                 goto descend_to_keyring;
822         }
823
824         /* We've dealt with all the slots in the current node, so now we need
825          * to ascend to the parent and continue processing there.
826          */
827         ptr = READ_ONCE(node->back_pointer);
828         slot = node->parent_slot;
829
830         if (ptr && assoc_array_ptr_is_shortcut(ptr)) {
831                 shortcut = assoc_array_ptr_to_shortcut(ptr);
832                 ptr = READ_ONCE(shortcut->back_pointer);
833                 slot = shortcut->parent_slot;
834         }
835         if (!ptr)
836                 goto not_this_keyring;
837         node = assoc_array_ptr_to_node(ptr);
838         slot++;
839
840         /* If we've ascended to the root (zero backpointer), we must have just
841          * finished processing the leftmost branch rather than the root slots -
842          * so there can't be any more keyrings for us to find.
843          */
844         if (node->back_pointer) {
845                 kdebug("ascend %d", slot);
846                 goto ascend_to_node;
847         }
848
849         /* The keyring we're looking at was disqualified or didn't contain a
850          * matching key.
851          */
852 not_this_keyring:
853         kdebug("not_this_keyring %d", sp);
854         if (sp <= 0) {
855                 kleave(" = false");
856                 return false;
857         }
858
859         /* Resume the processing of a keyring higher up in the tree */
860         sp--;
861         keyring = stack[sp].keyring;
862         node = stack[sp].node;
863         slot = stack[sp].slot + 1;
864         kdebug("ascend to %d [%d]", keyring->serial, slot);
865         goto ascend_to_node;
866
867         /* We found a viable match */
868 found:
869         key = key_ref_to_ptr(ctx->result);
870         key_check(key);
871         if (!(ctx->flags & KEYRING_SEARCH_NO_UPDATE_TIME)) {
872                 key->last_used_at = ctx->now;
873                 keyring->last_used_at = ctx->now;
874                 while (sp > 0)
875                         stack[--sp].keyring->last_used_at = ctx->now;
876         }
877         kleave(" = true");
878         return true;
879 }
880
881 /**
882  * keyring_search_rcu - Search a keyring tree for a matching key under RCU
883  * @keyring_ref: A pointer to the keyring with possession indicator.
884  * @ctx: The keyring search context.
885  *
886  * Search the supplied keyring tree for a key that matches the criteria given.
887  * The root keyring and any linked keyrings must grant Search permission to the
888  * caller to be searchable and keys can only be found if they too grant Search
889  * to the caller. The possession flag on the root keyring pointer controls use
890  * of the possessor bits in permissions checking of the entire tree.  In
891  * addition, the LSM gets to forbid keyring searches and key matches.
892  *
893  * The search is performed as a breadth-then-depth search up to the prescribed
894  * limit (KEYRING_SEARCH_MAX_DEPTH).  The caller must hold the RCU read lock to
895  * prevent keyrings from being destroyed or rearranged whilst they are being
896  * searched.
897  *
898  * Keys are matched to the type provided and are then filtered by the match
899  * function, which is given the description to use in any way it sees fit.  The
900  * match function may use any attributes of a key that it wishes to to
901  * determine the match.  Normally the match function from the key type would be
902  * used.
903  *
904  * RCU can be used to prevent the keyring key lists from disappearing without
905  * the need to take lots of locks.
906  *
907  * Returns a pointer to the found key and increments the key usage count if
908  * successful; -EAGAIN if no matching keys were found, or if expired or revoked
909  * keys were found; -ENOKEY if only negative keys were found; -ENOTDIR if the
910  * specified keyring wasn't a keyring.
911  *
912  * In the case of a successful return, the possession attribute from
913  * @keyring_ref is propagated to the returned key reference.
914  */
915 key_ref_t keyring_search_rcu(key_ref_t keyring_ref,
916                              struct keyring_search_context *ctx)
917 {
918         struct key *keyring;
919         long err;
920
921         ctx->iterator = keyring_search_iterator;
922         ctx->possessed = is_key_possessed(keyring_ref);
923         ctx->result = ERR_PTR(-EAGAIN);
924
925         keyring = key_ref_to_ptr(keyring_ref);
926         key_check(keyring);
927
928         if (keyring->type != &key_type_keyring)
929                 return ERR_PTR(-ENOTDIR);
930
931         if (!(ctx->flags & KEYRING_SEARCH_NO_CHECK_PERM)) {
932                 err = key_task_permission(keyring_ref, ctx->cred, KEY_NEED_SEARCH);
933                 if (err < 0)
934                         return ERR_PTR(err);
935         }
936
937         ctx->now = ktime_get_real_seconds();
938         if (search_nested_keyrings(keyring, ctx))
939                 __key_get(key_ref_to_ptr(ctx->result));
940         return ctx->result;
941 }
942
943 /**
944  * keyring_search - Search the supplied keyring tree for a matching key
945  * @keyring: The root of the keyring tree to be searched.
946  * @type: The type of keyring we want to find.
947  * @description: The name of the keyring we want to find.
948  * @recurse: True to search the children of @keyring also
949  *
950  * As keyring_search_rcu() above, but using the current task's credentials and
951  * type's default matching function and preferred search method.
952  */
953 key_ref_t keyring_search(key_ref_t keyring,
954                          struct key_type *type,
955                          const char *description,
956                          bool recurse)
957 {
958         struct keyring_search_context ctx = {
959                 .index_key.type         = type,
960                 .index_key.description  = description,
961                 .index_key.desc_len     = strlen(description),
962                 .cred                   = current_cred(),
963                 .match_data.cmp         = key_default_cmp,
964                 .match_data.raw_data    = description,
965                 .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT,
966                 .flags                  = KEYRING_SEARCH_DO_STATE_CHECK,
967         };
968         key_ref_t key;
969         int ret;
970
971         if (recurse)
972                 ctx.flags |= KEYRING_SEARCH_RECURSE;
973         if (type->match_preparse) {
974                 ret = type->match_preparse(&ctx.match_data);
975                 if (ret < 0)
976                         return ERR_PTR(ret);
977         }
978
979         rcu_read_lock();
980         key = keyring_search_rcu(keyring, &ctx);
981         rcu_read_unlock();
982
983         if (type->match_free)
984                 type->match_free(&ctx.match_data);
985         return key;
986 }
987 EXPORT_SYMBOL(keyring_search);
988
989 static struct key_restriction *keyring_restriction_alloc(
990         key_restrict_link_func_t check)
991 {
992         struct key_restriction *keyres =
993                 kzalloc(sizeof(struct key_restriction), GFP_KERNEL);
994
995         if (!keyres)
996                 return ERR_PTR(-ENOMEM);
997
998         keyres->check = check;
999
1000         return keyres;
1001 }
1002
1003 /*
1004  * Semaphore to serialise restriction setup to prevent reference count
1005  * cycles through restriction key pointers.
1006  */
1007 static DECLARE_RWSEM(keyring_serialise_restrict_sem);
1008
1009 /*
1010  * Check for restriction cycles that would prevent keyring garbage collection.
1011  * keyring_serialise_restrict_sem must be held.
1012  */
1013 static bool keyring_detect_restriction_cycle(const struct key *dest_keyring,
1014                                              struct key_restriction *keyres)
1015 {
1016         while (keyres && keyres->key &&
1017                keyres->key->type == &key_type_keyring) {
1018                 if (keyres->key == dest_keyring)
1019                         return true;
1020
1021                 keyres = keyres->key->restrict_link;
1022         }
1023
1024         return false;
1025 }
1026
1027 /**
1028  * keyring_restrict - Look up and apply a restriction to a keyring
1029  * @keyring_ref: The keyring to be restricted
1030  * @type: The key type that will provide the restriction checker.
1031  * @restriction: The restriction options to apply to the keyring
1032  *
1033  * Look up a keyring and apply a restriction to it.  The restriction is managed
1034  * by the specific key type, but can be configured by the options specified in
1035  * the restriction string.
1036  */
1037 int keyring_restrict(key_ref_t keyring_ref, const char *type,
1038                      const char *restriction)
1039 {
1040         struct key *keyring;
1041         struct key_type *restrict_type = NULL;
1042         struct key_restriction *restrict_link;
1043         int ret = 0;
1044
1045         keyring = key_ref_to_ptr(keyring_ref);
1046         key_check(keyring);
1047
1048         if (keyring->type != &key_type_keyring)
1049                 return -ENOTDIR;
1050
1051         if (!type) {
1052                 restrict_link = keyring_restriction_alloc(restrict_link_reject);
1053         } else {
1054                 restrict_type = key_type_lookup(type);
1055
1056                 if (IS_ERR(restrict_type))
1057                         return PTR_ERR(restrict_type);
1058
1059                 if (!restrict_type->lookup_restriction) {
1060                         ret = -ENOENT;
1061                         goto error;
1062                 }
1063
1064                 restrict_link = restrict_type->lookup_restriction(restriction);
1065         }
1066
1067         if (IS_ERR(restrict_link)) {
1068                 ret = PTR_ERR(restrict_link);
1069                 goto error;
1070         }
1071
1072         down_write(&keyring->sem);
1073         down_write(&keyring_serialise_restrict_sem);
1074
1075         if (keyring->restrict_link)
1076                 ret = -EEXIST;
1077         else if (keyring_detect_restriction_cycle(keyring, restrict_link))
1078                 ret = -EDEADLK;
1079         else
1080                 keyring->restrict_link = restrict_link;
1081
1082         up_write(&keyring_serialise_restrict_sem);
1083         up_write(&keyring->sem);
1084
1085         if (ret < 0) {
1086                 key_put(restrict_link->key);
1087                 kfree(restrict_link);
1088         }
1089
1090 error:
1091         if (restrict_type)
1092                 key_type_put(restrict_type);
1093
1094         return ret;
1095 }
1096 EXPORT_SYMBOL(keyring_restrict);
1097
1098 /*
1099  * Search the given keyring for a key that might be updated.
1100  *
1101  * The caller must guarantee that the keyring is a keyring and that the
1102  * permission is granted to modify the keyring as no check is made here.  The
1103  * caller must also hold a lock on the keyring semaphore.
1104  *
1105  * Returns a pointer to the found key with usage count incremented if
1106  * successful and returns NULL if not found.  Revoked and invalidated keys are
1107  * skipped over.
1108  *
1109  * If successful, the possession indicator is propagated from the keyring ref
1110  * to the returned key reference.
1111  */
1112 key_ref_t find_key_to_update(key_ref_t keyring_ref,
1113                              const struct keyring_index_key *index_key)
1114 {
1115         struct key *keyring, *key;
1116         const void *object;
1117
1118         keyring = key_ref_to_ptr(keyring_ref);
1119
1120         kenter("{%d},{%s,%s}",
1121                keyring->serial, index_key->type->name, index_key->description);
1122
1123         object = assoc_array_find(&keyring->keys, &keyring_assoc_array_ops,
1124                                   index_key);
1125
1126         if (object)
1127                 goto found;
1128
1129         kleave(" = NULL");
1130         return NULL;
1131
1132 found:
1133         key = keyring_ptr_to_key(object);
1134         if (key->flags & ((1 << KEY_FLAG_INVALIDATED) |
1135                           (1 << KEY_FLAG_REVOKED))) {
1136                 kleave(" = NULL [x]");
1137                 return NULL;
1138         }
1139         __key_get(key);
1140         kleave(" = {%d}", key->serial);
1141         return make_key_ref(key, is_key_possessed(keyring_ref));
1142 }
1143
1144 /*
1145  * Find a keyring with the specified name.
1146  *
1147  * Only keyrings that have nonzero refcount, are not revoked, and are owned by
1148  * a user in the current user namespace are considered.  If @uid_keyring is
1149  * %true, the keyring additionally must have been allocated as a user or user
1150  * session keyring; otherwise, it must grant JOIN permission directly to the
1151  * caller (ie. not through possession).
1152  *
1153  * Returns a pointer to the keyring with the keyring's refcount having being
1154  * incremented on success.  -ENOKEY is returned if a key could not be found.
1155  */
1156 struct key *find_keyring_by_name(const char *name, bool uid_keyring)
1157 {
1158         struct user_namespace *ns = current_user_ns();
1159         struct key *keyring;
1160
1161         if (!name)
1162                 return ERR_PTR(-EINVAL);
1163
1164         read_lock(&keyring_name_lock);
1165
1166         /* Search this hash bucket for a keyring with a matching name that
1167          * grants Search permission and that hasn't been revoked
1168          */
1169         list_for_each_entry(keyring, &ns->keyring_name_list, name_link) {
1170                 if (!kuid_has_mapping(ns, keyring->user->uid))
1171                         continue;
1172
1173                 if (test_bit(KEY_FLAG_REVOKED, &keyring->flags))
1174                         continue;
1175
1176                 if (strcmp(keyring->description, name) != 0)
1177                         continue;
1178
1179                 if (uid_keyring) {
1180                         if (!test_bit(KEY_FLAG_UID_KEYRING,
1181                                       &keyring->flags))
1182                                 continue;
1183                 } else {
1184                         if (key_permission(make_key_ref(keyring, 0),
1185                                            KEY_NEED_JOIN) < 0)
1186                                 continue;
1187                 }
1188
1189                 /* we've got a match but we might end up racing with
1190                  * key_cleanup() if the keyring is currently 'dead'
1191                  * (ie. it has a zero usage count) */
1192                 if (!refcount_inc_not_zero(&keyring->usage))
1193                         continue;
1194                 keyring->last_used_at = ktime_get_real_seconds();
1195                 goto out;
1196         }
1197
1198         keyring = ERR_PTR(-ENOKEY);
1199 out:
1200         read_unlock(&keyring_name_lock);
1201         return keyring;
1202 }
1203
1204 static int keyring_detect_cycle_iterator(const void *object,
1205                                          void *iterator_data)
1206 {
1207         struct keyring_search_context *ctx = iterator_data;
1208         const struct key *key = keyring_ptr_to_key(object);
1209
1210         kenter("{%d}", key->serial);
1211
1212         /* We might get a keyring with matching index-key that is nonetheless a
1213          * different keyring. */
1214         if (key != ctx->match_data.raw_data)
1215                 return 0;
1216
1217         ctx->result = ERR_PTR(-EDEADLK);
1218         return 1;
1219 }
1220
1221 /*
1222  * See if a cycle will will be created by inserting acyclic tree B in acyclic
1223  * tree A at the topmost level (ie: as a direct child of A).
1224  *
1225  * Since we are adding B to A at the top level, checking for cycles should just
1226  * be a matter of seeing if node A is somewhere in tree B.
1227  */
1228 static int keyring_detect_cycle(struct key *A, struct key *B)
1229 {
1230         struct keyring_search_context ctx = {
1231                 .index_key              = A->index_key,
1232                 .match_data.raw_data    = A,
1233                 .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT,
1234                 .iterator               = keyring_detect_cycle_iterator,
1235                 .flags                  = (KEYRING_SEARCH_NO_STATE_CHECK |
1236                                            KEYRING_SEARCH_NO_UPDATE_TIME |
1237                                            KEYRING_SEARCH_NO_CHECK_PERM |
1238                                            KEYRING_SEARCH_DETECT_TOO_DEEP |
1239                                            KEYRING_SEARCH_RECURSE),
1240         };
1241
1242         rcu_read_lock();
1243         search_nested_keyrings(B, &ctx);
1244         rcu_read_unlock();
1245         return PTR_ERR(ctx.result) == -EAGAIN ? 0 : PTR_ERR(ctx.result);
1246 }
1247
1248 /*
1249  * Lock keyring for link.
1250  */
1251 int __key_link_lock(struct key *keyring,
1252                     const struct keyring_index_key *index_key)
1253         __acquires(&keyring->sem)
1254         __acquires(&keyring_serialise_link_lock)
1255 {
1256         if (keyring->type != &key_type_keyring)
1257                 return -ENOTDIR;
1258
1259         down_write(&keyring->sem);
1260
1261         /* Serialise link/link calls to prevent parallel calls causing a cycle
1262          * when linking two keyring in opposite orders.
1263          */
1264         if (index_key->type == &key_type_keyring)
1265                 mutex_lock(&keyring_serialise_link_lock);
1266
1267         return 0;
1268 }
1269
1270 /*
1271  * Lock keyrings for move (link/unlink combination).
1272  */
1273 int __key_move_lock(struct key *l_keyring, struct key *u_keyring,
1274                     const struct keyring_index_key *index_key)
1275         __acquires(&l_keyring->sem)
1276         __acquires(&u_keyring->sem)
1277         __acquires(&keyring_serialise_link_lock)
1278 {
1279         if (l_keyring->type != &key_type_keyring ||
1280             u_keyring->type != &key_type_keyring)
1281                 return -ENOTDIR;
1282
1283         /* We have to be very careful here to take the keyring locks in the
1284          * right order, lest we open ourselves to deadlocking against another
1285          * move operation.
1286          */
1287         if (l_keyring < u_keyring) {
1288                 down_write(&l_keyring->sem);
1289                 down_write_nested(&u_keyring->sem, 1);
1290         } else {
1291                 down_write(&u_keyring->sem);
1292                 down_write_nested(&l_keyring->sem, 1);
1293         }
1294
1295         /* Serialise link/link calls to prevent parallel calls causing a cycle
1296          * when linking two keyring in opposite orders.
1297          */
1298         if (index_key->type == &key_type_keyring)
1299                 mutex_lock(&keyring_serialise_link_lock);
1300
1301         return 0;
1302 }
1303
1304 /*
1305  * Preallocate memory so that a key can be linked into to a keyring.
1306  */
1307 int __key_link_begin(struct key *keyring,
1308                      const struct keyring_index_key *index_key,
1309                      struct assoc_array_edit **_edit)
1310 {
1311         struct assoc_array_edit *edit;
1312         int ret;
1313
1314         kenter("%d,%s,%s,",
1315                keyring->serial, index_key->type->name, index_key->description);
1316
1317         BUG_ON(index_key->desc_len == 0);
1318         BUG_ON(*_edit != NULL);
1319
1320         *_edit = NULL;
1321
1322         ret = -EKEYREVOKED;
1323         if (test_bit(KEY_FLAG_REVOKED, &keyring->flags))
1324                 goto error;
1325
1326         /* Create an edit script that will insert/replace the key in the
1327          * keyring tree.
1328          */
1329         edit = assoc_array_insert(&keyring->keys,
1330                                   &keyring_assoc_array_ops,
1331                                   index_key,
1332                                   NULL);
1333         if (IS_ERR(edit)) {
1334                 ret = PTR_ERR(edit);
1335                 goto error;
1336         }
1337
1338         /* If we're not replacing a link in-place then we're going to need some
1339          * extra quota.
1340          */
1341         if (!edit->dead_leaf) {
1342                 ret = key_payload_reserve(keyring,
1343                                           keyring->datalen + KEYQUOTA_LINK_BYTES);
1344                 if (ret < 0)
1345                         goto error_cancel;
1346         }
1347
1348         *_edit = edit;
1349         kleave(" = 0");
1350         return 0;
1351
1352 error_cancel:
1353         assoc_array_cancel_edit(edit);
1354 error:
1355         kleave(" = %d", ret);
1356         return ret;
1357 }
1358
1359 /*
1360  * Check already instantiated keys aren't going to be a problem.
1361  *
1362  * The caller must have called __key_link_begin(). Don't need to call this for
1363  * keys that were created since __key_link_begin() was called.
1364  */
1365 int __key_link_check_live_key(struct key *keyring, struct key *key)
1366 {
1367         if (key->type == &key_type_keyring)
1368                 /* check that we aren't going to create a cycle by linking one
1369                  * keyring to another */
1370                 return keyring_detect_cycle(keyring, key);
1371         return 0;
1372 }
1373
1374 /*
1375  * Link a key into to a keyring.
1376  *
1377  * Must be called with __key_link_begin() having being called.  Discards any
1378  * already extant link to matching key if there is one, so that each keyring
1379  * holds at most one link to any given key of a particular type+description
1380  * combination.
1381  */
1382 void __key_link(struct key *key, struct assoc_array_edit **_edit)
1383 {
1384         __key_get(key);
1385         assoc_array_insert_set_object(*_edit, keyring_key_to_ptr(key));
1386         assoc_array_apply_edit(*_edit);
1387         *_edit = NULL;
1388 }
1389
1390 /*
1391  * Finish linking a key into to a keyring.
1392  *
1393  * Must be called with __key_link_begin() having being called.
1394  */
1395 void __key_link_end(struct key *keyring,
1396                     const struct keyring_index_key *index_key,
1397                     struct assoc_array_edit *edit)
1398         __releases(&keyring->sem)
1399         __releases(&keyring_serialise_link_lock)
1400 {
1401         BUG_ON(index_key->type == NULL);
1402         kenter("%d,%s,", keyring->serial, index_key->type->name);
1403
1404         if (edit) {
1405                 if (!edit->dead_leaf) {
1406                         key_payload_reserve(keyring,
1407                                 keyring->datalen - KEYQUOTA_LINK_BYTES);
1408                 }
1409                 assoc_array_cancel_edit(edit);
1410         }
1411         up_write(&keyring->sem);
1412
1413         if (index_key->type == &key_type_keyring)
1414                 mutex_unlock(&keyring_serialise_link_lock);
1415 }
1416
1417 /*
1418  * Check addition of keys to restricted keyrings.
1419  */
1420 static int __key_link_check_restriction(struct key *keyring, struct key *key)
1421 {
1422         if (!keyring->restrict_link || !keyring->restrict_link->check)
1423                 return 0;
1424         return keyring->restrict_link->check(keyring, key->type, &key->payload,
1425                                              keyring->restrict_link->key);
1426 }
1427
1428 /**
1429  * key_link - Link a key to a keyring
1430  * @keyring: The keyring to make the link in.
1431  * @key: The key to link to.
1432  *
1433  * Make a link in a keyring to a key, such that the keyring holds a reference
1434  * on that key and the key can potentially be found by searching that keyring.
1435  *
1436  * This function will write-lock the keyring's semaphore and will consume some
1437  * of the user's key data quota to hold the link.
1438  *
1439  * Returns 0 if successful, -ENOTDIR if the keyring isn't a keyring,
1440  * -EKEYREVOKED if the keyring has been revoked, -ENFILE if the keyring is
1441  * full, -EDQUOT if there is insufficient key data quota remaining to add
1442  * another link or -ENOMEM if there's insufficient memory.
1443  *
1444  * It is assumed that the caller has checked that it is permitted for a link to
1445  * be made (the keyring should have Write permission and the key Link
1446  * permission).
1447  */
1448 int key_link(struct key *keyring, struct key *key)
1449 {
1450         struct assoc_array_edit *edit = NULL;
1451         int ret;
1452
1453         kenter("{%d,%d}", keyring->serial, refcount_read(&keyring->usage));
1454
1455         key_check(keyring);
1456         key_check(key);
1457
1458         ret = __key_link_lock(keyring, &key->index_key);
1459         if (ret < 0)
1460                 goto error;
1461
1462         ret = __key_link_begin(keyring, &key->index_key, &edit);
1463         if (ret < 0)
1464                 goto error_end;
1465
1466         kdebug("begun {%d,%d}", keyring->serial, refcount_read(&keyring->usage));
1467         ret = __key_link_check_restriction(keyring, key);
1468         if (ret == 0)
1469                 ret = __key_link_check_live_key(keyring, key);
1470         if (ret == 0)
1471                 __key_link(key, &edit);
1472
1473 error_end:
1474         __key_link_end(keyring, &key->index_key, edit);
1475 error:
1476         kleave(" = %d {%d,%d}", ret, keyring->serial, refcount_read(&keyring->usage));
1477         return ret;
1478 }
1479 EXPORT_SYMBOL(key_link);
1480
1481 /*
1482  * Lock a keyring for unlink.
1483  */
1484 static int __key_unlink_lock(struct key *keyring)
1485         __acquires(&keyring->sem)
1486 {
1487         if (keyring->type != &key_type_keyring)
1488                 return -ENOTDIR;
1489
1490         down_write(&keyring->sem);
1491         return 0;
1492 }
1493
1494 /*
1495  * Begin the process of unlinking a key from a keyring.
1496  */
1497 static int __key_unlink_begin(struct key *keyring, struct key *key,
1498                               struct assoc_array_edit **_edit)
1499 {
1500         struct assoc_array_edit *edit;
1501
1502         BUG_ON(*_edit != NULL);
1503         
1504         edit = assoc_array_delete(&keyring->keys, &keyring_assoc_array_ops,
1505                                   &key->index_key);
1506         if (IS_ERR(edit))
1507                 return PTR_ERR(edit);
1508
1509         if (!edit)
1510                 return -ENOENT;
1511
1512         *_edit = edit;
1513         return 0;
1514 }
1515
1516 /*
1517  * Apply an unlink change.
1518  */
1519 static void __key_unlink(struct key *keyring, struct key *key,
1520                          struct assoc_array_edit **_edit)
1521 {
1522         assoc_array_apply_edit(*_edit);
1523         *_edit = NULL;
1524         key_payload_reserve(keyring, keyring->datalen - KEYQUOTA_LINK_BYTES);
1525 }
1526
1527 /*
1528  * Finish unlinking a key from to a keyring.
1529  */
1530 static void __key_unlink_end(struct key *keyring,
1531                              struct key *key,
1532                              struct assoc_array_edit *edit)
1533         __releases(&keyring->sem)
1534 {
1535         if (edit)
1536                 assoc_array_cancel_edit(edit);
1537         up_write(&keyring->sem);
1538 }
1539
1540 /**
1541  * key_unlink - Unlink the first link to a key from a keyring.
1542  * @keyring: The keyring to remove the link from.
1543  * @key: The key the link is to.
1544  *
1545  * Remove a link from a keyring to a key.
1546  *
1547  * This function will write-lock the keyring's semaphore.
1548  *
1549  * Returns 0 if successful, -ENOTDIR if the keyring isn't a keyring, -ENOENT if
1550  * the key isn't linked to by the keyring or -ENOMEM if there's insufficient
1551  * memory.
1552  *
1553  * It is assumed that the caller has checked that it is permitted for a link to
1554  * be removed (the keyring should have Write permission; no permissions are
1555  * required on the key).
1556  */
1557 int key_unlink(struct key *keyring, struct key *key)
1558 {
1559         struct assoc_array_edit *edit = NULL;
1560         int ret;
1561
1562         key_check(keyring);
1563         key_check(key);
1564
1565         ret = __key_unlink_lock(keyring);
1566         if (ret < 0)
1567                 return ret;
1568
1569         ret = __key_unlink_begin(keyring, key, &edit);
1570         if (ret == 0)
1571                 __key_unlink(keyring, key, &edit);
1572         __key_unlink_end(keyring, key, edit);
1573         return ret;
1574 }
1575 EXPORT_SYMBOL(key_unlink);
1576
1577 /**
1578  * key_move - Move a key from one keyring to another
1579  * @key: The key to move
1580  * @from_keyring: The keyring to remove the link from.
1581  * @to_keyring: The keyring to make the link in.
1582  * @flags: Qualifying flags, such as KEYCTL_MOVE_EXCL.
1583  *
1584  * Make a link in @to_keyring to a key, such that the keyring holds a reference
1585  * on that key and the key can potentially be found by searching that keyring
1586  * whilst simultaneously removing a link to the key from @from_keyring.
1587  *
1588  * This function will write-lock both keyring's semaphores and will consume
1589  * some of the user's key data quota to hold the link on @to_keyring.
1590  *
1591  * Returns 0 if successful, -ENOTDIR if either keyring isn't a keyring,
1592  * -EKEYREVOKED if either keyring has been revoked, -ENFILE if the second
1593  * keyring is full, -EDQUOT if there is insufficient key data quota remaining
1594  * to add another link or -ENOMEM if there's insufficient memory.  If
1595  * KEYCTL_MOVE_EXCL is set, then -EEXIST will be returned if there's already a
1596  * matching key in @to_keyring.
1597  *
1598  * It is assumed that the caller has checked that it is permitted for a link to
1599  * be made (the keyring should have Write permission and the key Link
1600  * permission).
1601  */
1602 int key_move(struct key *key,
1603              struct key *from_keyring,
1604              struct key *to_keyring,
1605              unsigned int flags)
1606 {
1607         struct assoc_array_edit *from_edit = NULL, *to_edit = NULL;
1608         int ret;
1609
1610         kenter("%d,%d,%d", key->serial, from_keyring->serial, to_keyring->serial);
1611
1612         if (from_keyring == to_keyring)
1613                 return 0;
1614
1615         key_check(key);
1616         key_check(from_keyring);
1617         key_check(to_keyring);
1618
1619         ret = __key_move_lock(from_keyring, to_keyring, &key->index_key);
1620         if (ret < 0)
1621                 goto out;
1622         ret = __key_unlink_begin(from_keyring, key, &from_edit);
1623         if (ret < 0)
1624                 goto error;
1625         ret = __key_link_begin(to_keyring, &key->index_key, &to_edit);
1626         if (ret < 0)
1627                 goto error;
1628
1629         ret = -EEXIST;
1630         if (to_edit->dead_leaf && (flags & KEYCTL_MOVE_EXCL))
1631                 goto error;
1632
1633         ret = __key_link_check_restriction(to_keyring, key);
1634         if (ret < 0)
1635                 goto error;
1636         ret = __key_link_check_live_key(to_keyring, key);
1637         if (ret < 0)
1638                 goto error;
1639
1640         __key_unlink(from_keyring, key, &from_edit);
1641         __key_link(key, &to_edit);
1642 error:
1643         __key_link_end(to_keyring, &key->index_key, to_edit);
1644         __key_unlink_end(from_keyring, key, from_edit);
1645 out:
1646         kleave(" = %d", ret);
1647         return ret;
1648 }
1649 EXPORT_SYMBOL(key_move);
1650
1651 /**
1652  * keyring_clear - Clear a keyring
1653  * @keyring: The keyring to clear.
1654  *
1655  * Clear the contents of the specified keyring.
1656  *
1657  * Returns 0 if successful or -ENOTDIR if the keyring isn't a keyring.
1658  */
1659 int keyring_clear(struct key *keyring)
1660 {
1661         struct assoc_array_edit *edit;
1662         int ret;
1663
1664         if (keyring->type != &key_type_keyring)
1665                 return -ENOTDIR;
1666
1667         down_write(&keyring->sem);
1668
1669         edit = assoc_array_clear(&keyring->keys, &keyring_assoc_array_ops);
1670         if (IS_ERR(edit)) {
1671                 ret = PTR_ERR(edit);
1672         } else {
1673                 if (edit)
1674                         assoc_array_apply_edit(edit);
1675                 key_payload_reserve(keyring, 0);
1676                 ret = 0;
1677         }
1678
1679         up_write(&keyring->sem);
1680         return ret;
1681 }
1682 EXPORT_SYMBOL(keyring_clear);
1683
1684 /*
1685  * Dispose of the links from a revoked keyring.
1686  *
1687  * This is called with the key sem write-locked.
1688  */
1689 static void keyring_revoke(struct key *keyring)
1690 {
1691         struct assoc_array_edit *edit;
1692
1693         edit = assoc_array_clear(&keyring->keys, &keyring_assoc_array_ops);
1694         if (!IS_ERR(edit)) {
1695                 if (edit)
1696                         assoc_array_apply_edit(edit);
1697                 key_payload_reserve(keyring, 0);
1698         }
1699 }
1700
1701 static bool keyring_gc_select_iterator(void *object, void *iterator_data)
1702 {
1703         struct key *key = keyring_ptr_to_key(object);
1704         time64_t *limit = iterator_data;
1705
1706         if (key_is_dead(key, *limit))
1707                 return false;
1708         key_get(key);
1709         return true;
1710 }
1711
1712 static int keyring_gc_check_iterator(const void *object, void *iterator_data)
1713 {
1714         const struct key *key = keyring_ptr_to_key(object);
1715         time64_t *limit = iterator_data;
1716
1717         key_check(key);
1718         return key_is_dead(key, *limit);
1719 }
1720
1721 /*
1722  * Garbage collect pointers from a keyring.
1723  *
1724  * Not called with any locks held.  The keyring's key struct will not be
1725  * deallocated under us as only our caller may deallocate it.
1726  */
1727 void keyring_gc(struct key *keyring, time64_t limit)
1728 {
1729         int result;
1730
1731         kenter("%x{%s}", keyring->serial, keyring->description ?: "");
1732
1733         if (keyring->flags & ((1 << KEY_FLAG_INVALIDATED) |
1734                               (1 << KEY_FLAG_REVOKED)))
1735                 goto dont_gc;
1736
1737         /* scan the keyring looking for dead keys */
1738         rcu_read_lock();
1739         result = assoc_array_iterate(&keyring->keys,
1740                                      keyring_gc_check_iterator, &limit);
1741         rcu_read_unlock();
1742         if (result == true)
1743                 goto do_gc;
1744
1745 dont_gc:
1746         kleave(" [no gc]");
1747         return;
1748
1749 do_gc:
1750         down_write(&keyring->sem);
1751         assoc_array_gc(&keyring->keys, &keyring_assoc_array_ops,
1752                        keyring_gc_select_iterator, &limit);
1753         up_write(&keyring->sem);
1754         kleave(" [gc]");
1755 }
1756
1757 /*
1758  * Garbage collect restriction pointers from a keyring.
1759  *
1760  * Keyring restrictions are associated with a key type, and must be cleaned
1761  * up if the key type is unregistered. The restriction is altered to always
1762  * reject additional keys so a keyring cannot be opened up by unregistering
1763  * a key type.
1764  *
1765  * Not called with any keyring locks held. The keyring's key struct will not
1766  * be deallocated under us as only our caller may deallocate it.
1767  *
1768  * The caller is required to hold key_types_sem and dead_type->sem. This is
1769  * fulfilled by key_gc_keytype() holding the locks on behalf of
1770  * key_garbage_collector(), which it invokes on a workqueue.
1771  */
1772 void keyring_restriction_gc(struct key *keyring, struct key_type *dead_type)
1773 {
1774         struct key_restriction *keyres;
1775
1776         kenter("%x{%s}", keyring->serial, keyring->description ?: "");
1777
1778         /*
1779          * keyring->restrict_link is only assigned at key allocation time
1780          * or with the key type locked, so the only values that could be
1781          * concurrently assigned to keyring->restrict_link are for key
1782          * types other than dead_type. Given this, it's ok to check
1783          * the key type before acquiring keyring->sem.
1784          */
1785         if (!dead_type || !keyring->restrict_link ||
1786             keyring->restrict_link->keytype != dead_type) {
1787                 kleave(" [no restriction gc]");
1788                 return;
1789         }
1790
1791         /* Lock the keyring to ensure that a link is not in progress */
1792         down_write(&keyring->sem);
1793
1794         keyres = keyring->restrict_link;
1795
1796         keyres->check = restrict_link_reject;
1797
1798         key_put(keyres->key);
1799         keyres->key = NULL;
1800         keyres->keytype = NULL;
1801
1802         up_write(&keyring->sem);
1803
1804         kleave(" [restriction gc]");
1805 }