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