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