linux/security/keys/encrypted-keys/encrypted.c
<<
>>
Prefs
   1/*
   2 * Copyright (C) 2010 IBM Corporation
   3 * Copyright (C) 2010 Politecnico di Torino, Italy
   4 *                    TORSEC group -- http://security.polito.it
   5 *
   6 * Authors:
   7 * Mimi Zohar <zohar@us.ibm.com>
   8 * Roberto Sassu <roberto.sassu@polito.it>
   9 *
  10 * This program is free software; you can redistribute it and/or modify
  11 * it under the terms of the GNU General Public License as published by
  12 * the Free Software Foundation, version 2 of the License.
  13 *
  14 * See Documentation/security/keys-trusted-encrypted.txt
  15 */
  16
  17#include <linux/uaccess.h>
  18#include <linux/module.h>
  19#include <linux/init.h>
  20#include <linux/slab.h>
  21#include <linux/parser.h>
  22#include <linux/string.h>
  23#include <linux/err.h>
  24#include <keys/user-type.h>
  25#include <keys/trusted-type.h>
  26#include <keys/encrypted-type.h>
  27#include <linux/key-type.h>
  28#include <linux/random.h>
  29#include <linux/rcupdate.h>
  30#include <linux/scatterlist.h>
  31#include <linux/crypto.h>
  32#include <linux/ctype.h>
  33#include <crypto/algapi.h>
  34#include <crypto/hash.h>
  35#include <crypto/sha.h>
  36#include <crypto/aes.h>
  37
  38#include "encrypted.h"
  39#include "ecryptfs_format.h"
  40
  41static const char KEY_TRUSTED_PREFIX[] = "trusted:";
  42static const char KEY_USER_PREFIX[] = "user:";
  43static const char hash_alg[] = "sha256";
  44static const char hmac_alg[] = "hmac(sha256)";
  45static const char blkcipher_alg[] = "cbc(aes)";
  46static const char key_format_default[] = "default";
  47static const char key_format_ecryptfs[] = "ecryptfs";
  48static const char key_format_enc32[] = "enc32";
  49static unsigned int ivsize;
  50static int blksize;
  51
  52#define KEY_TRUSTED_PREFIX_LEN (sizeof (KEY_TRUSTED_PREFIX) - 1)
  53#define KEY_USER_PREFIX_LEN (sizeof (KEY_USER_PREFIX) - 1)
  54#define KEY_ECRYPTFS_DESC_LEN 16
  55#define HASH_SIZE SHA256_DIGEST_SIZE
  56#define MAX_DATA_SIZE 4096
  57#define MIN_DATA_SIZE  20
  58#define KEY_ENC32_PAYLOAD_LEN 32
  59
  60static struct crypto_shash *hash_tfm;
  61
  62enum {
  63        Opt_err = -1, Opt_new, Opt_load, Opt_update
  64};
  65
  66enum {
  67        Opt_error = -1, Opt_default, Opt_ecryptfs, Opt_enc32
  68};
  69
  70static const match_table_t key_format_tokens = {
  71        {Opt_default, "default"},
  72        {Opt_ecryptfs, "ecryptfs"},
  73        {Opt_enc32, "enc32"},
  74        {Opt_error, NULL}
  75};
  76
  77static const match_table_t key_tokens = {
  78        {Opt_new, "new"},
  79        {Opt_load, "load"},
  80        {Opt_update, "update"},
  81        {Opt_err, NULL}
  82};
  83
  84static int aes_get_sizes(void)
  85{
  86        struct crypto_blkcipher *tfm;
  87
  88        tfm = crypto_alloc_blkcipher(blkcipher_alg, 0, CRYPTO_ALG_ASYNC);
  89        if (IS_ERR(tfm)) {
  90                pr_err("encrypted_key: failed to alloc_cipher (%ld)\n",
  91                       PTR_ERR(tfm));
  92                return PTR_ERR(tfm);
  93        }
  94        ivsize = crypto_blkcipher_ivsize(tfm);
  95        blksize = crypto_blkcipher_blocksize(tfm);
  96        crypto_free_blkcipher(tfm);
  97        return 0;
  98}
  99
 100/*
 101 * valid_ecryptfs_desc - verify the description of a new/loaded encrypted key
 102 *
 103 * The description of a encrypted key with format 'ecryptfs' must contain
 104 * exactly 16 hexadecimal characters.
 105 *
 106 */
 107static int valid_ecryptfs_desc(const char *ecryptfs_desc)
 108{
 109        int i;
 110
 111        if (strlen(ecryptfs_desc) != KEY_ECRYPTFS_DESC_LEN) {
 112                pr_err("encrypted_key: key description must be %d hexadecimal "
 113                       "characters long\n", KEY_ECRYPTFS_DESC_LEN);
 114                return -EINVAL;
 115        }
 116
 117        for (i = 0; i < KEY_ECRYPTFS_DESC_LEN; i++) {
 118                if (!isxdigit(ecryptfs_desc[i])) {
 119                        pr_err("encrypted_key: key description must contain "
 120                               "only hexadecimal characters\n");
 121                        return -EINVAL;
 122                }
 123        }
 124
 125        return 0;
 126}
 127
 128/*
 129 * valid_master_desc - verify the 'key-type:desc' of a new/updated master-key
 130 *
 131 * key-type:= "trusted:" | "user:"
 132 * desc:= master-key description
 133 *
 134 * Verify that 'key-type' is valid and that 'desc' exists. On key update,
 135 * only the master key description is permitted to change, not the key-type.
 136 * The key-type remains constant.
 137 *
 138 * On success returns 0, otherwise -EINVAL.
 139 */
 140static int valid_master_desc(const char *new_desc, const char *orig_desc)
 141{
 142        int prefix_len;
 143
 144        if (!strncmp(new_desc, KEY_TRUSTED_PREFIX, KEY_TRUSTED_PREFIX_LEN))
 145                prefix_len = KEY_TRUSTED_PREFIX_LEN;
 146        else if (!strncmp(new_desc, KEY_USER_PREFIX, KEY_USER_PREFIX_LEN))
 147                prefix_len = KEY_USER_PREFIX_LEN;
 148        else
 149                return -EINVAL;
 150
 151        if (!new_desc[prefix_len])
 152                return -EINVAL;
 153
 154        if (orig_desc && strncmp(new_desc, orig_desc, prefix_len))
 155                return -EINVAL;
 156
 157        return 0;
 158}
 159
 160/*
 161 * datablob_parse - parse the keyctl data
 162 *
 163 * datablob format:
 164 * new [<format>] <master-key name> <decrypted data length>
 165 * load [<format>] <master-key name> <decrypted data length>
 166 *     <encrypted iv + data>
 167 * update <new-master-key name>
 168 *
 169 * Tokenizes a copy of the keyctl data, returning a pointer to each token,
 170 * which is null terminated.
 171 *
 172 * On success returns 0, otherwise -EINVAL.
 173 */
 174static int datablob_parse(char *datablob, const char **format,
 175                          char **master_desc, char **decrypted_datalen,
 176                          char **hex_encoded_iv)
 177{
 178        substring_t args[MAX_OPT_ARGS];
 179        int ret = -EINVAL;
 180        int key_cmd;
 181        int key_format;
 182        char *p, *keyword;
 183
 184        keyword = strsep(&datablob, " \t");
 185        if (!keyword) {
 186                pr_info("encrypted_key: insufficient parameters specified\n");
 187                return ret;
 188        }
 189        key_cmd = match_token(keyword, key_tokens, args);
 190
 191        /* Get optional format: default | ecryptfs */
 192        p = strsep(&datablob, " \t");
 193        if (!p) {
 194                pr_err("encrypted_key: insufficient parameters specified\n");
 195                return ret;
 196        }
 197
 198        key_format = match_token(p, key_format_tokens, args);
 199        switch (key_format) {
 200        case Opt_ecryptfs:
 201        case Opt_enc32:
 202        case Opt_default:
 203                *format = p;
 204                *master_desc = strsep(&datablob, " \t");
 205                break;
 206        case Opt_error:
 207                *master_desc = p;
 208                break;
 209        }
 210
 211        if (!*master_desc) {
 212                pr_info("encrypted_key: master key parameter is missing\n");
 213                goto out;
 214        }
 215
 216        if (valid_master_desc(*master_desc, NULL) < 0) {
 217                pr_info("encrypted_key: master key parameter \'%s\' "
 218                        "is invalid\n", *master_desc);
 219                goto out;
 220        }
 221
 222        if (decrypted_datalen) {
 223                *decrypted_datalen = strsep(&datablob, " \t");
 224                if (!*decrypted_datalen) {
 225                        pr_info("encrypted_key: keylen parameter is missing\n");
 226                        goto out;
 227                }
 228        }
 229
 230        switch (key_cmd) {
 231        case Opt_new:
 232                if (!decrypted_datalen) {
 233                        pr_info("encrypted_key: keyword \'%s\' not allowed "
 234                                "when called from .update method\n", keyword);
 235                        break;
 236                }
 237                ret = 0;
 238                break;
 239        case Opt_load:
 240                if (!decrypted_datalen) {
 241                        pr_info("encrypted_key: keyword \'%s\' not allowed "
 242                                "when called from .update method\n", keyword);
 243                        break;
 244                }
 245                *hex_encoded_iv = strsep(&datablob, " \t");
 246                if (!*hex_encoded_iv) {
 247                        pr_info("encrypted_key: hex blob is missing\n");
 248                        break;
 249                }
 250                ret = 0;
 251                break;
 252        case Opt_update:
 253                if (decrypted_datalen) {
 254                        pr_info("encrypted_key: keyword \'%s\' not allowed "
 255                                "when called from .instantiate method\n",
 256                                keyword);
 257                        break;
 258                }
 259                ret = 0;
 260                break;
 261        case Opt_err:
 262                pr_info("encrypted_key: keyword \'%s\' not recognized\n",
 263                        keyword);
 264                break;
 265        }
 266out:
 267        return ret;
 268}
 269
 270/*
 271 * datablob_format - format as an ascii string, before copying to userspace
 272 */
 273static char *datablob_format(struct encrypted_key_payload *epayload,
 274                             size_t asciiblob_len)
 275{
 276        char *ascii_buf, *bufp;
 277        u8 *iv = epayload->iv;
 278        int len;
 279        int i;
 280
 281        ascii_buf = kmalloc(asciiblob_len + 1, GFP_KERNEL);
 282        if (!ascii_buf)
 283                goto out;
 284
 285        ascii_buf[asciiblob_len] = '\0';
 286
 287        /* copy datablob master_desc and datalen strings */
 288        len = sprintf(ascii_buf, "%s %s %s ", epayload->format,
 289                      epayload->master_desc, epayload->datalen);
 290
 291        /* convert the hex encoded iv, encrypted-data and HMAC to ascii */
 292        bufp = &ascii_buf[len];
 293        for (i = 0; i < (asciiblob_len - len) / 2; i++)
 294                bufp = hex_byte_pack(bufp, iv[i]);
 295out:
 296        return ascii_buf;
 297}
 298
 299/*
 300 * request_user_key - request the user key
 301 *
 302 * Use a user provided key to encrypt/decrypt an encrypted-key.
 303 */
 304static struct key *request_user_key(const char *master_desc, u8 **master_key,
 305                                    size_t *master_keylen)
 306{
 307        struct user_key_payload *upayload;
 308        struct key *ukey;
 309
 310        ukey = request_key(&key_type_user, master_desc, NULL);
 311        if (IS_ERR(ukey))
 312                goto error;
 313
 314        down_read(&ukey->sem);
 315        upayload = user_key_payload_locked(ukey);
 316        if (!upayload) {
 317                /* key was revoked before we acquired its semaphore */
 318                up_read(&ukey->sem);
 319                key_put(ukey);
 320                ukey = ERR_PTR(-EKEYREVOKED);
 321                goto error;
 322        }
 323        *master_key = upayload->data;
 324        *master_keylen = upayload->datalen;
 325error:
 326        return ukey;
 327}
 328
 329static int calc_hash(struct crypto_shash *tfm, u8 *digest,
 330                     const u8 *buf, unsigned int buflen)
 331{
 332        SHASH_DESC_ON_STACK(desc, tfm);
 333        int err;
 334
 335        desc->tfm = tfm;
 336        desc->flags = 0;
 337
 338        err = crypto_shash_digest(desc, buf, buflen, digest);
 339        shash_desc_zero(desc);
 340        return err;
 341}
 342
 343static int calc_hmac(u8 *digest, const u8 *key, unsigned int keylen,
 344                     const u8 *buf, unsigned int buflen)
 345{
 346        struct crypto_shash *tfm;
 347        int err;
 348
 349        tfm = crypto_alloc_shash(hmac_alg, 0, CRYPTO_ALG_ASYNC);
 350        if (IS_ERR(tfm)) {
 351                pr_err("encrypted_key: can't alloc %s transform: %ld\n",
 352                       hmac_alg, PTR_ERR(tfm));
 353                return PTR_ERR(tfm);
 354        }
 355
 356        err = crypto_shash_setkey(tfm, key, keylen);
 357        if (!err)
 358                err = calc_hash(tfm, digest, buf, buflen);
 359        crypto_free_shash(tfm);
 360        return err;
 361}
 362
 363enum derived_key_type { ENC_KEY, AUTH_KEY };
 364
 365/* Derive authentication/encryption key from trusted key */
 366static int get_derived_key(u8 *derived_key, enum derived_key_type key_type,
 367                           const u8 *master_key, size_t master_keylen)
 368{
 369        u8 *derived_buf;
 370        unsigned int derived_buf_len;
 371        int ret;
 372
 373        derived_buf_len = strlen("AUTH_KEY") + 1 + master_keylen;
 374        if (derived_buf_len < HASH_SIZE)
 375                derived_buf_len = HASH_SIZE;
 376
 377        derived_buf = kzalloc(derived_buf_len, GFP_KERNEL);
 378        if (!derived_buf)
 379                return -ENOMEM;
 380
 381        if (key_type)
 382                strcpy(derived_buf, "AUTH_KEY");
 383        else
 384                strcpy(derived_buf, "ENC_KEY");
 385
 386        memcpy(derived_buf + strlen(derived_buf) + 1, master_key,
 387               master_keylen);
 388        ret = calc_hash(hash_tfm, derived_key, derived_buf, derived_buf_len);
 389        kzfree(derived_buf);
 390        return ret;
 391}
 392
 393static int init_blkcipher_desc(struct blkcipher_desc *desc, const u8 *key,
 394                               unsigned int key_len, const u8 *iv,
 395                               unsigned int ivsize)
 396{
 397        int ret;
 398
 399        desc->tfm = crypto_alloc_blkcipher(blkcipher_alg, 0, CRYPTO_ALG_ASYNC);
 400        if (IS_ERR(desc->tfm)) {
 401                pr_err("encrypted_key: failed to load %s transform (%ld)\n",
 402                       blkcipher_alg, PTR_ERR(desc->tfm));
 403                return PTR_ERR(desc->tfm);
 404        }
 405        desc->flags = 0;
 406
 407        ret = crypto_blkcipher_setkey(desc->tfm, key, key_len);
 408        if (ret < 0) {
 409                pr_err("encrypted_key: failed to setkey (%d)\n", ret);
 410                crypto_free_blkcipher(desc->tfm);
 411                return ret;
 412        }
 413        crypto_blkcipher_set_iv(desc->tfm, iv, ivsize);
 414        return 0;
 415}
 416
 417static struct key *request_master_key(struct encrypted_key_payload *epayload,
 418                                      u8 **master_key, size_t *master_keylen)
 419{
 420        struct key *mkey = ERR_PTR(-EINVAL);
 421
 422        if (!strncmp(epayload->master_desc, KEY_TRUSTED_PREFIX,
 423                     KEY_TRUSTED_PREFIX_LEN)) {
 424                mkey = request_trusted_key(epayload->master_desc +
 425                                           KEY_TRUSTED_PREFIX_LEN,
 426                                           master_key, master_keylen);
 427        } else if (!strncmp(epayload->master_desc, KEY_USER_PREFIX,
 428                            KEY_USER_PREFIX_LEN)) {
 429                mkey = request_user_key(epayload->master_desc +
 430                                        KEY_USER_PREFIX_LEN,
 431                                        master_key, master_keylen);
 432        } else
 433                goto out;
 434
 435        if (IS_ERR(mkey)) {
 436                int ret = PTR_ERR(mkey);
 437
 438                if (ret == -ENOTSUPP)
 439                        pr_info("encrypted_key: key %s not supported",
 440                                epayload->master_desc);
 441                else
 442                        pr_info("encrypted_key: key %s not found",
 443                                epayload->master_desc);
 444                goto out;
 445        }
 446
 447        dump_master_key(*master_key, *master_keylen);
 448out:
 449        return mkey;
 450}
 451
 452/* Before returning data to userspace, encrypt decrypted data. */
 453static int derived_key_encrypt(struct encrypted_key_payload *epayload,
 454                               const u8 *derived_key,
 455                               unsigned int derived_keylen)
 456{
 457        struct scatterlist sg_in[2];
 458        struct scatterlist sg_out[1];
 459        struct blkcipher_desc desc;
 460        unsigned int encrypted_datalen;
 461        unsigned int padlen;
 462        char pad[16];
 463        int ret;
 464
 465        encrypted_datalen = roundup(epayload->decrypted_datalen, blksize);
 466        padlen = encrypted_datalen - epayload->decrypted_datalen;
 467
 468        ret = init_blkcipher_desc(&desc, derived_key, derived_keylen,
 469                                  epayload->iv, ivsize);
 470        if (ret < 0)
 471                goto out;
 472        dump_decrypted_data(epayload);
 473
 474        memset(pad, 0, sizeof pad);
 475        sg_init_table(sg_in, 2);
 476        sg_set_buf(&sg_in[0], epayload->decrypted_data,
 477                   epayload->decrypted_datalen);
 478        sg_set_buf(&sg_in[1], pad, padlen);
 479
 480        sg_init_table(sg_out, 1);
 481        sg_set_buf(sg_out, epayload->encrypted_data, encrypted_datalen);
 482
 483        ret = crypto_blkcipher_encrypt(&desc, sg_out, sg_in, encrypted_datalen);
 484        crypto_free_blkcipher(desc.tfm);
 485        if (ret < 0)
 486                pr_err("encrypted_key: failed to encrypt (%d)\n", ret);
 487        else
 488                dump_encrypted_data(epayload, encrypted_datalen);
 489out:
 490        return ret;
 491}
 492
 493static int datablob_hmac_append(struct encrypted_key_payload *epayload,
 494                                const u8 *master_key, size_t master_keylen)
 495{
 496        u8 derived_key[HASH_SIZE];
 497        u8 *digest;
 498        int ret;
 499
 500        ret = get_derived_key(derived_key, AUTH_KEY, master_key, master_keylen);
 501        if (ret < 0)
 502                goto out;
 503
 504        digest = epayload->format + epayload->datablob_len;
 505        ret = calc_hmac(digest, derived_key, sizeof derived_key,
 506                        epayload->format, epayload->datablob_len);
 507        if (!ret)
 508                dump_hmac(NULL, digest, HASH_SIZE);
 509out:
 510        memzero_explicit(derived_key, sizeof(derived_key));
 511        return ret;
 512}
 513
 514/* verify HMAC before decrypting encrypted key */
 515static int datablob_hmac_verify(struct encrypted_key_payload *epayload,
 516                                const u8 *format, const u8 *master_key,
 517                                size_t master_keylen)
 518{
 519        u8 derived_key[HASH_SIZE];
 520        u8 digest[HASH_SIZE];
 521        int ret;
 522        char *p;
 523        unsigned short len;
 524
 525        ret = get_derived_key(derived_key, AUTH_KEY, master_key, master_keylen);
 526        if (ret < 0)
 527                goto out;
 528
 529        len = epayload->datablob_len;
 530        if (!format) {
 531                p = epayload->master_desc;
 532                len -= strlen(epayload->format) + 1;
 533        } else
 534                p = epayload->format;
 535
 536        ret = calc_hmac(digest, derived_key, sizeof derived_key, p, len);
 537        if (ret < 0)
 538                goto out;
 539        ret = crypto_memneq(digest, epayload->format + epayload->datablob_len,
 540                            sizeof(digest));
 541        if (ret) {
 542                ret = -EINVAL;
 543                dump_hmac("datablob",
 544                          epayload->format + epayload->datablob_len,
 545                          HASH_SIZE);
 546                dump_hmac("calc", digest, HASH_SIZE);
 547        }
 548out:
 549        memzero_explicit(derived_key, sizeof(derived_key));
 550        return ret;
 551}
 552
 553static int derived_key_decrypt(struct encrypted_key_payload *epayload,
 554                               const u8 *derived_key,
 555                               unsigned int derived_keylen)
 556{
 557        struct scatterlist sg_in[1];
 558        struct scatterlist sg_out[2];
 559        struct blkcipher_desc desc;
 560        unsigned int encrypted_datalen;
 561        char pad[16];
 562        int ret;
 563
 564        encrypted_datalen = roundup(epayload->decrypted_datalen, blksize);
 565        ret = init_blkcipher_desc(&desc, derived_key, derived_keylen,
 566                                  epayload->iv, ivsize);
 567        if (ret < 0)
 568                goto out;
 569        dump_encrypted_data(epayload, encrypted_datalen);
 570
 571        memset(pad, 0, sizeof pad);
 572        sg_init_table(sg_in, 1);
 573        sg_init_table(sg_out, 2);
 574        sg_set_buf(sg_in, epayload->encrypted_data, encrypted_datalen);
 575        sg_set_buf(&sg_out[0], epayload->decrypted_data,
 576                   epayload->decrypted_datalen);
 577        sg_set_buf(&sg_out[1], pad, sizeof pad);
 578
 579        ret = crypto_blkcipher_decrypt(&desc, sg_out, sg_in, encrypted_datalen);
 580        crypto_free_blkcipher(desc.tfm);
 581        if (ret < 0)
 582                goto out;
 583        dump_decrypted_data(epayload);
 584out:
 585        return ret;
 586}
 587
 588/* Allocate memory for decrypted key and datablob. */
 589static struct encrypted_key_payload *encrypted_key_alloc(struct key *key,
 590                                                         const char *format,
 591                                                         const char *master_desc,
 592                                                         const char *datalen)
 593{
 594        struct encrypted_key_payload *epayload = NULL;
 595        unsigned short datablob_len;
 596        unsigned short decrypted_datalen;
 597        unsigned short payload_datalen;
 598        unsigned int encrypted_datalen;
 599        unsigned int format_len;
 600        long dlen;
 601        int ret;
 602
 603        ret = strict_strtol(datalen, 10, &dlen);
 604        if (ret < 0 || dlen < MIN_DATA_SIZE || dlen > MAX_DATA_SIZE)
 605                return ERR_PTR(-EINVAL);
 606
 607        format_len = (!format) ? strlen(key_format_default) : strlen(format);
 608        decrypted_datalen = dlen;
 609        payload_datalen = decrypted_datalen;
 610        if (format) {
 611                if (!strcmp(format, key_format_ecryptfs)) {
 612                        if (dlen != ECRYPTFS_MAX_KEY_BYTES) {
 613                                pr_err("encrypted_key: keylen for the ecryptfs format must be equal to %d bytes\n",
 614                                        ECRYPTFS_MAX_KEY_BYTES);
 615                                return ERR_PTR(-EINVAL);
 616                        }
 617                        decrypted_datalen = ECRYPTFS_MAX_KEY_BYTES;
 618                        payload_datalen = sizeof(struct ecryptfs_auth_tok);
 619                } else if (!strcmp(format, key_format_enc32)) {
 620                        if (decrypted_datalen != KEY_ENC32_PAYLOAD_LEN) {
 621                                pr_err("encrypted_key: enc32 key payload incorrect length: %d\n",
 622                                                decrypted_datalen);
 623                                return ERR_PTR(-EINVAL);
 624                        }
 625                }
 626        }
 627
 628        encrypted_datalen = roundup(decrypted_datalen, blksize);
 629
 630        datablob_len = format_len + 1 + strlen(master_desc) + 1
 631            + strlen(datalen) + 1 + ivsize + 1 + encrypted_datalen;
 632
 633        ret = key_payload_reserve(key, payload_datalen + datablob_len
 634                                  + HASH_SIZE + 1);
 635        if (ret < 0)
 636                return ERR_PTR(ret);
 637
 638        epayload = kzalloc(sizeof(*epayload) + payload_datalen +
 639                           datablob_len + HASH_SIZE + 1, GFP_KERNEL);
 640        if (!epayload)
 641                return ERR_PTR(-ENOMEM);
 642
 643        epayload->payload_datalen = payload_datalen;
 644        epayload->decrypted_datalen = decrypted_datalen;
 645        epayload->datablob_len = datablob_len;
 646        return epayload;
 647}
 648
 649static int encrypted_key_decrypt(struct encrypted_key_payload *epayload,
 650                                 const char *format, const char *hex_encoded_iv)
 651{
 652        struct key *mkey;
 653        u8 derived_key[HASH_SIZE];
 654        u8 *master_key;
 655        u8 *hmac;
 656        const char *hex_encoded_data;
 657        unsigned int encrypted_datalen;
 658        size_t master_keylen;
 659        size_t asciilen;
 660        int ret;
 661
 662        encrypted_datalen = roundup(epayload->decrypted_datalen, blksize);
 663        asciilen = (ivsize + 1 + encrypted_datalen + HASH_SIZE) * 2;
 664        if (strlen(hex_encoded_iv) != asciilen)
 665                return -EINVAL;
 666
 667        hex_encoded_data = hex_encoded_iv + (2 * ivsize) + 2;
 668        ret = hex2bin(epayload->iv, hex_encoded_iv, ivsize);
 669        if (ret < 0)
 670                return -EINVAL;
 671        ret = hex2bin(epayload->encrypted_data, hex_encoded_data,
 672                      encrypted_datalen);
 673        if (ret < 0)
 674                return -EINVAL;
 675
 676        hmac = epayload->format + epayload->datablob_len;
 677        ret = hex2bin(hmac, hex_encoded_data + (encrypted_datalen * 2),
 678                      HASH_SIZE);
 679        if (ret < 0)
 680                return -EINVAL;
 681
 682        mkey = request_master_key(epayload, &master_key, &master_keylen);
 683        if (IS_ERR(mkey))
 684                return PTR_ERR(mkey);
 685
 686        ret = datablob_hmac_verify(epayload, format, master_key, master_keylen);
 687        if (ret < 0) {
 688                pr_err("encrypted_key: bad hmac (%d)\n", ret);
 689                goto out;
 690        }
 691
 692        ret = get_derived_key(derived_key, ENC_KEY, master_key, master_keylen);
 693        if (ret < 0)
 694                goto out;
 695
 696        ret = derived_key_decrypt(epayload, derived_key, sizeof derived_key);
 697        if (ret < 0)
 698                pr_err("encrypted_key: failed to decrypt key (%d)\n", ret);
 699out:
 700        up_read(&mkey->sem);
 701        key_put(mkey);
 702        memzero_explicit(derived_key, sizeof(derived_key));
 703        return ret;
 704}
 705
 706static void __ekey_init(struct encrypted_key_payload *epayload,
 707                        const char *format, const char *master_desc,
 708                        const char *datalen)
 709{
 710        unsigned int format_len;
 711
 712        format_len = (!format) ? strlen(key_format_default) : strlen(format);
 713        epayload->format = epayload->payload_data + epayload->payload_datalen;
 714        epayload->master_desc = epayload->format + format_len + 1;
 715        epayload->datalen = epayload->master_desc + strlen(master_desc) + 1;
 716        epayload->iv = epayload->datalen + strlen(datalen) + 1;
 717        epayload->encrypted_data = epayload->iv + ivsize + 1;
 718        epayload->decrypted_data = epayload->payload_data;
 719
 720        if (!format)
 721                memcpy(epayload->format, key_format_default, format_len);
 722        else {
 723                if (!strcmp(format, key_format_ecryptfs))
 724                        epayload->decrypted_data =
 725                                ecryptfs_get_auth_tok_key((struct ecryptfs_auth_tok *)epayload->payload_data);
 726
 727                memcpy(epayload->format, format, format_len);
 728        }
 729
 730        memcpy(epayload->master_desc, master_desc, strlen(master_desc));
 731        memcpy(epayload->datalen, datalen, strlen(datalen));
 732}
 733
 734/*
 735 * encrypted_init - initialize an encrypted key
 736 *
 737 * For a new key, use a random number for both the iv and data
 738 * itself.  For an old key, decrypt the hex encoded data.
 739 */
 740static int encrypted_init(struct encrypted_key_payload *epayload,
 741                          const char *key_desc, const char *format,
 742                          const char *master_desc, const char *datalen,
 743                          const char *hex_encoded_iv)
 744{
 745        int ret = 0;
 746
 747        if (format && !strcmp(format, key_format_ecryptfs)) {
 748                ret = valid_ecryptfs_desc(key_desc);
 749                if (ret < 0)
 750                        return ret;
 751
 752                ecryptfs_fill_auth_tok((struct ecryptfs_auth_tok *)epayload->payload_data,
 753                                       key_desc);
 754        }
 755
 756        __ekey_init(epayload, format, master_desc, datalen);
 757        if (!hex_encoded_iv) {
 758                get_random_bytes(epayload->iv, ivsize);
 759
 760                get_random_bytes(epayload->decrypted_data,
 761                                 epayload->decrypted_datalen);
 762        } else
 763                ret = encrypted_key_decrypt(epayload, format, hex_encoded_iv);
 764        return ret;
 765}
 766
 767/*
 768 * encrypted_instantiate - instantiate an encrypted key
 769 *
 770 * Decrypt an existing encrypted datablob or create a new encrypted key
 771 * based on a kernel random number.
 772 *
 773 * On success, return 0. Otherwise return errno.
 774 */
 775static int encrypted_instantiate(struct key *key,
 776                                 struct key_preparsed_payload *prep)
 777{
 778        struct encrypted_key_payload *epayload = NULL;
 779        char *datablob = NULL;
 780        const char *format = NULL;
 781        char *master_desc = NULL;
 782        char *decrypted_datalen = NULL;
 783        char *hex_encoded_iv = NULL;
 784        size_t datalen = prep->datalen;
 785        int ret;
 786
 787        if (datalen <= 0 || datalen > 32767 || !prep->data)
 788                return -EINVAL;
 789
 790        datablob = kmalloc(datalen + 1, GFP_KERNEL);
 791        if (!datablob)
 792                return -ENOMEM;
 793        datablob[datalen] = 0;
 794        memcpy(datablob, prep->data, datalen);
 795        ret = datablob_parse(datablob, &format, &master_desc,
 796                             &decrypted_datalen, &hex_encoded_iv);
 797        if (ret < 0)
 798                goto out;
 799
 800        epayload = encrypted_key_alloc(key, format, master_desc,
 801                                       decrypted_datalen);
 802        if (IS_ERR(epayload)) {
 803                ret = PTR_ERR(epayload);
 804                goto out;
 805        }
 806        ret = encrypted_init(epayload, key->description, format, master_desc,
 807                             decrypted_datalen, hex_encoded_iv);
 808        if (ret < 0) {
 809                kzfree(epayload);
 810                goto out;
 811        }
 812
 813        rcu_assign_keypointer(key, epayload);
 814out:
 815        kzfree(datablob);
 816        return ret;
 817}
 818
 819static void encrypted_rcu_free(struct rcu_head *rcu)
 820{
 821        struct encrypted_key_payload *epayload;
 822
 823        epayload = container_of(rcu, struct encrypted_key_payload, rcu);
 824        kzfree(epayload);
 825}
 826
 827/*
 828 * encrypted_update - update the master key description
 829 *
 830 * Change the master key description for an existing encrypted key.
 831 * The next read will return an encrypted datablob using the new
 832 * master key description.
 833 *
 834 * On success, return 0. Otherwise return errno.
 835 */
 836static int encrypted_update(struct key *key, struct key_preparsed_payload *prep)
 837{
 838        struct encrypted_key_payload *epayload = key->payload.data;
 839        struct encrypted_key_payload *new_epayload;
 840        char *buf;
 841        char *new_master_desc = NULL;
 842        const char *format = NULL;
 843        size_t datalen = prep->datalen;
 844        int ret = 0;
 845
 846        if (key_is_negative(key))
 847                return -ENOKEY;
 848        if (datalen <= 0 || datalen > 32767 || !prep->data)
 849                return -EINVAL;
 850
 851        buf = kmalloc(datalen + 1, GFP_KERNEL);
 852        if (!buf)
 853                return -ENOMEM;
 854
 855        buf[datalen] = 0;
 856        memcpy(buf, prep->data, datalen);
 857        ret = datablob_parse(buf, &format, &new_master_desc, NULL, NULL);
 858        if (ret < 0)
 859                goto out;
 860
 861        ret = valid_master_desc(new_master_desc, epayload->master_desc);
 862        if (ret < 0)
 863                goto out;
 864
 865        new_epayload = encrypted_key_alloc(key, epayload->format,
 866                                           new_master_desc, epayload->datalen);
 867        if (IS_ERR(new_epayload)) {
 868                ret = PTR_ERR(new_epayload);
 869                goto out;
 870        }
 871
 872        __ekey_init(new_epayload, epayload->format, new_master_desc,
 873                    epayload->datalen);
 874
 875        memcpy(new_epayload->iv, epayload->iv, ivsize);
 876        memcpy(new_epayload->payload_data, epayload->payload_data,
 877               epayload->payload_datalen);
 878
 879        rcu_assign_keypointer(key, new_epayload);
 880        call_rcu(&epayload->rcu, encrypted_rcu_free);
 881out:
 882        kzfree(buf);
 883        return ret;
 884}
 885
 886/*
 887 * encrypted_read - format and copy the encrypted data to userspace
 888 *
 889 * The resulting datablob format is:
 890 * <master-key name> <decrypted data length> <encrypted iv> <encrypted data>
 891 *
 892 * On success, return to userspace the encrypted key datablob size.
 893 */
 894static long encrypted_read(const struct key *key, char __user *buffer,
 895                           size_t buflen)
 896{
 897        struct encrypted_key_payload *epayload;
 898        struct key *mkey;
 899        u8 *master_key;
 900        size_t master_keylen;
 901        char derived_key[HASH_SIZE];
 902        char *ascii_buf;
 903        size_t asciiblob_len;
 904        int ret;
 905
 906        epayload = dereference_key_locked(key);
 907
 908        /* returns the hex encoded iv, encrypted-data, and hmac as ascii */
 909        asciiblob_len = epayload->datablob_len + ivsize + 1
 910            + roundup(epayload->decrypted_datalen, blksize)
 911            + (HASH_SIZE * 2);
 912
 913        if (!buffer || buflen < asciiblob_len)
 914                return asciiblob_len;
 915
 916        mkey = request_master_key(epayload, &master_key, &master_keylen);
 917        if (IS_ERR(mkey))
 918                return PTR_ERR(mkey);
 919
 920        ret = get_derived_key(derived_key, ENC_KEY, master_key, master_keylen);
 921        if (ret < 0)
 922                goto out;
 923
 924        ret = derived_key_encrypt(epayload, derived_key, sizeof derived_key);
 925        if (ret < 0)
 926                goto out;
 927
 928        ret = datablob_hmac_append(epayload, master_key, master_keylen);
 929        if (ret < 0)
 930                goto out;
 931
 932        ascii_buf = datablob_format(epayload, asciiblob_len);
 933        if (!ascii_buf) {
 934                ret = -ENOMEM;
 935                goto out;
 936        }
 937
 938        up_read(&mkey->sem);
 939        key_put(mkey);
 940        memzero_explicit(derived_key, sizeof(derived_key));
 941
 942        if (copy_to_user(buffer, ascii_buf, asciiblob_len) != 0)
 943                ret = -EFAULT;
 944        kzfree(ascii_buf);
 945
 946        return asciiblob_len;
 947out:
 948        up_read(&mkey->sem);
 949        key_put(mkey);
 950        memzero_explicit(derived_key, sizeof(derived_key));
 951        return ret;
 952}
 953
 954/*
 955 * encrypted_destroy - clear and free the key's payload
 956 */
 957static void encrypted_destroy(struct key *key)
 958{
 959        kzfree(key->payload.data);
 960}
 961
 962struct key_type key_type_encrypted = {
 963        .name = "encrypted",
 964        .instantiate = encrypted_instantiate,
 965        .update = encrypted_update,
 966        .match = user_match,
 967        .destroy = encrypted_destroy,
 968        .describe = user_describe,
 969        .read = encrypted_read,
 970};
 971EXPORT_SYMBOL_GPL(key_type_encrypted);
 972
 973static int __init init_encrypted(void)
 974{
 975        int ret;
 976
 977        hash_tfm = crypto_alloc_shash(hash_alg, 0, CRYPTO_ALG_ASYNC);
 978        if (IS_ERR(hash_tfm)) {
 979                pr_err("encrypted_key: can't allocate %s transform: %ld\n",
 980                       hash_alg, PTR_ERR(hash_tfm));
 981                return PTR_ERR(hash_tfm);
 982        }
 983
 984        ret = aes_get_sizes();
 985        if (ret < 0)
 986                goto out;
 987        ret = register_key_type(&key_type_encrypted);
 988        if (ret < 0)
 989                goto out;
 990        return 0;
 991out:
 992        crypto_free_shash(hash_tfm);
 993        return ret;
 994
 995}
 996
 997static void __exit cleanup_encrypted(void)
 998{
 999        crypto_free_shash(hash_tfm);
1000        unregister_key_type(&key_type_encrypted);
1001}
1002
1003late_initcall(init_encrypted);
1004module_exit(cleanup_encrypted);
1005
1006MODULE_LICENSE("GPL");
1007