/* Basic authentication token and access key management1*2* Copyright (C) 2004-2008 Red Hat, Inc. All Rights Reserved.3* Written by David Howells ([email protected])4*5* This program is free software; you can redistribute it and/or6* modify it under the terms of the GNU General Public License7* as published by the Free Software Foundation; either version8* 2 of the License, or (at your option) any later version.9*/1011#include <linux/module.h>12#include <linux/init.h>13#include <linux/poison.h>14#include <linux/sched.h>15#include <linux/slab.h>16#include <linux/security.h>17#include <linux/workqueue.h>18#include <linux/random.h>19#include <linux/err.h>20#include <linux/user_namespace.h>21#include "internal.h"2223static struct kmem_cache *key_jar;24struct rb_root key_serial_tree; /* tree of keys indexed by serial */25DEFINE_SPINLOCK(key_serial_lock);2627struct rb_root key_user_tree; /* tree of quota records indexed by UID */28DEFINE_SPINLOCK(key_user_lock);2930unsigned int key_quota_root_maxkeys = 200; /* root's key count quota */31unsigned int key_quota_root_maxbytes = 20000; /* root's key space quota */32unsigned int key_quota_maxkeys = 200; /* general key count quota */33unsigned int key_quota_maxbytes = 20000; /* general key space quota */3435static LIST_HEAD(key_types_list);36static DECLARE_RWSEM(key_types_sem);3738static void key_cleanup(struct work_struct *work);39static DECLARE_WORK(key_cleanup_task, key_cleanup);4041/* We serialise key instantiation and link */42DEFINE_MUTEX(key_construction_mutex);4344/* Any key who's type gets unegistered will be re-typed to this */45static struct key_type key_type_dead = {46.name = "dead",47};4849#ifdef KEY_DEBUGGING50void __key_check(const struct key *key)51{52printk("__key_check: key %p {%08x} should be {%08x}\n",53key, key->magic, KEY_DEBUG_MAGIC);54BUG();55}56#endif5758/*59* Get the key quota record for a user, allocating a new record if one doesn't60* already exist.61*/62struct key_user *key_user_lookup(uid_t uid, struct user_namespace *user_ns)63{64struct key_user *candidate = NULL, *user;65struct rb_node *parent = NULL;66struct rb_node **p;6768try_again:69p = &key_user_tree.rb_node;70spin_lock(&key_user_lock);7172/* search the tree for a user record with a matching UID */73while (*p) {74parent = *p;75user = rb_entry(parent, struct key_user, node);7677if (uid < user->uid)78p = &(*p)->rb_left;79else if (uid > user->uid)80p = &(*p)->rb_right;81else if (user_ns < user->user_ns)82p = &(*p)->rb_left;83else if (user_ns > user->user_ns)84p = &(*p)->rb_right;85else86goto found;87}8889/* if we get here, we failed to find a match in the tree */90if (!candidate) {91/* allocate a candidate user record if we don't already have92* one */93spin_unlock(&key_user_lock);9495user = NULL;96candidate = kmalloc(sizeof(struct key_user), GFP_KERNEL);97if (unlikely(!candidate))98goto out;99100/* the allocation may have scheduled, so we need to repeat the101* search lest someone else added the record whilst we were102* asleep */103goto try_again;104}105106/* if we get here, then the user record still hadn't appeared on the107* second pass - so we use the candidate record */108atomic_set(&candidate->usage, 1);109atomic_set(&candidate->nkeys, 0);110atomic_set(&candidate->nikeys, 0);111candidate->uid = uid;112candidate->user_ns = get_user_ns(user_ns);113candidate->qnkeys = 0;114candidate->qnbytes = 0;115spin_lock_init(&candidate->lock);116mutex_init(&candidate->cons_lock);117118rb_link_node(&candidate->node, parent, p);119rb_insert_color(&candidate->node, &key_user_tree);120spin_unlock(&key_user_lock);121user = candidate;122goto out;123124/* okay - we found a user record for this UID */125found:126atomic_inc(&user->usage);127spin_unlock(&key_user_lock);128kfree(candidate);129out:130return user;131}132133/*134* Dispose of a user structure135*/136void key_user_put(struct key_user *user)137{138if (atomic_dec_and_lock(&user->usage, &key_user_lock)) {139rb_erase(&user->node, &key_user_tree);140spin_unlock(&key_user_lock);141put_user_ns(user->user_ns);142143kfree(user);144}145}146147/*148* Allocate a serial number for a key. These are assigned randomly to avoid149* security issues through covert channel problems.150*/151static inline void key_alloc_serial(struct key *key)152{153struct rb_node *parent, **p;154struct key *xkey;155156/* propose a random serial number and look for a hole for it in the157* serial number tree */158do {159get_random_bytes(&key->serial, sizeof(key->serial));160161key->serial >>= 1; /* negative numbers are not permitted */162} while (key->serial < 3);163164spin_lock(&key_serial_lock);165166attempt_insertion:167parent = NULL;168p = &key_serial_tree.rb_node;169170while (*p) {171parent = *p;172xkey = rb_entry(parent, struct key, serial_node);173174if (key->serial < xkey->serial)175p = &(*p)->rb_left;176else if (key->serial > xkey->serial)177p = &(*p)->rb_right;178else179goto serial_exists;180}181182/* we've found a suitable hole - arrange for this key to occupy it */183rb_link_node(&key->serial_node, parent, p);184rb_insert_color(&key->serial_node, &key_serial_tree);185186spin_unlock(&key_serial_lock);187return;188189/* we found a key with the proposed serial number - walk the tree from190* that point looking for the next unused serial number */191serial_exists:192for (;;) {193key->serial++;194if (key->serial < 3) {195key->serial = 3;196goto attempt_insertion;197}198199parent = rb_next(parent);200if (!parent)201goto attempt_insertion;202203xkey = rb_entry(parent, struct key, serial_node);204if (key->serial < xkey->serial)205goto attempt_insertion;206}207}208209/**210* key_alloc - Allocate a key of the specified type.211* @type: The type of key to allocate.212* @desc: The key description to allow the key to be searched out.213* @uid: The owner of the new key.214* @gid: The group ID for the new key's group permissions.215* @cred: The credentials specifying UID namespace.216* @perm: The permissions mask of the new key.217* @flags: Flags specifying quota properties.218*219* Allocate a key of the specified type with the attributes given. The key is220* returned in an uninstantiated state and the caller needs to instantiate the221* key before returning.222*223* The user's key count quota is updated to reflect the creation of the key and224* the user's key data quota has the default for the key type reserved. The225* instantiation function should amend this as necessary. If insufficient226* quota is available, -EDQUOT will be returned.227*228* The LSM security modules can prevent a key being created, in which case229* -EACCES will be returned.230*231* Returns a pointer to the new key if successful and an error code otherwise.232*233* Note that the caller needs to ensure the key type isn't uninstantiated.234* Internally this can be done by locking key_types_sem. Externally, this can235* be done by either never unregistering the key type, or making sure236* key_alloc() calls don't race with module unloading.237*/238struct key *key_alloc(struct key_type *type, const char *desc,239uid_t uid, gid_t gid, const struct cred *cred,240key_perm_t perm, unsigned long flags)241{242struct key_user *user = NULL;243struct key *key;244size_t desclen, quotalen;245int ret;246247key = ERR_PTR(-EINVAL);248if (!desc || !*desc)249goto error;250251if (type->vet_description) {252ret = type->vet_description(desc);253if (ret < 0) {254key = ERR_PTR(ret);255goto error;256}257}258259desclen = strlen(desc) + 1;260quotalen = desclen + type->def_datalen;261262/* get hold of the key tracking for this user */263user = key_user_lookup(uid, cred->user->user_ns);264if (!user)265goto no_memory_1;266267/* check that the user's quota permits allocation of another key and268* its description */269if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) {270unsigned maxkeys = (uid == 0) ?271key_quota_root_maxkeys : key_quota_maxkeys;272unsigned maxbytes = (uid == 0) ?273key_quota_root_maxbytes : key_quota_maxbytes;274275spin_lock(&user->lock);276if (!(flags & KEY_ALLOC_QUOTA_OVERRUN)) {277if (user->qnkeys + 1 >= maxkeys ||278user->qnbytes + quotalen >= maxbytes ||279user->qnbytes + quotalen < user->qnbytes)280goto no_quota;281}282283user->qnkeys++;284user->qnbytes += quotalen;285spin_unlock(&user->lock);286}287288/* allocate and initialise the key and its description */289key = kmem_cache_alloc(key_jar, GFP_KERNEL);290if (!key)291goto no_memory_2;292293if (desc) {294key->description = kmemdup(desc, desclen, GFP_KERNEL);295if (!key->description)296goto no_memory_3;297}298299atomic_set(&key->usage, 1);300init_rwsem(&key->sem);301key->type = type;302key->user = user;303key->quotalen = quotalen;304key->datalen = type->def_datalen;305key->uid = uid;306key->gid = gid;307key->perm = perm;308key->flags = 0;309key->expiry = 0;310key->payload.data = NULL;311key->security = NULL;312313if (!(flags & KEY_ALLOC_NOT_IN_QUOTA))314key->flags |= 1 << KEY_FLAG_IN_QUOTA;315316memset(&key->type_data, 0, sizeof(key->type_data));317318#ifdef KEY_DEBUGGING319key->magic = KEY_DEBUG_MAGIC;320#endif321322/* let the security module know about the key */323ret = security_key_alloc(key, cred, flags);324if (ret < 0)325goto security_error;326327/* publish the key by giving it a serial number */328atomic_inc(&user->nkeys);329key_alloc_serial(key);330331error:332return key;333334security_error:335kfree(key->description);336kmem_cache_free(key_jar, key);337if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) {338spin_lock(&user->lock);339user->qnkeys--;340user->qnbytes -= quotalen;341spin_unlock(&user->lock);342}343key_user_put(user);344key = ERR_PTR(ret);345goto error;346347no_memory_3:348kmem_cache_free(key_jar, key);349no_memory_2:350if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) {351spin_lock(&user->lock);352user->qnkeys--;353user->qnbytes -= quotalen;354spin_unlock(&user->lock);355}356key_user_put(user);357no_memory_1:358key = ERR_PTR(-ENOMEM);359goto error;360361no_quota:362spin_unlock(&user->lock);363key_user_put(user);364key = ERR_PTR(-EDQUOT);365goto error;366}367EXPORT_SYMBOL(key_alloc);368369/**370* key_payload_reserve - Adjust data quota reservation for the key's payload371* @key: The key to make the reservation for.372* @datalen: The amount of data payload the caller now wants.373*374* Adjust the amount of the owning user's key data quota that a key reserves.375* If the amount is increased, then -EDQUOT may be returned if there isn't376* enough free quota available.377*378* If successful, 0 is returned.379*/380int key_payload_reserve(struct key *key, size_t datalen)381{382int delta = (int)datalen - key->datalen;383int ret = 0;384385key_check(key);386387/* contemplate the quota adjustment */388if (delta != 0 && test_bit(KEY_FLAG_IN_QUOTA, &key->flags)) {389unsigned maxbytes = (key->user->uid == 0) ?390key_quota_root_maxbytes : key_quota_maxbytes;391392spin_lock(&key->user->lock);393394if (delta > 0 &&395(key->user->qnbytes + delta >= maxbytes ||396key->user->qnbytes + delta < key->user->qnbytes)) {397ret = -EDQUOT;398}399else {400key->user->qnbytes += delta;401key->quotalen += delta;402}403spin_unlock(&key->user->lock);404}405406/* change the recorded data length if that didn't generate an error */407if (ret == 0)408key->datalen = datalen;409410return ret;411}412EXPORT_SYMBOL(key_payload_reserve);413414/*415* Instantiate a key and link it into the target keyring atomically. Must be416* called with the target keyring's semaphore writelocked. The target key's417* semaphore need not be locked as instantiation is serialised by418* key_construction_mutex.419*/420static int __key_instantiate_and_link(struct key *key,421const void *data,422size_t datalen,423struct key *keyring,424struct key *authkey,425unsigned long *_prealloc)426{427int ret, awaken;428429key_check(key);430key_check(keyring);431432awaken = 0;433ret = -EBUSY;434435mutex_lock(&key_construction_mutex);436437/* can't instantiate twice */438if (!test_bit(KEY_FLAG_INSTANTIATED, &key->flags)) {439/* instantiate the key */440ret = key->type->instantiate(key, data, datalen);441442if (ret == 0) {443/* mark the key as being instantiated */444atomic_inc(&key->user->nikeys);445set_bit(KEY_FLAG_INSTANTIATED, &key->flags);446447if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags))448awaken = 1;449450/* and link it into the destination keyring */451if (keyring)452__key_link(keyring, key, _prealloc);453454/* disable the authorisation key */455if (authkey)456key_revoke(authkey);457}458}459460mutex_unlock(&key_construction_mutex);461462/* wake up anyone waiting for a key to be constructed */463if (awaken)464wake_up_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT);465466return ret;467}468469/**470* key_instantiate_and_link - Instantiate a key and link it into the keyring.471* @key: The key to instantiate.472* @data: The data to use to instantiate the keyring.473* @datalen: The length of @data.474* @keyring: Keyring to create a link in on success (or NULL).475* @authkey: The authorisation token permitting instantiation.476*477* Instantiate a key that's in the uninstantiated state using the provided data478* and, if successful, link it in to the destination keyring if one is479* supplied.480*481* If successful, 0 is returned, the authorisation token is revoked and anyone482* waiting for the key is woken up. If the key was already instantiated,483* -EBUSY will be returned.484*/485int key_instantiate_and_link(struct key *key,486const void *data,487size_t datalen,488struct key *keyring,489struct key *authkey)490{491unsigned long prealloc;492int ret;493494if (keyring) {495ret = __key_link_begin(keyring, key->type, key->description,496&prealloc);497if (ret < 0)498return ret;499}500501ret = __key_instantiate_and_link(key, data, datalen, keyring, authkey,502&prealloc);503504if (keyring)505__key_link_end(keyring, key->type, prealloc);506507return ret;508}509510EXPORT_SYMBOL(key_instantiate_and_link);511512/**513* key_reject_and_link - Negatively instantiate a key and link it into the keyring.514* @key: The key to instantiate.515* @timeout: The timeout on the negative key.516* @error: The error to return when the key is hit.517* @keyring: Keyring to create a link in on success (or NULL).518* @authkey: The authorisation token permitting instantiation.519*520* Negatively instantiate a key that's in the uninstantiated state and, if521* successful, set its timeout and stored error and link it in to the522* destination keyring if one is supplied. The key and any links to the key523* will be automatically garbage collected after the timeout expires.524*525* Negative keys are used to rate limit repeated request_key() calls by causing526* them to return the stored error code (typically ENOKEY) until the negative527* key expires.528*529* If successful, 0 is returned, the authorisation token is revoked and anyone530* waiting for the key is woken up. If the key was already instantiated,531* -EBUSY will be returned.532*/533int key_reject_and_link(struct key *key,534unsigned timeout,535unsigned error,536struct key *keyring,537struct key *authkey)538{539unsigned long prealloc;540struct timespec now;541int ret, awaken, link_ret = 0;542543key_check(key);544key_check(keyring);545546awaken = 0;547ret = -EBUSY;548549if (keyring)550link_ret = __key_link_begin(keyring, key->type,551key->description, &prealloc);552553mutex_lock(&key_construction_mutex);554555/* can't instantiate twice */556if (!test_bit(KEY_FLAG_INSTANTIATED, &key->flags)) {557/* mark the key as being negatively instantiated */558atomic_inc(&key->user->nikeys);559set_bit(KEY_FLAG_NEGATIVE, &key->flags);560set_bit(KEY_FLAG_INSTANTIATED, &key->flags);561key->type_data.reject_error = -error;562now = current_kernel_time();563key->expiry = now.tv_sec + timeout;564key_schedule_gc(key->expiry + key_gc_delay);565566if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags))567awaken = 1;568569ret = 0;570571/* and link it into the destination keyring */572if (keyring && link_ret == 0)573__key_link(keyring, key, &prealloc);574575/* disable the authorisation key */576if (authkey)577key_revoke(authkey);578}579580mutex_unlock(&key_construction_mutex);581582if (keyring)583__key_link_end(keyring, key->type, prealloc);584585/* wake up anyone waiting for a key to be constructed */586if (awaken)587wake_up_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT);588589return ret == 0 ? link_ret : ret;590}591EXPORT_SYMBOL(key_reject_and_link);592593/*594* Garbage collect keys in process context so that we don't have to disable595* interrupts all over the place.596*597* key_put() schedules this rather than trying to do the cleanup itself, which598* means key_put() doesn't have to sleep.599*/600static void key_cleanup(struct work_struct *work)601{602struct rb_node *_n;603struct key *key;604605go_again:606/* look for a dead key in the tree */607spin_lock(&key_serial_lock);608609for (_n = rb_first(&key_serial_tree); _n; _n = rb_next(_n)) {610key = rb_entry(_n, struct key, serial_node);611612if (atomic_read(&key->usage) == 0)613goto found_dead_key;614}615616spin_unlock(&key_serial_lock);617return;618619found_dead_key:620/* we found a dead key - once we've removed it from the tree, we can621* drop the lock */622rb_erase(&key->serial_node, &key_serial_tree);623spin_unlock(&key_serial_lock);624625key_check(key);626627security_key_free(key);628629/* deal with the user's key tracking and quota */630if (test_bit(KEY_FLAG_IN_QUOTA, &key->flags)) {631spin_lock(&key->user->lock);632key->user->qnkeys--;633key->user->qnbytes -= key->quotalen;634spin_unlock(&key->user->lock);635}636637atomic_dec(&key->user->nkeys);638if (test_bit(KEY_FLAG_INSTANTIATED, &key->flags))639atomic_dec(&key->user->nikeys);640641key_user_put(key->user);642643/* now throw away the key memory */644if (key->type->destroy)645key->type->destroy(key);646647kfree(key->description);648649#ifdef KEY_DEBUGGING650key->magic = KEY_DEBUG_MAGIC_X;651#endif652kmem_cache_free(key_jar, key);653654/* there may, of course, be more than one key to destroy */655goto go_again;656}657658/**659* key_put - Discard a reference to a key.660* @key: The key to discard a reference from.661*662* Discard a reference to a key, and when all the references are gone, we663* schedule the cleanup task to come and pull it out of the tree in process664* context at some later time.665*/666void key_put(struct key *key)667{668if (key) {669key_check(key);670671if (atomic_dec_and_test(&key->usage))672schedule_work(&key_cleanup_task);673}674}675EXPORT_SYMBOL(key_put);676677/*678* Find a key by its serial number.679*/680struct key *key_lookup(key_serial_t id)681{682struct rb_node *n;683struct key *key;684685spin_lock(&key_serial_lock);686687/* search the tree for the specified key */688n = key_serial_tree.rb_node;689while (n) {690key = rb_entry(n, struct key, serial_node);691692if (id < key->serial)693n = n->rb_left;694else if (id > key->serial)695n = n->rb_right;696else697goto found;698}699700not_found:701key = ERR_PTR(-ENOKEY);702goto error;703704found:705/* pretend it doesn't exist if it is awaiting deletion */706if (atomic_read(&key->usage) == 0)707goto not_found;708709/* this races with key_put(), but that doesn't matter since key_put()710* doesn't actually change the key711*/712atomic_inc(&key->usage);713714error:715spin_unlock(&key_serial_lock);716return key;717}718719/*720* Find and lock the specified key type against removal.721*722* We return with the sem read-locked if successful. If the type wasn't723* available -ENOKEY is returned instead.724*/725struct key_type *key_type_lookup(const char *type)726{727struct key_type *ktype;728729down_read(&key_types_sem);730731/* look up the key type to see if it's one of the registered kernel732* types */733list_for_each_entry(ktype, &key_types_list, link) {734if (strcmp(ktype->name, type) == 0)735goto found_kernel_type;736}737738up_read(&key_types_sem);739ktype = ERR_PTR(-ENOKEY);740741found_kernel_type:742return ktype;743}744745/*746* Unlock a key type locked by key_type_lookup().747*/748void key_type_put(struct key_type *ktype)749{750up_read(&key_types_sem);751}752753/*754* Attempt to update an existing key.755*756* The key is given to us with an incremented refcount that we need to discard757* if we get an error.758*/759static inline key_ref_t __key_update(key_ref_t key_ref,760const void *payload, size_t plen)761{762struct key *key = key_ref_to_ptr(key_ref);763int ret;764765/* need write permission on the key to update it */766ret = key_permission(key_ref, KEY_WRITE);767if (ret < 0)768goto error;769770ret = -EEXIST;771if (!key->type->update)772goto error;773774down_write(&key->sem);775776ret = key->type->update(key, payload, plen);777if (ret == 0)778/* updating a negative key instantiates it */779clear_bit(KEY_FLAG_NEGATIVE, &key->flags);780781up_write(&key->sem);782783if (ret < 0)784goto error;785out:786return key_ref;787788error:789key_put(key);790key_ref = ERR_PTR(ret);791goto out;792}793794/**795* key_create_or_update - Update or create and instantiate a key.796* @keyring_ref: A pointer to the destination keyring with possession flag.797* @type: The type of key.798* @description: The searchable description for the key.799* @payload: The data to use to instantiate or update the key.800* @plen: The length of @payload.801* @perm: The permissions mask for a new key.802* @flags: The quota flags for a new key.803*804* Search the destination keyring for a key of the same description and if one805* is found, update it, otherwise create and instantiate a new one and create a806* link to it from that keyring.807*808* If perm is KEY_PERM_UNDEF then an appropriate key permissions mask will be809* concocted.810*811* Returns a pointer to the new key if successful, -ENODEV if the key type812* wasn't available, -ENOTDIR if the keyring wasn't a keyring, -EACCES if the813* caller isn't permitted to modify the keyring or the LSM did not permit814* creation of the key.815*816* On success, the possession flag from the keyring ref will be tacked on to817* the key ref before it is returned.818*/819key_ref_t key_create_or_update(key_ref_t keyring_ref,820const char *type,821const char *description,822const void *payload,823size_t plen,824key_perm_t perm,825unsigned long flags)826{827unsigned long prealloc;828const struct cred *cred = current_cred();829struct key_type *ktype;830struct key *keyring, *key = NULL;831key_ref_t key_ref;832int ret;833834/* look up the key type to see if it's one of the registered kernel835* types */836ktype = key_type_lookup(type);837if (IS_ERR(ktype)) {838key_ref = ERR_PTR(-ENODEV);839goto error;840}841842key_ref = ERR_PTR(-EINVAL);843if (!ktype->match || !ktype->instantiate)844goto error_2;845846keyring = key_ref_to_ptr(keyring_ref);847848key_check(keyring);849850key_ref = ERR_PTR(-ENOTDIR);851if (keyring->type != &key_type_keyring)852goto error_2;853854ret = __key_link_begin(keyring, ktype, description, &prealloc);855if (ret < 0)856goto error_2;857858/* if we're going to allocate a new key, we're going to have859* to modify the keyring */860ret = key_permission(keyring_ref, KEY_WRITE);861if (ret < 0) {862key_ref = ERR_PTR(ret);863goto error_3;864}865866/* if it's possible to update this type of key, search for an existing867* key of the same type and description in the destination keyring and868* update that instead if possible869*/870if (ktype->update) {871key_ref = __keyring_search_one(keyring_ref, ktype, description,8720);873if (!IS_ERR(key_ref))874goto found_matching_key;875}876877/* if the client doesn't provide, decide on the permissions we want */878if (perm == KEY_PERM_UNDEF) {879perm = KEY_POS_VIEW | KEY_POS_SEARCH | KEY_POS_LINK | KEY_POS_SETATTR;880perm |= KEY_USR_VIEW | KEY_USR_SEARCH | KEY_USR_LINK | KEY_USR_SETATTR;881882if (ktype->read)883perm |= KEY_POS_READ | KEY_USR_READ;884885if (ktype == &key_type_keyring || ktype->update)886perm |= KEY_USR_WRITE;887}888889/* allocate a new key */890key = key_alloc(ktype, description, cred->fsuid, cred->fsgid, cred,891perm, flags);892if (IS_ERR(key)) {893key_ref = ERR_CAST(key);894goto error_3;895}896897/* instantiate it and link it into the target keyring */898ret = __key_instantiate_and_link(key, payload, plen, keyring, NULL,899&prealloc);900if (ret < 0) {901key_put(key);902key_ref = ERR_PTR(ret);903goto error_3;904}905906key_ref = make_key_ref(key, is_key_possessed(keyring_ref));907908error_3:909__key_link_end(keyring, ktype, prealloc);910error_2:911key_type_put(ktype);912error:913return key_ref;914915found_matching_key:916/* we found a matching key, so we're going to try to update it917* - we can drop the locks first as we have the key pinned918*/919__key_link_end(keyring, ktype, prealloc);920key_type_put(ktype);921922key_ref = __key_update(key_ref, payload, plen);923goto error;924}925EXPORT_SYMBOL(key_create_or_update);926927/**928* key_update - Update a key's contents.929* @key_ref: The pointer (plus possession flag) to the key.930* @payload: The data to be used to update the key.931* @plen: The length of @payload.932*933* Attempt to update the contents of a key with the given payload data. The934* caller must be granted Write permission on the key. Negative keys can be935* instantiated by this method.936*937* Returns 0 on success, -EACCES if not permitted and -EOPNOTSUPP if the key938* type does not support updating. The key type may return other errors.939*/940int key_update(key_ref_t key_ref, const void *payload, size_t plen)941{942struct key *key = key_ref_to_ptr(key_ref);943int ret;944945key_check(key);946947/* the key must be writable */948ret = key_permission(key_ref, KEY_WRITE);949if (ret < 0)950goto error;951952/* attempt to update it if supported */953ret = -EOPNOTSUPP;954if (key->type->update) {955down_write(&key->sem);956957ret = key->type->update(key, payload, plen);958if (ret == 0)959/* updating a negative key instantiates it */960clear_bit(KEY_FLAG_NEGATIVE, &key->flags);961962up_write(&key->sem);963}964965error:966return ret;967}968EXPORT_SYMBOL(key_update);969970/**971* key_revoke - Revoke a key.972* @key: The key to be revoked.973*974* Mark a key as being revoked and ask the type to free up its resources. The975* revocation timeout is set and the key and all its links will be976* automatically garbage collected after key_gc_delay amount of time if they977* are not manually dealt with first.978*/979void key_revoke(struct key *key)980{981struct timespec now;982time_t time;983984key_check(key);985986/* make sure no one's trying to change or use the key when we mark it987* - we tell lockdep that we might nest because we might be revoking an988* authorisation key whilst holding the sem on a key we've just989* instantiated990*/991down_write_nested(&key->sem, 1);992if (!test_and_set_bit(KEY_FLAG_REVOKED, &key->flags) &&993key->type->revoke)994key->type->revoke(key);995996/* set the death time to no more than the expiry time */997now = current_kernel_time();998time = now.tv_sec;999if (key->revoked_at == 0 || key->revoked_at > time) {1000key->revoked_at = time;1001key_schedule_gc(key->revoked_at + key_gc_delay);1002}10031004up_write(&key->sem);1005}1006EXPORT_SYMBOL(key_revoke);10071008/**1009* register_key_type - Register a type of key.1010* @ktype: The new key type.1011*1012* Register a new key type.1013*1014* Returns 0 on success or -EEXIST if a type of this name already exists.1015*/1016int register_key_type(struct key_type *ktype)1017{1018struct key_type *p;1019int ret;10201021ret = -EEXIST;1022down_write(&key_types_sem);10231024/* disallow key types with the same name */1025list_for_each_entry(p, &key_types_list, link) {1026if (strcmp(p->name, ktype->name) == 0)1027goto out;1028}10291030/* store the type */1031list_add(&ktype->link, &key_types_list);1032ret = 0;10331034out:1035up_write(&key_types_sem);1036return ret;1037}1038EXPORT_SYMBOL(register_key_type);10391040/**1041* unregister_key_type - Unregister a type of key.1042* @ktype: The key type.1043*1044* Unregister a key type and mark all the extant keys of this type as dead.1045* Those keys of this type are then destroyed to get rid of their payloads and1046* they and their links will be garbage collected as soon as possible.1047*/1048void unregister_key_type(struct key_type *ktype)1049{1050struct rb_node *_n;1051struct key *key;10521053down_write(&key_types_sem);10541055/* withdraw the key type */1056list_del_init(&ktype->link);10571058/* mark all the keys of this type dead */1059spin_lock(&key_serial_lock);10601061for (_n = rb_first(&key_serial_tree); _n; _n = rb_next(_n)) {1062key = rb_entry(_n, struct key, serial_node);10631064if (key->type == ktype) {1065key->type = &key_type_dead;1066set_bit(KEY_FLAG_DEAD, &key->flags);1067}1068}10691070spin_unlock(&key_serial_lock);10711072/* make sure everyone revalidates their keys */1073synchronize_rcu();10741075/* we should now be able to destroy the payloads of all the keys of1076* this type with impunity */1077spin_lock(&key_serial_lock);10781079for (_n = rb_first(&key_serial_tree); _n; _n = rb_next(_n)) {1080key = rb_entry(_n, struct key, serial_node);10811082if (key->type == ktype) {1083if (ktype->destroy)1084ktype->destroy(key);1085memset(&key->payload, KEY_DESTROY, sizeof(key->payload));1086}1087}10881089spin_unlock(&key_serial_lock);1090up_write(&key_types_sem);10911092key_schedule_gc(0);1093}1094EXPORT_SYMBOL(unregister_key_type);10951096/*1097* Initialise the key management state.1098*/1099void __init key_init(void)1100{1101/* allocate a slab in which we can store keys */1102key_jar = kmem_cache_create("key_jar", sizeof(struct key),11030, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL);11041105/* add the special key types */1106list_add_tail(&key_type_keyring.link, &key_types_list);1107list_add_tail(&key_type_dead.link, &key_types_list);1108list_add_tail(&key_type_user.link, &key_types_list);11091110/* record the root user tracking */1111rb_link_node(&root_key_user.node,1112NULL,1113&key_user_tree.rb_node);11141115rb_insert_color(&root_key_user.node,1116&key_user_tree);1117}111811191120