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);
60 * get the key quota record for a user, allocating a new record if one doesn't
63 struct key_user *key_user_lookup(uid_t uid, struct user_namespace *user_ns)
65 struct key_user *candidate = NULL, *user;
66 struct rb_node *parent = NULL;
70 p = &key_user_tree.rb_node;
71 spin_lock(&key_user_lock);
73 /* search the tree for a user record with a matching UID */
76 user = rb_entry(parent, struct key_user, node);
80 else if (uid > user->uid)
82 else if (user_ns < user->user_ns)
84 else if (user_ns > user->user_ns)
90 /* if we get here, we failed to find a match in the tree */
92 /* allocate a candidate user record if we don't already have
94 spin_unlock(&key_user_lock);
97 candidate = kmalloc(sizeof(struct key_user), GFP_KERNEL);
98 if (unlikely(!candidate))
101 /* the allocation may have scheduled, so we need to repeat the
102 * search lest someone else added the record whilst we were
107 /* if we get here, then the user record still hadn't appeared on the
108 * second pass - so we use the candidate record */
109 atomic_set(&candidate->usage, 1);
110 atomic_set(&candidate->nkeys, 0);
111 atomic_set(&candidate->nikeys, 0);
112 candidate->uid = uid;
113 candidate->user_ns = get_user_ns(user_ns);
114 candidate->qnkeys = 0;
115 candidate->qnbytes = 0;
116 spin_lock_init(&candidate->lock);
117 mutex_init(&candidate->cons_lock);
119 rb_link_node(&candidate->node, parent, p);
120 rb_insert_color(&candidate->node, &key_user_tree);
121 spin_unlock(&key_user_lock);
125 /* okay - we found a user record for this UID */
127 atomic_inc(&user->usage);
128 spin_unlock(&key_user_lock);
135 * dispose of a user structure
137 void key_user_put(struct key_user *user)
139 if (atomic_dec_and_lock(&user->usage, &key_user_lock)) {
140 rb_erase(&user->node, &key_user_tree);
141 spin_unlock(&key_user_lock);
142 put_user_ns(user->user_ns);
149 * assign a key the next unique serial number
150 * - these are assigned randomly to avoid security issues through covert
153 static inline void key_alloc_serial(struct key *key)
155 struct rb_node *parent, **p;
158 /* propose a random serial number and look for a hole for it in the
159 * serial number tree */
161 get_random_bytes(&key->serial, sizeof(key->serial));
163 key->serial >>= 1; /* negative numbers are not permitted */
164 } while (key->serial < 3);
166 spin_lock(&key_serial_lock);
170 p = &key_serial_tree.rb_node;
174 xkey = rb_entry(parent, struct key, serial_node);
176 if (key->serial < xkey->serial)
178 else if (key->serial > xkey->serial)
184 /* we've found a suitable hole - arrange for this key to occupy it */
185 rb_link_node(&key->serial_node, parent, p);
186 rb_insert_color(&key->serial_node, &key_serial_tree);
188 spin_unlock(&key_serial_lock);
191 /* we found a key with the proposed serial number - walk the tree from
192 * that point looking for the next unused serial number */
196 if (key->serial < 3) {
198 goto attempt_insertion;
201 parent = rb_next(parent);
203 goto attempt_insertion;
205 xkey = rb_entry(parent, struct key, serial_node);
206 if (key->serial < xkey->serial)
207 goto attempt_insertion;
212 * allocate a key of the specified type
213 * - update the user's quota to reflect the existence of the key
214 * - called from a key-type operation with key_types_sem read-locked by
215 * key_create_or_update()
216 * - this prevents unregistration of the key type
217 * - upon return the key is as yet uninstantiated; the caller needs to either
218 * instantiate the key or discard it before returning
220 struct key *key_alloc(struct key_type *type, const char *desc,
221 uid_t uid, gid_t gid, const struct cred *cred,
222 key_perm_t perm, unsigned long flags)
224 struct key_user *user = NULL;
226 size_t desclen, quotalen;
229 key = ERR_PTR(-EINVAL);
233 desclen = strlen(desc) + 1;
234 quotalen = desclen + type->def_datalen;
236 /* get hold of the key tracking for this user */
237 user = key_user_lookup(uid, cred->user->user_ns);
241 /* check that the user's quota permits allocation of another key and
243 if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) {
244 unsigned maxkeys = (uid == 0) ?
245 key_quota_root_maxkeys : key_quota_maxkeys;
246 unsigned maxbytes = (uid == 0) ?
247 key_quota_root_maxbytes : key_quota_maxbytes;
249 spin_lock(&user->lock);
250 if (!(flags & KEY_ALLOC_QUOTA_OVERRUN)) {
251 if (user->qnkeys + 1 >= maxkeys ||
252 user->qnbytes + quotalen >= maxbytes ||
253 user->qnbytes + quotalen < user->qnbytes)
258 user->qnbytes += quotalen;
259 spin_unlock(&user->lock);
262 /* allocate and initialise the key and its description */
263 key = kmem_cache_alloc(key_jar, GFP_KERNEL);
268 key->description = kmemdup(desc, desclen, GFP_KERNEL);
269 if (!key->description)
273 atomic_set(&key->usage, 1);
274 init_rwsem(&key->sem);
277 key->quotalen = quotalen;
278 key->datalen = type->def_datalen;
284 key->payload.data = NULL;
285 key->security = NULL;
287 if (!(flags & KEY_ALLOC_NOT_IN_QUOTA))
288 key->flags |= 1 << KEY_FLAG_IN_QUOTA;
290 memset(&key->type_data, 0, sizeof(key->type_data));
293 key->magic = KEY_DEBUG_MAGIC;
296 /* let the security module know about the key */
297 ret = security_key_alloc(key, cred, flags);
301 /* publish the key by giving it a serial number */
302 atomic_inc(&user->nkeys);
303 key_alloc_serial(key);
309 kfree(key->description);
310 kmem_cache_free(key_jar, key);
311 if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) {
312 spin_lock(&user->lock);
314 user->qnbytes -= quotalen;
315 spin_unlock(&user->lock);
322 kmem_cache_free(key_jar, key);
324 if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) {
325 spin_lock(&user->lock);
327 user->qnbytes -= quotalen;
328 spin_unlock(&user->lock);
332 key = ERR_PTR(-ENOMEM);
336 spin_unlock(&user->lock);
338 key = ERR_PTR(-EDQUOT);
342 EXPORT_SYMBOL(key_alloc);
345 * reserve an amount of quota for the key's payload
347 int key_payload_reserve(struct key *key, size_t datalen)
349 int delta = (int)datalen - key->datalen;
354 /* contemplate the quota adjustment */
355 if (delta != 0 && test_bit(KEY_FLAG_IN_QUOTA, &key->flags)) {
356 unsigned maxbytes = (key->user->uid == 0) ?
357 key_quota_root_maxbytes : key_quota_maxbytes;
359 spin_lock(&key->user->lock);
362 (key->user->qnbytes + delta >= maxbytes ||
363 key->user->qnbytes + delta < key->user->qnbytes)) {
367 key->user->qnbytes += delta;
368 key->quotalen += delta;
370 spin_unlock(&key->user->lock);
373 /* change the recorded data length if that didn't generate an error */
375 key->datalen = datalen;
380 EXPORT_SYMBOL(key_payload_reserve);
383 * instantiate a key and link it into the target keyring atomically
384 * - called with the target keyring's semaphore writelocked
386 static int __key_instantiate_and_link(struct key *key,
391 struct keyring_list **_prealloc)
401 mutex_lock(&key_construction_mutex);
403 /* can't instantiate twice */
404 if (!test_bit(KEY_FLAG_INSTANTIATED, &key->flags)) {
405 /* instantiate the key */
406 ret = key->type->instantiate(key, data, datalen);
409 /* mark the key as being instantiated */
410 atomic_inc(&key->user->nikeys);
411 set_bit(KEY_FLAG_INSTANTIATED, &key->flags);
413 if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags))
416 /* and link it into the destination keyring */
418 __key_link(keyring, key, _prealloc);
420 /* disable the authorisation key */
426 mutex_unlock(&key_construction_mutex);
428 /* wake up anyone waiting for a key to be constructed */
430 wake_up_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT);
436 * instantiate a key and link it into the target keyring atomically
438 int key_instantiate_and_link(struct key *key,
444 struct keyring_list *prealloc;
448 ret = __key_link_begin(keyring, key->type, key->description,
454 ret = __key_instantiate_and_link(key, data, datalen, keyring, authkey,
458 __key_link_end(keyring, key->type, prealloc);
463 EXPORT_SYMBOL(key_instantiate_and_link);
466 * negatively instantiate a key and link it into the target keyring atomically
468 int key_negate_and_link(struct key *key,
473 struct keyring_list *prealloc;
475 int ret, awaken, link_ret = 0;
484 link_ret = __key_link_begin(keyring, key->type,
485 key->description, &prealloc);
487 mutex_lock(&key_construction_mutex);
489 /* can't instantiate twice */
490 if (!test_bit(KEY_FLAG_INSTANTIATED, &key->flags)) {
491 /* mark the key as being negatively instantiated */
492 atomic_inc(&key->user->nikeys);
493 set_bit(KEY_FLAG_NEGATIVE, &key->flags);
494 set_bit(KEY_FLAG_INSTANTIATED, &key->flags);
495 now = current_kernel_time();
496 key->expiry = now.tv_sec + timeout;
497 key_schedule_gc(key->expiry + key_gc_delay);
499 if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags))
504 /* and link it into the destination keyring */
505 if (keyring && link_ret == 0)
506 __key_link(keyring, key, &prealloc);
508 /* disable the authorisation key */
513 mutex_unlock(&key_construction_mutex);
516 __key_link_end(keyring, key->type, prealloc);
518 /* wake up anyone waiting for a key to be constructed */
520 wake_up_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT);
522 return ret == 0 ? link_ret : ret;
525 EXPORT_SYMBOL(key_negate_and_link);
528 * do cleaning up in process context so that we don't have to disable
529 * interrupts all over the place
531 static void key_cleanup(struct work_struct *work)
537 /* look for a dead key in the tree */
538 spin_lock(&key_serial_lock);
540 for (_n = rb_first(&key_serial_tree); _n; _n = rb_next(_n)) {
541 key = rb_entry(_n, struct key, serial_node);
543 if (atomic_read(&key->usage) == 0)
547 spin_unlock(&key_serial_lock);
551 /* we found a dead key - once we've removed it from the tree, we can
553 rb_erase(&key->serial_node, &key_serial_tree);
554 spin_unlock(&key_serial_lock);
558 security_key_free(key);
560 /* deal with the user's key tracking and quota */
561 if (test_bit(KEY_FLAG_IN_QUOTA, &key->flags)) {
562 spin_lock(&key->user->lock);
564 key->user->qnbytes -= key->quotalen;
565 spin_unlock(&key->user->lock);
568 atomic_dec(&key->user->nkeys);
569 if (test_bit(KEY_FLAG_INSTANTIATED, &key->flags))
570 atomic_dec(&key->user->nikeys);
572 key_user_put(key->user);
574 /* now throw away the key memory */
575 if (key->type->destroy)
576 key->type->destroy(key);
578 kfree(key->description);
581 key->magic = KEY_DEBUG_MAGIC_X;
583 kmem_cache_free(key_jar, key);
585 /* there may, of course, be more than one key to destroy */
590 * dispose of a reference to a key
591 * - when all the references are gone, we schedule the cleanup task to come and
592 * pull it out of the tree in definite process context
594 void key_put(struct key *key)
599 if (atomic_dec_and_test(&key->usage))
600 schedule_work(&key_cleanup_task);
604 EXPORT_SYMBOL(key_put);
607 * find a key by its serial number
609 struct key *key_lookup(key_serial_t id)
614 spin_lock(&key_serial_lock);
616 /* search the tree for the specified key */
617 n = key_serial_tree.rb_node;
619 key = rb_entry(n, struct key, serial_node);
621 if (id < key->serial)
623 else if (id > key->serial)
630 key = ERR_PTR(-ENOKEY);
634 /* pretend it doesn't exist if it is awaiting deletion */
635 if (atomic_read(&key->usage) == 0)
638 /* this races with key_put(), but that doesn't matter since key_put()
639 * doesn't actually change the key
641 atomic_inc(&key->usage);
644 spin_unlock(&key_serial_lock);
649 * find and lock the specified key type against removal
650 * - we return with the sem readlocked
652 struct key_type *key_type_lookup(const char *type)
654 struct key_type *ktype;
656 down_read(&key_types_sem);
658 /* look up the key type to see if it's one of the registered kernel
660 list_for_each_entry(ktype, &key_types_list, link) {
661 if (strcmp(ktype->name, type) == 0)
662 goto found_kernel_type;
665 up_read(&key_types_sem);
666 ktype = ERR_PTR(-ENOKEY);
675 void key_type_put(struct key_type *ktype)
677 up_read(&key_types_sem);
681 * attempt to update an existing key
682 * - the key has an incremented refcount
683 * - we need to put the key if we get an error
685 static inline key_ref_t __key_update(key_ref_t key_ref,
686 const void *payload, size_t plen)
688 struct key *key = key_ref_to_ptr(key_ref);
691 /* need write permission on the key to update it */
692 ret = key_permission(key_ref, KEY_WRITE);
697 if (!key->type->update)
700 down_write(&key->sem);
702 ret = key->type->update(key, payload, plen);
704 /* updating a negative key instantiates it */
705 clear_bit(KEY_FLAG_NEGATIVE, &key->flags);
716 key_ref = ERR_PTR(ret);
721 * search the specified keyring for a key of the same description; if one is
722 * found, update it, otherwise add a new one
724 key_ref_t key_create_or_update(key_ref_t keyring_ref,
726 const char *description,
732 struct keyring_list *prealloc;
733 const struct cred *cred = current_cred();
734 struct key_type *ktype;
735 struct key *keyring, *key = NULL;
739 /* look up the key type to see if it's one of the registered kernel
741 ktype = key_type_lookup(type);
743 key_ref = ERR_PTR(-ENODEV);
747 key_ref = ERR_PTR(-EINVAL);
748 if (!ktype->match || !ktype->instantiate)
751 keyring = key_ref_to_ptr(keyring_ref);
755 key_ref = ERR_PTR(-ENOTDIR);
756 if (keyring->type != &key_type_keyring)
759 ret = __key_link_begin(keyring, ktype, description, &prealloc);
763 /* if we're going to allocate a new key, we're going to have
764 * to modify the keyring */
765 ret = key_permission(keyring_ref, KEY_WRITE);
767 key_ref = ERR_PTR(ret);
771 /* if it's possible to update this type of key, search for an existing
772 * key of the same type and description in the destination keyring and
773 * update that instead if possible
776 key_ref = __keyring_search_one(keyring_ref, ktype, description,
778 if (!IS_ERR(key_ref))
779 goto found_matching_key;
782 /* if the client doesn't provide, decide on the permissions we want */
783 if (perm == KEY_PERM_UNDEF) {
784 perm = KEY_POS_VIEW | KEY_POS_SEARCH | KEY_POS_LINK | KEY_POS_SETATTR;
785 perm |= KEY_USR_VIEW | KEY_USR_SEARCH | KEY_USR_LINK | KEY_USR_SETATTR;
788 perm |= KEY_POS_READ | KEY_USR_READ;
790 if (ktype == &key_type_keyring || ktype->update)
791 perm |= KEY_USR_WRITE;
794 /* allocate a new key */
795 key = key_alloc(ktype, description, cred->fsuid, cred->fsgid, cred,
798 key_ref = ERR_CAST(key);
802 /* instantiate it and link it into the target keyring */
803 ret = __key_instantiate_and_link(key, payload, plen, keyring, NULL,
807 key_ref = ERR_PTR(ret);
811 key_ref = make_key_ref(key, is_key_possessed(keyring_ref));
814 __key_link_end(keyring, ktype, prealloc);
821 /* we found a matching key, so we're going to try to update it
822 * - we can drop the locks first as we have the key pinned
824 __key_link_end(keyring, ktype, prealloc);
827 key_ref = __key_update(key_ref, payload, plen);
831 EXPORT_SYMBOL(key_create_or_update);
836 int key_update(key_ref_t key_ref, const void *payload, size_t plen)
838 struct key *key = key_ref_to_ptr(key_ref);
843 /* the key must be writable */
844 ret = key_permission(key_ref, KEY_WRITE);
848 /* attempt to update it if supported */
850 if (key->type->update) {
851 down_write(&key->sem);
853 ret = key->type->update(key, payload, plen);
855 /* updating a negative key instantiates it */
856 clear_bit(KEY_FLAG_NEGATIVE, &key->flags);
865 EXPORT_SYMBOL(key_update);
870 void key_revoke(struct key *key)
877 /* make sure no one's trying to change or use the key when we mark it
878 * - we tell lockdep that we might nest because we might be revoking an
879 * authorisation key whilst holding the sem on a key we've just
882 down_write_nested(&key->sem, 1);
883 if (!test_and_set_bit(KEY_FLAG_REVOKED, &key->flags) &&
885 key->type->revoke(key);
887 /* set the death time to no more than the expiry time */
888 now = current_kernel_time();
890 if (key->revoked_at == 0 || key->revoked_at > time) {
891 key->revoked_at = time;
892 key_schedule_gc(key->revoked_at + key_gc_delay);
898 EXPORT_SYMBOL(key_revoke);
901 * register a type of key
903 int register_key_type(struct key_type *ktype)
909 down_write(&key_types_sem);
911 /* disallow key types with the same name */
912 list_for_each_entry(p, &key_types_list, link) {
913 if (strcmp(p->name, ktype->name) == 0)
918 list_add(&ktype->link, &key_types_list);
922 up_write(&key_types_sem);
926 EXPORT_SYMBOL(register_key_type);
929 * unregister a type of key
931 void unregister_key_type(struct key_type *ktype)
936 down_write(&key_types_sem);
938 /* withdraw the key type */
939 list_del_init(&ktype->link);
941 /* mark all the keys of this type dead */
942 spin_lock(&key_serial_lock);
944 for (_n = rb_first(&key_serial_tree); _n; _n = rb_next(_n)) {
945 key = rb_entry(_n, struct key, serial_node);
947 if (key->type == ktype) {
948 key->type = &key_type_dead;
949 set_bit(KEY_FLAG_DEAD, &key->flags);
953 spin_unlock(&key_serial_lock);
955 /* make sure everyone revalidates their keys */
958 /* we should now be able to destroy the payloads of all the keys of
959 * this type with impunity */
960 spin_lock(&key_serial_lock);
962 for (_n = rb_first(&key_serial_tree); _n; _n = rb_next(_n)) {
963 key = rb_entry(_n, struct key, serial_node);
965 if (key->type == ktype) {
968 memset(&key->payload, KEY_DESTROY, sizeof(key->payload));
972 spin_unlock(&key_serial_lock);
973 up_write(&key_types_sem);
978 EXPORT_SYMBOL(unregister_key_type);
981 * initialise the key management stuff
983 void __init key_init(void)
985 /* allocate a slab in which we can store keys */
986 key_jar = kmem_cache_create("key_jar", sizeof(struct key),
987 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL);
989 /* add the special key types */
990 list_add_tail(&key_type_keyring.link, &key_types_list);
991 list_add_tail(&key_type_dead.link, &key_types_list);
992 list_add_tail(&key_type_user.link, &key_types_list);
994 /* record the root user tracking */
995 rb_link_node(&root_key_user.node,
997 &key_user_tree.rb_node);
999 rb_insert_color(&root_key_user.node,