xref: /linux/security/keys/keyring.c (revision de891c73c1cf41ac8de12c07fa2c84d6a912ad0c)
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 	/* skip invalidated, revoked and expired keys */
602 	if (ctx->flags & KEYRING_SEARCH_DO_STATE_CHECK) {
603 		time64_t expiry = READ_ONCE(key->expiry);
604 
605 		if (kflags & ((1 << KEY_FLAG_INVALIDATED) |
606 			      (1 << KEY_FLAG_REVOKED))) {
607 			ctx->result = ERR_PTR(-EKEYREVOKED);
608 			kleave(" = %d [invrev]", ctx->skipped_ret);
609 			goto skipped;
610 		}
611 
612 		if (expiry && ctx->now >= expiry) {
613 			if (!(ctx->flags & KEYRING_SEARCH_SKIP_EXPIRED))
614 				ctx->result = ERR_PTR(-EKEYEXPIRED);
615 			kleave(" = %d [expire]", ctx->skipped_ret);
616 			goto skipped;
617 		}
618 	}
619 
620 	/* keys that don't match */
621 	if (!ctx->match_data.cmp(key, &ctx->match_data)) {
622 		kleave(" = 0 [!match]");
623 		return 0;
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 		.index_key.desc_len	= strlen(description),
961 		.cred			= current_cred(),
962 		.match_data.cmp		= key_default_cmp,
963 		.match_data.raw_data	= description,
964 		.match_data.lookup_type	= KEYRING_SEARCH_LOOKUP_DIRECT,
965 		.flags			= KEYRING_SEARCH_DO_STATE_CHECK,
966 	};
967 	key_ref_t key;
968 	int ret;
969 
970 	if (recurse)
971 		ctx.flags |= KEYRING_SEARCH_RECURSE;
972 	if (type->match_preparse) {
973 		ret = type->match_preparse(&ctx.match_data);
974 		if (ret < 0)
975 			return ERR_PTR(ret);
976 	}
977 
978 	rcu_read_lock();
979 	key = keyring_search_rcu(keyring, &ctx);
980 	rcu_read_unlock();
981 
982 	if (type->match_free)
983 		type->match_free(&ctx.match_data);
984 	return key;
985 }
986 EXPORT_SYMBOL(keyring_search);
987 
988 static struct key_restriction *keyring_restriction_alloc(
989 	key_restrict_link_func_t check)
990 {
991 	struct key_restriction *keyres =
992 		kzalloc_obj(struct key_restriction);
993 
994 	if (!keyres)
995 		return ERR_PTR(-ENOMEM);
996 
997 	keyres->check = check;
998 
999 	return keyres;
1000 }
1001 
1002 /*
1003  * Semaphore to serialise restriction setup to prevent reference count
1004  * cycles through restriction key pointers.
1005  */
1006 static DECLARE_RWSEM(keyring_serialise_restrict_sem);
1007 
1008 /*
1009  * Check for restriction cycles that would prevent keyring garbage collection.
1010  * keyring_serialise_restrict_sem must be held.
1011  */
1012 static bool keyring_detect_restriction_cycle(const struct key *dest_keyring,
1013 					     struct key_restriction *keyres)
1014 {
1015 	while (keyres && keyres->key &&
1016 	       keyres->key->type == &key_type_keyring) {
1017 		if (keyres->key == dest_keyring)
1018 			return true;
1019 
1020 		keyres = keyres->key->restrict_link;
1021 	}
1022 
1023 	return false;
1024 }
1025 
1026 /**
1027  * keyring_restrict - Look up and apply a restriction to a keyring
1028  * @keyring_ref: The keyring to be restricted
1029  * @type: The key type that will provide the restriction checker.
1030  * @restriction: The restriction options to apply to the keyring
1031  *
1032  * Look up a keyring and apply a restriction to it.  The restriction is managed
1033  * by the specific key type, but can be configured by the options specified in
1034  * the restriction string.
1035  */
1036 int keyring_restrict(key_ref_t keyring_ref, const char *type,
1037 		     const char *restriction)
1038 {
1039 	struct key *keyring;
1040 	struct key_type *restrict_type = NULL;
1041 	struct key_restriction *restrict_link;
1042 	int ret = 0;
1043 
1044 	keyring = key_ref_to_ptr(keyring_ref);
1045 	key_check(keyring);
1046 
1047 	if (keyring->type != &key_type_keyring)
1048 		return -ENOTDIR;
1049 
1050 	if (!type) {
1051 		restrict_link = keyring_restriction_alloc(restrict_link_reject);
1052 	} else {
1053 		restrict_type = key_type_lookup(type);
1054 
1055 		if (IS_ERR(restrict_type))
1056 			return PTR_ERR(restrict_type);
1057 
1058 		if (!restrict_type->lookup_restriction) {
1059 			ret = -ENOENT;
1060 			goto error;
1061 		}
1062 
1063 		restrict_link = restrict_type->lookup_restriction(restriction);
1064 	}
1065 
1066 	if (IS_ERR(restrict_link)) {
1067 		ret = PTR_ERR(restrict_link);
1068 		goto error;
1069 	}
1070 
1071 	down_write(&keyring->sem);
1072 	down_write(&keyring_serialise_restrict_sem);
1073 
1074 	if (keyring->restrict_link) {
1075 		ret = -EEXIST;
1076 	} else if (keyring_detect_restriction_cycle(keyring, restrict_link)) {
1077 		ret = -EDEADLK;
1078 	} else {
1079 		keyring->restrict_link = restrict_link;
1080 		notify_key(keyring, NOTIFY_KEY_SETATTR, 0);
1081 	}
1082 
1083 	up_write(&keyring_serialise_restrict_sem);
1084 	up_write(&keyring->sem);
1085 
1086 	if (ret < 0) {
1087 		key_put(restrict_link->key);
1088 		kfree(restrict_link);
1089 	}
1090 
1091 error:
1092 	if (restrict_type)
1093 		key_type_put(restrict_type);
1094 
1095 	return ret;
1096 }
1097 EXPORT_SYMBOL(keyring_restrict);
1098 
1099 /*
1100  * Search the given keyring for a key that might be updated.
1101  *
1102  * The caller must guarantee that the keyring is a keyring and that the
1103  * permission is granted to modify the keyring as no check is made here.  The
1104  * caller must also hold a lock on the keyring semaphore.
1105  *
1106  * Returns a pointer to the found key with usage count incremented if
1107  * successful and returns NULL if not found.  Revoked and invalidated keys are
1108  * skipped over.
1109  *
1110  * If successful, the possession indicator is propagated from the keyring ref
1111  * to the returned key reference.
1112  */
1113 key_ref_t find_key_to_update(key_ref_t keyring_ref,
1114 			     const struct keyring_index_key *index_key)
1115 {
1116 	struct key *keyring, *key;
1117 	const void *object;
1118 
1119 	keyring = key_ref_to_ptr(keyring_ref);
1120 
1121 	kenter("{%d},{%s,%s}",
1122 	       keyring->serial, index_key->type->name, index_key->description);
1123 
1124 	guard(rcu)();
1125 	object = assoc_array_find(&keyring->keys, &keyring_assoc_array_ops,
1126 				  index_key);
1127 
1128 	if (object)
1129 		goto found;
1130 
1131 	kleave(" = NULL");
1132 	return NULL;
1133 
1134 found:
1135 	key = keyring_ptr_to_key(object);
1136 	if (key->flags & ((1 << KEY_FLAG_INVALIDATED) |
1137 			  (1 << KEY_FLAG_REVOKED))) {
1138 		kleave(" = NULL [x]");
1139 		return NULL;
1140 	}
1141 	__key_get(key);
1142 	kleave(" = {%d}", key->serial);
1143 	return make_key_ref(key, is_key_possessed(keyring_ref));
1144 }
1145 
1146 /*
1147  * Find a keyring with the specified name.
1148  *
1149  * Only keyrings that have nonzero refcount, are not revoked, and are owned by a
1150  * user in the current user namespace are considered.  If @uid_keyring is %true,
1151  * the keyring additionally must have been allocated as a user or user session
1152  * keyring; otherwise, it must grant Search permission directly to the caller.
1153  *
1154  * Returns a pointer to the keyring with the keyring's refcount having being
1155  * incremented on success.  -ENOKEY is returned if a key could not be found.
1156  */
1157 struct key *find_keyring_by_name(const char *name, bool uid_keyring)
1158 {
1159 	struct user_namespace *ns = current_user_ns();
1160 	struct key *keyring;
1161 
1162 	if (!name)
1163 		return ERR_PTR(-EINVAL);
1164 
1165 	read_lock(&keyring_name_lock);
1166 
1167 	/* Search this hash bucket for a keyring with a matching name that
1168 	 * grants Search permission and that hasn't been revoked
1169 	 */
1170 	list_for_each_entry(keyring, &ns->keyring_name_list, name_link) {
1171 		if (!kuid_has_mapping(ns, keyring->uid))
1172 			continue;
1173 
1174 		if (test_bit(KEY_FLAG_REVOKED, &keyring->flags))
1175 			continue;
1176 
1177 		if (strcmp(keyring->description, name) != 0)
1178 			continue;
1179 
1180 		if (uid_keyring) {
1181 			if (!test_bit(KEY_FLAG_UID_KEYRING,
1182 				      &keyring->flags))
1183 				continue;
1184 		} else {
1185 			if (key_permission(make_key_ref(keyring, 0),
1186 					   KEY_NEED_SEARCH) < 0)
1187 				continue;
1188 		}
1189 
1190 		/* we've got a match but we might end up racing with
1191 		 * key_cleanup() if the keyring is currently 'dead'
1192 		 * (ie. it has a zero usage count) */
1193 		if (!refcount_inc_not_zero(&keyring->usage))
1194 			continue;
1195 		keyring->last_used_at = ktime_get_real_seconds();
1196 		goto out;
1197 	}
1198 
1199 	keyring = ERR_PTR(-ENOKEY);
1200 out:
1201 	read_unlock(&keyring_name_lock);
1202 	return keyring;
1203 }
1204 
1205 static int keyring_detect_cycle_iterator(const void *object,
1206 					 void *iterator_data)
1207 {
1208 	struct keyring_search_context *ctx = iterator_data;
1209 	const struct key *key = keyring_ptr_to_key(object);
1210 
1211 	kenter("{%d}", key->serial);
1212 
1213 	/* We might get a keyring with matching index-key that is nonetheless a
1214 	 * different keyring. */
1215 	if (key != ctx->match_data.raw_data)
1216 		return 0;
1217 
1218 	ctx->result = ERR_PTR(-EDEADLK);
1219 	return 1;
1220 }
1221 
1222 /*
1223  * See if a cycle will be created by inserting acyclic tree B in acyclic
1224  * tree A at the topmost level (ie: as a direct child of A).
1225  *
1226  * Since we are adding B to A at the top level, checking for cycles should just
1227  * be a matter of seeing if node A is somewhere in tree B.
1228  */
1229 static int keyring_detect_cycle(struct key *A, struct key *B)
1230 {
1231 	struct keyring_search_context ctx = {
1232 		.index_key		= A->index_key,
1233 		.match_data.raw_data	= A,
1234 		.match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT,
1235 		.iterator		= keyring_detect_cycle_iterator,
1236 		.flags			= (KEYRING_SEARCH_NO_STATE_CHECK |
1237 					   KEYRING_SEARCH_NO_UPDATE_TIME |
1238 					   KEYRING_SEARCH_NO_CHECK_PERM |
1239 					   KEYRING_SEARCH_DETECT_TOO_DEEP |
1240 					   KEYRING_SEARCH_RECURSE),
1241 	};
1242 
1243 	rcu_read_lock();
1244 	search_nested_keyrings(B, &ctx);
1245 	rcu_read_unlock();
1246 	return PTR_ERR(ctx.result) == -EAGAIN ? 0 : PTR_ERR(ctx.result);
1247 }
1248 
1249 /*
1250  * Lock keyring for link.
1251  */
1252 int __key_link_lock(struct key *keyring,
1253 		    const struct keyring_index_key *index_key)
1254 	__acquires(&keyring->sem)
1255 	__acquires(&keyring_serialise_link_lock)
1256 {
1257 	if (keyring->type != &key_type_keyring)
1258 		return -ENOTDIR;
1259 
1260 	down_write(&keyring->sem);
1261 
1262 	/* Serialise link/link calls to prevent parallel calls causing a cycle
1263 	 * when linking two keyring in opposite orders.
1264 	 */
1265 	if (index_key->type == &key_type_keyring)
1266 		mutex_lock(&keyring_serialise_link_lock);
1267 
1268 	return 0;
1269 }
1270 
1271 /*
1272  * Lock keyrings for move (link/unlink combination).
1273  */
1274 int __key_move_lock(struct key *l_keyring, struct key *u_keyring,
1275 		    const struct keyring_index_key *index_key)
1276 	__acquires(&l_keyring->sem)
1277 	__acquires(&u_keyring->sem)
1278 	__acquires(&keyring_serialise_link_lock)
1279 {
1280 	if (l_keyring->type != &key_type_keyring ||
1281 	    u_keyring->type != &key_type_keyring)
1282 		return -ENOTDIR;
1283 
1284 	/* We have to be very careful here to take the keyring locks in the
1285 	 * right order, lest we open ourselves to deadlocking against another
1286 	 * move operation.
1287 	 */
1288 	if (l_keyring < u_keyring) {
1289 		down_write(&l_keyring->sem);
1290 		down_write_nested(&u_keyring->sem, 1);
1291 	} else {
1292 		down_write(&u_keyring->sem);
1293 		down_write_nested(&l_keyring->sem, 1);
1294 	}
1295 
1296 	/* Serialise link/link calls to prevent parallel calls causing a cycle
1297 	 * when linking two keyring in opposite orders.
1298 	 */
1299 	if (index_key->type == &key_type_keyring)
1300 		mutex_lock(&keyring_serialise_link_lock);
1301 
1302 	return 0;
1303 }
1304 
1305 /*
1306  * Preallocate memory so that a key can be linked into to a keyring.
1307  */
1308 int __key_link_begin(struct key *keyring,
1309 		     const struct keyring_index_key *index_key,
1310 		     struct assoc_array_edit **_edit)
1311 {
1312 	struct assoc_array_edit *edit;
1313 	int ret;
1314 
1315 	kenter("%d,%s,%s,",
1316 	       keyring->serial, index_key->type->name, index_key->description);
1317 
1318 	BUG_ON(index_key->desc_len == 0);
1319 	BUG_ON(*_edit != NULL);
1320 
1321 	*_edit = NULL;
1322 
1323 	ret = -EKEYREVOKED;
1324 	if (test_bit(KEY_FLAG_REVOKED, &keyring->flags))
1325 		goto error;
1326 
1327 	/* Create an edit script that will insert/replace the key in the
1328 	 * keyring tree.
1329 	 */
1330 	edit = assoc_array_insert(&keyring->keys,
1331 				  &keyring_assoc_array_ops,
1332 				  index_key,
1333 				  NULL);
1334 	if (IS_ERR(edit)) {
1335 		ret = PTR_ERR(edit);
1336 		goto error;
1337 	}
1338 
1339 	/* If we're not replacing a link in-place then we're going to need some
1340 	 * extra quota.
1341 	 */
1342 	if (!edit->dead_leaf) {
1343 		ret = key_payload_reserve(keyring,
1344 					  keyring->datalen + KEYQUOTA_LINK_BYTES);
1345 		if (ret < 0)
1346 			goto error_cancel;
1347 	}
1348 
1349 	*_edit = edit;
1350 	kleave(" = 0");
1351 	return 0;
1352 
1353 error_cancel:
1354 	assoc_array_cancel_edit(edit);
1355 error:
1356 	kleave(" = %d", ret);
1357 	return ret;
1358 }
1359 
1360 /*
1361  * Check already instantiated keys aren't going to be a problem.
1362  *
1363  * The caller must have called __key_link_begin(). Don't need to call this for
1364  * keys that were created since __key_link_begin() was called.
1365  */
1366 int __key_link_check_live_key(struct key *keyring, struct key *key)
1367 {
1368 	if (key->type == &key_type_keyring)
1369 		/* check that we aren't going to create a cycle by linking one
1370 		 * keyring to another */
1371 		return keyring_detect_cycle(keyring, key);
1372 	return 0;
1373 }
1374 
1375 /*
1376  * Link a key into to a keyring.
1377  *
1378  * Must be called with __key_link_begin() having being called.  Discards any
1379  * already extant link to matching key if there is one, so that each keyring
1380  * holds at most one link to any given key of a particular type+description
1381  * combination.
1382  */
1383 void __key_link(struct key *keyring, struct key *key,
1384 		struct assoc_array_edit **_edit)
1385 {
1386 	__key_get(key);
1387 	assoc_array_insert_set_object(*_edit, keyring_key_to_ptr(key));
1388 	assoc_array_apply_edit(*_edit);
1389 	*_edit = NULL;
1390 	notify_key(keyring, NOTIFY_KEY_LINKED, key_serial(key));
1391 }
1392 
1393 /*
1394  * Finish linking a key into to a keyring.
1395  *
1396  * Must be called with __key_link_begin() having being called.
1397  */
1398 void __key_link_end(struct key *keyring,
1399 		    const struct keyring_index_key *index_key,
1400 		    struct assoc_array_edit *edit)
1401 	__releases(&keyring->sem)
1402 	__releases(&keyring_serialise_link_lock)
1403 {
1404 	BUG_ON(index_key->type == NULL);
1405 	kenter("%d,%s,", keyring->serial, index_key->type->name);
1406 
1407 	if (edit) {
1408 		if (!edit->dead_leaf) {
1409 			key_payload_reserve(keyring,
1410 				keyring->datalen - KEYQUOTA_LINK_BYTES);
1411 		}
1412 		assoc_array_cancel_edit(edit);
1413 	}
1414 	up_write(&keyring->sem);
1415 
1416 	if (index_key->type == &key_type_keyring)
1417 		mutex_unlock(&keyring_serialise_link_lock);
1418 }
1419 
1420 /*
1421  * Check addition of keys to restricted keyrings.
1422  */
1423 static int __key_link_check_restriction(struct key *keyring, struct key *key)
1424 {
1425 	if (!keyring->restrict_link || !keyring->restrict_link->check)
1426 		return 0;
1427 	return keyring->restrict_link->check(keyring, key->type, &key->payload,
1428 					     keyring->restrict_link->key);
1429 }
1430 
1431 /**
1432  * key_link - Link a key to a keyring
1433  * @keyring: The keyring to make the link in.
1434  * @key: The key to link to.
1435  *
1436  * Make a link in a keyring to a key, such that the keyring holds a reference
1437  * on that key and the key can potentially be found by searching that keyring.
1438  *
1439  * This function will write-lock the keyring's semaphore and will consume some
1440  * of the user's key data quota to hold the link.
1441  *
1442  * Returns 0 if successful, -ENOTDIR if the keyring isn't a keyring,
1443  * -EKEYREVOKED if the keyring has been revoked, -ENFILE if the keyring is
1444  * full, -EDQUOT if there is insufficient key data quota remaining to add
1445  * another link or -ENOMEM if there's insufficient memory.
1446  *
1447  * It is assumed that the caller has checked that it is permitted for a link to
1448  * be made (the keyring should have Write permission and the key Link
1449  * permission).
1450  */
1451 int key_link(struct key *keyring, struct key *key)
1452 {
1453 	struct assoc_array_edit *edit = NULL;
1454 	int ret;
1455 
1456 	kenter("{%d,%d}", keyring->serial, refcount_read(&keyring->usage));
1457 
1458 	key_check(keyring);
1459 	key_check(key);
1460 
1461 	ret = __key_link_lock(keyring, &key->index_key);
1462 	if (ret < 0)
1463 		goto error;
1464 
1465 	ret = __key_link_begin(keyring, &key->index_key, &edit);
1466 	if (ret < 0)
1467 		goto error_end;
1468 
1469 	kdebug("begun {%d,%d}", keyring->serial, refcount_read(&keyring->usage));
1470 	ret = __key_link_check_restriction(keyring, key);
1471 	if (ret == 0)
1472 		ret = __key_link_check_live_key(keyring, key);
1473 	if (ret == 0)
1474 		__key_link(keyring, key, &edit);
1475 
1476 error_end:
1477 	__key_link_end(keyring, &key->index_key, edit);
1478 error:
1479 	kleave(" = %d {%d,%d}", ret, keyring->serial, refcount_read(&keyring->usage));
1480 	return ret;
1481 }
1482 EXPORT_SYMBOL(key_link);
1483 
1484 /*
1485  * Lock a keyring for unlink.
1486  */
1487 static int __key_unlink_lock(struct key *keyring)
1488 	__acquires(&keyring->sem)
1489 {
1490 	if (keyring->type != &key_type_keyring)
1491 		return -ENOTDIR;
1492 
1493 	down_write(&keyring->sem);
1494 	return 0;
1495 }
1496 
1497 /*
1498  * Begin the process of unlinking a key from a keyring.
1499  */
1500 static int __key_unlink_begin(struct key *keyring, struct key *key,
1501 			      struct assoc_array_edit **_edit)
1502 {
1503 	struct assoc_array_edit *edit;
1504 
1505 	BUG_ON(*_edit != NULL);
1506 
1507 	edit = assoc_array_delete(&keyring->keys, &keyring_assoc_array_ops,
1508 				  &key->index_key);
1509 	if (IS_ERR(edit))
1510 		return PTR_ERR(edit);
1511 
1512 	if (!edit)
1513 		return -ENOENT;
1514 
1515 	*_edit = edit;
1516 	return 0;
1517 }
1518 
1519 /*
1520  * Apply an unlink change.
1521  */
1522 static void __key_unlink(struct key *keyring, struct key *key,
1523 			 struct assoc_array_edit **_edit)
1524 {
1525 	assoc_array_apply_edit(*_edit);
1526 	notify_key(keyring, NOTIFY_KEY_UNLINKED, key_serial(key));
1527 	*_edit = NULL;
1528 	key_payload_reserve(keyring, keyring->datalen - KEYQUOTA_LINK_BYTES);
1529 }
1530 
1531 /*
1532  * Finish unlinking a key from to a keyring.
1533  */
1534 static void __key_unlink_end(struct key *keyring,
1535 			     struct key *key,
1536 			     struct assoc_array_edit *edit)
1537 	__releases(&keyring->sem)
1538 {
1539 	if (edit)
1540 		assoc_array_cancel_edit(edit);
1541 	up_write(&keyring->sem);
1542 }
1543 
1544 /**
1545  * key_unlink - Unlink the first link to a key from a keyring.
1546  * @keyring: The keyring to remove the link from.
1547  * @key: The key the link is to.
1548  *
1549  * Remove a link from a keyring to a key.
1550  *
1551  * This function will write-lock the keyring's semaphore.
1552  *
1553  * Returns 0 if successful, -ENOTDIR if the keyring isn't a keyring, -ENOENT if
1554  * the key isn't linked to by the keyring or -ENOMEM if there's insufficient
1555  * memory.
1556  *
1557  * It is assumed that the caller has checked that it is permitted for a link to
1558  * be removed (the keyring should have Write permission; no permissions are
1559  * required on the key).
1560  */
1561 int key_unlink(struct key *keyring, struct key *key)
1562 {
1563 	struct assoc_array_edit *edit = NULL;
1564 	int ret;
1565 
1566 	key_check(keyring);
1567 	key_check(key);
1568 
1569 	ret = __key_unlink_lock(keyring);
1570 	if (ret < 0)
1571 		return ret;
1572 
1573 	ret = __key_unlink_begin(keyring, key, &edit);
1574 	if (ret == 0)
1575 		__key_unlink(keyring, key, &edit);
1576 	__key_unlink_end(keyring, key, edit);
1577 	return ret;
1578 }
1579 EXPORT_SYMBOL(key_unlink);
1580 
1581 /**
1582  * key_move - Move a key from one keyring to another
1583  * @key: The key to move
1584  * @from_keyring: The keyring to remove the link from.
1585  * @to_keyring: The keyring to make the link in.
1586  * @flags: Qualifying flags, such as KEYCTL_MOVE_EXCL.
1587  *
1588  * Make a link in @to_keyring to a key, such that the keyring holds a reference
1589  * on that key and the key can potentially be found by searching that keyring
1590  * whilst simultaneously removing a link to the key from @from_keyring.
1591  *
1592  * This function will write-lock both keyring's semaphores and will consume
1593  * some of the user's key data quota to hold the link on @to_keyring.
1594  *
1595  * Returns 0 if successful, -ENOTDIR if either keyring isn't a keyring,
1596  * -EKEYREVOKED if either keyring has been revoked, -ENFILE if the second
1597  * keyring is full, -EDQUOT if there is insufficient key data quota remaining
1598  * to add another link or -ENOMEM if there's insufficient memory.  If
1599  * KEYCTL_MOVE_EXCL is set, then -EEXIST will be returned if there's already a
1600  * matching key in @to_keyring.
1601  *
1602  * It is assumed that the caller has checked that it is permitted for a link to
1603  * be made (the keyring should have Write permission and the key Link
1604  * permission).
1605  */
1606 int key_move(struct key *key,
1607 	     struct key *from_keyring,
1608 	     struct key *to_keyring,
1609 	     unsigned int flags)
1610 {
1611 	struct assoc_array_edit *from_edit = NULL, *to_edit = NULL;
1612 	int ret;
1613 
1614 	kenter("%d,%d,%d", key->serial, from_keyring->serial, to_keyring->serial);
1615 
1616 	if (from_keyring == to_keyring)
1617 		return 0;
1618 
1619 	key_check(key);
1620 	key_check(from_keyring);
1621 	key_check(to_keyring);
1622 
1623 	ret = __key_move_lock(from_keyring, to_keyring, &key->index_key);
1624 	if (ret < 0)
1625 		goto out;
1626 	ret = __key_unlink_begin(from_keyring, key, &from_edit);
1627 	if (ret < 0)
1628 		goto error;
1629 	ret = __key_link_begin(to_keyring, &key->index_key, &to_edit);
1630 	if (ret < 0)
1631 		goto error;
1632 
1633 	ret = -EEXIST;
1634 	if (to_edit->dead_leaf && (flags & KEYCTL_MOVE_EXCL))
1635 		goto error;
1636 
1637 	ret = __key_link_check_restriction(to_keyring, key);
1638 	if (ret < 0)
1639 		goto error;
1640 	ret = __key_link_check_live_key(to_keyring, key);
1641 	if (ret < 0)
1642 		goto error;
1643 
1644 	__key_unlink(from_keyring, key, &from_edit);
1645 	__key_link(to_keyring, key, &to_edit);
1646 error:
1647 	__key_link_end(to_keyring, &key->index_key, to_edit);
1648 	__key_unlink_end(from_keyring, key, from_edit);
1649 out:
1650 	kleave(" = %d", ret);
1651 	return ret;
1652 }
1653 EXPORT_SYMBOL(key_move);
1654 
1655 /**
1656  * keyring_clear - Clear a keyring
1657  * @keyring: The keyring to clear.
1658  *
1659  * Clear the contents of the specified keyring.
1660  *
1661  * Returns 0 if successful or -ENOTDIR if the keyring isn't a keyring.
1662  */
1663 int keyring_clear(struct key *keyring)
1664 {
1665 	struct assoc_array_edit *edit;
1666 	int ret;
1667 
1668 	if (keyring->type != &key_type_keyring)
1669 		return -ENOTDIR;
1670 
1671 	down_write(&keyring->sem);
1672 
1673 	edit = assoc_array_clear(&keyring->keys, &keyring_assoc_array_ops);
1674 	if (IS_ERR(edit)) {
1675 		ret = PTR_ERR(edit);
1676 	} else {
1677 		if (edit)
1678 			assoc_array_apply_edit(edit);
1679 		notify_key(keyring, NOTIFY_KEY_CLEARED, 0);
1680 		key_payload_reserve(keyring, 0);
1681 		ret = 0;
1682 	}
1683 
1684 	up_write(&keyring->sem);
1685 	return ret;
1686 }
1687 EXPORT_SYMBOL(keyring_clear);
1688 
1689 /*
1690  * Dispose of the links from a revoked keyring.
1691  *
1692  * This is called with the key sem write-locked.
1693  */
1694 static void keyring_revoke(struct key *keyring)
1695 {
1696 	struct assoc_array_edit *edit;
1697 
1698 	edit = assoc_array_clear(&keyring->keys, &keyring_assoc_array_ops);
1699 	if (!IS_ERR(edit)) {
1700 		if (edit)
1701 			assoc_array_apply_edit(edit);
1702 		key_payload_reserve(keyring, 0);
1703 	}
1704 }
1705 
1706 static bool keyring_gc_select_iterator(void *object, void *iterator_data)
1707 {
1708 	struct key *key = keyring_ptr_to_key(object);
1709 	time64_t *limit = iterator_data;
1710 
1711 	if (key_is_dead(key, *limit))
1712 		return false;
1713 	key_get(key);
1714 	return true;
1715 }
1716 
1717 static int keyring_gc_check_iterator(const void *object, void *iterator_data)
1718 {
1719 	const struct key *key = keyring_ptr_to_key(object);
1720 	time64_t *limit = iterator_data;
1721 
1722 	key_check(key);
1723 	return key_is_dead(key, *limit);
1724 }
1725 
1726 /*
1727  * Garbage collect pointers from a keyring.
1728  *
1729  * Not called with any locks held.  The keyring's key struct will not be
1730  * deallocated under us as only our caller may deallocate it.
1731  */
1732 void keyring_gc(struct key *keyring, time64_t limit)
1733 {
1734 	int result;
1735 
1736 	kenter("%x{%s}", keyring->serial, keyring->description ?: "");
1737 
1738 	if (keyring->flags & ((1 << KEY_FLAG_INVALIDATED) |
1739 			      (1 << KEY_FLAG_REVOKED)))
1740 		goto dont_gc;
1741 
1742 	/* scan the keyring looking for dead keys */
1743 	rcu_read_lock();
1744 	result = assoc_array_iterate(&keyring->keys,
1745 				     keyring_gc_check_iterator, &limit);
1746 	rcu_read_unlock();
1747 	if (result == true)
1748 		goto do_gc;
1749 
1750 dont_gc:
1751 	kleave(" [no gc]");
1752 	return;
1753 
1754 do_gc:
1755 	down_write(&keyring->sem);
1756 	assoc_array_gc(&keyring->keys, &keyring_assoc_array_ops,
1757 		       keyring_gc_select_iterator, &limit);
1758 	up_write(&keyring->sem);
1759 	kleave(" [gc]");
1760 }
1761 
1762 /*
1763  * Garbage collect restriction pointers from a keyring.
1764  *
1765  * Keyring restrictions are associated with a key type, and must be cleaned
1766  * up if the key type is unregistered. The restriction is altered to always
1767  * reject additional keys so a keyring cannot be opened up by unregistering
1768  * a key type.
1769  *
1770  * Not called with any keyring locks held. The keyring's key struct will not
1771  * be deallocated under us as only our caller may deallocate it.
1772  *
1773  * The caller is required to hold key_types_sem and dead_type->sem. This is
1774  * fulfilled by key_gc_keytype() holding the locks on behalf of
1775  * key_garbage_collector(), which it invokes on a workqueue.
1776  */
1777 void keyring_restriction_gc(struct key *keyring, struct key_type *dead_type)
1778 {
1779 	struct key_restriction *keyres;
1780 
1781 	kenter("%x{%s}", keyring->serial, keyring->description ?: "");
1782 
1783 	/*
1784 	 * keyring->restrict_link is only assigned at key allocation time
1785 	 * or with the key type locked, so the only values that could be
1786 	 * concurrently assigned to keyring->restrict_link are for key
1787 	 * types other than dead_type. Given this, it's ok to check
1788 	 * the key type before acquiring keyring->sem.
1789 	 */
1790 	if (!dead_type || !keyring->restrict_link ||
1791 	    keyring->restrict_link->keytype != dead_type) {
1792 		kleave(" [no restriction gc]");
1793 		return;
1794 	}
1795 
1796 	/* Lock the keyring to ensure that a link is not in progress */
1797 	down_write(&keyring->sem);
1798 
1799 	keyres = keyring->restrict_link;
1800 
1801 	keyres->check = restrict_link_reject;
1802 
1803 	key_put(keyres->key);
1804 	keyres->key = NULL;
1805 	keyres->keytype = NULL;
1806 
1807 	up_write(&keyring->sem);
1808 
1809 	kleave(" [restriction gc]");
1810 }
1811