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