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