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