1 /* Basic authentication token and access key management
3 * Copyright (C) 2004-2008 Red Hat, Inc. All Rights Reserved.
4 * Written by David Howells (dhowells@redhat.com)
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.
12 #include <linux/module.h>
13 #include <linux/init.h>
14 #include <linux/poison.h>
15 #include <linux/sched.h>
16 #include <linux/slab.h>
17 #include <linux/security.h>
18 #include <linux/workqueue.h>
19 #include <linux/random.h>
20 #include <linux/err.h>
21 #include <linux/user_namespace.h>
24 static struct kmem_cache *key_jar;
25 struct rb_root key_serial_tree; /* tree of keys indexed by serial */
26 DEFINE_SPINLOCK(key_serial_lock);
28 struct rb_root key_user_tree; /* tree of quota records indexed by UID */
29 DEFINE_SPINLOCK(key_user_lock);
31 unsigned int key_quota_root_maxkeys = 200; /* root's key count quota */
32 unsigned int key_quota_root_maxbytes = 20000; /* root's key space quota */
33 unsigned int key_quota_maxkeys = 200; /* general key count quota */
34 unsigned int key_quota_maxbytes = 20000; /* general key space quota */
36 static LIST_HEAD(key_types_list);
37 static DECLARE_RWSEM(key_types_sem);
39 static void key_cleanup(struct work_struct *work);
40 static DECLARE_WORK(key_cleanup_task, key_cleanup);
42 /* we serialise key instantiation and link */
43 DEFINE_MUTEX(key_construction_mutex);
45 /* any key who's type gets unegistered will be re-typed to this */
46 static struct key_type key_type_dead = {
51 void __key_check(const struct key *key)
53 printk("__key_check: key %p {%08x} should be {%08x}\n",
54 key, key->magic, KEY_DEBUG_MAGIC);
59 /*****************************************************************************/
61 * get the key quota record for a user, allocating a new record if one doesn't
64 struct key_user *key_user_lookup(uid_t uid, struct user_namespace *user_ns)
66 struct key_user *candidate = NULL, *user;
67 struct rb_node *parent = NULL;
71 p = &key_user_tree.rb_node;
72 spin_lock(&key_user_lock);
74 /* search the tree for a user record with a matching UID */
77 user = rb_entry(parent, struct key_user, node);
81 else if (uid > user->uid)
83 else if (user_ns < user->user_ns)
85 else if (user_ns > user->user_ns)
91 /* if we get here, we failed to find a match in the tree */
93 /* allocate a candidate user record if we don't already have
95 spin_unlock(&key_user_lock);
98 candidate = kmalloc(sizeof(struct key_user), GFP_KERNEL);
99 if (unlikely(!candidate))
102 /* the allocation may have scheduled, so we need to repeat the
103 * search lest someone else added the record whilst we were
108 /* if we get here, then the user record still hadn't appeared on the
109 * second pass - so we use the candidate record */
110 atomic_set(&candidate->usage, 1);
111 atomic_set(&candidate->nkeys, 0);
112 atomic_set(&candidate->nikeys, 0);
113 candidate->uid = uid;
114 candidate->user_ns = get_user_ns(user_ns);
115 candidate->qnkeys = 0;
116 candidate->qnbytes = 0;
117 spin_lock_init(&candidate->lock);
118 mutex_init(&candidate->cons_lock);
120 rb_link_node(&candidate->node, parent, p);
121 rb_insert_color(&candidate->node, &key_user_tree);
122 spin_unlock(&key_user_lock);
126 /* okay - we found a user record for this UID */
128 atomic_inc(&user->usage);
129 spin_unlock(&key_user_lock);
134 } /* end key_user_lookup() */
136 /*****************************************************************************/
138 * dispose of a user structure
140 void key_user_put(struct key_user *user)
142 if (atomic_dec_and_lock(&user->usage, &key_user_lock)) {
143 rb_erase(&user->node, &key_user_tree);
144 spin_unlock(&key_user_lock);
145 put_user_ns(user->user_ns);
150 } /* end key_user_put() */
152 /*****************************************************************************/
154 * assign a key the next unique serial number
155 * - these are assigned randomly to avoid security issues through covert
158 static inline void key_alloc_serial(struct key *key)
160 struct rb_node *parent, **p;
163 /* propose a random serial number and look for a hole for it in the
164 * serial number tree */
166 get_random_bytes(&key->serial, sizeof(key->serial));
168 key->serial >>= 1; /* negative numbers are not permitted */
169 } while (key->serial < 3);
171 spin_lock(&key_serial_lock);
175 p = &key_serial_tree.rb_node;
179 xkey = rb_entry(parent, struct key, serial_node);
181 if (key->serial < xkey->serial)
183 else if (key->serial > xkey->serial)
189 /* we've found a suitable hole - arrange for this key to occupy it */
190 rb_link_node(&key->serial_node, parent, p);
191 rb_insert_color(&key->serial_node, &key_serial_tree);
193 spin_unlock(&key_serial_lock);
196 /* we found a key with the proposed serial number - walk the tree from
197 * that point looking for the next unused serial number */
201 if (key->serial < 3) {
203 goto attempt_insertion;
206 parent = rb_next(parent);
208 goto attempt_insertion;
210 xkey = rb_entry(parent, struct key, serial_node);
211 if (key->serial < xkey->serial)
212 goto attempt_insertion;
215 } /* end key_alloc_serial() */
217 /*****************************************************************************/
219 * allocate a key of the specified type
220 * - update the user's quota to reflect the existence of the key
221 * - called from a key-type operation with key_types_sem read-locked by
222 * key_create_or_update()
223 * - this prevents unregistration of the key type
224 * - upon return the key is as yet uninstantiated; the caller needs to either
225 * instantiate the key or discard it before returning
227 struct key *key_alloc(struct key_type *type, const char *desc,
228 uid_t uid, gid_t gid, const struct cred *cred,
229 key_perm_t perm, unsigned long flags)
231 struct key_user *user = NULL;
233 size_t desclen, quotalen;
236 key = ERR_PTR(-EINVAL);
240 desclen = strlen(desc) + 1;
241 quotalen = desclen + type->def_datalen;
243 /* get hold of the key tracking for this user */
244 user = key_user_lookup(uid, cred->user->user_ns);
248 /* check that the user's quota permits allocation of another key and
250 if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) {
251 unsigned maxkeys = (uid == 0) ?
252 key_quota_root_maxkeys : key_quota_maxkeys;
253 unsigned maxbytes = (uid == 0) ?
254 key_quota_root_maxbytes : key_quota_maxbytes;
256 spin_lock(&user->lock);
257 if (!(flags & KEY_ALLOC_QUOTA_OVERRUN)) {
258 if (user->qnkeys + 1 >= maxkeys ||
259 user->qnbytes + quotalen >= maxbytes ||
260 user->qnbytes + quotalen < user->qnbytes)
265 user->qnbytes += quotalen;
266 spin_unlock(&user->lock);
269 /* allocate and initialise the key and its description */
270 key = kmem_cache_alloc(key_jar, GFP_KERNEL);
275 key->description = kmemdup(desc, desclen, GFP_KERNEL);
276 if (!key->description)
280 atomic_set(&key->usage, 1);
281 init_rwsem(&key->sem);
284 key->quotalen = quotalen;
285 key->datalen = type->def_datalen;
291 key->payload.data = NULL;
292 key->security = NULL;
294 if (!(flags & KEY_ALLOC_NOT_IN_QUOTA))
295 key->flags |= 1 << KEY_FLAG_IN_QUOTA;
297 memset(&key->type_data, 0, sizeof(key->type_data));
300 key->magic = KEY_DEBUG_MAGIC;
303 /* let the security module know about the key */
304 ret = security_key_alloc(key, cred, flags);
308 /* publish the key by giving it a serial number */
309 atomic_inc(&user->nkeys);
310 key_alloc_serial(key);
316 kfree(key->description);
317 kmem_cache_free(key_jar, key);
318 if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) {
319 spin_lock(&user->lock);
321 user->qnbytes -= quotalen;
322 spin_unlock(&user->lock);
329 kmem_cache_free(key_jar, key);
331 if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) {
332 spin_lock(&user->lock);
334 user->qnbytes -= quotalen;
335 spin_unlock(&user->lock);
339 key = ERR_PTR(-ENOMEM);
343 spin_unlock(&user->lock);
345 key = ERR_PTR(-EDQUOT);
348 } /* end key_alloc() */
350 EXPORT_SYMBOL(key_alloc);
352 /*****************************************************************************/
354 * reserve an amount of quota for the key's payload
356 int key_payload_reserve(struct key *key, size_t datalen)
358 int delta = (int)datalen - key->datalen;
363 /* contemplate the quota adjustment */
364 if (delta != 0 && test_bit(KEY_FLAG_IN_QUOTA, &key->flags)) {
365 unsigned maxbytes = (key->user->uid == 0) ?
366 key_quota_root_maxbytes : key_quota_maxbytes;
368 spin_lock(&key->user->lock);
371 (key->user->qnbytes + delta >= maxbytes ||
372 key->user->qnbytes + delta < key->user->qnbytes)) {
376 key->user->qnbytes += delta;
377 key->quotalen += delta;
379 spin_unlock(&key->user->lock);
382 /* change the recorded data length if that didn't generate an error */
384 key->datalen = datalen;
388 } /* end key_payload_reserve() */
390 EXPORT_SYMBOL(key_payload_reserve);
392 /*****************************************************************************/
394 * instantiate a key and link it into the target keyring atomically
395 * - called with the target keyring's semaphore writelocked
397 static int __key_instantiate_and_link(struct key *key,
402 struct keyring_list **_prealloc)
412 mutex_lock(&key_construction_mutex);
414 /* can't instantiate twice */
415 if (!test_bit(KEY_FLAG_INSTANTIATED, &key->flags)) {
416 /* instantiate the key */
417 ret = key->type->instantiate(key, data, datalen);
420 /* mark the key as being instantiated */
421 atomic_inc(&key->user->nikeys);
422 set_bit(KEY_FLAG_INSTANTIATED, &key->flags);
424 if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags))
427 /* and link it into the destination keyring */
429 __key_link(keyring, key, _prealloc);
431 /* disable the authorisation key */
437 mutex_unlock(&key_construction_mutex);
439 /* wake up anyone waiting for a key to be constructed */
441 wake_up_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT);
445 } /* end __key_instantiate_and_link() */
447 /*****************************************************************************/
449 * instantiate a key and link it into the target keyring atomically
451 int key_instantiate_and_link(struct key *key,
457 struct keyring_list *prealloc;
461 ret = __key_link_begin(keyring, key->type, key->description,
467 ret = __key_instantiate_and_link(key, data, datalen, keyring, authkey,
471 __key_link_end(keyring, key->type, prealloc);
475 } /* end key_instantiate_and_link() */
477 EXPORT_SYMBOL(key_instantiate_and_link);
479 /*****************************************************************************/
481 * negatively instantiate a key and link it into the target keyring atomically
483 int key_negate_and_link(struct key *key,
488 struct keyring_list *prealloc;
490 int ret, awaken, link_ret = 0;
499 link_ret = __key_link_begin(keyring, key->type,
500 key->description, &prealloc);
502 mutex_lock(&key_construction_mutex);
504 /* can't instantiate twice */
505 if (!test_bit(KEY_FLAG_INSTANTIATED, &key->flags)) {
506 /* mark the key as being negatively instantiated */
507 atomic_inc(&key->user->nikeys);
508 set_bit(KEY_FLAG_NEGATIVE, &key->flags);
509 set_bit(KEY_FLAG_INSTANTIATED, &key->flags);
510 now = current_kernel_time();
511 key->expiry = now.tv_sec + timeout;
512 key_schedule_gc(key->expiry + key_gc_delay);
514 if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags))
519 /* and link it into the destination keyring */
520 if (keyring && link_ret == 0)
521 __key_link(keyring, key, &prealloc);
523 /* disable the authorisation key */
528 mutex_unlock(&key_construction_mutex);
531 __key_link_end(keyring, key->type, prealloc);
533 /* wake up anyone waiting for a key to be constructed */
535 wake_up_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT);
537 return ret == 0 ? link_ret : ret;
539 } /* end key_negate_and_link() */
541 EXPORT_SYMBOL(key_negate_and_link);
543 /*****************************************************************************/
545 * do cleaning up in process context so that we don't have to disable
546 * interrupts all over the place
548 static void key_cleanup(struct work_struct *work)
554 /* look for a dead key in the tree */
555 spin_lock(&key_serial_lock);
557 for (_n = rb_first(&key_serial_tree); _n; _n = rb_next(_n)) {
558 key = rb_entry(_n, struct key, serial_node);
560 if (atomic_read(&key->usage) == 0)
564 spin_unlock(&key_serial_lock);
568 /* we found a dead key - once we've removed it from the tree, we can
570 rb_erase(&key->serial_node, &key_serial_tree);
571 spin_unlock(&key_serial_lock);
575 security_key_free(key);
577 /* deal with the user's key tracking and quota */
578 if (test_bit(KEY_FLAG_IN_QUOTA, &key->flags)) {
579 spin_lock(&key->user->lock);
581 key->user->qnbytes -= key->quotalen;
582 spin_unlock(&key->user->lock);
585 atomic_dec(&key->user->nkeys);
586 if (test_bit(KEY_FLAG_INSTANTIATED, &key->flags))
587 atomic_dec(&key->user->nikeys);
589 key_user_put(key->user);
591 /* now throw away the key memory */
592 if (key->type->destroy)
593 key->type->destroy(key);
595 kfree(key->description);
598 key->magic = KEY_DEBUG_MAGIC_X;
600 kmem_cache_free(key_jar, key);
602 /* there may, of course, be more than one key to destroy */
605 } /* end key_cleanup() */
607 /*****************************************************************************/
609 * dispose of a reference to a key
610 * - when all the references are gone, we schedule the cleanup task to come and
611 * pull it out of the tree in definite process context
613 void key_put(struct key *key)
618 if (atomic_dec_and_test(&key->usage))
619 schedule_work(&key_cleanup_task);
622 } /* end key_put() */
624 EXPORT_SYMBOL(key_put);
626 /*****************************************************************************/
628 * find a key by its serial number
630 struct key *key_lookup(key_serial_t id)
635 spin_lock(&key_serial_lock);
637 /* search the tree for the specified key */
638 n = key_serial_tree.rb_node;
640 key = rb_entry(n, struct key, serial_node);
642 if (id < key->serial)
644 else if (id > key->serial)
651 key = ERR_PTR(-ENOKEY);
655 /* pretend it doesn't exist if it is awaiting deletion */
656 if (atomic_read(&key->usage) == 0)
659 /* this races with key_put(), but that doesn't matter since key_put()
660 * doesn't actually change the key
662 atomic_inc(&key->usage);
665 spin_unlock(&key_serial_lock);
668 } /* end key_lookup() */
670 /*****************************************************************************/
672 * find and lock the specified key type against removal
673 * - we return with the sem readlocked
675 struct key_type *key_type_lookup(const char *type)
677 struct key_type *ktype;
679 down_read(&key_types_sem);
681 /* look up the key type to see if it's one of the registered kernel
683 list_for_each_entry(ktype, &key_types_list, link) {
684 if (strcmp(ktype->name, type) == 0)
685 goto found_kernel_type;
688 up_read(&key_types_sem);
689 ktype = ERR_PTR(-ENOKEY);
694 } /* end key_type_lookup() */
696 /*****************************************************************************/
700 void key_type_put(struct key_type *ktype)
702 up_read(&key_types_sem);
704 } /* end key_type_put() */
706 /*****************************************************************************/
708 * attempt to update an existing key
709 * - the key has an incremented refcount
710 * - we need to put the key if we get an error
712 static inline key_ref_t __key_update(key_ref_t key_ref,
713 const void *payload, size_t plen)
715 struct key *key = key_ref_to_ptr(key_ref);
718 /* need write permission on the key to update it */
719 ret = key_permission(key_ref, KEY_WRITE);
724 if (!key->type->update)
727 down_write(&key->sem);
729 ret = key->type->update(key, payload, plen);
731 /* updating a negative key instantiates it */
732 clear_bit(KEY_FLAG_NEGATIVE, &key->flags);
743 key_ref = ERR_PTR(ret);
746 } /* end __key_update() */
748 /*****************************************************************************/
750 * search the specified keyring for a key of the same description; if one is
751 * found, update it, otherwise add a new one
753 key_ref_t key_create_or_update(key_ref_t keyring_ref,
755 const char *description,
761 struct keyring_list *prealloc;
762 const struct cred *cred = current_cred();
763 struct key_type *ktype;
764 struct key *keyring, *key = NULL;
768 /* look up the key type to see if it's one of the registered kernel
770 ktype = key_type_lookup(type);
772 key_ref = ERR_PTR(-ENODEV);
776 key_ref = ERR_PTR(-EINVAL);
777 if (!ktype->match || !ktype->instantiate)
780 keyring = key_ref_to_ptr(keyring_ref);
784 key_ref = ERR_PTR(-ENOTDIR);
785 if (keyring->type != &key_type_keyring)
788 ret = __key_link_begin(keyring, ktype, description, &prealloc);
792 /* if we're going to allocate a new key, we're going to have
793 * to modify the keyring */
794 ret = key_permission(keyring_ref, KEY_WRITE);
796 key_ref = ERR_PTR(ret);
800 /* if it's possible to update this type of key, search for an existing
801 * key of the same type and description in the destination keyring and
802 * update that instead if possible
805 key_ref = __keyring_search_one(keyring_ref, ktype, description,
807 if (!IS_ERR(key_ref))
808 goto found_matching_key;
811 /* if the client doesn't provide, decide on the permissions we want */
812 if (perm == KEY_PERM_UNDEF) {
813 perm = KEY_POS_VIEW | KEY_POS_SEARCH | KEY_POS_LINK | KEY_POS_SETATTR;
814 perm |= KEY_USR_VIEW | KEY_USR_SEARCH | KEY_USR_LINK | KEY_USR_SETATTR;
817 perm |= KEY_POS_READ | KEY_USR_READ;
819 if (ktype == &key_type_keyring || ktype->update)
820 perm |= KEY_USR_WRITE;
823 /* allocate a new key */
824 key = key_alloc(ktype, description, cred->fsuid, cred->fsgid, cred,
827 key_ref = ERR_CAST(key);
831 /* instantiate it and link it into the target keyring */
832 ret = __key_instantiate_and_link(key, payload, plen, keyring, NULL,
836 key_ref = ERR_PTR(ret);
840 key_ref = make_key_ref(key, is_key_possessed(keyring_ref));
843 __key_link_end(keyring, ktype, prealloc);
850 /* we found a matching key, so we're going to try to update it
851 * - we can drop the locks first as we have the key pinned
853 __key_link_end(keyring, ktype, prealloc);
856 key_ref = __key_update(key_ref, payload, plen);
859 } /* end key_create_or_update() */
861 EXPORT_SYMBOL(key_create_or_update);
863 /*****************************************************************************/
867 int key_update(key_ref_t key_ref, const void *payload, size_t plen)
869 struct key *key = key_ref_to_ptr(key_ref);
874 /* the key must be writable */
875 ret = key_permission(key_ref, KEY_WRITE);
879 /* attempt to update it if supported */
881 if (key->type->update) {
882 down_write(&key->sem);
884 ret = key->type->update(key, payload, plen);
886 /* updating a negative key instantiates it */
887 clear_bit(KEY_FLAG_NEGATIVE, &key->flags);
895 } /* end key_update() */
897 EXPORT_SYMBOL(key_update);
899 /*****************************************************************************/
903 void key_revoke(struct key *key)
910 /* make sure no one's trying to change or use the key when we mark it
911 * - we tell lockdep that we might nest because we might be revoking an
912 * authorisation key whilst holding the sem on a key we've just
915 down_write_nested(&key->sem, 1);
916 if (!test_and_set_bit(KEY_FLAG_REVOKED, &key->flags) &&
918 key->type->revoke(key);
920 /* set the death time to no more than the expiry time */
921 now = current_kernel_time();
923 if (key->revoked_at == 0 || key->revoked_at > time) {
924 key->revoked_at = time;
925 key_schedule_gc(key->revoked_at + key_gc_delay);
930 } /* end key_revoke() */
932 EXPORT_SYMBOL(key_revoke);
934 /*****************************************************************************/
936 * register a type of key
938 int register_key_type(struct key_type *ktype)
944 down_write(&key_types_sem);
946 /* disallow key types with the same name */
947 list_for_each_entry(p, &key_types_list, link) {
948 if (strcmp(p->name, ktype->name) == 0)
953 list_add(&ktype->link, &key_types_list);
957 up_write(&key_types_sem);
960 } /* end register_key_type() */
962 EXPORT_SYMBOL(register_key_type);
964 /*****************************************************************************/
966 * unregister a type of key
968 void unregister_key_type(struct key_type *ktype)
973 down_write(&key_types_sem);
975 /* withdraw the key type */
976 list_del_init(&ktype->link);
978 /* mark all the keys of this type dead */
979 spin_lock(&key_serial_lock);
981 for (_n = rb_first(&key_serial_tree); _n; _n = rb_next(_n)) {
982 key = rb_entry(_n, struct key, serial_node);
984 if (key->type == ktype) {
985 key->type = &key_type_dead;
986 set_bit(KEY_FLAG_DEAD, &key->flags);
990 spin_unlock(&key_serial_lock);
992 /* make sure everyone revalidates their keys */
995 /* we should now be able to destroy the payloads of all the keys of
996 * this type with impunity */
997 spin_lock(&key_serial_lock);
999 for (_n = rb_first(&key_serial_tree); _n; _n = rb_next(_n)) {
1000 key = rb_entry(_n, struct key, serial_node);
1002 if (key->type == ktype) {
1004 ktype->destroy(key);
1005 memset(&key->payload, KEY_DESTROY, sizeof(key->payload));
1009 spin_unlock(&key_serial_lock);
1010 up_write(&key_types_sem);
1014 } /* end unregister_key_type() */
1016 EXPORT_SYMBOL(unregister_key_type);
1018 /*****************************************************************************/
1020 * initialise the key management stuff
1022 void __init key_init(void)
1024 /* allocate a slab in which we can store keys */
1025 key_jar = kmem_cache_create("key_jar", sizeof(struct key),
1026 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL);
1028 /* add the special key types */
1029 list_add_tail(&key_type_keyring.link, &key_types_list);
1030 list_add_tail(&key_type_dead.link, &key_types_list);
1031 list_add_tail(&key_type_user.link, &key_types_list);
1033 /* record the root user tracking */
1034 rb_link_node(&root_key_user.node,
1036 &key_user_tree.rb_node);
1038 rb_insert_color(&root_key_user.node,
1041 } /* end key_init() */