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