Add DHX serialization
[openssl.git] / crypto / dh / dh_ameth.c
1 /*
2  * Copyright 2006-2020 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  * DH low level APIs are deprecated for public use, but still ok for
12  * internal use.
13  */
14 #include "internal/deprecated.h"
15
16 #include <stdio.h>
17 #include "internal/cryptlib.h"
18 #include <openssl/x509.h>
19 #include <openssl/asn1.h>
20 #include "dh_local.h"
21 #include <openssl/bn.h>
22 #include "crypto/asn1.h"
23 #include "crypto/dh.h"
24 #include "crypto/evp.h"
25 #include <openssl/cms.h>
26 #include <openssl/core_names.h>
27 #include <openssl/param_build.h>
28 #include "internal/ffc.h"
29
30 /*
31  * i2d/d2i like DH parameter functions which use the appropriate routine for
32  * PKCS#3 DH or X9.42 DH.
33  */
34
35 static DH *d2i_dhp(const EVP_PKEY *pkey, const unsigned char **pp,
36                    long length)
37 {
38     DH *dh = NULL;
39     int is_dhx = (pkey->ameth == &dhx_asn1_meth);
40
41     if (is_dhx)
42         dh = d2i_DHxparams(NULL, pp, length);
43     else
44         dh = d2i_DHparams(NULL, pp, length);
45
46     if (dh != NULL) {
47         DH_clear_flags(dh, DH_FLAG_TYPE_MASK);
48         DH_set_flags(dh, is_dhx ? DH_FLAG_TYPE_DHX : DH_FLAG_TYPE_DH);
49     }
50     return dh;
51 }
52
53 static int i2d_dhp(const EVP_PKEY *pkey, const DH *a, unsigned char **pp)
54 {
55     if (pkey->ameth == &dhx_asn1_meth)
56         return i2d_DHxparams(a, pp);
57     return i2d_DHparams(a, pp);
58 }
59
60 static void int_dh_free(EVP_PKEY *pkey)
61 {
62     DH_free(pkey->pkey.dh);
63 }
64
65 static int dh_pub_decode(EVP_PKEY *pkey, const X509_PUBKEY *pubkey)
66 {
67     const unsigned char *p, *pm;
68     int pklen, pmlen;
69     int ptype;
70     const void *pval;
71     const ASN1_STRING *pstr;
72     X509_ALGOR *palg;
73     ASN1_INTEGER *public_key = NULL;
74
75     DH *dh = NULL;
76
77     if (!X509_PUBKEY_get0_param(NULL, &p, &pklen, &palg, pubkey))
78         return 0;
79     X509_ALGOR_get0(NULL, &ptype, &pval, palg);
80
81     if (ptype != V_ASN1_SEQUENCE) {
82         DHerr(DH_F_DH_PUB_DECODE, DH_R_PARAMETER_ENCODING_ERROR);
83         goto err;
84     }
85
86     pstr = pval;
87     pm = pstr->data;
88     pmlen = pstr->length;
89
90     if ((dh = d2i_dhp(pkey, &pm, pmlen)) == NULL) {
91         DHerr(DH_F_DH_PUB_DECODE, DH_R_DECODE_ERROR);
92         goto err;
93     }
94
95     if ((public_key = d2i_ASN1_INTEGER(NULL, &p, pklen)) == NULL) {
96         DHerr(DH_F_DH_PUB_DECODE, DH_R_DECODE_ERROR);
97         goto err;
98     }
99
100     /* We have parameters now set public key */
101     if ((dh->pub_key = ASN1_INTEGER_to_BN(public_key, NULL)) == NULL) {
102         DHerr(DH_F_DH_PUB_DECODE, DH_R_BN_DECODE_ERROR);
103         goto err;
104     }
105
106     ASN1_INTEGER_free(public_key);
107     EVP_PKEY_assign(pkey, pkey->ameth->pkey_id, dh);
108     return 1;
109
110  err:
111     ASN1_INTEGER_free(public_key);
112     DH_free(dh);
113     return 0;
114 }
115
116 static int dh_pub_encode(X509_PUBKEY *pk, const EVP_PKEY *pkey)
117 {
118     DH *dh;
119     int ptype;
120     unsigned char *penc = NULL;
121     int penclen;
122     ASN1_STRING *str;
123     ASN1_INTEGER *pub_key = NULL;
124
125     dh = pkey->pkey.dh;
126
127     str = ASN1_STRING_new();
128     if (str == NULL) {
129         DHerr(DH_F_DH_PUB_ENCODE, ERR_R_MALLOC_FAILURE);
130         goto err;
131     }
132     str->length = i2d_dhp(pkey, dh, &str->data);
133     if (str->length <= 0) {
134         DHerr(DH_F_DH_PUB_ENCODE, ERR_R_MALLOC_FAILURE);
135         goto err;
136     }
137     ptype = V_ASN1_SEQUENCE;
138
139     pub_key = BN_to_ASN1_INTEGER(dh->pub_key, NULL);
140     if (pub_key == NULL)
141         goto err;
142
143     penclen = i2d_ASN1_INTEGER(pub_key, &penc);
144
145     ASN1_INTEGER_free(pub_key);
146
147     if (penclen <= 0) {
148         DHerr(DH_F_DH_PUB_ENCODE, ERR_R_MALLOC_FAILURE);
149         goto err;
150     }
151
152     if (X509_PUBKEY_set0_param(pk, OBJ_nid2obj(pkey->ameth->pkey_id),
153                                ptype, str, penc, penclen))
154         return 1;
155
156  err:
157     OPENSSL_free(penc);
158     ASN1_STRING_free(str);
159
160     return 0;
161 }
162
163 /*
164  * PKCS#8 DH is defined in PKCS#11 of all places. It is similar to DH in that
165  * the AlgorithmIdentifier contains the parameters, the private key is
166  * explicitly included and the pubkey must be recalculated.
167  */
168
169 static int dh_priv_decode(EVP_PKEY *pkey, const PKCS8_PRIV_KEY_INFO *p8)
170 {
171     const unsigned char *p, *pm;
172     int pklen, pmlen;
173     int ptype;
174     const void *pval;
175     const ASN1_STRING *pstr;
176     const X509_ALGOR *palg;
177     ASN1_INTEGER *privkey = NULL;
178     DH *dh = NULL;
179
180     if (!PKCS8_pkey_get0(NULL, &p, &pklen, &palg, p8))
181         return 0;
182
183     X509_ALGOR_get0(NULL, &ptype, &pval, palg);
184
185     if (ptype != V_ASN1_SEQUENCE)
186         goto decerr;
187     if ((privkey = d2i_ASN1_INTEGER(NULL, &p, pklen)) == NULL)
188         goto decerr;
189
190     pstr = pval;
191     pm = pstr->data;
192     pmlen = pstr->length;
193     if ((dh = d2i_dhp(pkey, &pm, pmlen)) == NULL)
194         goto decerr;
195
196     /* We have parameters now set private key */
197     if ((dh->priv_key = BN_secure_new()) == NULL
198         || !ASN1_INTEGER_to_BN(privkey, dh->priv_key)) {
199         DHerr(DH_F_DH_PRIV_DECODE, DH_R_BN_ERROR);
200         goto dherr;
201     }
202     /* Calculate public key, increments dirty_cnt */
203     if (!DH_generate_key(dh))
204         goto dherr;
205
206     EVP_PKEY_assign(pkey, pkey->ameth->pkey_id, dh);
207
208     ASN1_STRING_clear_free(privkey);
209
210     return 1;
211
212  decerr:
213     DHerr(DH_F_DH_PRIV_DECODE, EVP_R_DECODE_ERROR);
214  dherr:
215     DH_free(dh);
216     ASN1_STRING_clear_free(privkey);
217     return 0;
218 }
219
220 static int dh_priv_encode(PKCS8_PRIV_KEY_INFO *p8, const EVP_PKEY *pkey)
221 {
222     ASN1_STRING *params = NULL;
223     ASN1_INTEGER *prkey = NULL;
224     unsigned char *dp = NULL;
225     int dplen;
226
227     params = ASN1_STRING_new();
228
229     if (params == NULL) {
230         DHerr(DH_F_DH_PRIV_ENCODE, ERR_R_MALLOC_FAILURE);
231         goto err;
232     }
233
234     params->length = i2d_dhp(pkey, pkey->pkey.dh, &params->data);
235     if (params->length <= 0) {
236         DHerr(DH_F_DH_PRIV_ENCODE, ERR_R_MALLOC_FAILURE);
237         goto err;
238     }
239     params->type = V_ASN1_SEQUENCE;
240
241     /* Get private key into integer */
242     prkey = BN_to_ASN1_INTEGER(pkey->pkey.dh->priv_key, NULL);
243
244     if (prkey == NULL) {
245         DHerr(DH_F_DH_PRIV_ENCODE, DH_R_BN_ERROR);
246         goto err;
247     }
248
249     dplen = i2d_ASN1_INTEGER(prkey, &dp);
250
251     ASN1_STRING_clear_free(prkey);
252     prkey = NULL;
253
254     if (!PKCS8_pkey_set0(p8, OBJ_nid2obj(pkey->ameth->pkey_id), 0,
255                          V_ASN1_SEQUENCE, params, dp, dplen))
256         goto err;
257
258     return 1;
259
260  err:
261     OPENSSL_free(dp);
262     ASN1_STRING_free(params);
263     ASN1_STRING_clear_free(prkey);
264     return 0;
265 }
266
267 static int dh_param_decode(EVP_PKEY *pkey,
268                            const unsigned char **pder, int derlen)
269 {
270     DH *dh;
271
272     if ((dh = d2i_dhp(pkey, pder, derlen)) == NULL) {
273         DHerr(DH_F_DH_PARAM_DECODE, ERR_R_DH_LIB);
274         return 0;
275     }
276     dh->dirty_cnt++;
277     EVP_PKEY_assign(pkey, pkey->ameth->pkey_id, dh);
278     return 1;
279 }
280
281 static int dh_param_encode(const EVP_PKEY *pkey, unsigned char **pder)
282 {
283     return i2d_dhp(pkey, pkey->pkey.dh, pder);
284 }
285
286 static int do_dh_print(BIO *bp, const DH *x, int indent, int ptype)
287 {
288     int reason = ERR_R_BUF_LIB;
289     const char *ktype = NULL;
290     BIGNUM *priv_key, *pub_key;
291
292     if (ptype == 2)
293         priv_key = x->priv_key;
294     else
295         priv_key = NULL;
296
297     if (ptype > 0)
298         pub_key = x->pub_key;
299     else
300         pub_key = NULL;
301
302     if (x->params.p == NULL || (ptype == 2 && priv_key == NULL)
303             || (ptype > 0 && pub_key == NULL)) {
304         reason = ERR_R_PASSED_NULL_PARAMETER;
305         goto err;
306     }
307
308     if (ptype == 2)
309         ktype = "DH Private-Key";
310     else if (ptype == 1)
311         ktype = "DH Public-Key";
312     else
313         ktype = "DH Parameters";
314
315     if (!BIO_indent(bp, indent, 128)
316             || BIO_printf(bp, "%s: (%d bit)\n", ktype, DH_bits(x)) <= 0)
317         goto err;
318     indent += 4;
319
320     if (!ASN1_bn_print(bp, "private-key:", priv_key, NULL, indent))
321         goto err;
322     if (!ASN1_bn_print(bp, "public-key:", pub_key, NULL, indent))
323         goto err;
324
325     if (!ffc_params_print(bp, &x->params, indent))
326         goto err;
327
328     if (x->length != 0) {
329         if (!BIO_indent(bp, indent, 128)
330                 || BIO_printf(bp, "recommended-private-length: %d bits\n",
331                               (int)x->length) <= 0)
332             goto err;
333     }
334
335     return 1;
336
337  err:
338     DHerr(DH_F_DO_DH_PRINT, reason);
339     return 0;
340 }
341
342 static int int_dh_size(const EVP_PKEY *pkey)
343 {
344     return DH_size(pkey->pkey.dh);
345 }
346
347 static int dh_bits(const EVP_PKEY *pkey)
348 {
349     return DH_bits(pkey->pkey.dh);
350 }
351
352 static int dh_security_bits(const EVP_PKEY *pkey)
353 {
354     return DH_security_bits(pkey->pkey.dh);
355 }
356
357 static int dh_cmp_parameters(const EVP_PKEY *a, const EVP_PKEY *b)
358 {
359     return ffc_params_cmp(&a->pkey.dh->params, &a->pkey.dh->params,
360                           a->ameth != &dhx_asn1_meth);
361 }
362
363 static int int_dh_param_copy(DH *to, const DH *from, int is_x942)
364 {
365     if (is_x942 == -1)
366         is_x942 = (from->params.q != NULL);
367     if (!ffc_params_copy(&to->params, &from->params))
368         return 0;
369     if (!is_x942)
370         to->length = from->length;
371     to->dirty_cnt++;
372     return 1;
373 }
374
375 DH *DHparams_dup(const DH *dh)
376 {
377     DH *ret;
378     ret = DH_new();
379     if (ret == NULL)
380         return NULL;
381     if (!int_dh_param_copy(ret, dh, -1)) {
382         DH_free(ret);
383         return NULL;
384     }
385     return ret;
386 }
387
388 static int dh_copy_parameters(EVP_PKEY *to, const EVP_PKEY *from)
389 {
390     if (to->pkey.dh == NULL) {
391         to->pkey.dh = DH_new();
392         if (to->pkey.dh == NULL)
393             return 0;
394     }
395     return int_dh_param_copy(to->pkey.dh, from->pkey.dh,
396                              from->ameth == &dhx_asn1_meth);
397 }
398
399 static int dh_missing_parameters(const EVP_PKEY *a)
400 {
401     return a->pkey.dh == NULL
402         || a->pkey.dh->params.p == NULL
403         || a->pkey.dh->params.g == NULL;
404 }
405
406 static int dh_pub_cmp(const EVP_PKEY *a, const EVP_PKEY *b)
407 {
408     if (dh_cmp_parameters(a, b) == 0)
409         return 0;
410     if (BN_cmp(b->pkey.dh->pub_key, a->pkey.dh->pub_key) != 0)
411         return 0;
412     else
413         return 1;
414 }
415
416 static int dh_param_print(BIO *bp, const EVP_PKEY *pkey, int indent,
417                           ASN1_PCTX *ctx)
418 {
419     return do_dh_print(bp, pkey->pkey.dh, indent, 0);
420 }
421
422 static int dh_public_print(BIO *bp, const EVP_PKEY *pkey, int indent,
423                            ASN1_PCTX *ctx)
424 {
425     return do_dh_print(bp, pkey->pkey.dh, indent, 1);
426 }
427
428 static int dh_private_print(BIO *bp, const EVP_PKEY *pkey, int indent,
429                             ASN1_PCTX *ctx)
430 {
431     return do_dh_print(bp, pkey->pkey.dh, indent, 2);
432 }
433
434 int DHparams_print(BIO *bp, const DH *x)
435 {
436     return do_dh_print(bp, x, 4, 0);
437 }
438
439 #ifndef OPENSSL_NO_CMS
440 static int dh_cms_decrypt(CMS_RecipientInfo *ri);
441 static int dh_cms_encrypt(CMS_RecipientInfo *ri);
442 #endif
443
444 static int dh_pkey_ctrl(EVP_PKEY *pkey, int op, long arg1, void *arg2)
445 {
446     switch (op) {
447     case ASN1_PKEY_CTRL_SET1_TLS_ENCPT:
448         return dh_buf2key(EVP_PKEY_get0_DH(pkey), arg2, arg1);
449     case ASN1_PKEY_CTRL_GET1_TLS_ENCPT:
450         return dh_key2buf(EVP_PKEY_get0_DH(pkey), arg2, 0, 1);
451     default:
452         return -2;
453     }
454 }
455
456 static int dhx_pkey_ctrl(EVP_PKEY *pkey, int op, long arg1, void *arg2)
457 {
458     switch (op) {
459 #ifndef OPENSSL_NO_CMS
460
461     case ASN1_PKEY_CTRL_CMS_ENVELOPE:
462         if (arg1 == 1)
463             return dh_cms_decrypt(arg2);
464         else if (arg1 == 0)
465             return dh_cms_encrypt(arg2);
466         return -2;
467
468     case ASN1_PKEY_CTRL_CMS_RI_TYPE:
469         *(int *)arg2 = CMS_RECIPINFO_AGREE;
470         return 1;
471 #endif
472     default:
473         return -2;
474     }
475
476 }
477
478 static int dh_pkey_public_check(const EVP_PKEY *pkey)
479 {
480     DH *dh = pkey->pkey.dh;
481
482     if (dh->pub_key == NULL) {
483         DHerr(DH_F_DH_PKEY_PUBLIC_CHECK, DH_R_MISSING_PUBKEY);
484         return 0;
485     }
486
487     return DH_check_pub_key_ex(dh, dh->pub_key);
488 }
489
490 static int dh_pkey_param_check(const EVP_PKEY *pkey)
491 {
492     DH *dh = pkey->pkey.dh;
493
494     return DH_check_ex(dh);
495 }
496
497 static size_t dh_pkey_dirty_cnt(const EVP_PKEY *pkey)
498 {
499     return pkey->pkey.dh->dirty_cnt;
500 }
501
502 static int dh_pkey_export_to(const EVP_PKEY *from, void *to_keydata,
503                              EVP_KEYMGMT *to_keymgmt, OPENSSL_CTX *libctx,
504                              const char *propq)
505 {
506     DH *dh = from->pkey.dh;
507     OSSL_PARAM_BLD *tmpl;
508     const BIGNUM *p = DH_get0_p(dh), *g = DH_get0_g(dh), *q = DH_get0_q(dh);
509     const BIGNUM *pub_key = DH_get0_pub_key(dh);
510     const BIGNUM *priv_key = DH_get0_priv_key(dh);
511     OSSL_PARAM *params = NULL;
512     int selection = 0;
513     int rv = 0;
514
515     /*
516      * If the DH method is foreign, then we can't be sure of anything, and
517      * can therefore not export or pretend to export.
518      */
519     if (dh_get_method(dh) != DH_OpenSSL())
520         return 0;
521
522     if (p == NULL || g == NULL)
523         return 0;
524
525     tmpl = OSSL_PARAM_BLD_new();
526     if (tmpl == NULL)
527         return 0;
528     if (!OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_P, p)
529         || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_G, g))
530         goto err;
531     if (q != NULL) {
532         if (!OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_Q, q))
533             goto err;
534     }
535     selection |= OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS;
536     if (pub_key != NULL) {
537         if (!OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_PUB_KEY, pub_key))
538             goto err;
539         selection |= OSSL_KEYMGMT_SELECT_PUBLIC_KEY;
540     }
541     if (priv_key != NULL) {
542         if (!OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_PRIV_KEY,
543                                     priv_key))
544             goto err;
545         selection |= OSSL_KEYMGMT_SELECT_PRIVATE_KEY;
546     }
547
548     if ((params = OSSL_PARAM_BLD_to_param(tmpl)) == NULL)
549         goto err;
550
551     /* We export, the provider imports */
552     rv = evp_keymgmt_import(to_keymgmt, to_keydata, selection, params);
553
554     OSSL_PARAM_BLD_free_params(params);
555 err:
556     OSSL_PARAM_BLD_free(tmpl);
557     return rv;
558 }
559
560 static int dh_pkey_import_from_type(const OSSL_PARAM params[], void *vpctx,
561                                     int type)
562 {
563     EVP_PKEY_CTX *pctx = vpctx;
564     EVP_PKEY *pkey = EVP_PKEY_CTX_get0_pkey(pctx);
565     DH *dh = dh_new_with_libctx(pctx->libctx);
566
567     DH_clear_flags(dh, DH_FLAG_TYPE_MASK);
568     DH_set_flags(dh, type == EVP_PKEY_DH ? DH_FLAG_TYPE_DH : DH_FLAG_TYPE_DHX);
569
570     if (dh == NULL) {
571         ERR_raise(ERR_LIB_DH, ERR_R_MALLOC_FAILURE);
572         return 0;
573     }
574
575     if (!dh_ffc_params_fromdata(dh, params)
576         || !dh_key_fromdata(dh, params)
577         || !EVP_PKEY_assign(pkey, type, dh)) {
578         DH_free(dh);
579         return 0;
580     }
581     return 1;
582 }
583
584 static int dh_pkey_import_from(const OSSL_PARAM params[], void *vpctx)
585 {
586     return dh_pkey_import_from_type(params, vpctx, EVP_PKEY_DH);
587 }
588
589 static int dhx_pkey_import_from(const OSSL_PARAM params[], void *vpctx)
590 {
591     return dh_pkey_import_from_type(params, vpctx, EVP_PKEY_DHX);
592 }
593
594 const EVP_PKEY_ASN1_METHOD dh_asn1_meth = {
595     EVP_PKEY_DH,
596     EVP_PKEY_DH,
597     0,
598
599     "DH",
600     "OpenSSL PKCS#3 DH method",
601
602     dh_pub_decode,
603     dh_pub_encode,
604     dh_pub_cmp,
605     dh_public_print,
606
607     dh_priv_decode,
608     dh_priv_encode,
609     dh_private_print,
610
611     int_dh_size,
612     dh_bits,
613     dh_security_bits,
614
615     dh_param_decode,
616     dh_param_encode,
617     dh_missing_parameters,
618     dh_copy_parameters,
619     dh_cmp_parameters,
620     dh_param_print,
621     0,
622
623     int_dh_free,
624     dh_pkey_ctrl,
625
626     0, 0, 0, 0, 0,
627
628     0,
629     dh_pkey_public_check,
630     dh_pkey_param_check,
631
632     0, 0, 0, 0,
633
634     dh_pkey_dirty_cnt,
635     dh_pkey_export_to,
636     dh_pkey_import_from,
637 };
638
639 const EVP_PKEY_ASN1_METHOD dhx_asn1_meth = {
640     EVP_PKEY_DHX,
641     EVP_PKEY_DHX,
642     0,
643
644     "X9.42 DH",
645     "OpenSSL X9.42 DH method",
646
647     dh_pub_decode,
648     dh_pub_encode,
649     dh_pub_cmp,
650     dh_public_print,
651
652     dh_priv_decode,
653     dh_priv_encode,
654     dh_private_print,
655
656     int_dh_size,
657     dh_bits,
658     dh_security_bits,
659
660     dh_param_decode,
661     dh_param_encode,
662     dh_missing_parameters,
663     dh_copy_parameters,
664     dh_cmp_parameters,
665     dh_param_print,
666     0,
667
668     int_dh_free,
669     dhx_pkey_ctrl,
670
671     0, 0, 0, 0, 0,
672
673     0,
674     dh_pkey_public_check,
675     dh_pkey_param_check,
676     0, 0, 0, 0,
677     dh_pkey_dirty_cnt,
678     dh_pkey_export_to,
679     dhx_pkey_import_from,
680 };
681
682 #ifndef OPENSSL_NO_CMS
683
684 static int dh_cms_set_peerkey(EVP_PKEY_CTX *pctx,
685                               X509_ALGOR *alg, ASN1_BIT_STRING *pubkey)
686 {
687     const ASN1_OBJECT *aoid;
688     int atype;
689     const void *aval;
690     ASN1_INTEGER *public_key = NULL;
691     int rv = 0;
692     EVP_PKEY *pkpeer = NULL, *pk = NULL;
693     DH *dhpeer = NULL;
694     const unsigned char *p;
695     int plen;
696
697     X509_ALGOR_get0(&aoid, &atype, &aval, alg);
698     if (OBJ_obj2nid(aoid) != NID_dhpublicnumber)
699         goto err;
700     /* Only absent parameters allowed in RFC XXXX */
701     if (atype != V_ASN1_UNDEF && atype == V_ASN1_NULL)
702         goto err;
703
704     pk = EVP_PKEY_CTX_get0_pkey(pctx);
705     if (pk == NULL)
706         goto err;
707     if (pk->type != EVP_PKEY_DHX)
708         goto err;
709     /* Get parameters from parent key */
710     dhpeer = DHparams_dup(pk->pkey.dh);
711     /* We have parameters now set public key */
712     plen = ASN1_STRING_length(pubkey);
713     p = ASN1_STRING_get0_data(pubkey);
714     if (p == NULL || plen == 0)
715         goto err;
716
717     if ((public_key = d2i_ASN1_INTEGER(NULL, &p, plen)) == NULL) {
718         DHerr(DH_F_DH_CMS_SET_PEERKEY, DH_R_DECODE_ERROR);
719         goto err;
720     }
721
722     /* We have parameters now set public key */
723     if ((dhpeer->pub_key = ASN1_INTEGER_to_BN(public_key, NULL)) == NULL) {
724         DHerr(DH_F_DH_CMS_SET_PEERKEY, DH_R_BN_DECODE_ERROR);
725         goto err;
726     }
727
728     pkpeer = EVP_PKEY_new();
729     if (pkpeer == NULL)
730         goto err;
731     EVP_PKEY_assign(pkpeer, pk->ameth->pkey_id, dhpeer);
732     dhpeer = NULL;
733     if (EVP_PKEY_derive_set_peer(pctx, pkpeer) > 0)
734         rv = 1;
735  err:
736     ASN1_INTEGER_free(public_key);
737     EVP_PKEY_free(pkpeer);
738     DH_free(dhpeer);
739     return rv;
740 }
741
742 static int dh_cms_set_shared_info(EVP_PKEY_CTX *pctx, CMS_RecipientInfo *ri)
743 {
744     int rv = 0;
745
746     X509_ALGOR *alg, *kekalg = NULL;
747     ASN1_OCTET_STRING *ukm;
748     const unsigned char *p;
749     unsigned char *dukm = NULL;
750     size_t dukmlen = 0;
751     int keylen, plen;
752     const EVP_CIPHER *kekcipher;
753     EVP_CIPHER_CTX *kekctx;
754
755     if (!CMS_RecipientInfo_kari_get0_alg(ri, &alg, &ukm))
756         goto err;
757
758     /*
759      * For DH we only have one OID permissible. If ever any more get defined
760      * we will need something cleverer.
761      */
762     if (OBJ_obj2nid(alg->algorithm) != NID_id_smime_alg_ESDH) {
763         DHerr(DH_F_DH_CMS_SET_SHARED_INFO, DH_R_KDF_PARAMETER_ERROR);
764         goto err;
765     }
766
767     if (EVP_PKEY_CTX_set_dh_kdf_type(pctx, EVP_PKEY_DH_KDF_X9_42) <= 0)
768         goto err;
769
770     if (EVP_PKEY_CTX_set_dh_kdf_md(pctx, EVP_sha1()) <= 0)
771         goto err;
772
773     if (alg->parameter->type != V_ASN1_SEQUENCE)
774         goto err;
775
776     p = alg->parameter->value.sequence->data;
777     plen = alg->parameter->value.sequence->length;
778     kekalg = d2i_X509_ALGOR(NULL, &p, plen);
779     if (!kekalg)
780         goto err;
781     kekctx = CMS_RecipientInfo_kari_get0_ctx(ri);
782     if (!kekctx)
783         goto err;
784     kekcipher = EVP_get_cipherbyobj(kekalg->algorithm);
785     if (!kekcipher || EVP_CIPHER_mode(kekcipher) != EVP_CIPH_WRAP_MODE)
786         goto err;
787     if (!EVP_EncryptInit_ex(kekctx, kekcipher, NULL, NULL, NULL))
788         goto err;
789     if (EVP_CIPHER_asn1_to_param(kekctx, kekalg->parameter) <= 0)
790         goto err;
791
792     keylen = EVP_CIPHER_CTX_key_length(kekctx);
793     if (EVP_PKEY_CTX_set_dh_kdf_outlen(pctx, keylen) <= 0)
794         goto err;
795     /* Use OBJ_nid2obj to ensure we use built in OID that isn't freed */
796     if (EVP_PKEY_CTX_set0_dh_kdf_oid(pctx,
797                                      OBJ_nid2obj(EVP_CIPHER_type(kekcipher)))
798         <= 0)
799         goto err;
800
801     if (ukm) {
802         dukmlen = ASN1_STRING_length(ukm);
803         dukm = OPENSSL_memdup(ASN1_STRING_get0_data(ukm), dukmlen);
804         if (!dukm)
805             goto err;
806     }
807
808     if (EVP_PKEY_CTX_set0_dh_kdf_ukm(pctx, dukm, dukmlen) <= 0)
809         goto err;
810     dukm = NULL;
811
812     rv = 1;
813  err:
814     X509_ALGOR_free(kekalg);
815     OPENSSL_free(dukm);
816     return rv;
817 }
818
819 static int dh_cms_decrypt(CMS_RecipientInfo *ri)
820 {
821     EVP_PKEY_CTX *pctx;
822
823     pctx = CMS_RecipientInfo_get0_pkey_ctx(ri);
824
825     if (pctx == NULL)
826         return 0;
827     /* See if we need to set peer key */
828     if (!EVP_PKEY_CTX_get0_peerkey(pctx)) {
829         X509_ALGOR *alg;
830         ASN1_BIT_STRING *pubkey;
831         if (!CMS_RecipientInfo_kari_get0_orig_id(ri, &alg, &pubkey,
832                                                  NULL, NULL, NULL))
833             return 0;
834         if (!alg || !pubkey)
835             return 0;
836         if (!dh_cms_set_peerkey(pctx, alg, pubkey)) {
837             DHerr(DH_F_DH_CMS_DECRYPT, DH_R_PEER_KEY_ERROR);
838             return 0;
839         }
840     }
841     /* Set DH derivation parameters and initialise unwrap context */
842     if (!dh_cms_set_shared_info(pctx, ri)) {
843         DHerr(DH_F_DH_CMS_DECRYPT, DH_R_SHARED_INFO_ERROR);
844         return 0;
845     }
846     return 1;
847 }
848
849 static int dh_cms_encrypt(CMS_RecipientInfo *ri)
850 {
851     EVP_PKEY_CTX *pctx;
852     EVP_PKEY *pkey;
853     EVP_CIPHER_CTX *ctx;
854     int keylen;
855     X509_ALGOR *talg, *wrap_alg = NULL;
856     const ASN1_OBJECT *aoid;
857     ASN1_BIT_STRING *pubkey;
858     ASN1_STRING *wrap_str;
859     ASN1_OCTET_STRING *ukm;
860     unsigned char *penc = NULL, *dukm = NULL;
861     int penclen;
862     size_t dukmlen = 0;
863     int rv = 0;
864     int kdf_type, wrap_nid;
865     const EVP_MD *kdf_md;
866
867     pctx = CMS_RecipientInfo_get0_pkey_ctx(ri);
868     if (pctx == NULL)
869         return 0;
870     /* Get ephemeral key */
871     pkey = EVP_PKEY_CTX_get0_pkey(pctx);
872     if (!CMS_RecipientInfo_kari_get0_orig_id(ri, &talg, &pubkey,
873                                              NULL, NULL, NULL))
874         goto err;
875     X509_ALGOR_get0(&aoid, NULL, NULL, talg);
876     /* Is everything uninitialised? */
877     if (aoid == OBJ_nid2obj(NID_undef)) {
878         ASN1_INTEGER *pubk = BN_to_ASN1_INTEGER(pkey->pkey.dh->pub_key, NULL);
879
880         if (pubk == NULL)
881             goto err;
882         /* Set the key */
883
884         penclen = i2d_ASN1_INTEGER(pubk, &penc);
885         ASN1_INTEGER_free(pubk);
886         if (penclen <= 0)
887             goto err;
888         ASN1_STRING_set0(pubkey, penc, penclen);
889         pubkey->flags &= ~(ASN1_STRING_FLAG_BITS_LEFT | 0x07);
890         pubkey->flags |= ASN1_STRING_FLAG_BITS_LEFT;
891
892         penc = NULL;
893         X509_ALGOR_set0(talg, OBJ_nid2obj(NID_dhpublicnumber),
894                         V_ASN1_UNDEF, NULL);
895     }
896
897     /* See if custom parameters set */
898     kdf_type = EVP_PKEY_CTX_get_dh_kdf_type(pctx);
899     if (kdf_type <= 0)
900         goto err;
901     if (!EVP_PKEY_CTX_get_dh_kdf_md(pctx, &kdf_md))
902         goto err;
903
904     if (kdf_type == EVP_PKEY_DH_KDF_NONE) {
905         kdf_type = EVP_PKEY_DH_KDF_X9_42;
906         if (EVP_PKEY_CTX_set_dh_kdf_type(pctx, kdf_type) <= 0)
907             goto err;
908     } else if (kdf_type != EVP_PKEY_DH_KDF_X9_42)
909         /* Unknown KDF */
910         goto err;
911     if (kdf_md == NULL) {
912         /* Only SHA1 supported */
913         kdf_md = EVP_sha1();
914         if (EVP_PKEY_CTX_set_dh_kdf_md(pctx, kdf_md) <= 0)
915             goto err;
916     } else if (EVP_MD_type(kdf_md) != NID_sha1)
917         /* Unsupported digest */
918         goto err;
919
920     if (!CMS_RecipientInfo_kari_get0_alg(ri, &talg, &ukm))
921         goto err;
922
923     /* Get wrap NID */
924     ctx = CMS_RecipientInfo_kari_get0_ctx(ri);
925     wrap_nid = EVP_CIPHER_CTX_type(ctx);
926     if (EVP_PKEY_CTX_set0_dh_kdf_oid(pctx, OBJ_nid2obj(wrap_nid)) <= 0)
927         goto err;
928     keylen = EVP_CIPHER_CTX_key_length(ctx);
929
930     /* Package wrap algorithm in an AlgorithmIdentifier */
931
932     wrap_alg = X509_ALGOR_new();
933     if (wrap_alg == NULL)
934         goto err;
935     wrap_alg->algorithm = OBJ_nid2obj(wrap_nid);
936     wrap_alg->parameter = ASN1_TYPE_new();
937     if (wrap_alg->parameter == NULL)
938         goto err;
939     if (EVP_CIPHER_param_to_asn1(ctx, wrap_alg->parameter) <= 0)
940         goto err;
941     if (ASN1_TYPE_get(wrap_alg->parameter) == NID_undef) {
942         ASN1_TYPE_free(wrap_alg->parameter);
943         wrap_alg->parameter = NULL;
944     }
945
946     if (EVP_PKEY_CTX_set_dh_kdf_outlen(pctx, keylen) <= 0)
947         goto err;
948
949     if (ukm) {
950         dukmlen = ASN1_STRING_length(ukm);
951         dukm = OPENSSL_memdup(ASN1_STRING_get0_data(ukm), dukmlen);
952         if (!dukm)
953             goto err;
954     }
955
956     if (EVP_PKEY_CTX_set0_dh_kdf_ukm(pctx, dukm, dukmlen) <= 0)
957         goto err;
958     dukm = NULL;
959
960     /*
961      * Now need to wrap encoding of wrap AlgorithmIdentifier into parameter
962      * of another AlgorithmIdentifier.
963      */
964     penc = NULL;
965     penclen = i2d_X509_ALGOR(wrap_alg, &penc);
966     if (penc == NULL || penclen == 0)
967         goto err;
968     wrap_str = ASN1_STRING_new();
969     if (wrap_str == NULL)
970         goto err;
971     ASN1_STRING_set0(wrap_str, penc, penclen);
972     penc = NULL;
973     X509_ALGOR_set0(talg, OBJ_nid2obj(NID_id_smime_alg_ESDH),
974                     V_ASN1_SEQUENCE, wrap_str);
975
976     rv = 1;
977
978  err:
979     OPENSSL_free(penc);
980     X509_ALGOR_free(wrap_alg);
981     OPENSSL_free(dukm);
982     return rv;
983 }
984
985 #endif