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