xref: /linux/security/keys/key.c (revision 858259cf7d1c443c836a2022b78cb281f0a9b95e)
1 /* key.c: basic authentication token and access key management
2  *
3  * Copyright (C) 2004 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/workqueue.h>
18 #include <linux/err.h>
19 #include "internal.h"
20 
21 static kmem_cache_t	*key_jar;
22 static key_serial_t	key_serial_next = 3;
23 struct rb_root		key_serial_tree; /* tree of keys indexed by serial */
24 DEFINE_SPINLOCK(key_serial_lock);
25 
26 struct rb_root	key_user_tree; /* tree of quota records indexed by UID */
27 DEFINE_SPINLOCK(key_user_lock);
28 
29 static LIST_HEAD(key_types_list);
30 static DECLARE_RWSEM(key_types_sem);
31 
32 static void key_cleanup(void *data);
33 static DECLARE_WORK(key_cleanup_task, key_cleanup, NULL);
34 
35 /* we serialise key instantiation and link */
36 DECLARE_RWSEM(key_construction_sem);
37 
38 /* any key who's type gets unegistered will be re-typed to this */
39 struct key_type key_type_dead = {
40 	.name		= "dead",
41 };
42 
43 #ifdef KEY_DEBUGGING
44 void __key_check(const struct key *key)
45 {
46 	printk("__key_check: key %p {%08x} should be {%08x}\n",
47 	       key, key->magic, KEY_DEBUG_MAGIC);
48 	BUG();
49 }
50 #endif
51 
52 /*****************************************************************************/
53 /*
54  * get the key quota record for a user, allocating a new record if one doesn't
55  * already exist
56  */
57 struct key_user *key_user_lookup(uid_t uid)
58 {
59 	struct key_user *candidate = NULL, *user;
60 	struct rb_node *parent = NULL;
61 	struct rb_node **p;
62 
63  try_again:
64 	p = &key_user_tree.rb_node;
65 	spin_lock(&key_user_lock);
66 
67 	/* search the tree for a user record with a matching UID */
68 	while (*p) {
69 		parent = *p;
70 		user = rb_entry(parent, struct key_user, node);
71 
72 		if (uid < user->uid)
73 			p = &(*p)->rb_left;
74 		else if (uid > user->uid)
75 			p = &(*p)->rb_right;
76 		else
77 			goto found;
78 	}
79 
80 	/* if we get here, we failed to find a match in the tree */
81 	if (!candidate) {
82 		/* allocate a candidate user record if we don't already have
83 		 * one */
84 		spin_unlock(&key_user_lock);
85 
86 		user = NULL;
87 		candidate = kmalloc(sizeof(struct key_user), GFP_KERNEL);
88 		if (unlikely(!candidate))
89 			goto out;
90 
91 		/* the allocation may have scheduled, so we need to repeat the
92 		 * search lest someone else added the record whilst we were
93 		 * asleep */
94 		goto try_again;
95 	}
96 
97 	/* if we get here, then the user record still hadn't appeared on the
98 	 * second pass - so we use the candidate record */
99 	atomic_set(&candidate->usage, 1);
100 	atomic_set(&candidate->nkeys, 0);
101 	atomic_set(&candidate->nikeys, 0);
102 	candidate->uid = uid;
103 	candidate->qnkeys = 0;
104 	candidate->qnbytes = 0;
105 	spin_lock_init(&candidate->lock);
106 	INIT_LIST_HEAD(&candidate->consq);
107 
108 	rb_link_node(&candidate->node, parent, p);
109 	rb_insert_color(&candidate->node, &key_user_tree);
110 	spin_unlock(&key_user_lock);
111 	user = candidate;
112 	goto out;
113 
114 	/* okay - we found a user record for this UID */
115  found:
116 	atomic_inc(&user->usage);
117 	spin_unlock(&key_user_lock);
118 	if (candidate)
119 		kfree(candidate);
120  out:
121 	return user;
122 
123 } /* end key_user_lookup() */
124 
125 /*****************************************************************************/
126 /*
127  * dispose of a user structure
128  */
129 void key_user_put(struct key_user *user)
130 {
131 	if (atomic_dec_and_lock(&user->usage, &key_user_lock)) {
132 		rb_erase(&user->node, &key_user_tree);
133 		spin_unlock(&key_user_lock);
134 
135 		kfree(user);
136 	}
137 
138 } /* end key_user_put() */
139 
140 /*****************************************************************************/
141 /*
142  * insert a key with a fixed serial number
143  */
144 static void __init __key_insert_serial(struct key *key)
145 {
146 	struct rb_node *parent, **p;
147 	struct key *xkey;
148 
149 	parent = NULL;
150 	p = &key_serial_tree.rb_node;
151 
152 	while (*p) {
153 		parent = *p;
154 		xkey = rb_entry(parent, struct key, serial_node);
155 
156 		if (key->serial < xkey->serial)
157 			p = &(*p)->rb_left;
158 		else if (key->serial > xkey->serial)
159 			p = &(*p)->rb_right;
160 		else
161 			BUG();
162 	}
163 
164 	/* we've found a suitable hole - arrange for this key to occupy it */
165 	rb_link_node(&key->serial_node, parent, p);
166 	rb_insert_color(&key->serial_node, &key_serial_tree);
167 
168 } /* end __key_insert_serial() */
169 
170 /*****************************************************************************/
171 /*
172  * assign a key the next unique serial number
173  * - we work through all the serial numbers between 2 and 2^31-1 in turn and
174  *   then wrap
175  */
176 static inline void key_alloc_serial(struct key *key)
177 {
178 	struct rb_node *parent, **p;
179 	struct key *xkey;
180 
181 	spin_lock(&key_serial_lock);
182 
183 	/* propose a likely serial number and look for a hole for it in the
184 	 * serial number tree */
185 	key->serial = key_serial_next;
186 	if (key->serial < 3)
187 		key->serial = 3;
188 	key_serial_next = key->serial + 1;
189 
190 	parent = NULL;
191 	p = &key_serial_tree.rb_node;
192 
193 	while (*p) {
194 		parent = *p;
195 		xkey = rb_entry(parent, struct key, serial_node);
196 
197 		if (key->serial < xkey->serial)
198 			p = &(*p)->rb_left;
199 		else if (key->serial > xkey->serial)
200 			p = &(*p)->rb_right;
201 		else
202 			goto serial_exists;
203 	}
204 	goto insert_here;
205 
206 	/* we found a key with the proposed serial number - walk the tree from
207 	 * that point looking for the next unused serial number */
208  serial_exists:
209 	for (;;) {
210 		key->serial = key_serial_next;
211 		if (key->serial < 2)
212 			key->serial = 2;
213 		key_serial_next = key->serial + 1;
214 
215 		if (!parent->rb_parent)
216 			p = &key_serial_tree.rb_node;
217 		else if (parent->rb_parent->rb_left == parent)
218 			p = &parent->rb_parent->rb_left;
219 		else
220 			p = &parent->rb_parent->rb_right;
221 
222 		parent = rb_next(parent);
223 		if (!parent)
224 			break;
225 
226 		xkey = rb_entry(parent, struct key, serial_node);
227 		if (key->serial < xkey->serial)
228 			goto insert_here;
229 	}
230 
231 	/* we've found a suitable hole - arrange for this key to occupy it */
232  insert_here:
233 	rb_link_node(&key->serial_node, parent, p);
234 	rb_insert_color(&key->serial_node, &key_serial_tree);
235 
236 	spin_unlock(&key_serial_lock);
237 
238 } /* end key_alloc_serial() */
239 
240 /*****************************************************************************/
241 /*
242  * allocate a key of the specified type
243  * - update the user's quota to reflect the existence of the key
244  * - called from a key-type operation with key_types_sem read-locked by either
245  *   key_create_or_update() or by key_duplicate(); this prevents unregistration
246  *   of the key type
247  * - upon return the key is as yet uninstantiated; the caller needs to either
248  *   instantiate the key or discard it before returning
249  */
250 struct key *key_alloc(struct key_type *type, const char *desc,
251 		      uid_t uid, gid_t gid, key_perm_t perm,
252 		      int not_in_quota)
253 {
254 	struct key_user *user = NULL;
255 	struct key *key;
256 	size_t desclen, quotalen;
257 	int ret;
258 
259 	key = ERR_PTR(-EINVAL);
260 	if (!desc || !*desc)
261 		goto error;
262 
263 	desclen = strlen(desc) + 1;
264 	quotalen = desclen + type->def_datalen;
265 
266 	/* get hold of the key tracking for this user */
267 	user = key_user_lookup(uid);
268 	if (!user)
269 		goto no_memory_1;
270 
271 	/* check that the user's quota permits allocation of another key and
272 	 * its description */
273 	if (!not_in_quota) {
274 		spin_lock(&user->lock);
275 		if (user->qnkeys + 1 >= KEYQUOTA_MAX_KEYS &&
276 		    user->qnbytes + quotalen >= KEYQUOTA_MAX_BYTES
277 		    )
278 			goto no_quota;
279 
280 		user->qnkeys++;
281 		user->qnbytes += quotalen;
282 		spin_unlock(&user->lock);
283 	}
284 
285 	/* allocate and initialise the key and its description */
286 	key = kmem_cache_alloc(key_jar, SLAB_KERNEL);
287 	if (!key)
288 		goto no_memory_2;
289 
290 	if (desc) {
291 		key->description = kmalloc(desclen, GFP_KERNEL);
292 		if (!key->description)
293 			goto no_memory_3;
294 
295 		memcpy(key->description, desc, desclen);
296 	}
297 
298 	atomic_set(&key->usage, 1);
299 	init_rwsem(&key->sem);
300 	key->type = type;
301 	key->user = user;
302 	key->quotalen = quotalen;
303 	key->datalen = type->def_datalen;
304 	key->uid = uid;
305 	key->gid = gid;
306 	key->perm = perm;
307 	key->flags = 0;
308 	key->expiry = 0;
309 	key->payload.data = NULL;
310 	key->security = NULL;
311 
312 	if (!not_in_quota)
313 		key->flags |= 1 << KEY_FLAG_IN_QUOTA;
314 
315 	memset(&key->type_data, 0, sizeof(key->type_data));
316 
317 #ifdef KEY_DEBUGGING
318 	key->magic = KEY_DEBUG_MAGIC;
319 #endif
320 
321 	/* let the security module know about the key */
322 	ret = security_key_alloc(key);
323 	if (ret < 0)
324 		goto security_error;
325 
326 	/* publish the key by giving it a serial number */
327 	atomic_inc(&user->nkeys);
328 	key_alloc_serial(key);
329 
330 error:
331 	return key;
332 
333 security_error:
334 	kfree(key->description);
335 	kmem_cache_free(key_jar, key);
336 	if (!not_in_quota) {
337 		spin_lock(&user->lock);
338 		user->qnkeys--;
339 		user->qnbytes -= quotalen;
340 		spin_unlock(&user->lock);
341 	}
342 	key_user_put(user);
343 	key = ERR_PTR(ret);
344 	goto error;
345 
346 no_memory_3:
347 	kmem_cache_free(key_jar, key);
348 no_memory_2:
349 	if (!not_in_quota) {
350 		spin_lock(&user->lock);
351 		user->qnkeys--;
352 		user->qnbytes -= quotalen;
353 		spin_unlock(&user->lock);
354 	}
355 	key_user_put(user);
356 no_memory_1:
357 	key = ERR_PTR(-ENOMEM);
358 	goto error;
359 
360 no_quota:
361 	spin_unlock(&user->lock);
362 	key_user_put(user);
363 	key = ERR_PTR(-EDQUOT);
364 	goto error;
365 
366 } /* end key_alloc() */
367 
368 EXPORT_SYMBOL(key_alloc);
369 
370 /*****************************************************************************/
371 /*
372  * reserve an amount of quota for the key's payload
373  */
374 int key_payload_reserve(struct key *key, size_t datalen)
375 {
376 	int delta = (int) datalen - key->datalen;
377 	int ret = 0;
378 
379 	key_check(key);
380 
381 	/* contemplate the quota adjustment */
382 	if (delta != 0 && test_bit(KEY_FLAG_IN_QUOTA, &key->flags)) {
383 		spin_lock(&key->user->lock);
384 
385 		if (delta > 0 &&
386 		    key->user->qnbytes + delta > KEYQUOTA_MAX_BYTES
387 		    ) {
388 			ret = -EDQUOT;
389 		}
390 		else {
391 			key->user->qnbytes += delta;
392 			key->quotalen += delta;
393 		}
394 		spin_unlock(&key->user->lock);
395 	}
396 
397 	/* change the recorded data length if that didn't generate an error */
398 	if (ret == 0)
399 		key->datalen = datalen;
400 
401 	return ret;
402 
403 } /* end key_payload_reserve() */
404 
405 EXPORT_SYMBOL(key_payload_reserve);
406 
407 /*****************************************************************************/
408 /*
409  * instantiate a key and link it into the target keyring atomically
410  * - called with the target keyring's semaphore writelocked
411  */
412 static int __key_instantiate_and_link(struct key *key,
413 				      const void *data,
414 				      size_t datalen,
415 				      struct key *keyring,
416 				      struct key *instkey)
417 {
418 	int ret, awaken;
419 
420 	key_check(key);
421 	key_check(keyring);
422 
423 	awaken = 0;
424 	ret = -EBUSY;
425 
426 	down_write(&key_construction_sem);
427 
428 	/* can't instantiate twice */
429 	if (!test_bit(KEY_FLAG_INSTANTIATED, &key->flags)) {
430 		/* instantiate the key */
431 		ret = key->type->instantiate(key, data, datalen);
432 
433 		if (ret == 0) {
434 			/* mark the key as being instantiated */
435 			atomic_inc(&key->user->nikeys);
436 			set_bit(KEY_FLAG_INSTANTIATED, &key->flags);
437 
438 			if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags))
439 				awaken = 1;
440 
441 			/* and link it into the destination keyring */
442 			if (keyring)
443 				ret = __key_link(keyring, key);
444 
445 			/* disable the authorisation key */
446 			if (instkey)
447 				key_revoke(instkey);
448 		}
449 	}
450 
451 	up_write(&key_construction_sem);
452 
453 	/* wake up anyone waiting for a key to be constructed */
454 	if (awaken)
455 		wake_up_all(&request_key_conswq);
456 
457 	return ret;
458 
459 } /* end __key_instantiate_and_link() */
460 
461 /*****************************************************************************/
462 /*
463  * instantiate a key and link it into the target keyring atomically
464  */
465 int key_instantiate_and_link(struct key *key,
466 			     const void *data,
467 			     size_t datalen,
468 			     struct key *keyring,
469 			     struct key *instkey)
470 {
471 	int ret;
472 
473 	if (keyring)
474 		down_write(&keyring->sem);
475 
476 	ret = __key_instantiate_and_link(key, data, datalen, keyring, instkey);
477 
478 	if (keyring)
479 		up_write(&keyring->sem);
480 
481 	return ret;
482 
483 } /* end key_instantiate_and_link() */
484 
485 EXPORT_SYMBOL(key_instantiate_and_link);
486 
487 /*****************************************************************************/
488 /*
489  * negatively instantiate a key and link it into the target keyring atomically
490  */
491 int key_negate_and_link(struct key *key,
492 			unsigned timeout,
493 			struct key *keyring,
494 			struct key *instkey)
495 {
496 	struct timespec now;
497 	int ret, awaken;
498 
499 	key_check(key);
500 	key_check(keyring);
501 
502 	awaken = 0;
503 	ret = -EBUSY;
504 
505 	if (keyring)
506 		down_write(&keyring->sem);
507 
508 	down_write(&key_construction_sem);
509 
510 	/* can't instantiate twice */
511 	if (!test_bit(KEY_FLAG_INSTANTIATED, &key->flags)) {
512 		/* mark the key as being negatively instantiated */
513 		atomic_inc(&key->user->nikeys);
514 		set_bit(KEY_FLAG_NEGATIVE, &key->flags);
515 		set_bit(KEY_FLAG_INSTANTIATED, &key->flags);
516 		now = current_kernel_time();
517 		key->expiry = now.tv_sec + timeout;
518 
519 		if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags))
520 			awaken = 1;
521 
522 		ret = 0;
523 
524 		/* and link it into the destination keyring */
525 		if (keyring)
526 			ret = __key_link(keyring, key);
527 
528 		/* disable the authorisation key */
529 		if (instkey)
530 			key_revoke(instkey);
531 	}
532 
533 	up_write(&key_construction_sem);
534 
535 	if (keyring)
536 		up_write(&keyring->sem);
537 
538 	/* wake up anyone waiting for a key to be constructed */
539 	if (awaken)
540 		wake_up_all(&request_key_conswq);
541 
542 	return ret;
543 
544 } /* end key_negate_and_link() */
545 
546 EXPORT_SYMBOL(key_negate_and_link);
547 
548 /*****************************************************************************/
549 /*
550  * do cleaning up in process context so that we don't have to disable
551  * interrupts all over the place
552  */
553 static void key_cleanup(void *data)
554 {
555 	struct rb_node *_n;
556 	struct key *key;
557 
558  go_again:
559 	/* look for a dead key in the tree */
560 	spin_lock(&key_serial_lock);
561 
562 	for (_n = rb_first(&key_serial_tree); _n; _n = rb_next(_n)) {
563 		key = rb_entry(_n, struct key, serial_node);
564 
565 		if (atomic_read(&key->usage) == 0)
566 			goto found_dead_key;
567 	}
568 
569 	spin_unlock(&key_serial_lock);
570 	return;
571 
572  found_dead_key:
573 	/* we found a dead key - once we've removed it from the tree, we can
574 	 * drop the lock */
575 	rb_erase(&key->serial_node, &key_serial_tree);
576 	spin_unlock(&key_serial_lock);
577 
578 	key_check(key);
579 
580 	security_key_free(key);
581 
582 	/* deal with the user's key tracking and quota */
583 	if (test_bit(KEY_FLAG_IN_QUOTA, &key->flags)) {
584 		spin_lock(&key->user->lock);
585 		key->user->qnkeys--;
586 		key->user->qnbytes -= key->quotalen;
587 		spin_unlock(&key->user->lock);
588 	}
589 
590 	atomic_dec(&key->user->nkeys);
591 	if (test_bit(KEY_FLAG_INSTANTIATED, &key->flags))
592 		atomic_dec(&key->user->nikeys);
593 
594 	key_user_put(key->user);
595 
596 	/* now throw away the key memory */
597 	if (key->type->destroy)
598 		key->type->destroy(key);
599 
600 	kfree(key->description);
601 
602 #ifdef KEY_DEBUGGING
603 	key->magic = KEY_DEBUG_MAGIC_X;
604 #endif
605 	kmem_cache_free(key_jar, key);
606 
607 	/* there may, of course, be more than one key to destroy */
608 	goto go_again;
609 
610 } /* end key_cleanup() */
611 
612 /*****************************************************************************/
613 /*
614  * dispose of a reference to a key
615  * - when all the references are gone, we schedule the cleanup task to come and
616  *   pull it out of the tree in definite process context
617  */
618 void key_put(struct key *key)
619 {
620 	if (key) {
621 		key_check(key);
622 
623 		if (atomic_dec_and_test(&key->usage))
624 			schedule_work(&key_cleanup_task);
625 	}
626 
627 } /* end key_put() */
628 
629 EXPORT_SYMBOL(key_put);
630 
631 /*****************************************************************************/
632 /*
633  * find a key by its serial number
634  */
635 struct key *key_lookup(key_serial_t id)
636 {
637 	struct rb_node *n;
638 	struct key *key;
639 
640 	spin_lock(&key_serial_lock);
641 
642 	/* search the tree for the specified key */
643 	n = key_serial_tree.rb_node;
644 	while (n) {
645 		key = rb_entry(n, struct key, serial_node);
646 
647 		if (id < key->serial)
648 			n = n->rb_left;
649 		else if (id > key->serial)
650 			n = n->rb_right;
651 		else
652 			goto found;
653 	}
654 
655  not_found:
656 	key = ERR_PTR(-ENOKEY);
657 	goto error;
658 
659  found:
660 	/* pretend it doesn't exist if it's dead */
661 	if (atomic_read(&key->usage) == 0 ||
662 	    test_bit(KEY_FLAG_DEAD, &key->flags) ||
663 	    key->type == &key_type_dead)
664 		goto not_found;
665 
666 	/* this races with key_put(), but that doesn't matter since key_put()
667 	 * doesn't actually change the key
668 	 */
669 	atomic_inc(&key->usage);
670 
671  error:
672 	spin_unlock(&key_serial_lock);
673 	return key;
674 
675 } /* end key_lookup() */
676 
677 /*****************************************************************************/
678 /*
679  * find and lock the specified key type against removal
680  * - we return with the sem readlocked
681  */
682 struct key_type *key_type_lookup(const char *type)
683 {
684 	struct key_type *ktype;
685 
686 	down_read(&key_types_sem);
687 
688 	/* look up the key type to see if it's one of the registered kernel
689 	 * types */
690 	list_for_each_entry(ktype, &key_types_list, link) {
691 		if (strcmp(ktype->name, type) == 0)
692 			goto found_kernel_type;
693 	}
694 
695 	up_read(&key_types_sem);
696 	ktype = ERR_PTR(-ENOKEY);
697 
698  found_kernel_type:
699 	return ktype;
700 
701 } /* end key_type_lookup() */
702 
703 /*****************************************************************************/
704 /*
705  * unlock a key type
706  */
707 void key_type_put(struct key_type *ktype)
708 {
709 	up_read(&key_types_sem);
710 
711 } /* end key_type_put() */
712 
713 /*****************************************************************************/
714 /*
715  * attempt to update an existing key
716  * - the key has an incremented refcount
717  * - we need to put the key if we get an error
718  */
719 static inline key_ref_t __key_update(key_ref_t key_ref,
720 				     const void *payload, size_t plen)
721 {
722 	struct key *key = key_ref_to_ptr(key_ref);
723 	int ret;
724 
725 	/* need write permission on the key to update it */
726 	ret = key_permission(key_ref, KEY_WRITE);
727 	if (ret < 0)
728 		goto error;
729 
730 	ret = -EEXIST;
731 	if (!key->type->update)
732 		goto error;
733 
734 	down_write(&key->sem);
735 
736 	ret = key->type->update(key, payload, plen);
737 	if (ret == 0)
738 		/* updating a negative key instantiates it */
739 		clear_bit(KEY_FLAG_NEGATIVE, &key->flags);
740 
741 	up_write(&key->sem);
742 
743 	if (ret < 0)
744 		goto error;
745 out:
746 	return key_ref;
747 
748 error:
749 	key_put(key);
750 	key_ref = ERR_PTR(ret);
751 	goto out;
752 
753 } /* end __key_update() */
754 
755 /*****************************************************************************/
756 /*
757  * search the specified keyring for a key of the same description; if one is
758  * found, update it, otherwise add a new one
759  */
760 key_ref_t key_create_or_update(key_ref_t keyring_ref,
761 			       const char *type,
762 			       const char *description,
763 			       const void *payload,
764 			       size_t plen,
765 			       int not_in_quota)
766 {
767 	struct key_type *ktype;
768 	struct key *keyring, *key = NULL;
769 	key_perm_t perm;
770 	key_ref_t key_ref;
771 	int ret;
772 
773 	/* look up the key type to see if it's one of the registered kernel
774 	 * types */
775 	ktype = key_type_lookup(type);
776 	if (IS_ERR(ktype)) {
777 		key_ref = ERR_PTR(-ENODEV);
778 		goto error;
779 	}
780 
781 	key_ref = ERR_PTR(-EINVAL);
782 	if (!ktype->match || !ktype->instantiate)
783 		goto error_2;
784 
785 	keyring = key_ref_to_ptr(keyring_ref);
786 
787 	key_check(keyring);
788 
789 	down_write(&keyring->sem);
790 
791 	/* if we're going to allocate a new key, we're going to have
792 	 * to modify the keyring */
793 	ret = key_permission(keyring_ref, KEY_WRITE);
794 	if (ret < 0) {
795 		key_ref = ERR_PTR(ret);
796 		goto error_3;
797 	}
798 
799 	/* search for an existing key of the same type and description in the
800 	 * destination keyring
801 	 */
802 	key_ref = __keyring_search_one(keyring_ref, ktype, description, 0);
803 	if (!IS_ERR(key_ref))
804 		goto found_matching_key;
805 
806 	/* decide on the permissions we want */
807 	perm = KEY_POS_VIEW | KEY_POS_SEARCH | KEY_POS_LINK | KEY_POS_SETATTR;
808 	perm |= KEY_USR_VIEW | KEY_USR_SEARCH | KEY_USR_LINK | KEY_USR_SETATTR;
809 
810 	if (ktype->read)
811 		perm |= KEY_POS_READ | KEY_USR_READ;
812 
813 	if (ktype == &key_type_keyring || ktype->update)
814 		perm |= KEY_USR_WRITE;
815 
816 	/* allocate a new key */
817 	key = key_alloc(ktype, description, current->fsuid, current->fsgid,
818 			perm, not_in_quota);
819 	if (IS_ERR(key)) {
820 		key_ref = ERR_PTR(PTR_ERR(key));
821 		goto error_3;
822 	}
823 
824 	/* instantiate it and link it into the target keyring */
825 	ret = __key_instantiate_and_link(key, payload, plen, keyring, NULL);
826 	if (ret < 0) {
827 		key_put(key);
828 		key_ref = ERR_PTR(ret);
829 		goto error_3;
830 	}
831 
832 	key_ref = make_key_ref(key, is_key_possessed(keyring_ref));
833 
834  error_3:
835 	up_write(&keyring->sem);
836  error_2:
837 	key_type_put(ktype);
838  error:
839 	return key_ref;
840 
841  found_matching_key:
842 	/* we found a matching key, so we're going to try to update it
843 	 * - we can drop the locks first as we have the key pinned
844 	 */
845 	up_write(&keyring->sem);
846 	key_type_put(ktype);
847 
848 	key_ref = __key_update(key_ref, payload, plen);
849 	goto error;
850 
851 } /* end key_create_or_update() */
852 
853 EXPORT_SYMBOL(key_create_or_update);
854 
855 /*****************************************************************************/
856 /*
857  * update a key
858  */
859 int key_update(key_ref_t key_ref, const void *payload, size_t plen)
860 {
861 	struct key *key = key_ref_to_ptr(key_ref);
862 	int ret;
863 
864 	key_check(key);
865 
866 	/* the key must be writable */
867 	ret = key_permission(key_ref, KEY_WRITE);
868 	if (ret < 0)
869 		goto error;
870 
871 	/* attempt to update it if supported */
872 	ret = -EOPNOTSUPP;
873 	if (key->type->update) {
874 		down_write(&key->sem);
875 
876 		ret = key->type->update(key, payload, plen);
877 		if (ret == 0)
878 			/* updating a negative key instantiates it */
879 			clear_bit(KEY_FLAG_NEGATIVE, &key->flags);
880 
881 		up_write(&key->sem);
882 	}
883 
884  error:
885 	return ret;
886 
887 } /* end key_update() */
888 
889 EXPORT_SYMBOL(key_update);
890 
891 /*****************************************************************************/
892 /*
893  * duplicate a key, potentially with a revised description
894  * - must be supported by the keytype (keyrings for instance can be duplicated)
895  */
896 struct key *key_duplicate(struct key *source, const char *desc)
897 {
898 	struct key *key;
899 	int ret;
900 
901 	key_check(source);
902 
903 	if (!desc)
904 		desc = source->description;
905 
906 	down_read(&key_types_sem);
907 
908 	ret = -EINVAL;
909 	if (!source->type->duplicate)
910 		goto error;
911 
912 	/* allocate and instantiate a key */
913 	key = key_alloc(source->type, desc, current->fsuid, current->fsgid,
914 			source->perm, 0);
915 	if (IS_ERR(key))
916 		goto error_k;
917 
918 	down_read(&source->sem);
919 	ret = key->type->duplicate(key, source);
920 	up_read(&source->sem);
921 	if (ret < 0)
922 		goto error2;
923 
924 	atomic_inc(&key->user->nikeys);
925 	set_bit(KEY_FLAG_INSTANTIATED, &key->flags);
926 
927  error_k:
928 	up_read(&key_types_sem);
929  out:
930 	return key;
931 
932  error2:
933 	key_put(key);
934  error:
935 	up_read(&key_types_sem);
936 	key = ERR_PTR(ret);
937 	goto out;
938 
939 } /* end key_duplicate() */
940 
941 /*****************************************************************************/
942 /*
943  * revoke a key
944  */
945 void key_revoke(struct key *key)
946 {
947 	key_check(key);
948 
949 	/* make sure no one's trying to change or use the key when we mark
950 	 * it */
951 	down_write(&key->sem);
952 	set_bit(KEY_FLAG_REVOKED, &key->flags);
953 	up_write(&key->sem);
954 
955 } /* end key_revoke() */
956 
957 EXPORT_SYMBOL(key_revoke);
958 
959 /*****************************************************************************/
960 /*
961  * register a type of key
962  */
963 int register_key_type(struct key_type *ktype)
964 {
965 	struct key_type *p;
966 	int ret;
967 
968 	ret = -EEXIST;
969 	down_write(&key_types_sem);
970 
971 	/* disallow key types with the same name */
972 	list_for_each_entry(p, &key_types_list, link) {
973 		if (strcmp(p->name, ktype->name) == 0)
974 			goto out;
975 	}
976 
977 	/* store the type */
978 	list_add(&ktype->link, &key_types_list);
979 	ret = 0;
980 
981  out:
982 	up_write(&key_types_sem);
983 	return ret;
984 
985 } /* end register_key_type() */
986 
987 EXPORT_SYMBOL(register_key_type);
988 
989 /*****************************************************************************/
990 /*
991  * unregister a type of key
992  */
993 void unregister_key_type(struct key_type *ktype)
994 {
995 	struct rb_node *_n;
996 	struct key *key;
997 
998 	down_write(&key_types_sem);
999 
1000 	/* withdraw the key type */
1001 	list_del_init(&ktype->link);
1002 
1003 	/* mark all the keys of this type dead */
1004 	spin_lock(&key_serial_lock);
1005 
1006 	for (_n = rb_first(&key_serial_tree); _n; _n = rb_next(_n)) {
1007 		key = rb_entry(_n, struct key, serial_node);
1008 
1009 		if (key->type == ktype)
1010 			key->type = &key_type_dead;
1011 	}
1012 
1013 	spin_unlock(&key_serial_lock);
1014 
1015 	/* make sure everyone revalidates their keys */
1016 	synchronize_rcu();
1017 
1018 	/* we should now be able to destroy the payloads of all the keys of
1019 	 * this type with impunity */
1020 	spin_lock(&key_serial_lock);
1021 
1022 	for (_n = rb_first(&key_serial_tree); _n; _n = rb_next(_n)) {
1023 		key = rb_entry(_n, struct key, serial_node);
1024 
1025 		if (key->type == ktype) {
1026 			if (ktype->destroy)
1027 				ktype->destroy(key);
1028 			memset(&key->payload, 0xbd, sizeof(key->payload));
1029 		}
1030 	}
1031 
1032 	spin_unlock(&key_serial_lock);
1033 	up_write(&key_types_sem);
1034 
1035 } /* end unregister_key_type() */
1036 
1037 EXPORT_SYMBOL(unregister_key_type);
1038 
1039 /*****************************************************************************/
1040 /*
1041  * initialise the key management stuff
1042  */
1043 void __init key_init(void)
1044 {
1045 	/* allocate a slab in which we can store keys */
1046 	key_jar = kmem_cache_create("key_jar", sizeof(struct key),
1047 			0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL, NULL);
1048 
1049 	/* add the special key types */
1050 	list_add_tail(&key_type_keyring.link, &key_types_list);
1051 	list_add_tail(&key_type_dead.link, &key_types_list);
1052 	list_add_tail(&key_type_user.link, &key_types_list);
1053 
1054 	/* record the root user tracking */
1055 	rb_link_node(&root_key_user.node,
1056 		     NULL,
1057 		     &key_user_tree.rb_node);
1058 
1059 	rb_insert_color(&root_key_user.node,
1060 			&key_user_tree);
1061 
1062 	/* record root's user standard keyrings */
1063 	key_check(&root_user_keyring);
1064 	key_check(&root_session_keyring);
1065 
1066 	__key_insert_serial(&root_user_keyring);
1067 	__key_insert_serial(&root_session_keyring);
1068 
1069 	keyring_publish_name(&root_user_keyring);
1070 	keyring_publish_name(&root_session_keyring);
1071 
1072 	/* link the two root keyrings together */
1073 	key_link(&root_session_keyring, &root_user_keyring);
1074 
1075 } /* end key_init() */
1076