pvk: use PVK KDF
[openssl.git] / crypto / pem / pvkfmt.c
1 /*
2  * Copyright 2005-2021 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 <openssl/pem.h>
22 #include <openssl/rand.h>
23 #include <openssl/bn.h>
24 #include <openssl/dsa.h>
25 #include <openssl/rsa.h>
26 #include <openssl/kdf.h>
27 #include <openssl/core_names.h>
28 #include "internal/cryptlib.h"
29 #include "crypto/pem.h"
30 #include "crypto/evp.h"
31
32 /*
33  * Utility function: read a DWORD (4 byte unsigned integer) in little endian
34  * format
35  */
36
37 static unsigned int read_ledword(const unsigned char **in)
38 {
39     const unsigned char *p = *in;
40     unsigned int ret;
41
42     ret = (unsigned int)*p++;
43     ret |= (unsigned int)*p++ << 8;
44     ret |= (unsigned int)*p++ << 16;
45     ret |= (unsigned int)*p++ << 24;
46     *in = p;
47     return ret;
48 }
49
50 /*
51  * Read a BIGNUM in little endian format. The docs say that this should take
52  * up bitlen/8 bytes.
53  */
54
55 static int read_lebn(const unsigned char **in, unsigned int nbyte, BIGNUM **r)
56 {
57     *r = BN_lebin2bn(*in, nbyte, NULL);
58     if (*r == NULL)
59         return 0;
60     *in += nbyte;
61     return 1;
62 }
63
64 /*
65  * Create an EVP_PKEY from a type specific key.
66  * This takes ownership of |key|, as long as the |evp_type| is acceptable
67  * (EVP_PKEY_RSA or EVP_PKEY_DSA), even if the resulting EVP_PKEY wasn't
68  * created.
69  */
70 #define isdss_to_evp_type(isdss)                                \
71     (isdss == 0 ? EVP_PKEY_RSA : isdss == 1 ? EVP_PKEY_DSA : EVP_PKEY_NONE)
72 static EVP_PKEY *evp_pkey_new0_key(void *key, int evp_type)
73 {
74     EVP_PKEY *pkey = NULL;
75
76     /*
77      * It's assumed that if |key| is NULL, something went wrong elsewhere
78      * and suitable errors are already reported.
79      */
80     if (key == NULL)
81         return NULL;
82
83     if (!ossl_assert(evp_type == EVP_PKEY_RSA || evp_type == EVP_PKEY_DSA)) {
84         ERR_raise(ERR_LIB_PEM, ERR_R_INTERNAL_ERROR);
85         return NULL;
86     }
87
88     if ((pkey = EVP_PKEY_new()) != NULL) {
89         switch (evp_type) {
90         case EVP_PKEY_RSA:
91             if (EVP_PKEY_set1_RSA(pkey, key))
92                 break;
93             EVP_PKEY_free(pkey);
94             pkey = NULL;
95             break;
96 #ifndef OPENSSL_NO_DSA
97         case EVP_PKEY_DSA:
98             if (EVP_PKEY_set1_DSA(pkey, key))
99                 break;
100             EVP_PKEY_free(pkey);
101             pkey = NULL;
102             break;
103 #endif
104         }
105     }
106
107     switch (evp_type) {
108     case EVP_PKEY_RSA:
109         RSA_free(key);
110         break;
111 #ifndef OPENSSL_NO_DSA
112     case EVP_PKEY_DSA:
113         DSA_free(key);
114         break;
115 #endif
116     }
117
118     if (pkey == NULL)
119         ERR_raise(ERR_LIB_PEM, ERR_R_MALLOC_FAILURE);
120     return pkey;
121 }
122
123 /* Convert private key blob to EVP_PKEY: RSA and DSA keys supported */
124
125 # define MS_PUBLICKEYBLOB        0x6
126 # define MS_PRIVATEKEYBLOB       0x7
127 # define MS_RSA1MAGIC            0x31415352L
128 # define MS_RSA2MAGIC            0x32415352L
129 # define MS_DSS1MAGIC            0x31535344L
130 # define MS_DSS2MAGIC            0x32535344L
131
132 # define MS_KEYALG_RSA_KEYX      0xa400
133 # define MS_KEYALG_DSS_SIGN      0x2200
134
135 # define MS_KEYTYPE_KEYX         0x1
136 # define MS_KEYTYPE_SIGN         0x2
137
138 /* The PVK file magic number: seems to spell out "bobsfile", who is Bob? */
139 # define MS_PVKMAGIC             0xb0b5f11eL
140 /* Salt length for PVK files */
141 # define PVK_SALTLEN             0x10
142 /* Maximum length in PVK header */
143 # define PVK_MAX_KEYLEN          102400
144 /* Maximum salt length */
145 # define PVK_MAX_SALTLEN         10240
146
147 /*
148  * Read the MSBLOB header and get relevant data from it.
149  *
150  * |pisdss| and |pispub| have a double role, as they can be used for
151  * discovery as well as to check the the blob meets expectations.
152  * |*pisdss| is the indicator for whether the key is a DSA key or not.
153  * |*pispub| is the indicator for whether the key is public or not.
154  * In both cases, the following input values apply:
155  *
156  * 0    Expected to not be what the variable indicates.
157  * 1    Expected to be what the variable indicates.
158  * -1   No expectations, this function will assign 0 or 1 depending on
159  *      header data.
160  */
161 int ossl_do_blob_header(const unsigned char **in, unsigned int length,
162                         unsigned int *pmagic, unsigned int *pbitlen,
163                         int *pisdss, int *pispub)
164 {
165     const unsigned char *p = *in;
166
167     if (length < 16)
168         return 0;
169     /* bType */
170     switch (*p) {
171     case MS_PUBLICKEYBLOB:
172         if (*pispub == 0) {
173             ERR_raise(ERR_LIB_PEM, PEM_R_EXPECTING_PRIVATE_KEY_BLOB);
174             return 0;
175         }
176         *pispub = 1;
177         break;
178
179     case MS_PRIVATEKEYBLOB:
180         if (*pispub == 1) {
181             ERR_raise(ERR_LIB_PEM, PEM_R_EXPECTING_PUBLIC_KEY_BLOB);
182             return 0;
183         }
184         *pispub = 0;
185         break;
186
187     default:
188         return 0;
189     }
190     p++;
191     /* Version */
192     if (*p++ != 0x2) {
193         ERR_raise(ERR_LIB_PEM, PEM_R_BAD_VERSION_NUMBER);
194         return 0;
195     }
196     /* Ignore reserved, aiKeyAlg */
197     p += 6;
198     *pmagic = read_ledword(&p);
199     *pbitlen = read_ledword(&p);
200
201     /* Consistency check for private vs public */
202     switch (*pmagic) {
203     case MS_DSS1MAGIC:
204     case MS_RSA1MAGIC:
205         if (*pispub == 0) {
206             ERR_raise(ERR_LIB_PEM, PEM_R_EXPECTING_PRIVATE_KEY_BLOB);
207             return 0;
208         }
209         break;
210
211     case MS_DSS2MAGIC:
212     case MS_RSA2MAGIC:
213         if (*pispub == 1) {
214             ERR_raise(ERR_LIB_PEM, PEM_R_EXPECTING_PUBLIC_KEY_BLOB);
215             return 0;
216         }
217         break;
218
219     default:
220         ERR_raise(ERR_LIB_PEM, PEM_R_BAD_MAGIC_NUMBER);
221         return -1;
222     }
223
224     /* Check that we got the expected type */
225     switch (*pmagic) {
226     case MS_DSS1MAGIC:
227     case MS_DSS2MAGIC:
228         if (*pisdss == 0) {
229             ERR_raise(ERR_LIB_PEM, PEM_R_EXPECTING_DSS_KEY_BLOB);
230             return 0;
231         }
232         *pisdss = 1;
233         break;
234     case MS_RSA1MAGIC:
235     case MS_RSA2MAGIC:
236         if (*pisdss == 1) {
237             ERR_raise(ERR_LIB_PEM, PEM_R_EXPECTING_RSA_KEY_BLOB);
238             return 0;
239         }
240         *pisdss = 0;
241         break;
242
243     default:
244         ERR_raise(ERR_LIB_PEM, PEM_R_BAD_MAGIC_NUMBER);
245         return -1;
246     }
247     *in = p;
248     return 1;
249 }
250
251 unsigned int ossl_blob_length(unsigned bitlen, int isdss, int ispub)
252 {
253     unsigned int nbyte = (bitlen + 7) >> 3;
254     unsigned int hnbyte = (bitlen + 15) >> 4;
255
256     if (isdss) {
257
258         /*
259          * Expected length: 20 for q + 3 components bitlen each + 24 for seed
260          * structure.
261          */
262         if (ispub)
263             return 44 + 3 * nbyte;
264         /*
265          * Expected length: 20 for q, priv, 2 bitlen components + 24 for seed
266          * structure.
267          */
268         else
269             return 64 + 2 * nbyte;
270     } else {
271         /* Expected length: 4 for 'e' + 'n' */
272         if (ispub)
273             return 4 + nbyte;
274         else
275             /*
276              * Expected length: 4 for 'e' and 7 other components. 2
277              * components are bitlen size, 5 are bitlen/2
278              */
279             return 4 + 2 * nbyte + 5 * hnbyte;
280     }
281
282 }
283
284 static void *do_b2i_key(const unsigned char **in, unsigned int length,
285                         int *isdss, int *ispub)
286 {
287     const unsigned char *p = *in;
288     unsigned int bitlen, magic;
289     void *key = NULL;
290
291     if (ossl_do_blob_header(&p, length, &magic, &bitlen, isdss, ispub) <= 0) {
292         ERR_raise(ERR_LIB_PEM, PEM_R_KEYBLOB_HEADER_PARSE_ERROR);
293         return NULL;
294     }
295     length -= 16;
296     if (length < ossl_blob_length(bitlen, *isdss, *ispub)) {
297         ERR_raise(ERR_LIB_PEM, PEM_R_KEYBLOB_TOO_SHORT);
298         return NULL;
299     }
300     if (!*isdss)
301         key = ossl_b2i_RSA_after_header(&p, bitlen, *ispub);
302 #ifndef OPENSSL_NO_DSA
303     else
304         key = ossl_b2i_DSA_after_header(&p, bitlen, *ispub);
305 #endif
306
307     if (key == NULL) {
308         ERR_raise(ERR_LIB_PEM, PEM_R_UNSUPPORTED_PUBLIC_KEY_TYPE);
309         return NULL;
310     }
311
312     return key;
313 }
314
315 EVP_PKEY *ossl_b2i(const unsigned char **in, unsigned int length, int *ispub)
316 {
317     int isdss = -1;
318     void *key = do_b2i_key(in, length, &isdss, ispub);
319
320     return evp_pkey_new0_key(key, isdss_to_evp_type(isdss));
321 }
322
323 EVP_PKEY *ossl_b2i_bio(BIO *in, int *ispub)
324 {
325     const unsigned char *p;
326     unsigned char hdr_buf[16], *buf = NULL;
327     unsigned int bitlen, magic, length;
328     int isdss = -1;
329     void *key = NULL;
330     EVP_PKEY *pkey = NULL;
331
332     if (BIO_read(in, hdr_buf, 16) != 16) {
333         ERR_raise(ERR_LIB_PEM, PEM_R_KEYBLOB_TOO_SHORT);
334         return NULL;
335     }
336     p = hdr_buf;
337     if (ossl_do_blob_header(&p, 16, &magic, &bitlen, &isdss, ispub) <= 0)
338         return NULL;
339
340     length = ossl_blob_length(bitlen, isdss, *ispub);
341     if (length > BLOB_MAX_LENGTH) {
342         ERR_raise(ERR_LIB_PEM, PEM_R_HEADER_TOO_LONG);
343         return NULL;
344     }
345     buf = OPENSSL_malloc(length);
346     if (buf == NULL) {
347         ERR_raise(ERR_LIB_PEM, ERR_R_MALLOC_FAILURE);
348         goto err;
349     }
350     p = buf;
351     if (BIO_read(in, buf, length) != (int)length) {
352         ERR_raise(ERR_LIB_PEM, PEM_R_KEYBLOB_TOO_SHORT);
353         goto err;
354     }
355
356     if (!isdss)
357         key = ossl_b2i_RSA_after_header(&p, bitlen, *ispub);
358 #ifndef OPENSSL_NO_DSA
359     else
360         key = ossl_b2i_DSA_after_header(&p, bitlen, *ispub);
361 #endif
362
363     if (key == NULL) {
364         ERR_raise(ERR_LIB_PEM, PEM_R_UNSUPPORTED_PUBLIC_KEY_TYPE);
365         goto err;
366     }
367
368     pkey = evp_pkey_new0_key(key, isdss_to_evp_type(isdss));
369  err:
370     OPENSSL_free(buf);
371     return pkey;
372 }
373
374 #ifndef OPENSSL_NO_DSA
375 DSA *ossl_b2i_DSA_after_header(const unsigned char **in, unsigned int bitlen,
376                                int ispub)
377 {
378     const unsigned char *p = *in;
379     DSA *dsa = NULL;
380     BN_CTX *ctx = NULL;
381     BIGNUM *pbn = NULL, *qbn = NULL, *gbn = NULL, *priv_key = NULL;
382     BIGNUM *pub_key = NULL;
383     unsigned int nbyte = (bitlen + 7) >> 3;
384
385     dsa = DSA_new();
386     if (dsa == NULL)
387         goto memerr;
388     if (!read_lebn(&p, nbyte, &pbn))
389         goto memerr;
390
391     if (!read_lebn(&p, 20, &qbn))
392         goto memerr;
393
394     if (!read_lebn(&p, nbyte, &gbn))
395         goto memerr;
396
397     if (ispub) {
398         if (!read_lebn(&p, nbyte, &pub_key))
399             goto memerr;
400     } else {
401         if (!read_lebn(&p, 20, &priv_key))
402             goto memerr;
403
404         /* Set constant time flag before public key calculation */
405         BN_set_flags(priv_key, BN_FLG_CONSTTIME);
406
407         /* Calculate public key */
408         pub_key = BN_new();
409         if (pub_key == NULL)
410             goto memerr;
411         if ((ctx = BN_CTX_new()) == NULL)
412             goto memerr;
413
414         if (!BN_mod_exp(pub_key, gbn, priv_key, pbn, ctx))
415             goto memerr;
416
417         BN_CTX_free(ctx);
418         ctx = NULL;
419     }
420     if (!DSA_set0_pqg(dsa, pbn, qbn, gbn))
421         goto memerr;
422     pbn = qbn = gbn = NULL;
423     if (!DSA_set0_key(dsa, pub_key, priv_key))
424         goto memerr;
425     pub_key = priv_key = NULL;
426
427     *in = p;
428     return dsa;
429
430  memerr:
431     ERR_raise(ERR_LIB_PEM, ERR_R_MALLOC_FAILURE);
432     DSA_free(dsa);
433     BN_free(pbn);
434     BN_free(qbn);
435     BN_free(gbn);
436     BN_free(pub_key);
437     BN_free(priv_key);
438     BN_CTX_free(ctx);
439     return NULL;
440 }
441 #endif
442
443 RSA *ossl_b2i_RSA_after_header(const unsigned char **in, unsigned int bitlen,
444                                int ispub)
445 {
446     const unsigned char *pin = *in;
447     BIGNUM *e = NULL, *n = NULL, *d = NULL;
448     BIGNUM *p = NULL, *q = NULL, *dmp1 = NULL, *dmq1 = NULL, *iqmp = NULL;
449     RSA *rsa = NULL;
450     unsigned int nbyte = (bitlen + 7) >> 3;
451     unsigned int hnbyte = (bitlen + 15) >> 4;
452
453     rsa = RSA_new();
454     if (rsa == NULL)
455         goto memerr;
456     e = BN_new();
457     if (e == NULL)
458         goto memerr;
459     if (!BN_set_word(e, read_ledword(&pin)))
460         goto memerr;
461     if (!read_lebn(&pin, nbyte, &n))
462         goto memerr;
463     if (!ispub) {
464         if (!read_lebn(&pin, hnbyte, &p))
465             goto memerr;
466         if (!read_lebn(&pin, hnbyte, &q))
467             goto memerr;
468         if (!read_lebn(&pin, hnbyte, &dmp1))
469             goto memerr;
470         if (!read_lebn(&pin, hnbyte, &dmq1))
471             goto memerr;
472         if (!read_lebn(&pin, hnbyte, &iqmp))
473             goto memerr;
474         if (!read_lebn(&pin, nbyte, &d))
475             goto memerr;
476         if (!RSA_set0_factors(rsa, p, q))
477             goto memerr;
478         p = q = NULL;
479         if (!RSA_set0_crt_params(rsa, dmp1, dmq1, iqmp))
480             goto memerr;
481         dmp1 = dmq1 = iqmp = NULL;
482     }
483     if (!RSA_set0_key(rsa, n, e, d))
484         goto memerr;
485     n = e = d = NULL;
486
487     *in = pin;
488     return rsa;
489  memerr:
490     ERR_raise(ERR_LIB_PEM, ERR_R_MALLOC_FAILURE);
491     BN_free(e);
492     BN_free(n);
493     BN_free(p);
494     BN_free(q);
495     BN_free(dmp1);
496     BN_free(dmq1);
497     BN_free(iqmp);
498     BN_free(d);
499     RSA_free(rsa);
500     return NULL;
501 }
502
503 EVP_PKEY *b2i_PrivateKey(const unsigned char **in, long length)
504 {
505     int ispub = 0;
506
507     return ossl_b2i(in, length, &ispub);
508 }
509
510 EVP_PKEY *b2i_PublicKey(const unsigned char **in, long length)
511 {
512     int ispub = 1;
513
514     return ossl_b2i(in, length, &ispub);
515 }
516
517 EVP_PKEY *b2i_PrivateKey_bio(BIO *in)
518 {
519     int ispub = 0;
520
521     return ossl_b2i_bio(in, &ispub);
522 }
523
524 EVP_PKEY *b2i_PublicKey_bio(BIO *in)
525 {
526     int ispub = 1;
527
528     return ossl_b2i_bio(in, &ispub);
529 }
530
531 static void write_ledword(unsigned char **out, unsigned int dw)
532 {
533     unsigned char *p = *out;
534
535     *p++ = dw & 0xff;
536     *p++ = (dw >> 8) & 0xff;
537     *p++ = (dw >> 16) & 0xff;
538     *p++ = (dw >> 24) & 0xff;
539     *out = p;
540 }
541
542 static void write_lebn(unsigned char **out, const BIGNUM *bn, int len)
543 {
544     BN_bn2lebinpad(bn, *out, len);
545     *out += len;
546 }
547
548 static int check_bitlen_rsa(const RSA *rsa, int ispub, unsigned int *magic);
549 static void write_rsa(unsigned char **out, const RSA *rsa, int ispub);
550
551 #ifndef OPENSSL_NO_DSA
552 static int check_bitlen_dsa(const DSA *dsa, int ispub, unsigned int *magic);
553 static void write_dsa(unsigned char **out, const DSA *dsa, int ispub);
554 #endif
555
556 static int do_i2b(unsigned char **out, const EVP_PKEY *pk, int ispub)
557 {
558     unsigned char *p;
559     unsigned int bitlen = 0, magic = 0, keyalg = 0;
560     int outlen = -1, noinc = 0;
561
562     if (EVP_PKEY_is_a(pk, "RSA")) {
563         bitlen = check_bitlen_rsa(EVP_PKEY_get0_RSA(pk), ispub, &magic);
564         keyalg = MS_KEYALG_RSA_KEYX;
565 #ifndef OPENSSL_NO_DSA
566     } else if (EVP_PKEY_is_a(pk, "DSA")) {
567         bitlen = check_bitlen_dsa(EVP_PKEY_get0_DSA(pk), ispub, &magic);
568         keyalg = MS_KEYALG_DSS_SIGN;
569 #endif
570     }
571     if (bitlen == 0) {
572         goto end;
573     }
574     outlen = 16
575         + ossl_blob_length(bitlen, keyalg == MS_KEYALG_DSS_SIGN ? 1 : 0, ispub);
576     if (out == NULL)
577         goto end;
578     if (*out)
579         p = *out;
580     else {
581         if ((p = OPENSSL_malloc(outlen)) == NULL) {
582             ERR_raise(ERR_LIB_PEM, ERR_R_MALLOC_FAILURE);
583             outlen = -1;
584             goto end;
585         }
586         *out = p;
587         noinc = 1;
588     }
589     if (ispub)
590         *p++ = MS_PUBLICKEYBLOB;
591     else
592         *p++ = MS_PRIVATEKEYBLOB;
593     *p++ = 0x2;
594     *p++ = 0;
595     *p++ = 0;
596     write_ledword(&p, keyalg);
597     write_ledword(&p, magic);
598     write_ledword(&p, bitlen);
599     if (keyalg == MS_KEYALG_RSA_KEYX)
600         write_rsa(&p, EVP_PKEY_get0_RSA(pk), ispub);
601 #ifndef OPENSSL_NO_DSA
602     else
603         write_dsa(&p, EVP_PKEY_get0_DSA(pk), ispub);
604 #endif
605     if (!noinc)
606         *out += outlen;
607  end:
608     return outlen;
609 }
610
611 static int do_i2b_bio(BIO *out, const EVP_PKEY *pk, int ispub)
612 {
613     unsigned char *tmp = NULL;
614     int outlen, wrlen;
615
616     outlen = do_i2b(&tmp, pk, ispub);
617     if (outlen < 0)
618         return -1;
619     wrlen = BIO_write(out, tmp, outlen);
620     OPENSSL_free(tmp);
621     if (wrlen == outlen)
622         return outlen;
623     return -1;
624 }
625
626 static int check_bitlen_rsa(const RSA *rsa, int ispub, unsigned int *pmagic)
627 {
628     int nbyte, hnbyte, bitlen;
629     const BIGNUM *e;
630
631     RSA_get0_key(rsa, NULL, &e, NULL);
632     if (BN_num_bits(e) > 32)
633         goto badkey;
634     bitlen = RSA_bits(rsa);
635     nbyte = RSA_size(rsa);
636     hnbyte = (bitlen + 15) >> 4;
637     if (ispub) {
638         *pmagic = MS_RSA1MAGIC;
639         return bitlen;
640     } else {
641         const BIGNUM *d, *p, *q, *iqmp, *dmp1, *dmq1;
642
643         *pmagic = MS_RSA2MAGIC;
644
645         /*
646          * For private key each component must fit within nbyte or hnbyte.
647          */
648         RSA_get0_key(rsa, NULL, NULL, &d);
649         if (BN_num_bytes(d) > nbyte)
650             goto badkey;
651         RSA_get0_factors(rsa, &p, &q);
652         RSA_get0_crt_params(rsa, &dmp1, &dmq1, &iqmp);
653         if ((BN_num_bytes(iqmp) > hnbyte)
654             || (BN_num_bytes(p) > hnbyte)
655             || (BN_num_bytes(q) > hnbyte)
656             || (BN_num_bytes(dmp1) > hnbyte)
657             || (BN_num_bytes(dmq1) > hnbyte))
658             goto badkey;
659     }
660     return bitlen;
661  badkey:
662     ERR_raise(ERR_LIB_PEM, PEM_R_UNSUPPORTED_KEY_COMPONENTS);
663     return 0;
664 }
665
666 static void write_rsa(unsigned char **out, const RSA *rsa, int ispub)
667 {
668     int nbyte, hnbyte;
669     const BIGNUM *n, *d, *e, *p, *q, *iqmp, *dmp1, *dmq1;
670
671     nbyte = RSA_size(rsa);
672     hnbyte = (RSA_bits(rsa) + 15) >> 4;
673     RSA_get0_key(rsa, &n, &e, &d);
674     write_lebn(out, e, 4);
675     write_lebn(out, n, nbyte);
676     if (ispub)
677         return;
678     RSA_get0_factors(rsa, &p, &q);
679     RSA_get0_crt_params(rsa, &dmp1, &dmq1, &iqmp);
680     write_lebn(out, p, hnbyte);
681     write_lebn(out, q, hnbyte);
682     write_lebn(out, dmp1, hnbyte);
683     write_lebn(out, dmq1, hnbyte);
684     write_lebn(out, iqmp, hnbyte);
685     write_lebn(out, d, nbyte);
686 }
687
688 #ifndef OPENSSL_NO_DSA
689 static int check_bitlen_dsa(const DSA *dsa, int ispub, unsigned int *pmagic)
690 {
691     int bitlen;
692     const BIGNUM *p = NULL, *q = NULL, *g = NULL;
693     const BIGNUM *pub_key = NULL, *priv_key = NULL;
694
695     DSA_get0_pqg(dsa, &p, &q, &g);
696     DSA_get0_key(dsa, &pub_key, &priv_key);
697     bitlen = BN_num_bits(p);
698     if ((bitlen & 7) || (BN_num_bits(q) != 160)
699         || (BN_num_bits(g) > bitlen))
700         goto badkey;
701     if (ispub) {
702         if (BN_num_bits(pub_key) > bitlen)
703             goto badkey;
704         *pmagic = MS_DSS1MAGIC;
705     } else {
706         if (BN_num_bits(priv_key) > 160)
707             goto badkey;
708         *pmagic = MS_DSS2MAGIC;
709     }
710
711     return bitlen;
712  badkey:
713     ERR_raise(ERR_LIB_PEM, PEM_R_UNSUPPORTED_KEY_COMPONENTS);
714     return 0;
715 }
716
717 static void write_dsa(unsigned char **out, const DSA *dsa, int ispub)
718 {
719     int nbyte;
720     const BIGNUM *p = NULL, *q = NULL, *g = NULL;
721     const BIGNUM *pub_key = NULL, *priv_key = NULL;
722
723     DSA_get0_pqg(dsa, &p, &q, &g);
724     DSA_get0_key(dsa, &pub_key, &priv_key);
725     nbyte = BN_num_bytes(p);
726     write_lebn(out, p, nbyte);
727     write_lebn(out, q, 20);
728     write_lebn(out, g, nbyte);
729     if (ispub)
730         write_lebn(out, pub_key, nbyte);
731     else
732         write_lebn(out, priv_key, 20);
733     /* Set "invalid" for seed structure values */
734     memset(*out, 0xff, 24);
735     *out += 24;
736     return;
737 }
738 #endif
739
740 int i2b_PrivateKey_bio(BIO *out, const EVP_PKEY *pk)
741 {
742     return do_i2b_bio(out, pk, 0);
743 }
744
745 int i2b_PublicKey_bio(BIO *out, const EVP_PKEY *pk)
746 {
747     return do_i2b_bio(out, pk, 1);
748 }
749
750 int ossl_do_PVK_header(const unsigned char **in, unsigned int length,
751                        int skip_magic,
752                        unsigned int *psaltlen, unsigned int *pkeylen)
753 {
754     const unsigned char *p = *in;
755     unsigned int pvk_magic, is_encrypted;
756
757     if (skip_magic) {
758         if (length < 20) {
759             ERR_raise(ERR_LIB_PEM, PEM_R_PVK_TOO_SHORT);
760             return 0;
761         }
762     } else {
763         if (length < 24) {
764             ERR_raise(ERR_LIB_PEM, PEM_R_PVK_TOO_SHORT);
765             return 0;
766         }
767         pvk_magic = read_ledword(&p);
768         if (pvk_magic != MS_PVKMAGIC) {
769             ERR_raise(ERR_LIB_PEM, PEM_R_BAD_MAGIC_NUMBER);
770             return 0;
771         }
772     }
773     /* Skip reserved */
774     p += 4;
775     /*
776      * keytype =
777      */ read_ledword(&p);
778     is_encrypted = read_ledword(&p);
779     *psaltlen = read_ledword(&p);
780     *pkeylen = read_ledword(&p);
781
782     if (*pkeylen > PVK_MAX_KEYLEN || *psaltlen > PVK_MAX_SALTLEN)
783         return 0;
784
785     if (is_encrypted && *psaltlen == 0) {
786         ERR_raise(ERR_LIB_PEM, PEM_R_INCONSISTENT_HEADER);
787         return 0;
788     }
789
790     *in = p;
791     return 1;
792 }
793
794 #ifndef OPENSSL_NO_RC4
795 static int derive_pvk_key(unsigned char *key, size_t keylen,
796                           const unsigned char *salt, unsigned int saltlen,
797                           const unsigned char *pass, int passlen,
798                           OSSL_LIB_CTX *libctx, const char *propq)
799 {
800     EVP_KDF *kdf;
801     EVP_KDF_CTX *ctx;
802     OSSL_PARAM params[5], *p = params;
803     int rv;
804
805     if ((kdf = EVP_KDF_fetch(libctx, "PVKKDF", propq)) == NULL)
806         return 0;
807     ctx = EVP_KDF_CTX_new(kdf);
808     EVP_KDF_free(kdf);
809     if (ctx == NULL)
810         return 0;
811
812     *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SALT,
813                                              (void *)salt, saltlen);
814     *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_PASSWORD,
815                                              (void *)pass, passlen);
816     *p++ = OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_DIGEST, SN_sha1, 0);
817     *p++ = OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_PROPERTIES,
818                                             (char *)propq, 0);
819     *p = OSSL_PARAM_construct_end();
820
821     rv = EVP_KDF_derive(ctx, key, keylen, params);
822     EVP_KDF_CTX_free(ctx);
823     return rv;
824 }
825 #endif
826
827 static void *do_PVK_body_key(const unsigned char **in,
828                              unsigned int saltlen, unsigned int keylen,
829                              pem_password_cb *cb, void *u,
830                              int *isdss, int *ispub,
831                              OSSL_LIB_CTX *libctx, const char *propq)
832 {
833     const unsigned char *p = *in;
834     unsigned char *enctmp = NULL;
835     unsigned char keybuf[20];
836     void *key = NULL;
837 #ifndef OPENSSL_NO_RC4
838     EVP_CIPHER *rc4 = NULL;
839 #endif
840     EVP_CIPHER_CTX *cctx = EVP_CIPHER_CTX_new();
841
842     if (saltlen) {
843 #ifndef OPENSSL_NO_RC4
844         unsigned int magic;
845         char psbuf[PEM_BUFSIZE];
846         int enctmplen, inlen;
847         unsigned char *q;
848
849         if (cb)
850             inlen = cb(psbuf, PEM_BUFSIZE, 0, u);
851         else
852             inlen = PEM_def_callback(psbuf, PEM_BUFSIZE, 0, u);
853         if (inlen < 0) {
854             ERR_raise(ERR_LIB_PEM, PEM_R_BAD_PASSWORD_READ);
855             goto err;
856         }
857         enctmp = OPENSSL_malloc(keylen + 8);
858         if (enctmp == NULL) {
859             ERR_raise(ERR_LIB_PEM, ERR_R_MALLOC_FAILURE);
860             goto err;
861         }
862         if (!derive_pvk_key(keybuf, sizeof(keybuf), p, saltlen,
863                             (unsigned char *)psbuf, inlen, libctx, propq))
864             goto err;
865         p += saltlen;
866         /* Copy BLOBHEADER across, decrypt rest */
867         memcpy(enctmp, p, 8);
868         p += 8;
869         if (keylen < 8) {
870             ERR_raise(ERR_LIB_PEM, PEM_R_PVK_TOO_SHORT);
871             goto err;
872         }
873         inlen = keylen - 8;
874         q = enctmp + 8;
875         if ((rc4 = EVP_CIPHER_fetch(libctx, "RC4", propq)) == NULL)
876             goto err;
877         if (!EVP_DecryptInit_ex(cctx, rc4, NULL, keybuf, NULL))
878             goto err;
879         if (!EVP_DecryptUpdate(cctx, q, &enctmplen, p, inlen))
880             goto err;
881         if (!EVP_DecryptFinal_ex(cctx, q + enctmplen, &enctmplen))
882             goto err;
883         magic = read_ledword((const unsigned char **)&q);
884         if (magic != MS_RSA2MAGIC && magic != MS_DSS2MAGIC) {
885             q = enctmp + 8;
886             memset(keybuf + 5, 0, 11);
887             if (!EVP_DecryptInit_ex(cctx, rc4, NULL, keybuf, NULL))
888                 goto err;
889             if (!EVP_DecryptUpdate(cctx, q, &enctmplen, p, inlen))
890                 goto err;
891             if (!EVP_DecryptFinal_ex(cctx, q + enctmplen, &enctmplen))
892                 goto err;
893             magic = read_ledword((const unsigned char **)&q);
894             if (magic != MS_RSA2MAGIC && magic != MS_DSS2MAGIC) {
895                 ERR_raise(ERR_LIB_PEM, PEM_R_BAD_DECRYPT);
896                 goto err;
897             }
898         }
899         p = enctmp;
900 #else
901         ERR_raise(ERR_LIB_PEM, PEM_R_UNSUPPORTED_CIPHER);
902         goto err;
903 #endif
904     }
905
906     key = do_b2i_key(&p, keylen, isdss, ispub);
907  err:
908     EVP_CIPHER_CTX_free(cctx);
909 #ifndef OPENSSL_NO_RC4
910     EVP_CIPHER_free(rc4);
911 #endif
912     if (enctmp != NULL) {
913         OPENSSL_cleanse(keybuf, sizeof(keybuf));
914         OPENSSL_free(enctmp);
915     }
916     return key;
917 }
918
919 static void *do_PVK_key_bio(BIO *in, pem_password_cb *cb, void *u,
920                             int *isdss, int *ispub,
921                             OSSL_LIB_CTX *libctx, const char *propq)
922 {
923     unsigned char pvk_hdr[24], *buf = NULL;
924     const unsigned char *p;
925     int buflen;
926     void *key = NULL;
927     unsigned int saltlen, keylen;
928
929     if (BIO_read(in, pvk_hdr, 24) != 24) {
930         ERR_raise(ERR_LIB_PEM, PEM_R_PVK_DATA_TOO_SHORT);
931         return NULL;
932     }
933     p = pvk_hdr;
934
935     if (!ossl_do_PVK_header(&p, 24, 0, &saltlen, &keylen))
936         return 0;
937     buflen = (int)keylen + saltlen;
938     buf = OPENSSL_malloc(buflen);
939     if (buf == NULL) {
940         ERR_raise(ERR_LIB_PEM, ERR_R_MALLOC_FAILURE);
941         return 0;
942     }
943     p = buf;
944     if (BIO_read(in, buf, buflen) != buflen) {
945         ERR_raise(ERR_LIB_PEM, PEM_R_PVK_DATA_TOO_SHORT);
946         goto err;
947     }
948     key = do_PVK_body_key(&p, saltlen, keylen, cb, u, isdss, ispub, libctx, propq);
949
950  err:
951     OPENSSL_clear_free(buf, buflen);
952     return key;
953 }
954
955 #ifndef OPENSSL_NO_DSA
956 DSA *b2i_DSA_PVK_bio_ex(BIO *in, pem_password_cb *cb, void *u,
957                         OSSL_LIB_CTX *libctx, const char *propq)
958 {
959     int isdss = 1;
960     int ispub = 0;               /* PVK keys are always private */
961
962     return do_PVK_key_bio(in, cb, u, &isdss, &ispub, libctx, propq);
963 }
964
965 DSA *b2i_DSA_PVK_bio(BIO *in, pem_password_cb *cb, void *u)
966 {
967     return b2i_DSA_PVK_bio_ex(in, cb, u, NULL, NULL);
968 }
969 #endif
970
971 RSA *b2i_RSA_PVK_bio_ex(BIO *in, pem_password_cb *cb, void *u,
972                         OSSL_LIB_CTX *libctx, const char *propq)
973 {
974     int isdss = 0;
975     int ispub = 0;               /* PVK keys are always private */
976
977     return do_PVK_key_bio(in, cb, u, &isdss, &ispub, libctx, propq);
978 }
979
980 RSA *b2i_RSA_PVK_bio(BIO *in, pem_password_cb *cb, void *u)
981 {
982     return b2i_RSA_PVK_bio_ex(in, cb, u, NULL, NULL);
983 }
984
985 EVP_PKEY *b2i_PVK_bio_ex(BIO *in, pem_password_cb *cb, void *u,
986                          OSSL_LIB_CTX *libctx, const char *propq)
987 {
988     int isdss = -1;
989     int ispub = -1;
990     void *key = do_PVK_key_bio(in, cb, u, &isdss, &ispub, NULL, NULL);
991
992     return evp_pkey_new0_key(key, isdss_to_evp_type(isdss));
993 }
994
995 EVP_PKEY *b2i_PVK_bio(BIO *in, pem_password_cb *cb, void *u)
996 {
997     return b2i_PVK_bio_ex(in, cb, u, NULL, NULL);
998 }
999
1000 static int i2b_PVK(unsigned char **out, const EVP_PKEY *pk, int enclevel,
1001                    pem_password_cb *cb, void *u, OSSL_LIB_CTX *libctx,
1002                    const char *propq)
1003 {
1004     int ret = -1;
1005     int outlen = 24, pklen;
1006     unsigned char *p = NULL, *start = NULL;
1007     EVP_CIPHER_CTX *cctx = NULL;
1008 #ifndef OPENSSL_NO_RC4
1009     unsigned char *salt = NULL;
1010     EVP_CIPHER *rc4 = NULL;
1011 #endif
1012
1013     if (enclevel)
1014         outlen += PVK_SALTLEN;
1015     pklen = do_i2b(NULL, pk, 0);
1016     if (pklen < 0)
1017         return -1;
1018     outlen += pklen;
1019     if (out == NULL)
1020         return outlen;
1021     if (*out != NULL) {
1022         p = *out;
1023     } else {
1024         start = p = OPENSSL_malloc(outlen);
1025         if (p == NULL) {
1026             ERR_raise(ERR_LIB_PEM, ERR_R_MALLOC_FAILURE);
1027             return -1;
1028         }
1029     }
1030
1031     cctx = EVP_CIPHER_CTX_new();
1032     if (cctx == NULL)
1033         goto error;
1034
1035     write_ledword(&p, MS_PVKMAGIC);
1036     write_ledword(&p, 0);
1037     if (EVP_PKEY_get_id(pk) == EVP_PKEY_RSA)
1038         write_ledword(&p, MS_KEYTYPE_KEYX);
1039 #ifndef OPENSSL_NO_DSA
1040     else
1041         write_ledword(&p, MS_KEYTYPE_SIGN);
1042 #endif
1043     write_ledword(&p, enclevel ? 1 : 0);
1044     write_ledword(&p, enclevel ? PVK_SALTLEN : 0);
1045     write_ledword(&p, pklen);
1046     if (enclevel) {
1047 #ifndef OPENSSL_NO_RC4
1048         if (RAND_bytes_ex(libctx, p, PVK_SALTLEN, 0) <= 0)
1049             goto error;
1050         salt = p;
1051         p += PVK_SALTLEN;
1052 #endif
1053     }
1054     do_i2b(&p, pk, 0);
1055     if (enclevel != 0) {
1056 #ifndef OPENSSL_NO_RC4
1057         char psbuf[PEM_BUFSIZE];
1058         unsigned char keybuf[20];
1059         int enctmplen, inlen;
1060         if (cb)
1061             inlen = cb(psbuf, PEM_BUFSIZE, 1, u);
1062         else
1063             inlen = PEM_def_callback(psbuf, PEM_BUFSIZE, 1, u);
1064         if (inlen <= 0) {
1065             ERR_raise(ERR_LIB_PEM, PEM_R_BAD_PASSWORD_READ);
1066             goto error;
1067         }
1068         if (!derive_pvk_key(keybuf, sizeof(keybuf), salt, PVK_SALTLEN,
1069                             (unsigned char *)psbuf, inlen, libctx, propq))
1070             goto error;
1071         if ((rc4 = EVP_CIPHER_fetch(libctx, "RC4", propq)) == NULL)
1072             goto error;
1073         if (enclevel == 1)
1074             memset(keybuf + 5, 0, 11);
1075         p = salt + PVK_SALTLEN + 8;
1076         if (!EVP_EncryptInit_ex(cctx, rc4, NULL, keybuf, NULL))
1077             goto error;
1078         OPENSSL_cleanse(keybuf, 20);
1079         if (!EVP_EncryptUpdate(cctx, p, &enctmplen, p, pklen - 8))
1080             goto error;
1081         if (!EVP_EncryptFinal_ex(cctx, p + enctmplen, &enctmplen))
1082             goto error;
1083 #else
1084         ERR_raise(ERR_LIB_PEM, PEM_R_UNSUPPORTED_CIPHER);
1085         goto error;
1086 #endif
1087     }
1088
1089     if (*out == NULL)
1090         *out = start;
1091     ret = outlen;
1092  error:
1093     EVP_CIPHER_CTX_free(cctx);
1094 #ifndef OPENSSL_NO_RC4
1095     EVP_CIPHER_free(rc4);
1096 #endif
1097     if (*out == NULL)
1098         OPENSSL_free(start);
1099
1100     return ret;
1101 }
1102
1103 int i2b_PVK_bio_ex(BIO *out, const EVP_PKEY *pk, int enclevel,
1104                    pem_password_cb *cb, void *u, OSSL_LIB_CTX *libctx,
1105                    const char *propq)
1106 {
1107     unsigned char *tmp = NULL;
1108     int outlen, wrlen;
1109
1110     outlen = i2b_PVK(&tmp, pk, enclevel, cb, u, libctx, propq);
1111     if (outlen < 0)
1112         return -1;
1113     wrlen = BIO_write(out, tmp, outlen);
1114     OPENSSL_free(tmp);
1115     if (wrlen == outlen) {
1116         return outlen;
1117     }
1118     ERR_raise(ERR_LIB_PEM, PEM_R_BIO_WRITE_FAILURE);
1119     return -1;
1120 }
1121
1122 int i2b_PVK_bio(BIO *out, const EVP_PKEY *pk, int enclevel,
1123                 pem_password_cb *cb, void *u)
1124 {
1125     return i2b_PVK_bio_ex(out, pk, enclevel, cb, u, NULL, NULL);
1126 }
1127