Sanity check PVK file fields.
[openssl.git] / crypto / pem / pvkfmt.c
1 /*
2  * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project
3  * 2005.
4  */
5 /* ====================================================================
6  * Copyright (c) 2005 The OpenSSL Project.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in
17  *    the documentation and/or other materials provided with the
18  *    distribution.
19  *
20  * 3. All advertising materials mentioning features or use of this
21  *    software must display the following acknowledgment:
22  *    "This product includes software developed by the OpenSSL Project
23  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
24  *
25  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
26  *    endorse or promote products derived from this software without
27  *    prior written permission. For written permission, please contact
28  *    licensing@OpenSSL.org.
29  *
30  * 5. Products derived from this software may not be called "OpenSSL"
31  *    nor may "OpenSSL" appear in their names without prior written
32  *    permission of the OpenSSL Project.
33  *
34  * 6. Redistributions of any form whatsoever must retain the following
35  *    acknowledgment:
36  *    "This product includes software developed by the OpenSSL Project
37  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
38  *
39  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
40  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
43  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
45  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
46  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
48  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
50  * OF THE POSSIBILITY OF SUCH DAMAGE.
51  * ====================================================================
52  *
53  * This product includes cryptographic software written by Eric Young
54  * (eay@cryptsoft.com).  This product includes software written by Tim
55  * Hudson (tjh@cryptsoft.com).
56  *
57  */
58
59 /*
60  * Support for PVK format keys and related structures (such a PUBLICKEYBLOB
61  * and PRIVATEKEYBLOB).
62  */
63
64 #include "internal/cryptlib.h"
65 #include <openssl/pem.h>
66 #include <openssl/rand.h>
67 #include <openssl/bn.h>
68 #if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_NO_DSA)
69 # include <openssl/dsa.h>
70 # include <openssl/rsa.h>
71
72 /*
73  * Utility function: read a DWORD (4 byte unsigned integer) in little endian
74  * format
75  */
76
77 static unsigned int read_ledword(const unsigned char **in)
78 {
79     const unsigned char *p = *in;
80     unsigned int ret;
81     ret = *p++;
82     ret |= (*p++ << 8);
83     ret |= (*p++ << 16);
84     ret |= (*p++ << 24);
85     *in = p;
86     return ret;
87 }
88
89 /*
90  * Read a BIGNUM in little endian format. The docs say that this should take
91  * up bitlen/8 bytes.
92  */
93
94 static int read_lebn(const unsigned char **in, unsigned int nbyte, BIGNUM **r)
95 {
96     *r = BN_lebin2bn(*in, nbyte, NULL);
97     if (*r == NULL)
98         return 0;
99     *in += nbyte;
100     return 1;
101 }
102
103 /* Convert private key blob to EVP_PKEY: RSA and DSA keys supported */
104
105 # define MS_PUBLICKEYBLOB        0x6
106 # define MS_PRIVATEKEYBLOB       0x7
107 # define MS_RSA1MAGIC            0x31415352L
108 # define MS_RSA2MAGIC            0x32415352L
109 # define MS_DSS1MAGIC            0x31535344L
110 # define MS_DSS2MAGIC            0x32535344L
111
112 # define MS_KEYALG_RSA_KEYX      0xa400
113 # define MS_KEYALG_DSS_SIGN      0x2200
114
115 # define MS_KEYTYPE_KEYX         0x1
116 # define MS_KEYTYPE_SIGN         0x2
117
118 /* The PVK file magic number: seems to spell out "bobsfile", who is Bob? */
119 # define MS_PVKMAGIC             0xb0b5f11eL
120 /* Salt length for PVK files */
121 # define PVK_SALTLEN             0x10
122 /* Maximum length in PVK header */
123 # define PVK_MAX_KEYLEN          102400
124 /* Maximum salt length */
125 # define PVK_MAX_SALTLEN         10240
126
127 static EVP_PKEY *b2i_rsa(const unsigned char **in,
128                          unsigned int bitlen, int ispub);
129 static EVP_PKEY *b2i_dss(const unsigned char **in,
130                          unsigned int bitlen, int ispub);
131
132 static int do_blob_header(const unsigned char **in, unsigned int length,
133                           unsigned int *pmagic, unsigned int *pbitlen,
134                           int *pisdss, int *pispub)
135 {
136     const unsigned char *p = *in;
137     if (length < 16)
138         return 0;
139     /* bType */
140     if (*p == MS_PUBLICKEYBLOB) {
141         if (*pispub == 0) {
142             PEMerr(PEM_F_DO_BLOB_HEADER, PEM_R_EXPECTING_PRIVATE_KEY_BLOB);
143             return 0;
144         }
145         *pispub = 1;
146     } else if (*p == MS_PRIVATEKEYBLOB) {
147         if (*pispub == 1) {
148             PEMerr(PEM_F_DO_BLOB_HEADER, PEM_R_EXPECTING_PUBLIC_KEY_BLOB);
149             return 0;
150         }
151         *pispub = 0;
152     } else
153         return 0;
154     p++;
155     /* Version */
156     if (*p++ != 0x2) {
157         PEMerr(PEM_F_DO_BLOB_HEADER, PEM_R_BAD_VERSION_NUMBER);
158         return 0;
159     }
160     /* Ignore reserved, aiKeyAlg */
161     p += 6;
162     *pmagic = read_ledword(&p);
163     *pbitlen = read_ledword(&p);
164     *pisdss = 0;
165     switch (*pmagic) {
166
167     case MS_DSS1MAGIC:
168         *pisdss = 1;
169     case MS_RSA1MAGIC:
170         if (*pispub == 0) {
171             PEMerr(PEM_F_DO_BLOB_HEADER, PEM_R_EXPECTING_PRIVATE_KEY_BLOB);
172             return 0;
173         }
174         break;
175
176     case MS_DSS2MAGIC:
177         *pisdss = 1;
178     case MS_RSA2MAGIC:
179         if (*pispub == 1) {
180             PEMerr(PEM_F_DO_BLOB_HEADER, PEM_R_EXPECTING_PUBLIC_KEY_BLOB);
181             return 0;
182         }
183         break;
184
185     default:
186         PEMerr(PEM_F_DO_BLOB_HEADER, PEM_R_BAD_MAGIC_NUMBER);
187         return -1;
188     }
189     *in = p;
190     return 1;
191 }
192
193 static unsigned int blob_length(unsigned bitlen, int isdss, int ispub)
194 {
195     unsigned int nbyte, hnbyte;
196     nbyte = (bitlen + 7) >> 3;
197     hnbyte = (bitlen + 15) >> 4;
198     if (isdss) {
199
200         /*
201          * Expected length: 20 for q + 3 components bitlen each + 24 for seed
202          * structure.
203          */
204         if (ispub)
205             return 44 + 3 * nbyte;
206         /*
207          * Expected length: 20 for q, priv, 2 bitlen components + 24 for seed
208          * structure.
209          */
210         else
211             return 64 + 2 * nbyte;
212     } else {
213         /* Expected length: 4 for 'e' + 'n' */
214         if (ispub)
215             return 4 + nbyte;
216         else
217             /*
218              * Expected length: 4 for 'e' and 7 other components. 2
219              * components are bitlen size, 5 are bitlen/2
220              */
221             return 4 + 2 * nbyte + 5 * hnbyte;
222     }
223
224 }
225
226 static EVP_PKEY *do_b2i(const unsigned char **in, unsigned int length,
227                         int ispub)
228 {
229     const unsigned char *p = *in;
230     unsigned int bitlen, magic;
231     int isdss;
232     if (do_blob_header(&p, length, &magic, &bitlen, &isdss, &ispub) <= 0) {
233         PEMerr(PEM_F_DO_B2I, PEM_R_KEYBLOB_HEADER_PARSE_ERROR);
234         return NULL;
235     }
236     length -= 16;
237     if (length < blob_length(bitlen, isdss, ispub)) {
238         PEMerr(PEM_F_DO_B2I, PEM_R_KEYBLOB_TOO_SHORT);
239         return NULL;
240     }
241     if (isdss)
242         return b2i_dss(&p, bitlen, ispub);
243     else
244         return b2i_rsa(&p, bitlen, ispub);
245 }
246
247 static EVP_PKEY *do_b2i_bio(BIO *in, int ispub)
248 {
249     const unsigned char *p;
250     unsigned char hdr_buf[16], *buf = NULL;
251     unsigned int bitlen, magic, length;
252     int isdss;
253     EVP_PKEY *ret = NULL;
254     if (BIO_read(in, hdr_buf, 16) != 16) {
255         PEMerr(PEM_F_DO_B2I_BIO, PEM_R_KEYBLOB_TOO_SHORT);
256         return NULL;
257     }
258     p = hdr_buf;
259     if (do_blob_header(&p, 16, &magic, &bitlen, &isdss, &ispub) <= 0)
260         return NULL;
261
262     length = blob_length(bitlen, isdss, ispub);
263     buf = OPENSSL_malloc(length);
264     if (buf == NULL) {
265         PEMerr(PEM_F_DO_B2I_BIO, ERR_R_MALLOC_FAILURE);
266         goto err;
267     }
268     p = buf;
269     if (BIO_read(in, buf, length) != (int)length) {
270         PEMerr(PEM_F_DO_B2I_BIO, PEM_R_KEYBLOB_TOO_SHORT);
271         goto err;
272     }
273
274     if (isdss)
275         ret = b2i_dss(&p, bitlen, ispub);
276     else
277         ret = b2i_rsa(&p, bitlen, ispub);
278
279  err:
280     OPENSSL_free(buf);
281     return ret;
282 }
283
284 static EVP_PKEY *b2i_dss(const unsigned char **in,
285                          unsigned int bitlen, int ispub)
286 {
287     const unsigned char *p = *in;
288     EVP_PKEY *ret = NULL;
289     DSA *dsa = NULL;
290     BN_CTX *ctx = NULL;
291     unsigned int nbyte;
292     nbyte = (bitlen + 7) >> 3;
293
294     dsa = DSA_new();
295     ret = EVP_PKEY_new();
296     if (dsa == NULL || ret == NULL)
297         goto memerr;
298     if (!read_lebn(&p, nbyte, &dsa->p))
299         goto memerr;
300     if (!read_lebn(&p, 20, &dsa->q))
301         goto memerr;
302     if (!read_lebn(&p, nbyte, &dsa->g))
303         goto memerr;
304     if (ispub) {
305         if (!read_lebn(&p, nbyte, &dsa->pub_key))
306             goto memerr;
307     } else {
308         if (!read_lebn(&p, 20, &dsa->priv_key))
309             goto memerr;
310         /* Calculate public key */
311         if ((dsa->pub_key = BN_new()) == NULL)
312             goto memerr;
313         if ((ctx = BN_CTX_new()) == NULL)
314             goto memerr;
315
316         if (!BN_mod_exp(dsa->pub_key, dsa->g, dsa->priv_key, dsa->p, ctx))
317             goto memerr;
318         BN_CTX_free(ctx);
319     }
320
321     EVP_PKEY_set1_DSA(ret, dsa);
322     DSA_free(dsa);
323     *in = p;
324     return ret;
325
326  memerr:
327     PEMerr(PEM_F_B2I_DSS, ERR_R_MALLOC_FAILURE);
328     DSA_free(dsa);
329     EVP_PKEY_free(ret);
330     BN_CTX_free(ctx);
331     return NULL;
332 }
333
334 static EVP_PKEY *b2i_rsa(const unsigned char **in,
335                          unsigned int bitlen, int ispub)
336 {
337     const unsigned char *p = *in;
338     EVP_PKEY *ret = NULL;
339     RSA *rsa = NULL;
340     unsigned int nbyte, hnbyte;
341     nbyte = (bitlen + 7) >> 3;
342     hnbyte = (bitlen + 15) >> 4;
343     rsa = RSA_new();
344     ret = EVP_PKEY_new();
345     if (rsa == NULL || ret == NULL)
346         goto memerr;
347     rsa->e = BN_new();
348     if (rsa->e == NULL)
349         goto memerr;
350     if (!BN_set_word(rsa->e, read_ledword(&p)))
351         goto memerr;
352     if (!read_lebn(&p, nbyte, &rsa->n))
353         goto memerr;
354     if (!ispub) {
355         if (!read_lebn(&p, hnbyte, &rsa->p))
356             goto memerr;
357         if (!read_lebn(&p, hnbyte, &rsa->q))
358             goto memerr;
359         if (!read_lebn(&p, hnbyte, &rsa->dmp1))
360             goto memerr;
361         if (!read_lebn(&p, hnbyte, &rsa->dmq1))
362             goto memerr;
363         if (!read_lebn(&p, hnbyte, &rsa->iqmp))
364             goto memerr;
365         if (!read_lebn(&p, nbyte, &rsa->d))
366             goto memerr;
367     }
368
369     EVP_PKEY_set1_RSA(ret, rsa);
370     RSA_free(rsa);
371     *in = p;
372     return ret;
373  memerr:
374     PEMerr(PEM_F_B2I_RSA, ERR_R_MALLOC_FAILURE);
375     RSA_free(rsa);
376     EVP_PKEY_free(ret);
377     return NULL;
378 }
379
380 EVP_PKEY *b2i_PrivateKey(const unsigned char **in, long length)
381 {
382     return do_b2i(in, length, 0);
383 }
384
385 EVP_PKEY *b2i_PublicKey(const unsigned char **in, long length)
386 {
387     return do_b2i(in, length, 1);
388 }
389
390 EVP_PKEY *b2i_PrivateKey_bio(BIO *in)
391 {
392     return do_b2i_bio(in, 0);
393 }
394
395 EVP_PKEY *b2i_PublicKey_bio(BIO *in)
396 {
397     return do_b2i_bio(in, 1);
398 }
399
400 static void write_ledword(unsigned char **out, unsigned int dw)
401 {
402     unsigned char *p = *out;
403     *p++ = dw & 0xff;
404     *p++ = (dw >> 8) & 0xff;
405     *p++ = (dw >> 16) & 0xff;
406     *p++ = (dw >> 24) & 0xff;
407     *out = p;
408 }
409
410 static void write_lebn(unsigned char **out, const BIGNUM *bn, int len)
411 {
412     BN_bn2lebinpad(bn, *out, len);
413     *out += len;
414 }
415
416 static int check_bitlen_rsa(RSA *rsa, int ispub, unsigned int *magic);
417 static int check_bitlen_dsa(DSA *dsa, int ispub, unsigned int *magic);
418
419 static void write_rsa(unsigned char **out, RSA *rsa, int ispub);
420 static void write_dsa(unsigned char **out, DSA *dsa, int ispub);
421
422 static int do_i2b(unsigned char **out, EVP_PKEY *pk, int ispub)
423 {
424     unsigned char *p;
425     unsigned int bitlen, magic = 0, keyalg;
426     int outlen, noinc = 0;
427     int pktype = EVP_PKEY_id(pk);
428     if (pktype == EVP_PKEY_DSA) {
429         bitlen = check_bitlen_dsa(EVP_PKEY_get0_DSA(pk), ispub, &magic);
430         keyalg = MS_KEYALG_DSS_SIGN;
431     } else if (pktype == EVP_PKEY_RSA) {
432         bitlen = check_bitlen_rsa(EVP_PKEY_get0_RSA(pk), ispub, &magic);
433         keyalg = MS_KEYALG_RSA_KEYX;
434     } else
435         return -1;
436     if (bitlen == 0)
437         return -1;
438     outlen = 16 + blob_length(bitlen,
439                               keyalg == MS_KEYALG_DSS_SIGN ? 1 : 0, ispub);
440     if (out == NULL)
441         return outlen;
442     if (*out)
443         p = *out;
444     else {
445         p = OPENSSL_malloc(outlen);
446         if (p == NULL)
447             return -1;
448         *out = p;
449         noinc = 1;
450     }
451     if (ispub)
452         *p++ = MS_PUBLICKEYBLOB;
453     else
454         *p++ = MS_PRIVATEKEYBLOB;
455     *p++ = 0x2;
456     *p++ = 0;
457     *p++ = 0;
458     write_ledword(&p, keyalg);
459     write_ledword(&p, magic);
460     write_ledword(&p, bitlen);
461     if (keyalg == MS_KEYALG_DSS_SIGN)
462         write_dsa(&p, EVP_PKEY_get0_DSA(pk), ispub);
463     else
464         write_rsa(&p, EVP_PKEY_get0_RSA(pk), ispub);
465     if (!noinc)
466         *out += outlen;
467     return outlen;
468 }
469
470 static int do_i2b_bio(BIO *out, EVP_PKEY *pk, int ispub)
471 {
472     unsigned char *tmp = NULL;
473     int outlen, wrlen;
474     outlen = do_i2b(&tmp, pk, ispub);
475     if (outlen < 0)
476         return -1;
477     wrlen = BIO_write(out, tmp, outlen);
478     OPENSSL_free(tmp);
479     if (wrlen == outlen)
480         return outlen;
481     return -1;
482 }
483
484 static int check_bitlen_dsa(DSA *dsa, int ispub, unsigned int *pmagic)
485 {
486     int bitlen;
487     bitlen = BN_num_bits(dsa->p);
488     if ((bitlen & 7) || (BN_num_bits(dsa->q) != 160)
489         || (BN_num_bits(dsa->g) > bitlen))
490         goto badkey;
491     if (ispub) {
492         if (BN_num_bits(dsa->pub_key) > bitlen)
493             goto badkey;
494         *pmagic = MS_DSS1MAGIC;
495     } else {
496         if (BN_num_bits(dsa->priv_key) > 160)
497             goto badkey;
498         *pmagic = MS_DSS2MAGIC;
499     }
500
501     return bitlen;
502  badkey:
503     PEMerr(PEM_F_CHECK_BITLEN_DSA, PEM_R_UNSUPPORTED_KEY_COMPONENTS);
504     return 0;
505 }
506
507 static int check_bitlen_rsa(RSA *rsa, int ispub, unsigned int *pmagic)
508 {
509     int nbyte, hnbyte, bitlen;
510     if (BN_num_bits(rsa->e) > 32)
511         goto badkey;
512     bitlen = BN_num_bits(rsa->n);
513     nbyte = BN_num_bytes(rsa->n);
514     hnbyte = (BN_num_bits(rsa->n) + 15) >> 4;
515     if (ispub) {
516         *pmagic = MS_RSA1MAGIC;
517         return bitlen;
518     } else {
519         *pmagic = MS_RSA2MAGIC;
520         /*
521          * For private key each component must fit within nbyte or hnbyte.
522          */
523         if (BN_num_bytes(rsa->d) > nbyte)
524             goto badkey;
525         if ((BN_num_bytes(rsa->iqmp) > hnbyte)
526             || (BN_num_bytes(rsa->p) > hnbyte)
527             || (BN_num_bytes(rsa->q) > hnbyte)
528             || (BN_num_bytes(rsa->dmp1) > hnbyte)
529             || (BN_num_bytes(rsa->dmq1) > hnbyte))
530             goto badkey;
531     }
532     return bitlen;
533  badkey:
534     PEMerr(PEM_F_CHECK_BITLEN_RSA, PEM_R_UNSUPPORTED_KEY_COMPONENTS);
535     return 0;
536 }
537
538 static void write_rsa(unsigned char **out, RSA *rsa, int ispub)
539 {
540     int nbyte, hnbyte;
541     nbyte = BN_num_bytes(rsa->n);
542     hnbyte = (BN_num_bits(rsa->n) + 15) >> 4;
543     write_lebn(out, rsa->e, 4);
544     write_lebn(out, rsa->n, -1);
545     if (ispub)
546         return;
547     write_lebn(out, rsa->p, hnbyte);
548     write_lebn(out, rsa->q, hnbyte);
549     write_lebn(out, rsa->dmp1, hnbyte);
550     write_lebn(out, rsa->dmq1, hnbyte);
551     write_lebn(out, rsa->iqmp, hnbyte);
552     write_lebn(out, rsa->d, nbyte);
553 }
554
555 static void write_dsa(unsigned char **out, DSA *dsa, int ispub)
556 {
557     int nbyte;
558     nbyte = BN_num_bytes(dsa->p);
559     write_lebn(out, dsa->p, nbyte);
560     write_lebn(out, dsa->q, 20);
561     write_lebn(out, dsa->g, nbyte);
562     if (ispub)
563         write_lebn(out, dsa->pub_key, nbyte);
564     else
565         write_lebn(out, dsa->priv_key, 20);
566     /* Set "invalid" for seed structure values */
567     memset(*out, 0xff, 24);
568     *out += 24;
569     return;
570 }
571
572 int i2b_PrivateKey_bio(BIO *out, EVP_PKEY *pk)
573 {
574     return do_i2b_bio(out, pk, 0);
575 }
576
577 int i2b_PublicKey_bio(BIO *out, EVP_PKEY *pk)
578 {
579     return do_i2b_bio(out, pk, 1);
580 }
581
582 # ifndef OPENSSL_NO_RC4
583
584 static int do_PVK_header(const unsigned char **in, unsigned int length,
585                          int skip_magic,
586                          unsigned int *psaltlen, unsigned int *pkeylen)
587 {
588     const unsigned char *p = *in;
589     unsigned int pvk_magic, is_encrypted;
590     if (skip_magic) {
591         if (length < 20) {
592             PEMerr(PEM_F_DO_PVK_HEADER, PEM_R_PVK_TOO_SHORT);
593             return 0;
594         }
595     } else {
596         if (length < 24) {
597             PEMerr(PEM_F_DO_PVK_HEADER, PEM_R_PVK_TOO_SHORT);
598             return 0;
599         }
600         pvk_magic = read_ledword(&p);
601         if (pvk_magic != MS_PVKMAGIC) {
602             PEMerr(PEM_F_DO_PVK_HEADER, PEM_R_BAD_MAGIC_NUMBER);
603             return 0;
604         }
605     }
606     /* Skip reserved */
607     p += 4;
608     /*
609      * keytype =
610      */ read_ledword(&p);
611     is_encrypted = read_ledword(&p);
612     *psaltlen = read_ledword(&p);
613     *pkeylen = read_ledword(&p);
614
615     if (*pkeylen > PVK_MAX_KEYLEN || *psaltlen > PVK_MAX_SALTLEN)
616         return 0;
617
618     if (is_encrypted && !*psaltlen) {
619         PEMerr(PEM_F_DO_PVK_HEADER, PEM_R_INCONSISTENT_HEADER);
620         return 0;
621     }
622
623     *in = p;
624     return 1;
625 }
626
627 static int derive_pvk_key(unsigned char *key,
628                           const unsigned char *salt, unsigned int saltlen,
629                           const unsigned char *pass, int passlen)
630 {
631     EVP_MD_CTX *mctx = EVP_MD_CTX_new();
632     int rv = 1;
633     if (mctx == NULL
634         || !EVP_DigestInit_ex(mctx, EVP_sha1(), NULL)
635         || !EVP_DigestUpdate(mctx, salt, saltlen)
636         || !EVP_DigestUpdate(mctx, pass, passlen)
637         || !EVP_DigestFinal_ex(mctx, key, NULL))
638         rv = 0;
639
640     EVP_MD_CTX_free(mctx);
641     return rv;
642 }
643
644 static EVP_PKEY *do_PVK_body(const unsigned char **in,
645                              unsigned int saltlen, unsigned int keylen,
646                              pem_password_cb *cb, void *u)
647 {
648     EVP_PKEY *ret = NULL;
649     const unsigned char *p = *in;
650     unsigned int magic;
651     unsigned char *enctmp = NULL, *q;
652
653     EVP_CIPHER_CTX *cctx = EVP_CIPHER_CTX_new();
654     if (saltlen) {
655         char psbuf[PEM_BUFSIZE];
656         unsigned char keybuf[20];
657         int enctmplen, inlen;
658         if (cb)
659             inlen = cb(psbuf, PEM_BUFSIZE, 0, u);
660         else
661             inlen = PEM_def_callback(psbuf, PEM_BUFSIZE, 0, u);
662         if (inlen <= 0) {
663             PEMerr(PEM_F_DO_PVK_BODY, PEM_R_BAD_PASSWORD_READ);
664             goto err;
665         }
666         enctmp = OPENSSL_malloc(keylen + 8);
667         if (enctmp == NULL) {
668             PEMerr(PEM_F_DO_PVK_BODY, ERR_R_MALLOC_FAILURE);
669             goto err;
670         }
671         if (!derive_pvk_key(keybuf, p, saltlen,
672                             (unsigned char *)psbuf, inlen))
673             goto err;
674         p += saltlen;
675         /* Copy BLOBHEADER across, decrypt rest */
676         memcpy(enctmp, p, 8);
677         p += 8;
678         if (keylen < 8) {
679             PEMerr(PEM_F_DO_PVK_BODY, PEM_R_PVK_TOO_SHORT);
680             goto err;
681         }
682         inlen = keylen - 8;
683         q = enctmp + 8;
684         if (!EVP_DecryptInit_ex(cctx, EVP_rc4(), NULL, keybuf, NULL))
685             goto err;
686         if (!EVP_DecryptUpdate(cctx, q, &enctmplen, p, inlen))
687             goto err;
688         if (!EVP_DecryptFinal_ex(cctx, q + enctmplen, &enctmplen))
689             goto err;
690         magic = read_ledword((const unsigned char **)&q);
691         if (magic != MS_RSA2MAGIC && magic != MS_DSS2MAGIC) {
692             q = enctmp + 8;
693             memset(keybuf + 5, 0, 11);
694             if (!EVP_DecryptInit_ex(cctx, EVP_rc4(), NULL, keybuf, NULL))
695                 goto err;
696             OPENSSL_cleanse(keybuf, 20);
697             if (!EVP_DecryptUpdate(cctx, q, &enctmplen, p, inlen))
698                 goto err;
699             if (!EVP_DecryptFinal_ex(cctx, q + enctmplen, &enctmplen))
700                 goto err;
701             magic = read_ledword((const unsigned char **)&q);
702             if (magic != MS_RSA2MAGIC && magic != MS_DSS2MAGIC) {
703                 PEMerr(PEM_F_DO_PVK_BODY, PEM_R_BAD_DECRYPT);
704                 goto err;
705             }
706         } else
707             OPENSSL_cleanse(keybuf, 20);
708         p = enctmp;
709     }
710
711     ret = b2i_PrivateKey(&p, keylen);
712  err:
713     EVP_CIPHER_CTX_free(cctx);
714     OPENSSL_free(enctmp);
715     return ret;
716 }
717
718 EVP_PKEY *b2i_PVK_bio(BIO *in, pem_password_cb *cb, void *u)
719 {
720     unsigned char pvk_hdr[24], *buf = NULL;
721     const unsigned char *p;
722     int buflen;
723     EVP_PKEY *ret = NULL;
724     unsigned int saltlen, keylen;
725     if (BIO_read(in, pvk_hdr, 24) != 24) {
726         PEMerr(PEM_F_B2I_PVK_BIO, PEM_R_PVK_DATA_TOO_SHORT);
727         return NULL;
728     }
729     p = pvk_hdr;
730
731     if (!do_PVK_header(&p, 24, 0, &saltlen, &keylen))
732         return 0;
733     buflen = (int)keylen + saltlen;
734     buf = OPENSSL_malloc(buflen);
735     if (buf == NULL) {
736         PEMerr(PEM_F_B2I_PVK_BIO, ERR_R_MALLOC_FAILURE);
737         return 0;
738     }
739     p = buf;
740     if (BIO_read(in, buf, buflen) != buflen) {
741         PEMerr(PEM_F_B2I_PVK_BIO, PEM_R_PVK_DATA_TOO_SHORT);
742         goto err;
743     }
744     ret = do_PVK_body(&p, saltlen, keylen, cb, u);
745
746  err:
747     OPENSSL_clear_free(buf, buflen);
748     return ret;
749 }
750
751 static int i2b_PVK(unsigned char **out, EVP_PKEY *pk, int enclevel,
752                    pem_password_cb *cb, void *u)
753 {
754     int outlen = 24, pklen;
755     unsigned char *p, *salt = NULL;
756     EVP_CIPHER_CTX *cctx = EVP_CIPHER_CTX_new();
757     if (enclevel)
758         outlen += PVK_SALTLEN;
759     pklen = do_i2b(NULL, pk, 0);
760     if (pklen < 0)
761         return -1;
762     outlen += pklen;
763     if (!out)
764         return outlen;
765     if (*out)
766         p = *out;
767     else {
768         p = OPENSSL_malloc(outlen);
769         if (p == NULL) {
770             PEMerr(PEM_F_I2B_PVK, ERR_R_MALLOC_FAILURE);
771             return -1;
772         }
773         *out = p;
774     }
775
776     write_ledword(&p, MS_PVKMAGIC);
777     write_ledword(&p, 0);
778     if (EVP_PKEY_id(pk) == EVP_PKEY_DSA)
779         write_ledword(&p, MS_KEYTYPE_SIGN);
780     else
781         write_ledword(&p, MS_KEYTYPE_KEYX);
782     write_ledword(&p, enclevel ? 1 : 0);
783     write_ledword(&p, enclevel ? PVK_SALTLEN : 0);
784     write_ledword(&p, pklen);
785     if (enclevel) {
786         if (RAND_bytes(p, PVK_SALTLEN) <= 0)
787             goto error;
788         salt = p;
789         p += PVK_SALTLEN;
790     }
791     do_i2b(&p, pk, 0);
792     if (enclevel == 0)
793         return outlen;
794     else {
795         char psbuf[PEM_BUFSIZE];
796         unsigned char keybuf[20];
797         int enctmplen, inlen;
798         if (cb)
799             inlen = cb(psbuf, PEM_BUFSIZE, 1, u);
800         else
801             inlen = PEM_def_callback(psbuf, PEM_BUFSIZE, 1, u);
802         if (inlen <= 0) {
803             PEMerr(PEM_F_I2B_PVK, PEM_R_BAD_PASSWORD_READ);
804             goto error;
805         }
806         if (!derive_pvk_key(keybuf, salt, PVK_SALTLEN,
807                             (unsigned char *)psbuf, inlen))
808             goto error;
809         if (enclevel == 1)
810             memset(keybuf + 5, 0, 11);
811         p = salt + PVK_SALTLEN + 8;
812         if (!EVP_EncryptInit_ex(cctx, EVP_rc4(), NULL, keybuf, NULL))
813             goto error;
814         OPENSSL_cleanse(keybuf, 20);
815         if (!EVP_DecryptUpdate(cctx, p, &enctmplen, p, pklen - 8))
816             goto error;
817         if (!EVP_DecryptFinal_ex(cctx, p + enctmplen, &enctmplen))
818             goto error;
819     }
820     EVP_CIPHER_CTX_free(cctx);
821     return outlen;
822
823  error:
824     EVP_CIPHER_CTX_free(cctx);
825     return -1;
826 }
827
828 int i2b_PVK_bio(BIO *out, EVP_PKEY *pk, int enclevel,
829                 pem_password_cb *cb, void *u)
830 {
831     unsigned char *tmp = NULL;
832     int outlen, wrlen;
833     outlen = i2b_PVK(&tmp, pk, enclevel, cb, u);
834     if (outlen < 0)
835         return -1;
836     wrlen = BIO_write(out, tmp, outlen);
837     OPENSSL_free(tmp);
838     if (wrlen == outlen) {
839         PEMerr(PEM_F_I2B_PVK_BIO, PEM_R_BIO_WRITE_FAILURE);
840         return outlen;
841     }
842     return -1;
843 }
844
845 # endif
846
847 #endif