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