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