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.rst
  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/ctype.h>
  32#include <crypto/aes.h>
  33#include <crypto/algapi.h>
  34#include <crypto/hash.h>
  35#include <crypto/sha.h>
  36#include <crypto/skcipher.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_skcipher *tfm;
  84
  85        tfm = crypto_alloc_skcipher(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_skcipher_ivsize(tfm);
  92        blksize = crypto_skcipher_blocksize(tfm);
  93        crypto_free_skcipher(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, const u8 **master_key,
 301                                    size_t *master_keylen)
 302{
 303        const 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 struct skcipher_request *init_skcipher_req(const u8 *key,
 390                                                  unsigned int key_len)
 391{
 392        struct skcipher_request *req;
 393        struct crypto_skcipher *tfm;
 394        int ret;
 395
 396        tfm = crypto_alloc_skcipher(blkcipher_alg, 0, CRYPTO_ALG_ASYNC);
 397        if (IS_ERR(tfm)) {
 398                pr_err("encrypted_key: failed to load %s transform (%ld)\n",
 399                       blkcipher_alg, PTR_ERR(tfm));
 400                return ERR_CAST(tfm);
 401        }
 402
 403        ret = crypto_skcipher_setkey(tfm, key, key_len);
 404        if (ret < 0) {
 405                pr_err("encrypted_key: failed to setkey (%d)\n", ret);
 406                crypto_free_skcipher(tfm);
 407                return ERR_PTR(ret);
 408        }
 409
 410        req = skcipher_request_alloc(tfm, GFP_KERNEL);
 411        if (!req) {
 412                pr_err("encrypted_key: failed to allocate request for %s\n",
 413                       blkcipher_alg);
 414                crypto_free_skcipher(tfm);
 415                return ERR_PTR(-ENOMEM);
 416        }
 417
 418        skcipher_request_set_callback(req, 0, NULL, NULL);
 419        return req;
 420}
 421
 422static struct key *request_master_key(struct encrypted_key_payload *epayload,
 423                                      const u8 **master_key, size_t *master_keylen)
 424{
 425        struct key *mkey = ERR_PTR(-EINVAL);
 426
 427        if (!strncmp(epayload->master_desc, KEY_TRUSTED_PREFIX,
 428                     KEY_TRUSTED_PREFIX_LEN)) {
 429                mkey = request_trusted_key(epayload->master_desc +
 430                                           KEY_TRUSTED_PREFIX_LEN,
 431                                           master_key, master_keylen);
 432        } else if (!strncmp(epayload->master_desc, KEY_USER_PREFIX,
 433                            KEY_USER_PREFIX_LEN)) {
 434                mkey = request_user_key(epayload->master_desc +
 435                                        KEY_USER_PREFIX_LEN,
 436                                        master_key, master_keylen);
 437        } else
 438                goto out;
 439
 440        if (IS_ERR(mkey)) {
 441                int ret = PTR_ERR(mkey);
 442
 443                if (ret == -ENOTSUPP)
 444                        pr_info("encrypted_key: key %s not supported",
 445                                epayload->master_desc);
 446                else
 447                        pr_info("encrypted_key: key %s not found",
 448                                epayload->master_desc);
 449                goto out;
 450        }
 451
 452        dump_master_key(*master_key, *master_keylen);
 453out:
 454        return mkey;
 455}
 456
 457/* Before returning data to userspace, encrypt decrypted data. */
 458static int derived_key_encrypt(struct encrypted_key_payload *epayload,
 459                               const u8 *derived_key,
 460                               unsigned int derived_keylen)
 461{
 462        struct scatterlist sg_in[2];
 463        struct scatterlist sg_out[1];
 464        struct crypto_skcipher *tfm;
 465        struct skcipher_request *req;
 466        unsigned int encrypted_datalen;
 467        u8 iv[AES_BLOCK_SIZE];
 468        int ret;
 469
 470        encrypted_datalen = roundup(epayload->decrypted_datalen, blksize);
 471
 472        req = init_skcipher_req(derived_key, derived_keylen);
 473        ret = PTR_ERR(req);
 474        if (IS_ERR(req))
 475                goto out;
 476        dump_decrypted_data(epayload);
 477
 478        sg_init_table(sg_in, 2);
 479        sg_set_buf(&sg_in[0], epayload->decrypted_data,
 480                   epayload->decrypted_datalen);
 481        sg_set_page(&sg_in[1], ZERO_PAGE(0), AES_BLOCK_SIZE, 0);
 482
 483        sg_init_table(sg_out, 1);
 484        sg_set_buf(sg_out, epayload->encrypted_data, encrypted_datalen);
 485
 486        memcpy(iv, epayload->iv, sizeof(iv));
 487        skcipher_request_set_crypt(req, sg_in, sg_out, encrypted_datalen, iv);
 488        ret = crypto_skcipher_encrypt(req);
 489        tfm = crypto_skcipher_reqtfm(req);
 490        skcipher_request_free(req);
 491        crypto_free_skcipher(tfm);
 492        if (ret < 0)
 493                pr_err("encrypted_key: failed to encrypt (%d)\n", ret);
 494        else
 495                dump_encrypted_data(epayload, encrypted_datalen);
 496out:
 497        return ret;
 498}
 499
 500static int datablob_hmac_append(struct encrypted_key_payload *epayload,
 501                                const u8 *master_key, size_t master_keylen)
 502{
 503        u8 derived_key[HASH_SIZE];
 504        u8 *digest;
 505        int ret;
 506
 507        ret = get_derived_key(derived_key, AUTH_KEY, master_key, master_keylen);
 508        if (ret < 0)
 509                goto out;
 510
 511        digest = epayload->format + epayload->datablob_len;
 512        ret = calc_hmac(digest, derived_key, sizeof derived_key,
 513                        epayload->format, epayload->datablob_len);
 514        if (!ret)
 515                dump_hmac(NULL, digest, HASH_SIZE);
 516out:
 517        memzero_explicit(derived_key, sizeof(derived_key));
 518        return ret;
 519}
 520
 521/* verify HMAC before decrypting encrypted key */
 522static int datablob_hmac_verify(struct encrypted_key_payload *epayload,
 523                                const u8 *format, const u8 *master_key,
 524                                size_t master_keylen)
 525{
 526        u8 derived_key[HASH_SIZE];
 527        u8 digest[HASH_SIZE];
 528        int ret;
 529        char *p;
 530        unsigned short len;
 531
 532        ret = get_derived_key(derived_key, AUTH_KEY, master_key, master_keylen);
 533        if (ret < 0)
 534                goto out;
 535
 536        len = epayload->datablob_len;
 537        if (!format) {
 538                p = epayload->master_desc;
 539                len -= strlen(epayload->format) + 1;
 540        } else
 541                p = epayload->format;
 542
 543        ret = calc_hmac(digest, derived_key, sizeof derived_key, p, len);
 544        if (ret < 0)
 545                goto out;
 546        ret = crypto_memneq(digest, epayload->format + epayload->datablob_len,
 547                            sizeof(digest));
 548        if (ret) {
 549                ret = -EINVAL;
 550                dump_hmac("datablob",
 551                          epayload->format + epayload->datablob_len,
 552                          HASH_SIZE);
 553                dump_hmac("calc", digest, HASH_SIZE);
 554        }
 555out:
 556        memzero_explicit(derived_key, sizeof(derived_key));
 557        return ret;
 558}
 559
 560static int derived_key_decrypt(struct encrypted_key_payload *epayload,
 561                               const u8 *derived_key,
 562                               unsigned int derived_keylen)
 563{
 564        struct scatterlist sg_in[1];
 565        struct scatterlist sg_out[2];
 566        struct crypto_skcipher *tfm;
 567        struct skcipher_request *req;
 568        unsigned int encrypted_datalen;
 569        u8 iv[AES_BLOCK_SIZE];
 570        u8 *pad;
 571        int ret;
 572
 573        /* Throwaway buffer to hold the unused zero padding at the end */
 574        pad = kmalloc(AES_BLOCK_SIZE, GFP_KERNEL);
 575        if (!pad)
 576                return -ENOMEM;
 577
 578        encrypted_datalen = roundup(epayload->decrypted_datalen, blksize);
 579        req = init_skcipher_req(derived_key, derived_keylen);
 580        ret = PTR_ERR(req);
 581        if (IS_ERR(req))
 582                goto out;
 583        dump_encrypted_data(epayload, encrypted_datalen);
 584
 585        sg_init_table(sg_in, 1);
 586        sg_init_table(sg_out, 2);
 587        sg_set_buf(sg_in, epayload->encrypted_data, encrypted_datalen);
 588        sg_set_buf(&sg_out[0], epayload->decrypted_data,
 589                   epayload->decrypted_datalen);
 590        sg_set_buf(&sg_out[1], pad, AES_BLOCK_SIZE);
 591
 592        memcpy(iv, epayload->iv, sizeof(iv));
 593        skcipher_request_set_crypt(req, sg_in, sg_out, encrypted_datalen, iv);
 594        ret = crypto_skcipher_decrypt(req);
 595        tfm = crypto_skcipher_reqtfm(req);
 596        skcipher_request_free(req);
 597        crypto_free_skcipher(tfm);
 598        if (ret < 0)
 599                goto out;
 600        dump_decrypted_data(epayload);
 601out:
 602        kfree(pad);
 603        return ret;
 604}
 605
 606/* Allocate memory for decrypted key and datablob. */
 607static struct encrypted_key_payload *encrypted_key_alloc(struct key *key,
 608                                                         const char *format,
 609                                                         const char *master_desc,
 610                                                         const char *datalen)
 611{
 612        struct encrypted_key_payload *epayload = NULL;
 613        unsigned short datablob_len;
 614        unsigned short decrypted_datalen;
 615        unsigned short payload_datalen;
 616        unsigned int encrypted_datalen;
 617        unsigned int format_len;
 618        long dlen;
 619        int ret;
 620
 621        ret = kstrtol(datalen, 10, &dlen);
 622        if (ret < 0 || dlen < MIN_DATA_SIZE || dlen > MAX_DATA_SIZE)
 623                return ERR_PTR(-EINVAL);
 624
 625        format_len = (!format) ? strlen(key_format_default) : strlen(format);
 626        decrypted_datalen = dlen;
 627        payload_datalen = decrypted_datalen;
 628        if (format && !strcmp(format, key_format_ecryptfs)) {
 629                if (dlen != ECRYPTFS_MAX_KEY_BYTES) {
 630                        pr_err("encrypted_key: keylen for the ecryptfs format "
 631                               "must be equal to %d bytes\n",
 632                               ECRYPTFS_MAX_KEY_BYTES);
 633                        return ERR_PTR(-EINVAL);
 634                }
 635                decrypted_datalen = ECRYPTFS_MAX_KEY_BYTES;
 636                payload_datalen = sizeof(struct ecryptfs_auth_tok);
 637        }
 638
 639        encrypted_datalen = roundup(decrypted_datalen, blksize);
 640
 641        datablob_len = format_len + 1 + strlen(master_desc) + 1
 642            + strlen(datalen) + 1 + ivsize + 1 + encrypted_datalen;
 643
 644        ret = key_payload_reserve(key, payload_datalen + datablob_len
 645                                  + HASH_SIZE + 1);
 646        if (ret < 0)
 647                return ERR_PTR(ret);
 648
 649        epayload = kzalloc(sizeof(*epayload) + payload_datalen +
 650                           datablob_len + HASH_SIZE + 1, GFP_KERNEL);
 651        if (!epayload)
 652                return ERR_PTR(-ENOMEM);
 653
 654        epayload->payload_datalen = payload_datalen;
 655        epayload->decrypted_datalen = decrypted_datalen;
 656        epayload->datablob_len = datablob_len;
 657        return epayload;
 658}
 659
 660static int encrypted_key_decrypt(struct encrypted_key_payload *epayload,
 661                                 const char *format, const char *hex_encoded_iv)
 662{
 663        struct key *mkey;
 664        u8 derived_key[HASH_SIZE];
 665        const u8 *master_key;
 666        u8 *hmac;
 667        const char *hex_encoded_data;
 668        unsigned int encrypted_datalen;
 669        size_t master_keylen;
 670        size_t asciilen;
 671        int ret;
 672
 673        encrypted_datalen = roundup(epayload->decrypted_datalen, blksize);
 674        asciilen = (ivsize + 1 + encrypted_datalen + HASH_SIZE) * 2;
 675        if (strlen(hex_encoded_iv) != asciilen)
 676                return -EINVAL;
 677
 678        hex_encoded_data = hex_encoded_iv + (2 * ivsize) + 2;
 679        ret = hex2bin(epayload->iv, hex_encoded_iv, ivsize);
 680        if (ret < 0)
 681                return -EINVAL;
 682        ret = hex2bin(epayload->encrypted_data, hex_encoded_data,
 683                      encrypted_datalen);
 684        if (ret < 0)
 685                return -EINVAL;
 686
 687        hmac = epayload->format + epayload->datablob_len;
 688        ret = hex2bin(hmac, hex_encoded_data + (encrypted_datalen * 2),
 689                      HASH_SIZE);
 690        if (ret < 0)
 691                return -EINVAL;
 692
 693        mkey = request_master_key(epayload, &master_key, &master_keylen);
 694        if (IS_ERR(mkey))
 695                return PTR_ERR(mkey);
 696
 697        ret = datablob_hmac_verify(epayload, format, master_key, master_keylen);
 698        if (ret < 0) {
 699                pr_err("encrypted_key: bad hmac (%d)\n", ret);
 700                goto out;
 701        }
 702
 703        ret = get_derived_key(derived_key, ENC_KEY, master_key, master_keylen);
 704        if (ret < 0)
 705                goto out;
 706
 707        ret = derived_key_decrypt(epayload, derived_key, sizeof derived_key);
 708        if (ret < 0)
 709                pr_err("encrypted_key: failed to decrypt key (%d)\n", ret);
 710out:
 711        up_read(&mkey->sem);
 712        key_put(mkey);
 713        memzero_explicit(derived_key, sizeof(derived_key));
 714        return ret;
 715}
 716
 717static void __ekey_init(struct encrypted_key_payload *epayload,
 718                        const char *format, const char *master_desc,
 719                        const char *datalen)
 720{
 721        unsigned int format_len;
 722
 723        format_len = (!format) ? strlen(key_format_default) : strlen(format);
 724        epayload->format = epayload->payload_data + epayload->payload_datalen;
 725        epayload->master_desc = epayload->format + format_len + 1;
 726        epayload->datalen = epayload->master_desc + strlen(master_desc) + 1;
 727        epayload->iv = epayload->datalen + strlen(datalen) + 1;
 728        epayload->encrypted_data = epayload->iv + ivsize + 1;
 729        epayload->decrypted_data = epayload->payload_data;
 730
 731        if (!format)
 732                memcpy(epayload->format, key_format_default, format_len);
 733        else {
 734                if (!strcmp(format, key_format_ecryptfs))
 735                        epayload->decrypted_data =
 736                                ecryptfs_get_auth_tok_key((struct ecryptfs_auth_tok *)epayload->payload_data);
 737
 738                memcpy(epayload->format, format, format_len);
 739        }
 740
 741        memcpy(epayload->master_desc, master_desc, strlen(master_desc));
 742        memcpy(epayload->datalen, datalen, strlen(datalen));
 743}
 744
 745/*
 746 * encrypted_init - initialize an encrypted key
 747 *
 748 * For a new key, use a random number for both the iv and data
 749 * itself.  For an old key, decrypt the hex encoded data.
 750 */
 751static int encrypted_init(struct encrypted_key_payload *epayload,
 752                          const char *key_desc, const char *format,
 753                          const char *master_desc, const char *datalen,
 754                          const char *hex_encoded_iv)
 755{
 756        int ret = 0;
 757
 758        if (format && !strcmp(format, key_format_ecryptfs)) {
 759                ret = valid_ecryptfs_desc(key_desc);
 760                if (ret < 0)
 761                        return ret;
 762
 763                ecryptfs_fill_auth_tok((struct ecryptfs_auth_tok *)epayload->payload_data,
 764                                       key_desc);
 765        }
 766
 767        __ekey_init(epayload, format, master_desc, datalen);
 768        if (!hex_encoded_iv) {
 769                get_random_bytes(epayload->iv, ivsize);
 770
 771                get_random_bytes(epayload->decrypted_data,
 772                                 epayload->decrypted_datalen);
 773        } else
 774                ret = encrypted_key_decrypt(epayload, format, hex_encoded_iv);
 775        return ret;
 776}
 777
 778/*
 779 * encrypted_instantiate - instantiate an encrypted key
 780 *
 781 * Decrypt an existing encrypted datablob or create a new encrypted key
 782 * based on a kernel random number.
 783 *
 784 * On success, return 0. Otherwise return errno.
 785 */
 786static int encrypted_instantiate(struct key *key,
 787                                 struct key_preparsed_payload *prep)
 788{
 789        struct encrypted_key_payload *epayload = NULL;
 790        char *datablob = NULL;
 791        const char *format = NULL;
 792        char *master_desc = NULL;
 793        char *decrypted_datalen = NULL;
 794        char *hex_encoded_iv = NULL;
 795        size_t datalen = prep->datalen;
 796        int ret;
 797
 798        if (datalen <= 0 || datalen > 32767 || !prep->data)
 799                return -EINVAL;
 800
 801        datablob = kmalloc(datalen + 1, GFP_KERNEL);
 802        if (!datablob)
 803                return -ENOMEM;
 804        datablob[datalen] = 0;
 805        memcpy(datablob, prep->data, datalen);
 806        ret = datablob_parse(datablob, &format, &master_desc,
 807                             &decrypted_datalen, &hex_encoded_iv);
 808        if (ret < 0)
 809                goto out;
 810
 811        epayload = encrypted_key_alloc(key, format, master_desc,
 812                                       decrypted_datalen);
 813        if (IS_ERR(epayload)) {
 814                ret = PTR_ERR(epayload);
 815                goto out;
 816        }
 817        ret = encrypted_init(epayload, key->description, format, master_desc,
 818                             decrypted_datalen, hex_encoded_iv);
 819        if (ret < 0) {
 820                kzfree(epayload);
 821                goto out;
 822        }
 823
 824        rcu_assign_keypointer(key, epayload);
 825out:
 826        kzfree(datablob);
 827        return ret;
 828}
 829
 830static void encrypted_rcu_free(struct rcu_head *rcu)
 831{
 832        struct encrypted_key_payload *epayload;
 833
 834        epayload = container_of(rcu, struct encrypted_key_payload, rcu);
 835        kzfree(epayload);
 836}
 837
 838/*
 839 * encrypted_update - update the master key description
 840 *
 841 * Change the master key description for an existing encrypted key.
 842 * The next read will return an encrypted datablob using the new
 843 * master key description.
 844 *
 845 * On success, return 0. Otherwise return errno.
 846 */
 847static int encrypted_update(struct key *key, struct key_preparsed_payload *prep)
 848{
 849        struct encrypted_key_payload *epayload = key->payload.data[0];
 850        struct encrypted_key_payload *new_epayload;
 851        char *buf;
 852        char *new_master_desc = NULL;
 853        const char *format = NULL;
 854        size_t datalen = prep->datalen;
 855        int ret = 0;
 856
 857        if (key_is_negative(key))
 858                return -ENOKEY;
 859        if (datalen <= 0 || datalen > 32767 || !prep->data)
 860                return -EINVAL;
 861
 862        buf = kmalloc(datalen + 1, GFP_KERNEL);
 863        if (!buf)
 864                return -ENOMEM;
 865
 866        buf[datalen] = 0;
 867        memcpy(buf, prep->data, datalen);
 868        ret = datablob_parse(buf, &format, &new_master_desc, NULL, NULL);
 869        if (ret < 0)
 870                goto out;
 871
 872        ret = valid_master_desc(new_master_desc, epayload->master_desc);
 873        if (ret < 0)
 874                goto out;
 875
 876        new_epayload = encrypted_key_alloc(key, epayload->format,
 877                                           new_master_desc, epayload->datalen);
 878        if (IS_ERR(new_epayload)) {
 879                ret = PTR_ERR(new_epayload);
 880                goto out;
 881        }
 882
 883        __ekey_init(new_epayload, epayload->format, new_master_desc,
 884                    epayload->datalen);
 885
 886        memcpy(new_epayload->iv, epayload->iv, ivsize);
 887        memcpy(new_epayload->payload_data, epayload->payload_data,
 888               epayload->payload_datalen);
 889
 890        rcu_assign_keypointer(key, new_epayload);
 891        call_rcu(&epayload->rcu, encrypted_rcu_free);
 892out:
 893        kzfree(buf);
 894        return ret;
 895}
 896
 897/*
 898 * encrypted_read - format and copy the encrypted data to userspace
 899 *
 900 * The resulting datablob format is:
 901 * <master-key name> <decrypted data length> <encrypted iv> <encrypted data>
 902 *
 903 * On success, return to userspace the encrypted key datablob size.
 904 */
 905static long encrypted_read(const struct key *key, char __user *buffer,
 906                           size_t buflen)
 907{
 908        struct encrypted_key_payload *epayload;
 909        struct key *mkey;
 910        const u8 *master_key;
 911        size_t master_keylen;
 912        char derived_key[HASH_SIZE];
 913        char *ascii_buf;
 914        size_t asciiblob_len;
 915        int ret;
 916
 917        epayload = dereference_key_locked(key);
 918
 919        /* returns the hex encoded iv, encrypted-data, and hmac as ascii */
 920        asciiblob_len = epayload->datablob_len + ivsize + 1
 921            + roundup(epayload->decrypted_datalen, blksize)
 922            + (HASH_SIZE * 2);
 923
 924        if (!buffer || buflen < asciiblob_len)
 925                return asciiblob_len;
 926
 927        mkey = request_master_key(epayload, &master_key, &master_keylen);
 928        if (IS_ERR(mkey))
 929                return PTR_ERR(mkey);
 930
 931        ret = get_derived_key(derived_key, ENC_KEY, master_key, master_keylen);
 932        if (ret < 0)
 933                goto out;
 934
 935        ret = derived_key_encrypt(epayload, derived_key, sizeof derived_key);
 936        if (ret < 0)
 937                goto out;
 938
 939        ret = datablob_hmac_append(epayload, master_key, master_keylen);
 940        if (ret < 0)
 941                goto out;
 942
 943        ascii_buf = datablob_format(epayload, asciiblob_len);
 944        if (!ascii_buf) {
 945                ret = -ENOMEM;
 946                goto out;
 947        }
 948
 949        up_read(&mkey->sem);
 950        key_put(mkey);
 951        memzero_explicit(derived_key, sizeof(derived_key));
 952
 953        if (copy_to_user(buffer, ascii_buf, asciiblob_len) != 0)
 954                ret = -EFAULT;
 955        kzfree(ascii_buf);
 956
 957        return asciiblob_len;
 958out:
 959        up_read(&mkey->sem);
 960        key_put(mkey);
 961        memzero_explicit(derived_key, sizeof(derived_key));
 962        return ret;
 963}
 964
 965/*
 966 * encrypted_destroy - clear and free the key's payload
 967 */
 968static void encrypted_destroy(struct key *key)
 969{
 970        kzfree(key->payload.data[0]);
 971}
 972
 973struct key_type key_type_encrypted = {
 974        .name = "encrypted",
 975        .instantiate = encrypted_instantiate,
 976        .update = encrypted_update,
 977        .destroy = encrypted_destroy,
 978        .describe = user_describe,
 979        .read = encrypted_read,
 980};
 981EXPORT_SYMBOL_GPL(key_type_encrypted);
 982
 983static int __init init_encrypted(void)
 984{
 985        int ret;
 986
 987        hash_tfm = crypto_alloc_shash(hash_alg, 0, CRYPTO_ALG_ASYNC);
 988        if (IS_ERR(hash_tfm)) {
 989                pr_err("encrypted_key: can't allocate %s transform: %ld\n",
 990                       hash_alg, PTR_ERR(hash_tfm));
 991                return PTR_ERR(hash_tfm);
 992        }
 993
 994        ret = aes_get_sizes();
 995        if (ret < 0)
 996                goto out;
 997        ret = register_key_type(&key_type_encrypted);
 998        if (ret < 0)
 999                goto out;
1000        return 0;
1001out:
1002        crypto_free_shash(hash_tfm);
1003        return ret;
1004
1005}
1006
1007static void __exit cleanup_encrypted(void)
1008{
1009        crypto_free_shash(hash_tfm);
1010        unregister_key_type(&key_type_encrypted);
1011}
1012
1013late_initcall(init_encrypted);
1014module_exit(cleanup_encrypted);
1015
1016MODULE_LICENSE("GPL");
1017