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 "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     const unsigned char *p;
97     unsigned char *tmpbuf, *q;
98     unsigned int i;
99     p = *in + nbyte - 1;
100     tmpbuf = OPENSSL_malloc(nbyte);
101     if (!tmpbuf)
102         return 0;
103     q = tmpbuf;
104     for (i = 0; i < nbyte; i++)
105         *q++ = *p--;
106     *r = BN_bin2bn(tmpbuf, nbyte, NULL);
107     OPENSSL_free(tmpbuf);
108     if (*r) {
109         *in += nbyte;
110         return 1;
111     } else
112         return 0;
113 }
114
115 /* Convert private key blob to EVP_PKEY: RSA and DSA keys supported */
116
117 # define MS_PUBLICKEYBLOB        0x6
118 # define MS_PRIVATEKEYBLOB       0x7
119 # define MS_RSA1MAGIC            0x31415352L
120 # define MS_RSA2MAGIC            0x32415352L
121 # define MS_DSS1MAGIC            0x31535344L
122 # define MS_DSS2MAGIC            0x32535344L
123
124 # define MS_KEYALG_RSA_KEYX      0xa400
125 # define MS_KEYALG_DSS_SIGN      0x2200
126
127 # define MS_KEYTYPE_KEYX         0x1
128 # 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 /* Maximum length in PVK header */
135 # define PVK_MAX_KEYLEN          102400
136 /* Maximum salt length */
137 # define PVK_MAX_SALTLEN         10240
138
139 static EVP_PKEY *b2i_rsa(const unsigned char **in, unsigned int length,
140                          unsigned int bitlen, int ispub);
141 static EVP_PKEY *b2i_dss(const unsigned char **in, unsigned int length,
142                          unsigned int bitlen, int ispub);
143
144 static int do_blob_header(const unsigned char **in, unsigned int length,
145                           unsigned int *pmagic, unsigned int *pbitlen,
146                           int *pisdss, int *pispub)
147 {
148     const unsigned char *p = *in;
149     if (length < 16)
150         return 0;
151     /* bType */
152     if (*p == MS_PUBLICKEYBLOB) {
153         if (*pispub == 0) {
154             PEMerr(PEM_F_DO_BLOB_HEADER, PEM_R_EXPECTING_PRIVATE_KEY_BLOB);
155             return 0;
156         }
157         *pispub = 1;
158     } else if (*p == MS_PRIVATEKEYBLOB) {
159         if (*pispub == 1) {
160             PEMerr(PEM_F_DO_BLOB_HEADER, PEM_R_EXPECTING_PUBLIC_KEY_BLOB);
161             return 0;
162         }
163         *pispub = 0;
164     } else
165         return 0;
166     p++;
167     /* Version */
168     if (*p++ != 0x2) {
169         PEMerr(PEM_F_DO_BLOB_HEADER, PEM_R_BAD_VERSION_NUMBER);
170         return 0;
171     }
172     /* Ignore reserved, aiKeyAlg */
173     p += 6;
174     *pmagic = read_ledword(&p);
175     *pbitlen = read_ledword(&p);
176     *pisdss = 0;
177     switch (*pmagic) {
178
179     case MS_DSS1MAGIC:
180         *pisdss = 1;
181     case MS_RSA1MAGIC:
182         if (*pispub == 0) {
183             PEMerr(PEM_F_DO_BLOB_HEADER, PEM_R_EXPECTING_PRIVATE_KEY_BLOB);
184             return 0;
185         }
186         break;
187
188     case MS_DSS2MAGIC:
189         *pisdss = 1;
190     case MS_RSA2MAGIC:
191         if (*pispub == 1) {
192             PEMerr(PEM_F_DO_BLOB_HEADER, PEM_R_EXPECTING_PUBLIC_KEY_BLOB);
193             return 0;
194         }
195         break;
196
197     default:
198         PEMerr(PEM_F_DO_BLOB_HEADER, PEM_R_BAD_MAGIC_NUMBER);
199         return -1;
200     }
201     *in = p;
202     return 1;
203 }
204
205 static unsigned int blob_length(unsigned bitlen, int isdss, int ispub)
206 {
207     unsigned int nbyte, hnbyte;
208     nbyte = (bitlen + 7) >> 3;
209     hnbyte = (bitlen + 15) >> 4;
210     if (isdss) {
211
212         /*
213          * Expected length: 20 for q + 3 components bitlen each + 24 for seed
214          * structure.
215          */
216         if (ispub)
217             return 44 + 3 * nbyte;
218         /*
219          * Expected length: 20 for q, priv, 2 bitlen components + 24 for seed
220          * structure.
221          */
222         else
223             return 64 + 2 * nbyte;
224     } else {
225         /* Expected length: 4 for 'e' + 'n' */
226         if (ispub)
227             return 4 + nbyte;
228         else
229             /*
230              * Expected length: 4 for 'e' and 7 other components. 2
231              * components are bitlen size, 5 are bitlen/2
232              */
233             return 4 + 2 * nbyte + 5 * hnbyte;
234     }
235
236 }
237
238 static EVP_PKEY *do_b2i(const unsigned char **in, unsigned int length,
239                         int ispub)
240 {
241     const unsigned char *p = *in;
242     unsigned int bitlen, magic;
243     int isdss;
244     if (do_blob_header(&p, length, &magic, &bitlen, &isdss, &ispub) <= 0) {
245         PEMerr(PEM_F_DO_B2I, PEM_R_KEYBLOB_HEADER_PARSE_ERROR);
246         return NULL;
247     }
248     length -= 16;
249     if (length < blob_length(bitlen, isdss, ispub)) {
250         PEMerr(PEM_F_DO_B2I, PEM_R_KEYBLOB_TOO_SHORT);
251         return NULL;
252     }
253     if (isdss)
254         return b2i_dss(&p, length, bitlen, ispub);
255     else
256         return b2i_rsa(&p, length, bitlen, ispub);
257 }
258
259 static EVP_PKEY *do_b2i_bio(BIO *in, int ispub)
260 {
261     const unsigned char *p;
262     unsigned char hdr_buf[16], *buf = NULL;
263     unsigned int bitlen, magic, length;
264     int isdss;
265     EVP_PKEY *ret = NULL;
266     if (BIO_read(in, hdr_buf, 16) != 16) {
267         PEMerr(PEM_F_DO_B2I_BIO, PEM_R_KEYBLOB_TOO_SHORT);
268         return NULL;
269     }
270     p = hdr_buf;
271     if (do_blob_header(&p, 16, &magic, &bitlen, &isdss, &ispub) <= 0)
272         return NULL;
273
274     length = blob_length(bitlen, isdss, ispub);
275     buf = OPENSSL_malloc(length);
276     if (!buf) {
277         PEMerr(PEM_F_DO_B2I_BIO, ERR_R_MALLOC_FAILURE);
278         goto err;
279     }
280     p = buf;
281     if (BIO_read(in, buf, length) != (int)length) {
282         PEMerr(PEM_F_DO_B2I_BIO, PEM_R_KEYBLOB_TOO_SHORT);
283         goto err;
284     }
285
286     if (isdss)
287         ret = b2i_dss(&p, length, bitlen, ispub);
288     else
289         ret = b2i_rsa(&p, length, bitlen, ispub);
290
291  err:
292     if (buf)
293         OPENSSL_free(buf);
294     return ret;
295 }
296
297 static EVP_PKEY *b2i_dss(const unsigned char **in, unsigned int length,
298                          unsigned int bitlen, int ispub)
299 {
300     const unsigned char *p = *in;
301     EVP_PKEY *ret = NULL;
302     DSA *dsa = NULL;
303     BN_CTX *ctx = NULL;
304     unsigned int nbyte;
305     nbyte = (bitlen + 7) >> 3;
306
307     dsa = DSA_new();
308     ret = EVP_PKEY_new();
309     if (!dsa || !ret)
310         goto memerr;
311     if (!read_lebn(&p, nbyte, &dsa->p))
312         goto memerr;
313     if (!read_lebn(&p, 20, &dsa->q))
314         goto memerr;
315     if (!read_lebn(&p, nbyte, &dsa->g))
316         goto memerr;
317     if (ispub) {
318         if (!read_lebn(&p, nbyte, &dsa->pub_key))
319             goto memerr;
320     } else {
321         if (!read_lebn(&p, 20, &dsa->priv_key))
322             goto memerr;
323         /* Calculate public key */
324         if (!(dsa->pub_key = BN_new()))
325             goto memerr;
326         if (!(ctx = BN_CTX_new()))
327             goto memerr;
328
329         if (!BN_mod_exp(dsa->pub_key, dsa->g, dsa->priv_key, dsa->p, ctx))
330
331             goto memerr;
332         BN_CTX_free(ctx);
333     }
334
335     EVP_PKEY_set1_DSA(ret, dsa);
336     DSA_free(dsa);
337     *in = p;
338     return ret;
339
340  memerr:
341     PEMerr(PEM_F_B2I_DSS, ERR_R_MALLOC_FAILURE);
342     if (dsa)
343         DSA_free(dsa);
344     if (ret)
345         EVP_PKEY_free(ret);
346     if (ctx)
347         BN_CTX_free(ctx);
348     return NULL;
349 }
350
351 static EVP_PKEY *b2i_rsa(const unsigned char **in, unsigned int length,
352                          unsigned int bitlen, int ispub)
353 {
354     const unsigned char *p = *in;
355     EVP_PKEY *ret = NULL;
356     RSA *rsa = NULL;
357     unsigned int nbyte, hnbyte;
358     nbyte = (bitlen + 7) >> 3;
359     hnbyte = (bitlen + 15) >> 4;
360     rsa = RSA_new();
361     ret = EVP_PKEY_new();
362     if (!rsa || !ret)
363         goto memerr;
364     rsa->e = BN_new();
365     if (!rsa->e)
366         goto memerr;
367     if (!BN_set_word(rsa->e, read_ledword(&p)))
368         goto memerr;
369     if (!read_lebn(&p, nbyte, &rsa->n))
370         goto memerr;
371     if (!ispub) {
372         if (!read_lebn(&p, hnbyte, &rsa->p))
373             goto memerr;
374         if (!read_lebn(&p, hnbyte, &rsa->q))
375             goto memerr;
376         if (!read_lebn(&p, hnbyte, &rsa->dmp1))
377             goto memerr;
378         if (!read_lebn(&p, hnbyte, &rsa->dmq1))
379             goto memerr;
380         if (!read_lebn(&p, hnbyte, &rsa->iqmp))
381             goto memerr;
382         if (!read_lebn(&p, nbyte, &rsa->d))
383             goto memerr;
384     }
385
386     EVP_PKEY_set1_RSA(ret, rsa);
387     RSA_free(rsa);
388     *in = p;
389     return ret;
390  memerr:
391     PEMerr(PEM_F_B2I_RSA, ERR_R_MALLOC_FAILURE);
392     if (rsa)
393         RSA_free(rsa);
394     if (ret)
395         EVP_PKEY_free(ret);
396     return NULL;
397 }
398
399 EVP_PKEY *b2i_PrivateKey(const unsigned char **in, long length)
400 {
401     return do_b2i(in, length, 0);
402 }
403
404 EVP_PKEY *b2i_PublicKey(const unsigned char **in, long length)
405 {
406     return do_b2i(in, length, 1);
407 }
408
409 EVP_PKEY *b2i_PrivateKey_bio(BIO *in)
410 {
411     return do_b2i_bio(in, 0);
412 }
413
414 EVP_PKEY *b2i_PublicKey_bio(BIO *in)
415 {
416     return do_b2i_bio(in, 1);
417 }
418
419 static void write_ledword(unsigned char **out, unsigned int dw)
420 {
421     unsigned char *p = *out;
422     *p++ = dw & 0xff;
423     *p++ = (dw >> 8) & 0xff;
424     *p++ = (dw >> 16) & 0xff;
425     *p++ = (dw >> 24) & 0xff;
426     *out = p;
427 }
428
429 static void write_lebn(unsigned char **out, const BIGNUM *bn, int len)
430 {
431     int nb, i;
432     unsigned char *p = *out, *q, c;
433     nb = BN_num_bytes(bn);
434     BN_bn2bin(bn, p);
435     q = p + nb - 1;
436     /* In place byte order reversal */
437     for (i = 0; i < nb / 2; i++) {
438         c = *p;
439         *p++ = *q;
440         *q-- = c;
441     }
442     *out += nb;
443     /* Pad with zeroes if we have to */
444     if (len > 0) {
445         len -= nb;
446         if (len > 0) {
447             memset(*out, 0, len);
448             *out += len;
449         }
450     }
451 }
452
453 static int check_bitlen_rsa(RSA *rsa, int ispub, unsigned int *magic);
454 static int check_bitlen_dsa(DSA *dsa, int ispub, unsigned int *magic);
455
456 static void write_rsa(unsigned char **out, RSA *rsa, int ispub);
457 static void write_dsa(unsigned char **out, DSA *dsa, int ispub);
458
459 static int do_i2b(unsigned char **out, EVP_PKEY *pk, int ispub)
460 {
461     unsigned char *p;
462     unsigned int bitlen, magic = 0, keyalg;
463     int outlen, noinc = 0;
464     if (pk->type == EVP_PKEY_DSA) {
465         bitlen = check_bitlen_dsa(pk->pkey.dsa, ispub, &magic);
466         keyalg = MS_KEYALG_DSS_SIGN;
467     } else if (pk->type == EVP_PKEY_RSA) {
468         bitlen = check_bitlen_rsa(pk->pkey.rsa, ispub, &magic);
469         keyalg = MS_KEYALG_RSA_KEYX;
470     } else
471         return -1;
472     if (bitlen == 0)
473         return -1;
474     outlen = 16 + blob_length(bitlen,
475                               keyalg == MS_KEYALG_DSS_SIGN ? 1 : 0, ispub);
476     if (out == NULL)
477         return outlen;
478     if (*out)
479         p = *out;
480     else {
481         p = OPENSSL_malloc(outlen);
482         if (!p)
483             return -1;
484         *out = p;
485         noinc = 1;
486     }
487     if (ispub)
488         *p++ = MS_PUBLICKEYBLOB;
489     else
490         *p++ = MS_PRIVATEKEYBLOB;
491     *p++ = 0x2;
492     *p++ = 0;
493     *p++ = 0;
494     write_ledword(&p, keyalg);
495     write_ledword(&p, magic);
496     write_ledword(&p, bitlen);
497     if (keyalg == MS_KEYALG_DSS_SIGN)
498         write_dsa(&p, pk->pkey.dsa, ispub);
499     else
500         write_rsa(&p, pk->pkey.rsa, ispub);
501     if (!noinc)
502         *out += outlen;
503     return outlen;
504 }
505
506 static int do_i2b_bio(BIO *out, EVP_PKEY *pk, int ispub)
507 {
508     unsigned char *tmp = NULL;
509     int outlen, wrlen;
510     outlen = do_i2b(&tmp, pk, ispub);
511     if (outlen < 0)
512         return -1;
513     wrlen = BIO_write(out, tmp, outlen);
514     OPENSSL_free(tmp);
515     if (wrlen == outlen)
516         return outlen;
517     return -1;
518 }
519
520 static int check_bitlen_dsa(DSA *dsa, int ispub, unsigned int *pmagic)
521 {
522     int bitlen;
523     bitlen = BN_num_bits(dsa->p);
524     if ((bitlen & 7) || (BN_num_bits(dsa->q) != 160)
525         || (BN_num_bits(dsa->g) > bitlen))
526         goto badkey;
527     if (ispub) {
528         if (BN_num_bits(dsa->pub_key) > bitlen)
529             goto badkey;
530         *pmagic = MS_DSS1MAGIC;
531     } else {
532         if (BN_num_bits(dsa->priv_key) > 160)
533             goto badkey;
534         *pmagic = MS_DSS2MAGIC;
535     }
536
537     return bitlen;
538  badkey:
539     PEMerr(PEM_F_CHECK_BITLEN_DSA, PEM_R_UNSUPPORTED_KEY_COMPONENTS);
540     return 0;
541 }
542
543 static int check_bitlen_rsa(RSA *rsa, int ispub, unsigned int *pmagic)
544 {
545     int nbyte, hnbyte, bitlen;
546     if (BN_num_bits(rsa->e) > 32)
547         goto badkey;
548     bitlen = BN_num_bits(rsa->n);
549     nbyte = BN_num_bytes(rsa->n);
550     hnbyte = (BN_num_bits(rsa->n) + 15) >> 4;
551     if (ispub) {
552         *pmagic = MS_RSA1MAGIC;
553         return bitlen;
554     } else {
555         *pmagic = MS_RSA2MAGIC;
556         /*
557          * For private key each component must fit within nbyte or hnbyte.
558          */
559         if (BN_num_bytes(rsa->d) > nbyte)
560             goto badkey;
561         if ((BN_num_bytes(rsa->iqmp) > hnbyte)
562             || (BN_num_bytes(rsa->p) > hnbyte)
563             || (BN_num_bytes(rsa->q) > hnbyte)
564             || (BN_num_bytes(rsa->dmp1) > hnbyte)
565             || (BN_num_bytes(rsa->dmq1) > hnbyte))
566             goto badkey;
567     }
568     return bitlen;
569  badkey:
570     PEMerr(PEM_F_CHECK_BITLEN_RSA, PEM_R_UNSUPPORTED_KEY_COMPONENTS);
571     return 0;
572 }
573
574 static void write_rsa(unsigned char **out, RSA *rsa, int ispub)
575 {
576     int nbyte, hnbyte;
577     nbyte = BN_num_bytes(rsa->n);
578     hnbyte = (BN_num_bits(rsa->n) + 15) >> 4;
579     write_lebn(out, rsa->e, 4);
580     write_lebn(out, rsa->n, -1);
581     if (ispub)
582         return;
583     write_lebn(out, rsa->p, hnbyte);
584     write_lebn(out, rsa->q, hnbyte);
585     write_lebn(out, rsa->dmp1, hnbyte);
586     write_lebn(out, rsa->dmq1, hnbyte);
587     write_lebn(out, rsa->iqmp, hnbyte);
588     write_lebn(out, rsa->d, nbyte);
589 }
590
591 static void write_dsa(unsigned char **out, DSA *dsa, int ispub)
592 {
593     int nbyte;
594     nbyte = BN_num_bytes(dsa->p);
595     write_lebn(out, dsa->p, nbyte);
596     write_lebn(out, dsa->q, 20);
597     write_lebn(out, dsa->g, nbyte);
598     if (ispub)
599         write_lebn(out, dsa->pub_key, nbyte);
600     else
601         write_lebn(out, dsa->priv_key, 20);
602     /* Set "invalid" for seed structure values */
603     memset(*out, 0xff, 24);
604     *out += 24;
605     return;
606 }
607
608 int i2b_PrivateKey_bio(BIO *out, EVP_PKEY *pk)
609 {
610     return do_i2b_bio(out, pk, 0);
611 }
612
613 int i2b_PublicKey_bio(BIO *out, EVP_PKEY *pk)
614 {
615     return do_i2b_bio(out, pk, 1);
616 }
617
618 # ifndef OPENSSL_NO_RC4
619
620 static int do_PVK_header(const unsigned char **in, unsigned int length,
621                          int skip_magic,
622                          unsigned int *psaltlen, unsigned int *pkeylen)
623 {
624     const unsigned char *p = *in;
625     unsigned int pvk_magic, is_encrypted;
626     if (skip_magic) {
627         if (length < 20) {
628             PEMerr(PEM_F_DO_PVK_HEADER, PEM_R_PVK_TOO_SHORT);
629             return 0;
630         }
631     } else {
632         if (length < 24) {
633             PEMerr(PEM_F_DO_PVK_HEADER, PEM_R_PVK_TOO_SHORT);
634             return 0;
635         }
636         pvk_magic = read_ledword(&p);
637         if (pvk_magic != MS_PVKMAGIC) {
638             PEMerr(PEM_F_DO_PVK_HEADER, PEM_R_BAD_MAGIC_NUMBER);
639             return 0;
640         }
641     }
642     /* Skip reserved */
643     p += 4;
644     /*
645      * keytype =
646      */ read_ledword(&p);
647     is_encrypted = read_ledword(&p);
648     *psaltlen = read_ledword(&p);
649     *pkeylen = read_ledword(&p);
650
651     if (*pkeylen > PVK_MAX_KEYLEN || *psaltlen > PVK_MAX_SALTLEN)
652         return 0;
653
654     if (is_encrypted && !*psaltlen) {
655         PEMerr(PEM_F_DO_PVK_HEADER, PEM_R_INCONSISTENT_HEADER);
656         return 0;
657     }
658
659     *in = p;
660     return 1;
661 }
662
663 static int derive_pvk_key(unsigned char *key,
664                           const unsigned char *salt, unsigned int saltlen,
665                           const unsigned char *pass, int passlen)
666 {
667     EVP_MD_CTX mctx;
668     int rv = 1;
669     EVP_MD_CTX_init(&mctx);
670     if (!EVP_DigestInit_ex(&mctx, EVP_sha1(), NULL)
671         || !EVP_DigestUpdate(&mctx, salt, saltlen)
672         || !EVP_DigestUpdate(&mctx, pass, passlen)
673         || !EVP_DigestFinal_ex(&mctx, key, NULL))
674         rv = 0;
675
676     EVP_MD_CTX_cleanup(&mctx);
677     return rv;
678 }
679
680 static EVP_PKEY *do_PVK_body(const unsigned char **in,
681                              unsigned int saltlen, unsigned int keylen,
682                              pem_password_cb *cb, void *u)
683 {
684     EVP_PKEY *ret = NULL;
685     const unsigned char *p = *in;
686     unsigned int magic;
687     unsigned char *enctmp = NULL, *q;
688     EVP_CIPHER_CTX cctx;
689     EVP_CIPHER_CTX_init(&cctx);
690     if (saltlen) {
691         char psbuf[PEM_BUFSIZE];
692         unsigned char keybuf[20];
693         int enctmplen, inlen;
694         if (cb)
695             inlen = cb(psbuf, PEM_BUFSIZE, 0, u);
696         else
697             inlen = PEM_def_callback(psbuf, PEM_BUFSIZE, 0, u);
698         if (inlen <= 0) {
699             PEMerr(PEM_F_DO_PVK_BODY, PEM_R_BAD_PASSWORD_READ);
700             goto err;
701         }
702         enctmp = OPENSSL_malloc(keylen + 8);
703         if (!enctmp) {
704             PEMerr(PEM_F_DO_PVK_BODY, ERR_R_MALLOC_FAILURE);
705             goto err;
706         }
707         if (!derive_pvk_key(keybuf, p, saltlen,
708                             (unsigned char *)psbuf, inlen))
709             goto err;
710         p += saltlen;
711         /* Copy BLOBHEADER across, decrypt rest */
712         memcpy(enctmp, p, 8);
713         p += 8;
714         if (keylen < 8) {
715             PEMerr(PEM_F_DO_PVK_BODY, PEM_R_PVK_TOO_SHORT);
716             goto err;
717         }
718         inlen = keylen - 8;
719         q = enctmp + 8;
720         if (!EVP_DecryptInit_ex(&cctx, EVP_rc4(), NULL, keybuf, NULL))
721             goto err;
722         if (!EVP_DecryptUpdate(&cctx, q, &enctmplen, p, inlen))
723             goto err;
724         if (!EVP_DecryptFinal_ex(&cctx, q + enctmplen, &enctmplen))
725             goto err;
726         magic = read_ledword((const unsigned char **)&q);
727         if (magic != MS_RSA2MAGIC && magic != MS_DSS2MAGIC) {
728             q = enctmp + 8;
729             memset(keybuf + 5, 0, 11);
730             if (!EVP_DecryptInit_ex(&cctx, EVP_rc4(), NULL, keybuf, NULL))
731                 goto err;
732             OPENSSL_cleanse(keybuf, 20);
733             if (!EVP_DecryptUpdate(&cctx, q, &enctmplen, p, inlen))
734                 goto err;
735             if (!EVP_DecryptFinal_ex(&cctx, q + enctmplen, &enctmplen))
736                 goto err;
737             magic = read_ledword((const unsigned char **)&q);
738             if (magic != MS_RSA2MAGIC && magic != MS_DSS2MAGIC) {
739                 PEMerr(PEM_F_DO_PVK_BODY, PEM_R_BAD_DECRYPT);
740                 goto err;
741             }
742         } else
743             OPENSSL_cleanse(keybuf, 20);
744         p = enctmp;
745     }
746
747     ret = b2i_PrivateKey(&p, keylen);
748  err:
749     EVP_CIPHER_CTX_cleanup(&cctx);
750     if (enctmp && saltlen)
751         OPENSSL_free(enctmp);
752     return ret;
753 }
754
755 EVP_PKEY *b2i_PVK_bio(BIO *in, pem_password_cb *cb, void *u)
756 {
757     unsigned char pvk_hdr[24], *buf = NULL;
758     const unsigned char *p;
759     int buflen;
760     EVP_PKEY *ret = NULL;
761     unsigned int saltlen, keylen;
762     if (BIO_read(in, pvk_hdr, 24) != 24) {
763         PEMerr(PEM_F_B2I_PVK_BIO, PEM_R_PVK_DATA_TOO_SHORT);
764         return NULL;
765     }
766     p = pvk_hdr;
767
768     if (!do_PVK_header(&p, 24, 0, &saltlen, &keylen))
769         return 0;
770     buflen = (int)keylen + saltlen;
771     buf = OPENSSL_malloc(buflen);
772     if (!buf) {
773         PEMerr(PEM_F_B2I_PVK_BIO, ERR_R_MALLOC_FAILURE);
774         return 0;
775     }
776     p = buf;
777     if (BIO_read(in, buf, buflen) != buflen) {
778         PEMerr(PEM_F_B2I_PVK_BIO, PEM_R_PVK_DATA_TOO_SHORT);
779         goto err;
780     }
781     ret = do_PVK_body(&p, saltlen, keylen, cb, u);
782
783  err:
784     if (buf) {
785         OPENSSL_cleanse(buf, buflen);
786         OPENSSL_free(buf);
787     }
788     return ret;
789 }
790
791 static int i2b_PVK(unsigned char **out, EVP_PKEY *pk, int enclevel,
792                    pem_password_cb *cb, void *u)
793 {
794     int outlen = 24, pklen;
795     unsigned char *p, *salt = NULL;
796     EVP_CIPHER_CTX cctx;
797     EVP_CIPHER_CTX_init(&cctx);
798     if (enclevel)
799         outlen += PVK_SALTLEN;
800     pklen = do_i2b(NULL, pk, 0);
801     if (pklen < 0)
802         return -1;
803     outlen += pklen;
804     if (!out)
805         return outlen;
806     if (*out)
807         p = *out;
808     else {
809         p = OPENSSL_malloc(outlen);
810         if (!p) {
811             PEMerr(PEM_F_I2B_PVK, ERR_R_MALLOC_FAILURE);
812             return -1;
813         }
814         *out = p;
815     }
816
817     write_ledword(&p, MS_PVKMAGIC);
818     write_ledword(&p, 0);
819     if (pk->type == EVP_PKEY_DSA)
820         write_ledword(&p, MS_KEYTYPE_SIGN);
821     else
822         write_ledword(&p, MS_KEYTYPE_KEYX);
823     write_ledword(&p, enclevel ? 1 : 0);
824     write_ledword(&p, enclevel ? PVK_SALTLEN : 0);
825     write_ledword(&p, pklen);
826     if (enclevel) {
827         if (RAND_bytes(p, PVK_SALTLEN) <= 0)
828             goto error;
829         salt = p;
830         p += PVK_SALTLEN;
831     }
832     do_i2b(&p, pk, 0);
833     if (enclevel == 0)
834         return outlen;
835     else {
836         char psbuf[PEM_BUFSIZE];
837         unsigned char keybuf[20];
838         int enctmplen, inlen;
839         if (cb)
840             inlen = cb(psbuf, PEM_BUFSIZE, 1, u);
841         else
842             inlen = PEM_def_callback(psbuf, PEM_BUFSIZE, 1, u);
843         if (inlen <= 0) {
844             PEMerr(PEM_F_I2B_PVK, PEM_R_BAD_PASSWORD_READ);
845             goto error;
846         }
847         if (!derive_pvk_key(keybuf, salt, PVK_SALTLEN,
848                             (unsigned char *)psbuf, inlen))
849             goto error;
850         if (enclevel == 1)
851             memset(keybuf + 5, 0, 11);
852         p = salt + PVK_SALTLEN + 8;
853         if (!EVP_EncryptInit_ex(&cctx, EVP_rc4(), NULL, keybuf, NULL))
854             goto error;
855         OPENSSL_cleanse(keybuf, 20);
856         if (!EVP_DecryptUpdate(&cctx, p, &enctmplen, p, pklen - 8))
857             goto error;
858         if (!EVP_DecryptFinal_ex(&cctx, p + enctmplen, &enctmplen))
859             goto error;
860     }
861     EVP_CIPHER_CTX_cleanup(&cctx);
862     return outlen;
863
864  error:
865     EVP_CIPHER_CTX_cleanup(&cctx);
866     return -1;
867 }
868
869 int i2b_PVK_bio(BIO *out, EVP_PKEY *pk, int enclevel,
870                 pem_password_cb *cb, void *u)
871 {
872     unsigned char *tmp = NULL;
873     int outlen, wrlen;
874     outlen = i2b_PVK(&tmp, pk, enclevel, cb, u);
875     if (outlen < 0)
876         return -1;
877     wrlen = BIO_write(out, tmp, outlen);
878     OPENSSL_free(tmp);
879     if (wrlen == outlen) {
880         PEMerr(PEM_F_I2B_PVK_BIO, PEM_R_BIO_WRITE_FAILURE);
881         return outlen;
882     }
883     return -1;
884 }
885
886 # endif
887
888 #endif