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