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