/* Key permission checking1*2* Copyright (C) 2005 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/security.h>13#include "internal.h"1415/**16* key_task_permission - Check a key can be used17* @key_ref: The key to check.18* @cred: The credentials to use.19* @perm: The permissions to check for.20*21* Check to see whether permission is granted to use a key in the desired way,22* but permit the security modules to override.23*24* The caller must hold either a ref on cred or must hold the RCU readlock.25*26* Returns 0 if successful, -EACCES if access is denied based on the27* permissions bits or the LSM check.28*/29int key_task_permission(const key_ref_t key_ref, const struct cred *cred,30key_perm_t perm)31{32struct key *key;33key_perm_t kperm;34int ret;3536key = key_ref_to_ptr(key_ref);3738if (key->user->user_ns != cred->user->user_ns)39goto use_other_perms;4041/* use the second 8-bits of permissions for keys the caller owns */42if (key->uid == cred->fsuid) {43kperm = key->perm >> 16;44goto use_these_perms;45}4647/* use the third 8-bits of permissions for keys the caller has a group48* membership in common with */49if (key->gid != -1 && key->perm & KEY_GRP_ALL) {50if (key->gid == cred->fsgid) {51kperm = key->perm >> 8;52goto use_these_perms;53}5455ret = groups_search(cred->group_info, key->gid);56if (ret) {57kperm = key->perm >> 8;58goto use_these_perms;59}60}6162use_other_perms:6364/* otherwise use the least-significant 8-bits */65kperm = key->perm;6667use_these_perms:6869/* use the top 8-bits of permissions for keys the caller possesses70* - possessor permissions are additive with other permissions71*/72if (is_key_possessed(key_ref))73kperm |= key->perm >> 24;7475kperm = kperm & perm & KEY_ALL;7677if (kperm != perm)78return -EACCES;7980/* let LSM be the final arbiter */81return security_key_permission(key_ref, cred, perm);82}83EXPORT_SYMBOL(key_task_permission);8485/**86* key_validate - Validate a key.87* @key: The key to be validated.88*89* Check that a key is valid, returning 0 if the key is okay, -EKEYREVOKED if90* the key's type has been removed or if the key has been revoked or91* -EKEYEXPIRED if the key has expired.92*/93int key_validate(struct key *key)94{95struct timespec now;96int ret = 0;9798if (key) {99/* check it's still accessible */100ret = -EKEYREVOKED;101if (test_bit(KEY_FLAG_REVOKED, &key->flags) ||102test_bit(KEY_FLAG_DEAD, &key->flags))103goto error;104105/* check it hasn't expired */106ret = 0;107if (key->expiry) {108now = current_kernel_time();109if (now.tv_sec >= key->expiry)110ret = -EKEYEXPIRED;111}112}113114error:115return ret;116}117EXPORT_SYMBOL(key_validate);118119120