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