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