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