pvkfmt.c 24.2 KB
Newer Older
1 2 3
/*
 * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project
 * 2005.
4 5 6 7 8 9 10 11 12
 */
/* ====================================================================
 * Copyright (c) 2005 The OpenSSL Project.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
13
 *    notice, this list of conditions and the following disclaimer.
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. All advertising materials mentioning features or use of this
 *    software must display the following acknowledgment:
 *    "This product includes software developed by the OpenSSL Project
 *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
 *
 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
 *    endorse or promote products derived from this software without
 *    prior written permission. For written permission, please contact
 *    licensing@OpenSSL.org.
 *
 * 5. Products derived from this software may not be called "OpenSSL"
 *    nor may "OpenSSL" appear in their names without prior written
 *    permission of the OpenSSL Project.
 *
 * 6. Redistributions of any form whatsoever must retain the following
 *    acknowledgment:
 *    "This product includes software developed by the OpenSSL Project
 *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
 *
 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 * ====================================================================
 *
 * This product includes cryptographic software written by Eric Young
 * (eay@cryptsoft.com).  This product includes software written by Tim
 * Hudson (tjh@cryptsoft.com).
 *
 */

59 60
/*
 * Support for PVK format keys and related structures (such a PUBLICKEYBLOB
61 62 63
 * and PRIVATEKEYBLOB).
 */

64
#include "internal/cryptlib.h"
65 66
#include <openssl/pem.h>
#include <openssl/rand.h>
67
#include <openssl/bn.h>
D
Dr. Stephen Henson 已提交
68
#if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_NO_DSA)
69 70
# include <openssl/dsa.h>
# include <openssl/rsa.h>
71

72 73
/*
 * Utility function: read a DWORD (4 byte unsigned integer) in little endian
74 75 76 77
 * format
 */

static unsigned int read_ledword(const unsigned char **in)
78 79 80 81 82 83 84 85 86 87 88 89 90 91
{
    const unsigned char *p = *in;
    unsigned int ret;
    ret = *p++;
    ret |= (*p++ << 8);
    ret |= (*p++ << 16);
    ret |= (*p++ << 24);
    *in = p;
    return ret;
}

/*
 * Read a BIGNUM in little endian format. The docs say that this should take
 * up bitlen/8 bytes.
92 93 94
 */

static int read_lebn(const unsigned char **in, unsigned int nbyte, BIGNUM **r)
95 96 97 98 99 100
{
    const unsigned char *p;
    unsigned char *tmpbuf, *q;
    unsigned int i;
    p = *in + nbyte - 1;
    tmpbuf = OPENSSL_malloc(nbyte);
101
    if (tmpbuf == NULL)
102 103 104 105 106 107 108 109 110 111 112 113
        return 0;
    q = tmpbuf;
    for (i = 0; i < nbyte; i++)
        *q++ = *p--;
    *r = BN_bin2bn(tmpbuf, nbyte, NULL);
    OPENSSL_free(tmpbuf);
    if (*r) {
        *in += nbyte;
        return 1;
    } else
        return 0;
}
114 115 116

/* Convert private key blob to EVP_PKEY: RSA and DSA keys supported */

117 118 119 120 121 122
# define MS_PUBLICKEYBLOB        0x6
# define MS_PRIVATEKEYBLOB       0x7
# define MS_RSA1MAGIC            0x31415352L
# define MS_RSA2MAGIC            0x32415352L
# define MS_DSS1MAGIC            0x31535344L
# define MS_DSS2MAGIC            0x32535344L
123

124 125
# define MS_KEYALG_RSA_KEYX      0xa400
# define MS_KEYALG_DSS_SIGN      0x2200
126

127 128
# define MS_KEYTYPE_KEYX         0x1
# define MS_KEYTYPE_SIGN         0x2
129 130

/* The PVK file magic number: seems to spell out "bobsfile", who is Bob? */
131
# define MS_PVKMAGIC             0xb0b5f11eL
132
/* Salt length for PVK files */
133
# define PVK_SALTLEN             0x10
134 135

static EVP_PKEY *b2i_rsa(const unsigned char **in, unsigned int length,
136
                         unsigned int bitlen, int ispub);
137
static EVP_PKEY *b2i_dss(const unsigned char **in, unsigned int length,
138
                         unsigned int bitlen, int ispub);
139 140

static int do_blob_header(const unsigned char **in, unsigned int length,
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
                          unsigned int *pmagic, unsigned int *pbitlen,
                          int *pisdss, int *pispub)
{
    const unsigned char *p = *in;
    if (length < 16)
        return 0;
    /* bType */
    if (*p == MS_PUBLICKEYBLOB) {
        if (*pispub == 0) {
            PEMerr(PEM_F_DO_BLOB_HEADER, PEM_R_EXPECTING_PRIVATE_KEY_BLOB);
            return 0;
        }
        *pispub = 1;
    } else if (*p == MS_PRIVATEKEYBLOB) {
        if (*pispub == 1) {
            PEMerr(PEM_F_DO_BLOB_HEADER, PEM_R_EXPECTING_PUBLIC_KEY_BLOB);
            return 0;
        }
        *pispub = 0;
    } else
        return 0;
    p++;
    /* Version */
    if (*p++ != 0x2) {
        PEMerr(PEM_F_DO_BLOB_HEADER, PEM_R_BAD_VERSION_NUMBER);
        return 0;
    }
    /* Ignore reserved, aiKeyAlg */
    p += 6;
    *pmagic = read_ledword(&p);
    *pbitlen = read_ledword(&p);
    *pisdss = 0;
    switch (*pmagic) {

    case MS_DSS1MAGIC:
        *pisdss = 1;
    case MS_RSA1MAGIC:
        if (*pispub == 0) {
            PEMerr(PEM_F_DO_BLOB_HEADER, PEM_R_EXPECTING_PRIVATE_KEY_BLOB);
            return 0;
        }
        break;

    case MS_DSS2MAGIC:
        *pisdss = 1;
    case MS_RSA2MAGIC:
        if (*pispub == 1) {
            PEMerr(PEM_F_DO_BLOB_HEADER, PEM_R_EXPECTING_PUBLIC_KEY_BLOB);
            return 0;
        }
        break;

    default:
        PEMerr(PEM_F_DO_BLOB_HEADER, PEM_R_BAD_MAGIC_NUMBER);
        return -1;
    }
    *in = p;
    return 1;
}
200 201

static unsigned int blob_length(unsigned bitlen, int isdss, int ispub)
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
{
    unsigned int nbyte, hnbyte;
    nbyte = (bitlen + 7) >> 3;
    hnbyte = (bitlen + 15) >> 4;
    if (isdss) {

        /*
         * Expected length: 20 for q + 3 components bitlen each + 24 for seed
         * structure.
         */
        if (ispub)
            return 44 + 3 * nbyte;
        /*
         * Expected length: 20 for q, priv, 2 bitlen components + 24 for seed
         * structure.
         */
        else
            return 64 + 2 * nbyte;
    } else {
        /* Expected length: 4 for 'e' + 'n' */
        if (ispub)
            return 4 + nbyte;
        else
            /*
             * Expected length: 4 for 'e' and 7 other components. 2
             * components are bitlen size, 5 are bitlen/2
             */
            return 4 + 2 * nbyte + 5 * hnbyte;
    }

}
233 234

static EVP_PKEY *do_b2i(const unsigned char **in, unsigned int length,
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
                        int ispub)
{
    const unsigned char *p = *in;
    unsigned int bitlen, magic;
    int isdss;
    if (do_blob_header(&p, length, &magic, &bitlen, &isdss, &ispub) <= 0) {
        PEMerr(PEM_F_DO_B2I, PEM_R_KEYBLOB_HEADER_PARSE_ERROR);
        return NULL;
    }
    length -= 16;
    if (length < blob_length(bitlen, isdss, ispub)) {
        PEMerr(PEM_F_DO_B2I, PEM_R_KEYBLOB_TOO_SHORT);
        return NULL;
    }
    if (isdss)
        return b2i_dss(&p, length, bitlen, ispub);
    else
        return b2i_rsa(&p, length, bitlen, ispub);
}
254 255

static EVP_PKEY *do_b2i_bio(BIO *in, int ispub)
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
{
    const unsigned char *p;
    unsigned char hdr_buf[16], *buf = NULL;
    unsigned int bitlen, magic, length;
    int isdss;
    EVP_PKEY *ret = NULL;
    if (BIO_read(in, hdr_buf, 16) != 16) {
        PEMerr(PEM_F_DO_B2I_BIO, PEM_R_KEYBLOB_TOO_SHORT);
        return NULL;
    }
    p = hdr_buf;
    if (do_blob_header(&p, 16, &magic, &bitlen, &isdss, &ispub) <= 0)
        return NULL;

    length = blob_length(bitlen, isdss, ispub);
    buf = OPENSSL_malloc(length);
272
    if (buf == NULL) {
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
        PEMerr(PEM_F_DO_B2I_BIO, ERR_R_MALLOC_FAILURE);
        goto err;
    }
    p = buf;
    if (BIO_read(in, buf, length) != (int)length) {
        PEMerr(PEM_F_DO_B2I_BIO, PEM_R_KEYBLOB_TOO_SHORT);
        goto err;
    }

    if (isdss)
        ret = b2i_dss(&p, length, bitlen, ispub);
    else
        ret = b2i_rsa(&p, length, bitlen, ispub);

 err:
R
Rich Salz 已提交
288
    OPENSSL_free(buf);
289 290
    return ret;
}
291 292

static EVP_PKEY *b2i_dss(const unsigned char **in, unsigned int length,
293 294 295 296 297 298 299 300 301 302 303
                         unsigned int bitlen, int ispub)
{
    const unsigned char *p = *in;
    EVP_PKEY *ret = NULL;
    DSA *dsa = NULL;
    BN_CTX *ctx = NULL;
    unsigned int nbyte;
    nbyte = (bitlen + 7) >> 3;

    dsa = DSA_new();
    ret = EVP_PKEY_new();
304
    if (dsa == NULL || ret == NULL)
305 306 307 308 309 310 311 312 313 314 315 316 317 318
        goto memerr;
    if (!read_lebn(&p, nbyte, &dsa->p))
        goto memerr;
    if (!read_lebn(&p, 20, &dsa->q))
        goto memerr;
    if (!read_lebn(&p, nbyte, &dsa->g))
        goto memerr;
    if (ispub) {
        if (!read_lebn(&p, nbyte, &dsa->pub_key))
            goto memerr;
    } else {
        if (!read_lebn(&p, 20, &dsa->priv_key))
            goto memerr;
        /* Calculate public key */
319
        if ((dsa->pub_key = BN_new()) == NULL)
320
            goto memerr;
321
        if ((ctx = BN_CTX_new()) == NULL)
322 323 324 325 326 327 328 329 330 331 332 333 334 335
            goto memerr;

        if (!BN_mod_exp(dsa->pub_key, dsa->g, dsa->priv_key, dsa->p, ctx))
            goto memerr;
        BN_CTX_free(ctx);
    }

    EVP_PKEY_set1_DSA(ret, dsa);
    DSA_free(dsa);
    *in = p;
    return ret;

 memerr:
    PEMerr(PEM_F_B2I_DSS, ERR_R_MALLOC_FAILURE);
R
Rich Salz 已提交
336
    DSA_free(dsa);
R
Rich Salz 已提交
337
    EVP_PKEY_free(ret);
R
Rich Salz 已提交
338
    BN_CTX_free(ctx);
339 340
    return NULL;
}
341 342

static EVP_PKEY *b2i_rsa(const unsigned char **in, unsigned int length,
343 344 345 346 347 348 349 350 351 352
                         unsigned int bitlen, int ispub)
{
    const unsigned char *p = *in;
    EVP_PKEY *ret = NULL;
    RSA *rsa = NULL;
    unsigned int nbyte, hnbyte;
    nbyte = (bitlen + 7) >> 3;
    hnbyte = (bitlen + 15) >> 4;
    rsa = RSA_new();
    ret = EVP_PKEY_new();
353
    if (rsa == NULL || ret == NULL)
354 355
        goto memerr;
    rsa->e = BN_new();
356
    if (rsa->e == NULL)
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
        goto memerr;
    if (!BN_set_word(rsa->e, read_ledword(&p)))
        goto memerr;
    if (!read_lebn(&p, nbyte, &rsa->n))
        goto memerr;
    if (!ispub) {
        if (!read_lebn(&p, hnbyte, &rsa->p))
            goto memerr;
        if (!read_lebn(&p, hnbyte, &rsa->q))
            goto memerr;
        if (!read_lebn(&p, hnbyte, &rsa->dmp1))
            goto memerr;
        if (!read_lebn(&p, hnbyte, &rsa->dmq1))
            goto memerr;
        if (!read_lebn(&p, hnbyte, &rsa->iqmp))
            goto memerr;
        if (!read_lebn(&p, nbyte, &rsa->d))
            goto memerr;
    }

    EVP_PKEY_set1_RSA(ret, rsa);
    RSA_free(rsa);
    *in = p;
    return ret;
 memerr:
    PEMerr(PEM_F_B2I_RSA, ERR_R_MALLOC_FAILURE);
R
Rich Salz 已提交
383
    RSA_free(rsa);
R
Rich Salz 已提交
384
    EVP_PKEY_free(ret);
385 386
    return NULL;
}
387 388

EVP_PKEY *b2i_PrivateKey(const unsigned char **in, long length)
389 390 391
{
    return do_b2i(in, length, 0);
}
392 393

EVP_PKEY *b2i_PublicKey(const unsigned char **in, long length)
394 395 396
{
    return do_b2i(in, length, 1);
}
397 398

EVP_PKEY *b2i_PrivateKey_bio(BIO *in)
399 400 401
{
    return do_b2i_bio(in, 0);
}
402 403

EVP_PKEY *b2i_PublicKey_bio(BIO *in)
404 405 406
{
    return do_b2i_bio(in, 1);
}
407 408

static void write_ledword(unsigned char **out, unsigned int dw)
409 410 411 412 413 414 415 416
{
    unsigned char *p = *out;
    *p++ = dw & 0xff;
    *p++ = (dw >> 8) & 0xff;
    *p++ = (dw >> 16) & 0xff;
    *p++ = (dw >> 24) & 0xff;
    *out = p;
}
417 418

static void write_lebn(unsigned char **out, const BIGNUM *bn, int len)
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
{
    int nb, i;
    unsigned char *p = *out, *q, c;
    nb = BN_num_bytes(bn);
    BN_bn2bin(bn, p);
    q = p + nb - 1;
    /* In place byte order reversal */
    for (i = 0; i < nb / 2; i++) {
        c = *p;
        *p++ = *q;
        *q-- = c;
    }
    *out += nb;
    /* Pad with zeroes if we have to */
    if (len > 0) {
        len -= nb;
        if (len > 0) {
            memset(*out, 0, len);
            *out += len;
        }
    }
}
441 442 443 444 445 446

static int check_bitlen_rsa(RSA *rsa, int ispub, unsigned int *magic);
static int check_bitlen_dsa(DSA *dsa, int ispub, unsigned int *magic);

static void write_rsa(unsigned char **out, RSA *rsa, int ispub);
static void write_dsa(unsigned char **out, DSA *dsa, int ispub);
447

448
static int do_i2b(unsigned char **out, EVP_PKEY *pk, int ispub)
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
{
    unsigned char *p;
    unsigned int bitlen, magic = 0, keyalg;
    int outlen, noinc = 0;
    if (pk->type == EVP_PKEY_DSA) {
        bitlen = check_bitlen_dsa(pk->pkey.dsa, ispub, &magic);
        keyalg = MS_KEYALG_DSS_SIGN;
    } else if (pk->type == EVP_PKEY_RSA) {
        bitlen = check_bitlen_rsa(pk->pkey.rsa, ispub, &magic);
        keyalg = MS_KEYALG_RSA_KEYX;
    } else
        return -1;
    if (bitlen == 0)
        return -1;
    outlen = 16 + blob_length(bitlen,
                              keyalg == MS_KEYALG_DSS_SIGN ? 1 : 0, ispub);
    if (out == NULL)
        return outlen;
    if (*out)
        p = *out;
    else {
        p = OPENSSL_malloc(outlen);
471
        if (p == NULL)
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
            return -1;
        *out = p;
        noinc = 1;
    }
    if (ispub)
        *p++ = MS_PUBLICKEYBLOB;
    else
        *p++ = MS_PRIVATEKEYBLOB;
    *p++ = 0x2;
    *p++ = 0;
    *p++ = 0;
    write_ledword(&p, keyalg);
    write_ledword(&p, magic);
    write_ledword(&p, bitlen);
    if (keyalg == MS_KEYALG_DSS_SIGN)
        write_dsa(&p, pk->pkey.dsa, ispub);
    else
        write_rsa(&p, pk->pkey.rsa, ispub);
    if (!noinc)
        *out += outlen;
    return outlen;
}
494 495

static int do_i2b_bio(BIO *out, EVP_PKEY *pk, int ispub)
496 497 498 499 500 501 502 503 504 505 506 507
{
    unsigned char *tmp = NULL;
    int outlen, wrlen;
    outlen = do_i2b(&tmp, pk, ispub);
    if (outlen < 0)
        return -1;
    wrlen = BIO_write(out, tmp, outlen);
    OPENSSL_free(tmp);
    if (wrlen == outlen)
        return outlen;
    return -1;
}
508 509

static int check_bitlen_dsa(DSA *dsa, int ispub, unsigned int *pmagic)
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
{
    int bitlen;
    bitlen = BN_num_bits(dsa->p);
    if ((bitlen & 7) || (BN_num_bits(dsa->q) != 160)
        || (BN_num_bits(dsa->g) > bitlen))
        goto badkey;
    if (ispub) {
        if (BN_num_bits(dsa->pub_key) > bitlen)
            goto badkey;
        *pmagic = MS_DSS1MAGIC;
    } else {
        if (BN_num_bits(dsa->priv_key) > 160)
            goto badkey;
        *pmagic = MS_DSS2MAGIC;
    }

    return bitlen;
 badkey:
    PEMerr(PEM_F_CHECK_BITLEN_DSA, PEM_R_UNSUPPORTED_KEY_COMPONENTS);
    return 0;
}
531 532

static int check_bitlen_rsa(RSA *rsa, int ispub, unsigned int *pmagic)
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
{
    int nbyte, hnbyte, bitlen;
    if (BN_num_bits(rsa->e) > 32)
        goto badkey;
    bitlen = BN_num_bits(rsa->n);
    nbyte = BN_num_bytes(rsa->n);
    hnbyte = (BN_num_bits(rsa->n) + 15) >> 4;
    if (ispub) {
        *pmagic = MS_RSA1MAGIC;
        return bitlen;
    } else {
        *pmagic = MS_RSA2MAGIC;
        /*
         * For private key each component must fit within nbyte or hnbyte.
         */
        if (BN_num_bytes(rsa->d) > nbyte)
            goto badkey;
        if ((BN_num_bytes(rsa->iqmp) > hnbyte)
            || (BN_num_bytes(rsa->p) > hnbyte)
            || (BN_num_bytes(rsa->q) > hnbyte)
            || (BN_num_bytes(rsa->dmp1) > hnbyte)
            || (BN_num_bytes(rsa->dmq1) > hnbyte))
            goto badkey;
    }
    return bitlen;
 badkey:
    PEMerr(PEM_F_CHECK_BITLEN_RSA, PEM_R_UNSUPPORTED_KEY_COMPONENTS);
    return 0;
}
562 563

static void write_rsa(unsigned char **out, RSA *rsa, int ispub)
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
{
    int nbyte, hnbyte;
    nbyte = BN_num_bytes(rsa->n);
    hnbyte = (BN_num_bits(rsa->n) + 15) >> 4;
    write_lebn(out, rsa->e, 4);
    write_lebn(out, rsa->n, -1);
    if (ispub)
        return;
    write_lebn(out, rsa->p, hnbyte);
    write_lebn(out, rsa->q, hnbyte);
    write_lebn(out, rsa->dmp1, hnbyte);
    write_lebn(out, rsa->dmq1, hnbyte);
    write_lebn(out, rsa->iqmp, hnbyte);
    write_lebn(out, rsa->d, nbyte);
}

580
static void write_dsa(unsigned char **out, DSA *dsa, int ispub)
581 582 583 584 585 586 587 588 589 590 591 592 593 594 595
{
    int nbyte;
    nbyte = BN_num_bytes(dsa->p);
    write_lebn(out, dsa->p, nbyte);
    write_lebn(out, dsa->q, 20);
    write_lebn(out, dsa->g, nbyte);
    if (ispub)
        write_lebn(out, dsa->pub_key, nbyte);
    else
        write_lebn(out, dsa->priv_key, 20);
    /* Set "invalid" for seed structure values */
    memset(*out, 0xff, 24);
    *out += 24;
    return;
}
596 597

int i2b_PrivateKey_bio(BIO *out, EVP_PKEY *pk)
598 599 600
{
    return do_i2b_bio(out, pk, 0);
}
601 602

int i2b_PublicKey_bio(BIO *out, EVP_PKEY *pk)
603 604 605
{
    return do_i2b_bio(out, pk, 1);
}
606

607
# ifndef OPENSSL_NO_RC4
D
Dr. Stephen Henson 已提交
608

609
static int do_PVK_header(const unsigned char **in, unsigned int length,
610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
                         int skip_magic,
                         unsigned int *psaltlen, unsigned int *pkeylen)
{
    const unsigned char *p = *in;
    unsigned int pvk_magic, is_encrypted;
    if (skip_magic) {
        if (length < 20) {
            PEMerr(PEM_F_DO_PVK_HEADER, PEM_R_PVK_TOO_SHORT);
            return 0;
        }
    } else {
        if (length < 24) {
            PEMerr(PEM_F_DO_PVK_HEADER, PEM_R_PVK_TOO_SHORT);
            return 0;
        }
        pvk_magic = read_ledword(&p);
        if (pvk_magic != MS_PVKMAGIC) {
            PEMerr(PEM_F_DO_PVK_HEADER, PEM_R_BAD_MAGIC_NUMBER);
            return 0;
        }
    }
    /* Skip reserved */
    p += 4;
    /*
     * keytype =
     */ read_ledword(&p);
    is_encrypted = read_ledword(&p);
    *psaltlen = read_ledword(&p);
    *pkeylen = read_ledword(&p);

    if (is_encrypted && !*psaltlen) {
        PEMerr(PEM_F_DO_PVK_HEADER, PEM_R_INCONSISTENT_HEADER);
        return 0;
    }

    *in = p;
    return 1;
}

static int derive_pvk_key(unsigned char *key,
                          const unsigned char *salt, unsigned int saltlen,
                          const unsigned char *pass, int passlen)
{
R
Richard Levitte 已提交
653
    EVP_MD_CTX *mctx = EVP_MD_CTX_new();
654
    int rv = 1;
655 656 657 658 659
    if (mctx == NULL
        || !EVP_DigestInit_ex(mctx, EVP_sha1(), NULL)
        || !EVP_DigestUpdate(mctx, salt, saltlen)
        || !EVP_DigestUpdate(mctx, pass, passlen)
        || !EVP_DigestFinal_ex(mctx, key, NULL))
660 661
        rv = 0;

662
    EVP_MD_CTX_free(mctx);
663 664
    return rv;
}
665 666

static EVP_PKEY *do_PVK_body(const unsigned char **in,
667 668 669 670 671 672 673
                             unsigned int saltlen, unsigned int keylen,
                             pem_password_cb *cb, void *u)
{
    EVP_PKEY *ret = NULL;
    const unsigned char *p = *in;
    unsigned int magic;
    unsigned char *enctmp = NULL, *q;
R
Rich Salz 已提交
674

675
    EVP_CIPHER_CTX *cctx = EVP_CIPHER_CTX_new();
676 677 678 679 680 681 682 683 684 685
    if (saltlen) {
        char psbuf[PEM_BUFSIZE];
        unsigned char keybuf[20];
        int enctmplen, inlen;
        if (cb)
            inlen = cb(psbuf, PEM_BUFSIZE, 0, u);
        else
            inlen = PEM_def_callback(psbuf, PEM_BUFSIZE, 0, u);
        if (inlen <= 0) {
            PEMerr(PEM_F_DO_PVK_BODY, PEM_R_BAD_PASSWORD_READ);
686
            goto err;
687 688
        }
        enctmp = OPENSSL_malloc(keylen + 8);
689
        if (enctmp == NULL) {
690
            PEMerr(PEM_F_DO_PVK_BODY, ERR_R_MALLOC_FAILURE);
691
            goto err;
692 693 694
        }
        if (!derive_pvk_key(keybuf, p, saltlen,
                            (unsigned char *)psbuf, inlen))
695
            goto err;
696 697 698 699 700 701
        p += saltlen;
        /* Copy BLOBHEADER across, decrypt rest */
        memcpy(enctmp, p, 8);
        p += 8;
        if (keylen < 8) {
            PEMerr(PEM_F_DO_PVK_BODY, PEM_R_PVK_TOO_SHORT);
702
            goto err;
703 704 705
        }
        inlen = keylen - 8;
        q = enctmp + 8;
706
        if (!EVP_DecryptInit_ex(cctx, EVP_rc4(), NULL, keybuf, NULL))
707
            goto err;
708
        if (!EVP_DecryptUpdate(cctx, q, &enctmplen, p, inlen))
709
            goto err;
710
        if (!EVP_DecryptFinal_ex(cctx, q + enctmplen, &enctmplen))
711 712 713 714 715
            goto err;
        magic = read_ledword((const unsigned char **)&q);
        if (magic != MS_RSA2MAGIC && magic != MS_DSS2MAGIC) {
            q = enctmp + 8;
            memset(keybuf + 5, 0, 11);
716
            if (!EVP_DecryptInit_ex(cctx, EVP_rc4(), NULL, keybuf, NULL))
717 718
                goto err;
            OPENSSL_cleanse(keybuf, 20);
719
            if (!EVP_DecryptUpdate(cctx, q, &enctmplen, p, inlen))
720
                goto err;
721
            if (!EVP_DecryptFinal_ex(cctx, q + enctmplen, &enctmplen))
722 723 724 725 726 727 728 729 730 731 732 733 734
                goto err;
            magic = read_ledword((const unsigned char **)&q);
            if (magic != MS_RSA2MAGIC && magic != MS_DSS2MAGIC) {
                PEMerr(PEM_F_DO_PVK_BODY, PEM_R_BAD_DECRYPT);
                goto err;
            }
        } else
            OPENSSL_cleanse(keybuf, 20);
        p = enctmp;
    }

    ret = b2i_PrivateKey(&p, keylen);
 err:
735
    EVP_CIPHER_CTX_free(cctx);
R
Rich Salz 已提交
736
    OPENSSL_free(enctmp);
737 738
    return ret;
}
739 740

EVP_PKEY *b2i_PVK_bio(BIO *in, pem_password_cb *cb, void *u)
741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756
{
    unsigned char pvk_hdr[24], *buf = NULL;
    const unsigned char *p;
    int buflen;
    EVP_PKEY *ret = NULL;
    unsigned int saltlen, keylen;
    if (BIO_read(in, pvk_hdr, 24) != 24) {
        PEMerr(PEM_F_B2I_PVK_BIO, PEM_R_PVK_DATA_TOO_SHORT);
        return NULL;
    }
    p = pvk_hdr;

    if (!do_PVK_header(&p, 24, 0, &saltlen, &keylen))
        return 0;
    buflen = (int)keylen + saltlen;
    buf = OPENSSL_malloc(buflen);
757
    if (buf == NULL) {
758 759 760 761 762 763 764 765 766 767 768
        PEMerr(PEM_F_B2I_PVK_BIO, ERR_R_MALLOC_FAILURE);
        return 0;
    }
    p = buf;
    if (BIO_read(in, buf, buflen) != buflen) {
        PEMerr(PEM_F_B2I_PVK_BIO, PEM_R_PVK_DATA_TOO_SHORT);
        goto err;
    }
    ret = do_PVK_body(&p, saltlen, keylen, cb, u);

 err:
R
Rich Salz 已提交
769
    OPENSSL_clear_free(buf, buflen);
770 771 772 773 774 775 776 777
    return ret;
}

static int i2b_PVK(unsigned char **out, EVP_PKEY *pk, int enclevel,
                   pem_password_cb *cb, void *u)
{
    int outlen = 24, pklen;
    unsigned char *p, *salt = NULL;
778
    EVP_CIPHER_CTX *cctx = EVP_CIPHER_CTX_new();
779 780 781 782 783 784 785 786 787 788 789 790
    if (enclevel)
        outlen += PVK_SALTLEN;
    pklen = do_i2b(NULL, pk, 0);
    if (pklen < 0)
        return -1;
    outlen += pklen;
    if (!out)
        return outlen;
    if (*out)
        p = *out;
    else {
        p = OPENSSL_malloc(outlen);
791
        if (p == NULL) {
792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833
            PEMerr(PEM_F_I2B_PVK, ERR_R_MALLOC_FAILURE);
            return -1;
        }
        *out = p;
    }

    write_ledword(&p, MS_PVKMAGIC);
    write_ledword(&p, 0);
    if (pk->type == EVP_PKEY_DSA)
        write_ledword(&p, MS_KEYTYPE_SIGN);
    else
        write_ledword(&p, MS_KEYTYPE_KEYX);
    write_ledword(&p, enclevel ? 1 : 0);
    write_ledword(&p, enclevel ? PVK_SALTLEN : 0);
    write_ledword(&p, pklen);
    if (enclevel) {
        if (RAND_bytes(p, PVK_SALTLEN) <= 0)
            goto error;
        salt = p;
        p += PVK_SALTLEN;
    }
    do_i2b(&p, pk, 0);
    if (enclevel == 0)
        return outlen;
    else {
        char psbuf[PEM_BUFSIZE];
        unsigned char keybuf[20];
        int enctmplen, inlen;
        if (cb)
            inlen = cb(psbuf, PEM_BUFSIZE, 1, u);
        else
            inlen = PEM_def_callback(psbuf, PEM_BUFSIZE, 1, u);
        if (inlen <= 0) {
            PEMerr(PEM_F_I2B_PVK, PEM_R_BAD_PASSWORD_READ);
            goto error;
        }
        if (!derive_pvk_key(keybuf, salt, PVK_SALTLEN,
                            (unsigned char *)psbuf, inlen))
            goto error;
        if (enclevel == 1)
            memset(keybuf + 5, 0, 11);
        p = salt + PVK_SALTLEN + 8;
834
        if (!EVP_EncryptInit_ex(cctx, EVP_rc4(), NULL, keybuf, NULL))
835 836
            goto error;
        OPENSSL_cleanse(keybuf, 20);
837
        if (!EVP_DecryptUpdate(cctx, p, &enctmplen, p, pklen - 8))
838
            goto error;
839
        if (!EVP_DecryptFinal_ex(cctx, p + enctmplen, &enctmplen))
840 841
            goto error;
    }
842
    EVP_CIPHER_CTX_free(cctx);
843 844 845
    return outlen;

 error:
846
    EVP_CIPHER_CTX_free(cctx);
847 848
    return -1;
}
849 850

int i2b_PVK_bio(BIO *out, EVP_PKEY *pk, int enclevel,
851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867
                pem_password_cb *cb, void *u)
{
    unsigned char *tmp = NULL;
    int outlen, wrlen;
    outlen = i2b_PVK(&tmp, pk, enclevel, cb, u);
    if (outlen < 0)
        return -1;
    wrlen = BIO_write(out, tmp, outlen);
    OPENSSL_free(tmp);
    if (wrlen == outlen) {
        PEMerr(PEM_F_I2B_PVK_BIO, PEM_R_BIO_WRITE_FAILURE);
        return outlen;
    }
    return -1;
}

# endif
D
Dr. Stephen Henson 已提交
868

D
Dr. Stephen Henson 已提交
869
#endif