xref: /openbmc/linux/security/keys/keyring.c (revision e57e8669f2ab8350d30f771dd2fdd5377f183db2)
1 /* Keyring handling
2  *
3  * Copyright (C) 2004-2005, 2008 Red Hat, Inc. All Rights Reserved.
4  * Written by David Howells (dhowells@redhat.com)
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version
9  * 2 of the License, or (at your option) any later version.
10  */
11 
12 #include <linux/module.h>
13 #include <linux/init.h>
14 #include <linux/sched.h>
15 #include <linux/slab.h>
16 #include <linux/security.h>
17 #include <linux/seq_file.h>
18 #include <linux/err.h>
19 #include <keys/keyring-type.h>
20 #include <linux/uaccess.h>
21 #include "internal.h"
22 
23 #define rcu_dereference_locked_keyring(keyring)				\
24 	(rcu_dereference_protected(					\
25 		(keyring)->payload.subscriptions,			\
26 		rwsem_is_locked((struct rw_semaphore *)&(keyring)->sem)))
27 
28 #define rcu_deref_link_locked(klist, index, keyring)			\
29 	(rcu_dereference_protected(					\
30 		(klist)->keys[index],					\
31 		rwsem_is_locked((struct rw_semaphore *)&(keyring)->sem)))
32 
33 #define MAX_KEYRING_LINKS						\
34 	min_t(size_t, USHRT_MAX - 1,					\
35 	      ((PAGE_SIZE - sizeof(struct keyring_list)) / sizeof(struct key *)))
36 
37 #define KEY_LINK_FIXQUOTA 1UL
38 
39 /*
40  * When plumbing the depths of the key tree, this sets a hard limit
41  * set on how deep we're willing to go.
42  */
43 #define KEYRING_SEARCH_MAX_DEPTH 6
44 
45 /*
46  * We keep all named keyrings in a hash to speed looking them up.
47  */
48 #define KEYRING_NAME_HASH_SIZE	(1 << 5)
49 
50 static struct list_head	keyring_name_hash[KEYRING_NAME_HASH_SIZE];
51 static DEFINE_RWLOCK(keyring_name_lock);
52 
53 static inline unsigned keyring_hash(const char *desc)
54 {
55 	unsigned bucket = 0;
56 
57 	for (; *desc; desc++)
58 		bucket += (unsigned char)*desc;
59 
60 	return bucket & (KEYRING_NAME_HASH_SIZE - 1);
61 }
62 
63 /*
64  * The keyring key type definition.  Keyrings are simply keys of this type and
65  * can be treated as ordinary keys in addition to having their own special
66  * operations.
67  */
68 static int keyring_instantiate(struct key *keyring,
69 			       struct key_preparsed_payload *prep);
70 static int keyring_match(const struct key *keyring, const void *criterion);
71 static void keyring_revoke(struct key *keyring);
72 static void keyring_destroy(struct key *keyring);
73 static void keyring_describe(const struct key *keyring, struct seq_file *m);
74 static long keyring_read(const struct key *keyring,
75 			 char __user *buffer, size_t buflen);
76 
77 struct key_type key_type_keyring = {
78 	.name		= "keyring",
79 	.def_datalen	= sizeof(struct keyring_list),
80 	.instantiate	= keyring_instantiate,
81 	.match		= keyring_match,
82 	.revoke		= keyring_revoke,
83 	.destroy	= keyring_destroy,
84 	.describe	= keyring_describe,
85 	.read		= keyring_read,
86 };
87 EXPORT_SYMBOL(key_type_keyring);
88 
89 /*
90  * Semaphore to serialise link/link calls to prevent two link calls in parallel
91  * introducing a cycle.
92  */
93 static DECLARE_RWSEM(keyring_serialise_link_sem);
94 
95 /*
96  * Publish the name of a keyring so that it can be found by name (if it has
97  * one).
98  */
99 static void keyring_publish_name(struct key *keyring)
100 {
101 	int bucket;
102 
103 	if (keyring->description) {
104 		bucket = keyring_hash(keyring->description);
105 
106 		write_lock(&keyring_name_lock);
107 
108 		if (!keyring_name_hash[bucket].next)
109 			INIT_LIST_HEAD(&keyring_name_hash[bucket]);
110 
111 		list_add_tail(&keyring->type_data.link,
112 			      &keyring_name_hash[bucket]);
113 
114 		write_unlock(&keyring_name_lock);
115 	}
116 }
117 
118 /*
119  * Initialise a keyring.
120  *
121  * Returns 0 on success, -EINVAL if given any data.
122  */
123 static int keyring_instantiate(struct key *keyring,
124 			       struct key_preparsed_payload *prep)
125 {
126 	int ret;
127 
128 	ret = -EINVAL;
129 	if (prep->datalen == 0) {
130 		/* make the keyring available by name if it has one */
131 		keyring_publish_name(keyring);
132 		ret = 0;
133 	}
134 
135 	return ret;
136 }
137 
138 /*
139  * Match keyrings on their name
140  */
141 static int keyring_match(const struct key *keyring, const void *description)
142 {
143 	return keyring->description &&
144 		strcmp(keyring->description, description) == 0;
145 }
146 
147 /*
148  * Clean up a keyring when it is destroyed.  Unpublish its name if it had one
149  * and dispose of its data.
150  *
151  * The garbage collector detects the final key_put(), removes the keyring from
152  * the serial number tree and then does RCU synchronisation before coming here,
153  * so we shouldn't need to worry about code poking around here with the RCU
154  * readlock held by this time.
155  */
156 static void keyring_destroy(struct key *keyring)
157 {
158 	struct keyring_list *klist;
159 	int loop;
160 
161 	if (keyring->description) {
162 		write_lock(&keyring_name_lock);
163 
164 		if (keyring->type_data.link.next != NULL &&
165 		    !list_empty(&keyring->type_data.link))
166 			list_del(&keyring->type_data.link);
167 
168 		write_unlock(&keyring_name_lock);
169 	}
170 
171 	klist = rcu_access_pointer(keyring->payload.subscriptions);
172 	if (klist) {
173 		for (loop = klist->nkeys - 1; loop >= 0; loop--)
174 			key_put(rcu_access_pointer(klist->keys[loop]));
175 		kfree(klist);
176 	}
177 }
178 
179 /*
180  * Describe a keyring for /proc.
181  */
182 static void keyring_describe(const struct key *keyring, struct seq_file *m)
183 {
184 	struct keyring_list *klist;
185 
186 	if (keyring->description)
187 		seq_puts(m, keyring->description);
188 	else
189 		seq_puts(m, "[anon]");
190 
191 	if (key_is_instantiated(keyring)) {
192 		rcu_read_lock();
193 		klist = rcu_dereference(keyring->payload.subscriptions);
194 		if (klist)
195 			seq_printf(m, ": %u/%u", klist->nkeys, klist->maxkeys);
196 		else
197 			seq_puts(m, ": empty");
198 		rcu_read_unlock();
199 	}
200 }
201 
202 /*
203  * Read a list of key IDs from the keyring's contents in binary form
204  *
205  * The keyring's semaphore is read-locked by the caller.
206  */
207 static long keyring_read(const struct key *keyring,
208 			 char __user *buffer, size_t buflen)
209 {
210 	struct keyring_list *klist;
211 	struct key *key;
212 	size_t qty, tmp;
213 	int loop, ret;
214 
215 	ret = 0;
216 	klist = rcu_dereference_locked_keyring(keyring);
217 	if (klist) {
218 		/* calculate how much data we could return */
219 		qty = klist->nkeys * sizeof(key_serial_t);
220 
221 		if (buffer && buflen > 0) {
222 			if (buflen > qty)
223 				buflen = qty;
224 
225 			/* copy the IDs of the subscribed keys into the
226 			 * buffer */
227 			ret = -EFAULT;
228 
229 			for (loop = 0; loop < klist->nkeys; loop++) {
230 				key = rcu_deref_link_locked(klist, loop,
231 							    keyring);
232 
233 				tmp = sizeof(key_serial_t);
234 				if (tmp > buflen)
235 					tmp = buflen;
236 
237 				if (copy_to_user(buffer,
238 						 &key->serial,
239 						 tmp) != 0)
240 					goto error;
241 
242 				buflen -= tmp;
243 				if (buflen == 0)
244 					break;
245 				buffer += tmp;
246 			}
247 		}
248 
249 		ret = qty;
250 	}
251 
252 error:
253 	return ret;
254 }
255 
256 /*
257  * Allocate a keyring and link into the destination keyring.
258  */
259 struct key *keyring_alloc(const char *description, kuid_t uid, kgid_t gid,
260 			  const struct cred *cred, key_perm_t perm,
261 			  unsigned long flags, struct key *dest)
262 {
263 	struct key *keyring;
264 	int ret;
265 
266 	keyring = key_alloc(&key_type_keyring, description,
267 			    uid, gid, cred, perm, flags);
268 	if (!IS_ERR(keyring)) {
269 		ret = key_instantiate_and_link(keyring, NULL, 0, dest, NULL);
270 		if (ret < 0) {
271 			key_put(keyring);
272 			keyring = ERR_PTR(ret);
273 		}
274 	}
275 
276 	return keyring;
277 }
278 EXPORT_SYMBOL(keyring_alloc);
279 
280 /**
281  * keyring_search_aux - Search a keyring tree for a key matching some criteria
282  * @keyring_ref: A pointer to the keyring with possession indicator.
283  * @ctx: The keyring search context.
284  *
285  * Search the supplied keyring tree for a key that matches the criteria given.
286  * The root keyring and any linked keyrings must grant Search permission to the
287  * caller to be searchable and keys can only be found if they too grant Search
288  * to the caller. The possession flag on the root keyring pointer controls use
289  * of the possessor bits in permissions checking of the entire tree.  In
290  * addition, the LSM gets to forbid keyring searches and key matches.
291  *
292  * The search is performed as a breadth-then-depth search up to the prescribed
293  * limit (KEYRING_SEARCH_MAX_DEPTH).
294  *
295  * Keys are matched to the type provided and are then filtered by the match
296  * function, which is given the description to use in any way it sees fit.  The
297  * match function may use any attributes of a key that it wishes to to
298  * determine the match.  Normally the match function from the key type would be
299  * used.
300  *
301  * RCU is used to prevent the keyring key lists from disappearing without the
302  * need to take lots of locks.
303  *
304  * Returns a pointer to the found key and increments the key usage count if
305  * successful; -EAGAIN if no matching keys were found, or if expired or revoked
306  * keys were found; -ENOKEY if only negative keys were found; -ENOTDIR if the
307  * specified keyring wasn't a keyring.
308  *
309  * In the case of a successful return, the possession attribute from
310  * @keyring_ref is propagated to the returned key reference.
311  */
312 key_ref_t keyring_search_aux(key_ref_t keyring_ref,
313 			     struct keyring_search_context *ctx)
314 {
315 	struct {
316 		/* Need a separate keylist pointer for RCU purposes */
317 		struct key *keyring;
318 		struct keyring_list *keylist;
319 		int kix;
320 	} stack[KEYRING_SEARCH_MAX_DEPTH];
321 
322 	struct keyring_list *keylist;
323 	unsigned long kflags;
324 	struct key *keyring, *key;
325 	key_ref_t key_ref;
326 	long err;
327 	int sp, nkeys, kix;
328 
329 	keyring = key_ref_to_ptr(keyring_ref);
330 	ctx->possessed = is_key_possessed(keyring_ref);
331 	key_check(keyring);
332 
333 	/* top keyring must have search permission to begin the search */
334 	err = key_task_permission(keyring_ref, ctx->cred, KEY_SEARCH);
335 	if (err < 0) {
336 		key_ref = ERR_PTR(err);
337 		goto error;
338 	}
339 
340 	key_ref = ERR_PTR(-ENOTDIR);
341 	if (keyring->type != &key_type_keyring)
342 		goto error;
343 
344 	rcu_read_lock();
345 
346 	ctx->now = current_kernel_time();
347 	err = -EAGAIN;
348 	sp = 0;
349 
350 	/* firstly we should check to see if this top-level keyring is what we
351 	 * are looking for */
352 	key_ref = ERR_PTR(-EAGAIN);
353 	kflags = keyring->flags;
354 	if (keyring->type == ctx->index_key.type &&
355 	    ctx->match(keyring, ctx->match_data)) {
356 		key = keyring;
357 		if (ctx->flags & KEYRING_SEARCH_NO_STATE_CHECK)
358 			goto found;
359 
360 		/* check it isn't negative and hasn't expired or been
361 		 * revoked */
362 		if (kflags & (1 << KEY_FLAG_REVOKED))
363 			goto error_2;
364 		if (key->expiry && ctx->now.tv_sec >= key->expiry)
365 			goto error_2;
366 		key_ref = ERR_PTR(key->type_data.reject_error);
367 		if (kflags & (1 << KEY_FLAG_NEGATIVE))
368 			goto error_2;
369 		goto found;
370 	}
371 
372 	/* otherwise, the top keyring must not be revoked, expired, or
373 	 * negatively instantiated if we are to search it */
374 	key_ref = ERR_PTR(-EAGAIN);
375 	if (kflags & ((1 << KEY_FLAG_INVALIDATED) |
376 		      (1 << KEY_FLAG_REVOKED) |
377 		      (1 << KEY_FLAG_NEGATIVE)) ||
378 	    (keyring->expiry && ctx->now.tv_sec >= keyring->expiry))
379 		goto error_2;
380 
381 	/* start processing a new keyring */
382 descend:
383 	kflags = keyring->flags;
384 	if (kflags & ((1 << KEY_FLAG_INVALIDATED) |
385 		      (1 << KEY_FLAG_REVOKED)))
386 		goto not_this_keyring;
387 
388 	keylist = rcu_dereference(keyring->payload.subscriptions);
389 	if (!keylist)
390 		goto not_this_keyring;
391 
392 	/* iterate through the keys in this keyring first */
393 	nkeys = keylist->nkeys;
394 	smp_rmb();
395 	for (kix = 0; kix < nkeys; kix++) {
396 		key = rcu_dereference(keylist->keys[kix]);
397 		kflags = key->flags;
398 
399 		/* ignore keys not of this type */
400 		if (key->type != ctx->index_key.type)
401 			continue;
402 
403 		/* skip invalidated, revoked and expired keys */
404 		if (!(ctx->flags & KEYRING_SEARCH_NO_STATE_CHECK)) {
405 			if (kflags & ((1 << KEY_FLAG_INVALIDATED) |
406 				      (1 << KEY_FLAG_REVOKED)))
407 				continue;
408 
409 			if (key->expiry && ctx->now.tv_sec >= key->expiry)
410 				continue;
411 		}
412 
413 		/* keys that don't match */
414 		if (!ctx->match(key, ctx->match_data))
415 			continue;
416 
417 		/* key must have search permissions */
418 		if (key_task_permission(make_key_ref(key, ctx->possessed),
419 					ctx->cred, KEY_SEARCH) < 0)
420 			continue;
421 
422 		if (ctx->flags & KEYRING_SEARCH_NO_STATE_CHECK)
423 			goto found;
424 
425 		/* we set a different error code if we pass a negative key */
426 		if (kflags & (1 << KEY_FLAG_NEGATIVE)) {
427 			err = key->type_data.reject_error;
428 			continue;
429 		}
430 
431 		goto found;
432 	}
433 
434 	/* search through the keyrings nested in this one */
435 	kix = 0;
436 ascend:
437 	nkeys = keylist->nkeys;
438 	smp_rmb();
439 	for (; kix < nkeys; kix++) {
440 		key = rcu_dereference(keylist->keys[kix]);
441 		if (key->type != &key_type_keyring)
442 			continue;
443 
444 		/* recursively search nested keyrings
445 		 * - only search keyrings for which we have search permission
446 		 */
447 		if (sp >= KEYRING_SEARCH_MAX_DEPTH)
448 			continue;
449 
450 		if (key_task_permission(make_key_ref(key, ctx->possessed),
451 					ctx->cred, KEY_SEARCH) < 0)
452 			continue;
453 
454 		/* stack the current position */
455 		stack[sp].keyring = keyring;
456 		stack[sp].keylist = keylist;
457 		stack[sp].kix = kix;
458 		sp++;
459 
460 		/* begin again with the new keyring */
461 		keyring = key;
462 		goto descend;
463 	}
464 
465 	/* the keyring we're looking at was disqualified or didn't contain a
466 	 * matching key */
467 not_this_keyring:
468 	if (sp > 0) {
469 		/* resume the processing of a keyring higher up in the tree */
470 		sp--;
471 		keyring = stack[sp].keyring;
472 		keylist = stack[sp].keylist;
473 		kix = stack[sp].kix + 1;
474 		goto ascend;
475 	}
476 
477 	key_ref = ERR_PTR(err);
478 	goto error_2;
479 
480 	/* we found a viable match */
481 found:
482 	__key_get(key);
483 	key->last_used_at = ctx->now.tv_sec;
484 	keyring->last_used_at = ctx->now.tv_sec;
485 	while (sp > 0)
486 		stack[--sp].keyring->last_used_at = ctx->now.tv_sec;
487 	key_check(key);
488 	key_ref = make_key_ref(key, ctx->possessed);
489 error_2:
490 	rcu_read_unlock();
491 error:
492 	return key_ref;
493 }
494 
495 /**
496  * keyring_search - Search the supplied keyring tree for a matching key
497  * @keyring: The root of the keyring tree to be searched.
498  * @type: The type of keyring we want to find.
499  * @description: The name of the keyring we want to find.
500  *
501  * As keyring_search_aux() above, but using the current task's credentials and
502  * type's default matching function.
503  */
504 key_ref_t keyring_search(key_ref_t keyring,
505 			 struct key_type *type,
506 			 const char *description)
507 {
508 	struct keyring_search_context ctx = {
509 		.index_key.type		= type,
510 		.index_key.description	= description,
511 		.cred			= current_cred(),
512 		.match			= type->match,
513 		.match_data		= description,
514 		.flags			= (type->def_lookup_type |
515 					   KEYRING_SEARCH_DO_STATE_CHECK),
516 	};
517 
518 	if (!ctx.match)
519 		return ERR_PTR(-ENOKEY);
520 
521 	return keyring_search_aux(keyring, &ctx);
522 }
523 EXPORT_SYMBOL(keyring_search);
524 
525 /*
526  * Search the given keyring only (no recursion).
527  *
528  * The caller must guarantee that the keyring is a keyring and that the
529  * permission is granted to search the keyring as no check is made here.
530  *
531  * RCU is used to make it unnecessary to lock the keyring key list here.
532  *
533  * Returns a pointer to the found key with usage count incremented if
534  * successful and returns -ENOKEY if not found.  Revoked and invalidated keys
535  * are skipped over.
536  *
537  * If successful, the possession indicator is propagated from the keyring ref
538  * to the returned key reference.
539  */
540 key_ref_t __keyring_search_one(key_ref_t keyring_ref,
541 			       const struct keyring_index_key *index_key)
542 {
543 	struct keyring_list *klist;
544 	struct key *keyring, *key;
545 	bool possessed;
546 	int nkeys, loop;
547 
548 	keyring = key_ref_to_ptr(keyring_ref);
549 	possessed = is_key_possessed(keyring_ref);
550 
551 	rcu_read_lock();
552 
553 	klist = rcu_dereference(keyring->payload.subscriptions);
554 	if (klist) {
555 		nkeys = klist->nkeys;
556 		smp_rmb();
557 		for (loop = 0; loop < nkeys ; loop++) {
558 			key = rcu_dereference(klist->keys[loop]);
559 			if (key->type == index_key->type &&
560 			    (!key->type->match ||
561 			     key->type->match(key, index_key->description)) &&
562 			    !(key->flags & ((1 << KEY_FLAG_INVALIDATED) |
563 					    (1 << KEY_FLAG_REVOKED)))
564 			    )
565 				goto found;
566 		}
567 	}
568 
569 	rcu_read_unlock();
570 	return ERR_PTR(-ENOKEY);
571 
572 found:
573 	__key_get(key);
574 	keyring->last_used_at = key->last_used_at =
575 		current_kernel_time().tv_sec;
576 	rcu_read_unlock();
577 	return make_key_ref(key, possessed);
578 }
579 
580 /*
581  * Find a keyring with the specified name.
582  *
583  * All named keyrings in the current user namespace are searched, provided they
584  * grant Search permission directly to the caller (unless this check is
585  * skipped).  Keyrings whose usage points have reached zero or who have been
586  * revoked are skipped.
587  *
588  * Returns a pointer to the keyring with the keyring's refcount having being
589  * incremented on success.  -ENOKEY is returned if a key could not be found.
590  */
591 struct key *find_keyring_by_name(const char *name, bool skip_perm_check)
592 {
593 	struct key *keyring;
594 	int bucket;
595 
596 	if (!name)
597 		return ERR_PTR(-EINVAL);
598 
599 	bucket = keyring_hash(name);
600 
601 	read_lock(&keyring_name_lock);
602 
603 	if (keyring_name_hash[bucket].next) {
604 		/* search this hash bucket for a keyring with a matching name
605 		 * that's readable and that hasn't been revoked */
606 		list_for_each_entry(keyring,
607 				    &keyring_name_hash[bucket],
608 				    type_data.link
609 				    ) {
610 			if (!kuid_has_mapping(current_user_ns(), keyring->user->uid))
611 				continue;
612 
613 			if (test_bit(KEY_FLAG_REVOKED, &keyring->flags))
614 				continue;
615 
616 			if (strcmp(keyring->description, name) != 0)
617 				continue;
618 
619 			if (!skip_perm_check &&
620 			    key_permission(make_key_ref(keyring, 0),
621 					   KEY_SEARCH) < 0)
622 				continue;
623 
624 			/* we've got a match but we might end up racing with
625 			 * key_cleanup() if the keyring is currently 'dead'
626 			 * (ie. it has a zero usage count) */
627 			if (!atomic_inc_not_zero(&keyring->usage))
628 				continue;
629 			keyring->last_used_at = current_kernel_time().tv_sec;
630 			goto out;
631 		}
632 	}
633 
634 	keyring = ERR_PTR(-ENOKEY);
635 out:
636 	read_unlock(&keyring_name_lock);
637 	return keyring;
638 }
639 
640 /*
641  * See if a cycle will will be created by inserting acyclic tree B in acyclic
642  * tree A at the topmost level (ie: as a direct child of A).
643  *
644  * Since we are adding B to A at the top level, checking for cycles should just
645  * be a matter of seeing if node A is somewhere in tree B.
646  */
647 static int keyring_detect_cycle(struct key *A, struct key *B)
648 {
649 	struct {
650 		struct keyring_list *keylist;
651 		int kix;
652 	} stack[KEYRING_SEARCH_MAX_DEPTH];
653 
654 	struct keyring_list *keylist;
655 	struct key *subtree, *key;
656 	int sp, nkeys, kix, ret;
657 
658 	rcu_read_lock();
659 
660 	ret = -EDEADLK;
661 	if (A == B)
662 		goto cycle_detected;
663 
664 	subtree = B;
665 	sp = 0;
666 
667 	/* start processing a new keyring */
668 descend:
669 	if (test_bit(KEY_FLAG_REVOKED, &subtree->flags))
670 		goto not_this_keyring;
671 
672 	keylist = rcu_dereference(subtree->payload.subscriptions);
673 	if (!keylist)
674 		goto not_this_keyring;
675 	kix = 0;
676 
677 ascend:
678 	/* iterate through the remaining keys in this keyring */
679 	nkeys = keylist->nkeys;
680 	smp_rmb();
681 	for (; kix < nkeys; kix++) {
682 		key = rcu_dereference(keylist->keys[kix]);
683 
684 		if (key == A)
685 			goto cycle_detected;
686 
687 		/* recursively check nested keyrings */
688 		if (key->type == &key_type_keyring) {
689 			if (sp >= KEYRING_SEARCH_MAX_DEPTH)
690 				goto too_deep;
691 
692 			/* stack the current position */
693 			stack[sp].keylist = keylist;
694 			stack[sp].kix = kix;
695 			sp++;
696 
697 			/* begin again with the new keyring */
698 			subtree = key;
699 			goto descend;
700 		}
701 	}
702 
703 	/* the keyring we're looking at was disqualified or didn't contain a
704 	 * matching key */
705 not_this_keyring:
706 	if (sp > 0) {
707 		/* resume the checking of a keyring higher up in the tree */
708 		sp--;
709 		keylist = stack[sp].keylist;
710 		kix = stack[sp].kix + 1;
711 		goto ascend;
712 	}
713 
714 	ret = 0; /* no cycles detected */
715 
716 error:
717 	rcu_read_unlock();
718 	return ret;
719 
720 too_deep:
721 	ret = -ELOOP;
722 	goto error;
723 
724 cycle_detected:
725 	ret = -EDEADLK;
726 	goto error;
727 }
728 
729 /*
730  * Dispose of a keyring list after the RCU grace period, freeing the unlinked
731  * key
732  */
733 static void keyring_unlink_rcu_disposal(struct rcu_head *rcu)
734 {
735 	struct keyring_list *klist =
736 		container_of(rcu, struct keyring_list, rcu);
737 
738 	if (klist->delkey != USHRT_MAX)
739 		key_put(rcu_access_pointer(klist->keys[klist->delkey]));
740 	kfree(klist);
741 }
742 
743 /*
744  * Preallocate memory so that a key can be linked into to a keyring.
745  */
746 int __key_link_begin(struct key *keyring, const struct keyring_index_key *index_key,
747 		     unsigned long *_prealloc)
748 	__acquires(&keyring->sem)
749 	__acquires(&keyring_serialise_link_sem)
750 {
751 	struct keyring_list *klist, *nklist;
752 	unsigned long prealloc;
753 	unsigned max;
754 	time_t lowest_lru;
755 	size_t size;
756 	int loop, lru, ret;
757 
758 	kenter("%d,%s,%s,",
759 	       key_serial(keyring), index_key->type->name, index_key->description);
760 
761 	if (keyring->type != &key_type_keyring)
762 		return -ENOTDIR;
763 
764 	down_write(&keyring->sem);
765 
766 	ret = -EKEYREVOKED;
767 	if (test_bit(KEY_FLAG_REVOKED, &keyring->flags))
768 		goto error_krsem;
769 
770 	/* serialise link/link calls to prevent parallel calls causing a cycle
771 	 * when linking two keyring in opposite orders */
772 	if (index_key->type == &key_type_keyring)
773 		down_write(&keyring_serialise_link_sem);
774 
775 	klist = rcu_dereference_locked_keyring(keyring);
776 
777 	/* see if there's a matching key we can displace */
778 	lru = -1;
779 	if (klist && klist->nkeys > 0) {
780 		lowest_lru = TIME_T_MAX;
781 		for (loop = klist->nkeys - 1; loop >= 0; loop--) {
782 			struct key *key = rcu_deref_link_locked(klist, loop,
783 								keyring);
784 			if (key->type == index_key->type &&
785 			    strcmp(key->description, index_key->description) == 0) {
786 				/* Found a match - we'll replace the link with
787 				 * one to the new key.  We record the slot
788 				 * position.
789 				 */
790 				klist->delkey = loop;
791 				prealloc = 0;
792 				goto done;
793 			}
794 			if (key->last_used_at < lowest_lru) {
795 				lowest_lru = key->last_used_at;
796 				lru = loop;
797 			}
798 		}
799 	}
800 
801 	/* If the keyring is full then do an LRU discard */
802 	if (klist &&
803 	    klist->nkeys == klist->maxkeys &&
804 	    klist->maxkeys >= MAX_KEYRING_LINKS) {
805 		kdebug("LRU discard %d\n", lru);
806 		klist->delkey = lru;
807 		prealloc = 0;
808 		goto done;
809 	}
810 
811 	/* check that we aren't going to overrun the user's quota */
812 	ret = key_payload_reserve(keyring,
813 				  keyring->datalen + KEYQUOTA_LINK_BYTES);
814 	if (ret < 0)
815 		goto error_sem;
816 
817 	if (klist && klist->nkeys < klist->maxkeys) {
818 		/* there's sufficient slack space to append directly */
819 		klist->delkey = klist->nkeys;
820 		prealloc = KEY_LINK_FIXQUOTA;
821 	} else {
822 		/* grow the key list */
823 		max = 4;
824 		if (klist) {
825 			max += klist->maxkeys;
826 			if (max > MAX_KEYRING_LINKS)
827 				max = MAX_KEYRING_LINKS;
828 			BUG_ON(max <= klist->maxkeys);
829 		}
830 
831 		size = sizeof(*klist) + sizeof(struct key *) * max;
832 
833 		ret = -ENOMEM;
834 		nklist = kmalloc(size, GFP_KERNEL);
835 		if (!nklist)
836 			goto error_quota;
837 
838 		nklist->maxkeys = max;
839 		if (klist) {
840 			memcpy(nklist->keys, klist->keys,
841 			       sizeof(struct key *) * klist->nkeys);
842 			nklist->delkey = klist->nkeys;
843 			nklist->nkeys = klist->nkeys + 1;
844 			klist->delkey = USHRT_MAX;
845 		} else {
846 			nklist->nkeys = 1;
847 			nklist->delkey = 0;
848 		}
849 
850 		/* add the key into the new space */
851 		RCU_INIT_POINTER(nklist->keys[nklist->delkey], NULL);
852 		prealloc = (unsigned long)nklist | KEY_LINK_FIXQUOTA;
853 	}
854 
855 done:
856 	*_prealloc = prealloc;
857 	kleave(" = 0");
858 	return 0;
859 
860 error_quota:
861 	/* undo the quota changes */
862 	key_payload_reserve(keyring,
863 			    keyring->datalen - KEYQUOTA_LINK_BYTES);
864 error_sem:
865 	if (index_key->type == &key_type_keyring)
866 		up_write(&keyring_serialise_link_sem);
867 error_krsem:
868 	up_write(&keyring->sem);
869 	kleave(" = %d", ret);
870 	return ret;
871 }
872 
873 /*
874  * Check already instantiated keys aren't going to be a problem.
875  *
876  * The caller must have called __key_link_begin(). Don't need to call this for
877  * keys that were created since __key_link_begin() was called.
878  */
879 int __key_link_check_live_key(struct key *keyring, struct key *key)
880 {
881 	if (key->type == &key_type_keyring)
882 		/* check that we aren't going to create a cycle by linking one
883 		 * keyring to another */
884 		return keyring_detect_cycle(keyring, key);
885 	return 0;
886 }
887 
888 /*
889  * Link a key into to a keyring.
890  *
891  * Must be called with __key_link_begin() having being called.  Discards any
892  * already extant link to matching key if there is one, so that each keyring
893  * holds at most one link to any given key of a particular type+description
894  * combination.
895  */
896 void __key_link(struct key *keyring, struct key *key,
897 		unsigned long *_prealloc)
898 {
899 	struct keyring_list *klist, *nklist;
900 	struct key *discard;
901 
902 	nklist = (struct keyring_list *)(*_prealloc & ~KEY_LINK_FIXQUOTA);
903 	*_prealloc = 0;
904 
905 	kenter("%d,%d,%p", keyring->serial, key->serial, nklist);
906 
907 	klist = rcu_dereference_locked_keyring(keyring);
908 
909 	__key_get(key);
910 	keyring->last_used_at = key->last_used_at =
911 		current_kernel_time().tv_sec;
912 
913 	/* there's a matching key we can displace or an empty slot in a newly
914 	 * allocated list we can fill */
915 	if (nklist) {
916 		kdebug("reissue %hu/%hu/%hu",
917 		       nklist->delkey, nklist->nkeys, nklist->maxkeys);
918 
919 		RCU_INIT_POINTER(nklist->keys[nklist->delkey], key);
920 
921 		rcu_assign_pointer(keyring->payload.subscriptions, nklist);
922 
923 		/* dispose of the old keyring list and, if there was one, the
924 		 * displaced key */
925 		if (klist) {
926 			kdebug("dispose %hu/%hu/%hu",
927 			       klist->delkey, klist->nkeys, klist->maxkeys);
928 			call_rcu(&klist->rcu, keyring_unlink_rcu_disposal);
929 		}
930 	} else if (klist->delkey < klist->nkeys) {
931 		kdebug("replace %hu/%hu/%hu",
932 		       klist->delkey, klist->nkeys, klist->maxkeys);
933 
934 		discard = rcu_dereference_protected(
935 			klist->keys[klist->delkey],
936 			rwsem_is_locked(&keyring->sem));
937 		rcu_assign_pointer(klist->keys[klist->delkey], key);
938 		/* The garbage collector will take care of RCU
939 		 * synchronisation */
940 		key_put(discard);
941 	} else {
942 		/* there's sufficient slack space to append directly */
943 		kdebug("append %hu/%hu/%hu",
944 		       klist->delkey, klist->nkeys, klist->maxkeys);
945 
946 		RCU_INIT_POINTER(klist->keys[klist->delkey], key);
947 		smp_wmb();
948 		klist->nkeys++;
949 	}
950 }
951 
952 /*
953  * Finish linking a key into to a keyring.
954  *
955  * Must be called with __key_link_begin() having being called.
956  */
957 void __key_link_end(struct key *keyring,
958 		    const struct keyring_index_key *index_key,
959 		    unsigned long prealloc)
960 	__releases(&keyring->sem)
961 	__releases(&keyring_serialise_link_sem)
962 {
963 	BUG_ON(index_key->type == NULL);
964 	BUG_ON(index_key->type->name == NULL);
965 	kenter("%d,%s,%lx", keyring->serial, index_key->type->name, prealloc);
966 
967 	if (index_key->type == &key_type_keyring)
968 		up_write(&keyring_serialise_link_sem);
969 
970 	if (prealloc) {
971 		if (prealloc & KEY_LINK_FIXQUOTA)
972 			key_payload_reserve(keyring,
973 					    keyring->datalen -
974 					    KEYQUOTA_LINK_BYTES);
975 		kfree((struct keyring_list *)(prealloc & ~KEY_LINK_FIXQUOTA));
976 	}
977 	up_write(&keyring->sem);
978 }
979 
980 /**
981  * key_link - Link a key to a keyring
982  * @keyring: The keyring to make the link in.
983  * @key: The key to link to.
984  *
985  * Make a link in a keyring to a key, such that the keyring holds a reference
986  * on that key and the key can potentially be found by searching that keyring.
987  *
988  * This function will write-lock the keyring's semaphore and will consume some
989  * of the user's key data quota to hold the link.
990  *
991  * Returns 0 if successful, -ENOTDIR if the keyring isn't a keyring,
992  * -EKEYREVOKED if the keyring has been revoked, -ENFILE if the keyring is
993  * full, -EDQUOT if there is insufficient key data quota remaining to add
994  * another link or -ENOMEM if there's insufficient memory.
995  *
996  * It is assumed that the caller has checked that it is permitted for a link to
997  * be made (the keyring should have Write permission and the key Link
998  * permission).
999  */
1000 int key_link(struct key *keyring, struct key *key)
1001 {
1002 	unsigned long prealloc;
1003 	int ret;
1004 
1005 	key_check(keyring);
1006 	key_check(key);
1007 
1008 	ret = __key_link_begin(keyring, &key->index_key, &prealloc);
1009 	if (ret == 0) {
1010 		ret = __key_link_check_live_key(keyring, key);
1011 		if (ret == 0)
1012 			__key_link(keyring, key, &prealloc);
1013 		__key_link_end(keyring, &key->index_key, prealloc);
1014 	}
1015 
1016 	return ret;
1017 }
1018 EXPORT_SYMBOL(key_link);
1019 
1020 /**
1021  * key_unlink - Unlink the first link to a key from a keyring.
1022  * @keyring: The keyring to remove the link from.
1023  * @key: The key the link is to.
1024  *
1025  * Remove a link from a keyring to a key.
1026  *
1027  * This function will write-lock the keyring's semaphore.
1028  *
1029  * Returns 0 if successful, -ENOTDIR if the keyring isn't a keyring, -ENOENT if
1030  * the key isn't linked to by the keyring or -ENOMEM if there's insufficient
1031  * memory.
1032  *
1033  * It is assumed that the caller has checked that it is permitted for a link to
1034  * be removed (the keyring should have Write permission; no permissions are
1035  * required on the key).
1036  */
1037 int key_unlink(struct key *keyring, struct key *key)
1038 {
1039 	struct keyring_list *klist, *nklist;
1040 	int loop, ret;
1041 
1042 	key_check(keyring);
1043 	key_check(key);
1044 
1045 	ret = -ENOTDIR;
1046 	if (keyring->type != &key_type_keyring)
1047 		goto error;
1048 
1049 	down_write(&keyring->sem);
1050 
1051 	klist = rcu_dereference_locked_keyring(keyring);
1052 	if (klist) {
1053 		/* search the keyring for the key */
1054 		for (loop = 0; loop < klist->nkeys; loop++)
1055 			if (rcu_access_pointer(klist->keys[loop]) == key)
1056 				goto key_is_present;
1057 	}
1058 
1059 	up_write(&keyring->sem);
1060 	ret = -ENOENT;
1061 	goto error;
1062 
1063 key_is_present:
1064 	/* we need to copy the key list for RCU purposes */
1065 	nklist = kmalloc(sizeof(*klist) +
1066 			 sizeof(struct key *) * klist->maxkeys,
1067 			 GFP_KERNEL);
1068 	if (!nklist)
1069 		goto nomem;
1070 	nklist->maxkeys = klist->maxkeys;
1071 	nklist->nkeys = klist->nkeys - 1;
1072 
1073 	if (loop > 0)
1074 		memcpy(&nklist->keys[0],
1075 		       &klist->keys[0],
1076 		       loop * sizeof(struct key *));
1077 
1078 	if (loop < nklist->nkeys)
1079 		memcpy(&nklist->keys[loop],
1080 		       &klist->keys[loop + 1],
1081 		       (nklist->nkeys - loop) * sizeof(struct key *));
1082 
1083 	/* adjust the user's quota */
1084 	key_payload_reserve(keyring,
1085 			    keyring->datalen - KEYQUOTA_LINK_BYTES);
1086 
1087 	rcu_assign_pointer(keyring->payload.subscriptions, nklist);
1088 
1089 	up_write(&keyring->sem);
1090 
1091 	/* schedule for later cleanup */
1092 	klist->delkey = loop;
1093 	call_rcu(&klist->rcu, keyring_unlink_rcu_disposal);
1094 
1095 	ret = 0;
1096 
1097 error:
1098 	return ret;
1099 nomem:
1100 	ret = -ENOMEM;
1101 	up_write(&keyring->sem);
1102 	goto error;
1103 }
1104 EXPORT_SYMBOL(key_unlink);
1105 
1106 /*
1107  * Dispose of a keyring list after the RCU grace period, releasing the keys it
1108  * links to.
1109  */
1110 static void keyring_clear_rcu_disposal(struct rcu_head *rcu)
1111 {
1112 	struct keyring_list *klist;
1113 	int loop;
1114 
1115 	klist = container_of(rcu, struct keyring_list, rcu);
1116 
1117 	for (loop = klist->nkeys - 1; loop >= 0; loop--)
1118 		key_put(rcu_access_pointer(klist->keys[loop]));
1119 
1120 	kfree(klist);
1121 }
1122 
1123 /**
1124  * keyring_clear - Clear a keyring
1125  * @keyring: The keyring to clear.
1126  *
1127  * Clear the contents of the specified keyring.
1128  *
1129  * Returns 0 if successful or -ENOTDIR if the keyring isn't a keyring.
1130  */
1131 int keyring_clear(struct key *keyring)
1132 {
1133 	struct keyring_list *klist;
1134 	int ret;
1135 
1136 	ret = -ENOTDIR;
1137 	if (keyring->type == &key_type_keyring) {
1138 		/* detach the pointer block with the locks held */
1139 		down_write(&keyring->sem);
1140 
1141 		klist = rcu_dereference_locked_keyring(keyring);
1142 		if (klist) {
1143 			/* adjust the quota */
1144 			key_payload_reserve(keyring,
1145 					    sizeof(struct keyring_list));
1146 
1147 			rcu_assign_pointer(keyring->payload.subscriptions,
1148 					   NULL);
1149 		}
1150 
1151 		up_write(&keyring->sem);
1152 
1153 		/* free the keys after the locks have been dropped */
1154 		if (klist)
1155 			call_rcu(&klist->rcu, keyring_clear_rcu_disposal);
1156 
1157 		ret = 0;
1158 	}
1159 
1160 	return ret;
1161 }
1162 EXPORT_SYMBOL(keyring_clear);
1163 
1164 /*
1165  * Dispose of the links from a revoked keyring.
1166  *
1167  * This is called with the key sem write-locked.
1168  */
1169 static void keyring_revoke(struct key *keyring)
1170 {
1171 	struct keyring_list *klist;
1172 
1173 	klist = rcu_dereference_locked_keyring(keyring);
1174 
1175 	/* adjust the quota */
1176 	key_payload_reserve(keyring, 0);
1177 
1178 	if (klist) {
1179 		rcu_assign_pointer(keyring->payload.subscriptions, NULL);
1180 		call_rcu(&klist->rcu, keyring_clear_rcu_disposal);
1181 	}
1182 }
1183 
1184 /*
1185  * Collect garbage from the contents of a keyring, replacing the old list with
1186  * a new one with the pointers all shuffled down.
1187  *
1188  * Dead keys are classed as oned that are flagged as being dead or are revoked,
1189  * expired or negative keys that were revoked or expired before the specified
1190  * limit.
1191  */
1192 void keyring_gc(struct key *keyring, time_t limit)
1193 {
1194 	struct keyring_list *klist, *new;
1195 	struct key *key;
1196 	int loop, keep, max;
1197 
1198 	kenter("{%x,%s}", key_serial(keyring), keyring->description);
1199 
1200 	down_write(&keyring->sem);
1201 
1202 	klist = rcu_dereference_locked_keyring(keyring);
1203 	if (!klist)
1204 		goto no_klist;
1205 
1206 	/* work out how many subscriptions we're keeping */
1207 	keep = 0;
1208 	for (loop = klist->nkeys - 1; loop >= 0; loop--)
1209 		if (!key_is_dead(rcu_deref_link_locked(klist, loop, keyring),
1210 				 limit))
1211 			keep++;
1212 
1213 	if (keep == klist->nkeys)
1214 		goto just_return;
1215 
1216 	/* allocate a new keyring payload */
1217 	max = roundup(keep, 4);
1218 	new = kmalloc(sizeof(struct keyring_list) + max * sizeof(struct key *),
1219 		      GFP_KERNEL);
1220 	if (!new)
1221 		goto nomem;
1222 	new->maxkeys = max;
1223 	new->nkeys = 0;
1224 	new->delkey = 0;
1225 
1226 	/* install the live keys
1227 	 * - must take care as expired keys may be updated back to life
1228 	 */
1229 	keep = 0;
1230 	for (loop = klist->nkeys - 1; loop >= 0; loop--) {
1231 		key = rcu_deref_link_locked(klist, loop, keyring);
1232 		if (!key_is_dead(key, limit)) {
1233 			if (keep >= max)
1234 				goto discard_new;
1235 			RCU_INIT_POINTER(new->keys[keep++], key_get(key));
1236 		}
1237 	}
1238 	new->nkeys = keep;
1239 
1240 	/* adjust the quota */
1241 	key_payload_reserve(keyring,
1242 			    sizeof(struct keyring_list) +
1243 			    KEYQUOTA_LINK_BYTES * keep);
1244 
1245 	if (keep == 0) {
1246 		rcu_assign_pointer(keyring->payload.subscriptions, NULL);
1247 		kfree(new);
1248 	} else {
1249 		rcu_assign_pointer(keyring->payload.subscriptions, new);
1250 	}
1251 
1252 	up_write(&keyring->sem);
1253 
1254 	call_rcu(&klist->rcu, keyring_clear_rcu_disposal);
1255 	kleave(" [yes]");
1256 	return;
1257 
1258 discard_new:
1259 	new->nkeys = keep;
1260 	keyring_clear_rcu_disposal(&new->rcu);
1261 	up_write(&keyring->sem);
1262 	kleave(" [discard]");
1263 	return;
1264 
1265 just_return:
1266 	up_write(&keyring->sem);
1267 	kleave(" [no dead]");
1268 	return;
1269 
1270 no_klist:
1271 	up_write(&keyring->sem);
1272 	kleave(" [no_klist]");
1273 	return;
1274 
1275 nomem:
1276 	up_write(&keyring->sem);
1277 	kleave(" [oom]");
1278 }
1279