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