]> www.wagner.pp.ru Git - openssl-gost/engine.git/blob - gost_ec_keyx.c
Add explicit support for NID_id_GostR3410_2001DH (GOST R 34.10-2001 DH)
[openssl-gost/engine.git] / gost_ec_keyx.c
1 /**********************************************************************
2  *                        gost_ec_keyx.c                              *
3  *                                                                    *
4  *             Copyright (c) 2005-2013 Cryptocom LTD                  *
5  *   Copyright (c) 2018,2020 Dmitry Belyavskiy <beldmit@gmail.com>    *
6  *   Copyright (c) 2020 Billy Brumley <bbrumley@gmail.com>            *
7  *                                                                    *
8  *         This file is distributed under the same license as OpenSSL *
9  *                                                                    *
10  *   VK0 R 50.1.113-2016 / RFC 7836                                   *
11  *   KEG R 1323565.1.020-2018                                         *
12  *   VK0 34.10-2001 key exchange and GOST R 34.10-2001 (RFC 4357)     *
13  *   based PKCS7/SMIME support                                        *
14  *          Requires OpenSSL 0.9.9 for compilation                    *
15  **********************************************************************/
16 #include <openssl/evp.h>
17 #include <openssl/err.h>
18 #include <openssl/rand.h>
19 #include <string.h>
20 #include <openssl/objects.h>
21 #include "gost89.h"
22 #include "e_gost_err.h"
23 #include "gost_keywrap.h"
24 #include "gost_lcl.h"
25
26 /* Implementation of CryptoPro VKO 34.10-2001/2012 algorithm */
27 int VKO_compute_key(unsigned char *shared_key,
28                     const EC_POINT *pub_key, const EC_KEY *priv_key,
29                     const unsigned char *ukm, const size_t ukm_size,
30                     const int vko_dgst_nid)
31 {
32     unsigned char *databuf = NULL;
33     BIGNUM *scalar = NULL, *X = NULL, *Y = NULL;
34     const EC_GROUP *grp = NULL;
35     EC_POINT *pnt = NULL;
36     BN_CTX *ctx = NULL;
37     EVP_MD_CTX *mdctx = NULL;
38     const EVP_MD *md = NULL;
39     int buf_len, half_len;
40     int ret = 0;
41
42     if ((ctx = BN_CTX_secure_new()) == NULL) {
43         GOSTerr(GOST_F_VKO_COMPUTE_KEY, ERR_R_MALLOC_FAILURE);
44         return 0;
45     }
46     BN_CTX_start(ctx);
47
48     md = EVP_get_digestbynid(vko_dgst_nid);
49     if (!md) {
50         GOSTerr(GOST_F_VKO_COMPUTE_KEY, GOST_R_INVALID_DIGEST_TYPE);
51         goto err;
52     }
53
54     grp = EC_KEY_get0_group(priv_key);
55     scalar = BN_CTX_get(ctx);
56     X = BN_CTX_get(ctx);
57
58     if ((Y = BN_CTX_get(ctx)) == NULL
59         || (pnt = EC_POINT_new(grp)) == NULL
60         || BN_lebin2bn(ukm, ukm_size, scalar) == NULL
61         || !BN_mod_mul(scalar, scalar, EC_KEY_get0_private_key(priv_key),
62                        EC_GROUP_get0_order(grp), ctx))
63         goto err;
64
65     /* these two curves have cofactor 4; the rest have cofactor 1 */
66     switch (EC_GROUP_get_curve_name(grp)) {
67         case NID_id_tc26_gost_3410_2012_256_paramSetA:
68         case NID_id_tc26_gost_3410_2012_512_paramSetC:
69             if (!BN_lshift(scalar, scalar, 2))
70                 goto err;
71             break;
72     }
73
74     if (!gost_ec_point_mul(grp, pnt, NULL, pub_key, scalar, ctx)) {
75         GOSTerr(GOST_F_VKO_COMPUTE_KEY, GOST_R_ERROR_POINT_MUL);
76         goto err;
77     }
78     if (!EC_POINT_get_affine_coordinates(grp, pnt, X, Y, ctx)) {
79         GOSTerr(GOST_F_VKO_COMPUTE_KEY, ERR_R_EC_LIB);
80         goto err;
81     }
82
83     half_len = BN_num_bytes(EC_GROUP_get0_field(grp));
84     buf_len = 2 * half_len;
85     if ((databuf = OPENSSL_malloc(buf_len)) == NULL) {
86         GOSTerr(GOST_F_VKO_COMPUTE_KEY, ERR_R_MALLOC_FAILURE);
87         goto err;
88     }
89
90     /*
91      * Serialize elliptic curve point same way as we do it when saving key
92      */
93     if (BN_bn2lebinpad(X, databuf, half_len) != half_len
94         || BN_bn2lebinpad(Y, databuf + half_len, half_len) != half_len)
95         goto err;
96
97     if ((mdctx = EVP_MD_CTX_new()) == NULL) {
98         GOSTerr(GOST_F_VKO_COMPUTE_KEY, ERR_R_MALLOC_FAILURE);
99         goto err;
100     }
101
102     if (EVP_MD_CTX_init(mdctx) == 0
103         || EVP_DigestInit_ex(mdctx, md, NULL) == 0
104         || EVP_DigestUpdate(mdctx, databuf, buf_len) == 0
105         || EVP_DigestFinal_ex(mdctx, shared_key, NULL) == 0) {
106         GOSTerr(GOST_F_VKO_COMPUTE_KEY, ERR_R_EVP_LIB);
107         goto err;
108     }
109
110     ret = (EVP_MD_size(md) > 0) ? EVP_MD_size(md) : 0;
111
112  err:
113     BN_CTX_end(ctx);
114     BN_CTX_free(ctx);
115     EC_POINT_free(pnt);
116     EVP_MD_CTX_free(mdctx);
117     OPENSSL_free(databuf);
118
119     return ret;
120 }
121
122 /*
123  * KEG Algorithm described in R 1323565.1.020-2018 6.4.5.1.
124  * keyout expected to be 64 bytes
125  * */
126 static int gost_keg(const unsigned char *ukm_source, int pkey_nid,
127                     const EC_POINT *pub_key, const EC_KEY *priv_key,
128                     unsigned char *keyout)
129 {
130 /* Adjust UKM */
131     unsigned char real_ukm[16];
132     size_t keylen = 0;
133
134     memset(real_ukm, 0, 16);
135     if (memcmp(ukm_source, real_ukm, 16) == 0)
136         real_ukm[15] = 1;
137     else {
138         memcpy(real_ukm, ukm_source, 16);
139         BUF_reverse(real_ukm, NULL, 16);
140     }
141
142     switch (pkey_nid) {
143     case NID_id_GostR3410_2012_512:
144         keylen =
145             VKO_compute_key(keyout, pub_key, priv_key, real_ukm, 16,
146                             NID_id_GostR3411_2012_512);
147         return (keylen) ? keylen : 0;
148         break;
149
150     case NID_id_GostR3410_2012_256:
151         {
152             unsigned char tmpkey[32];
153             keylen =
154               VKO_compute_key(tmpkey, pub_key, priv_key, real_ukm, 16,
155                   NID_id_GostR3411_2012_256);
156
157             if (keylen == 0)
158                 return 0;
159
160             if (gost_kdftree2012_256
161                 (keyout, 64, tmpkey, 32, (const unsigned char *)"kdf tree", 8,
162                  ukm_source + 16, 8, 1) > 0)
163                 keylen = 64;
164             else
165                 keylen = 0;
166
167             OPENSSL_cleanse(tmpkey, 32);
168             return (keylen) ? keylen : 0;
169         }
170     default:
171         return 0;
172     }
173 }
174
175 /*
176  * EVP_PKEY_METHOD callback derive.
177  * Implements VKO R 34.10-2001/2012 algorithms
178  */
179 /*
180  * Backend for EVP_PKEY_derive()
181  * It have KEG mode (default) and VKO mode (enable by EVP_PKEY_CTRL_SET_VKO).
182  */
183 int pkey_gost_ec_derive(EVP_PKEY_CTX *ctx, unsigned char *key, size_t *keylen)
184 {
185     /*
186      * Public key of peer in the ctx field peerkey
187      * Our private key in the ctx pkey
188      * ukm is in the algorithm specific context data
189      */
190     EVP_PKEY *my_key = EVP_PKEY_CTX_get0_pkey(ctx);
191     EVP_PKEY *peer_key = EVP_PKEY_CTX_get0_peerkey(ctx);
192     struct gost_pmeth_data *data = EVP_PKEY_CTX_get_data(ctx);
193     int dgst_nid = NID_undef;
194
195     if (!data || data->shared_ukm_size == 0) {
196         GOSTerr(GOST_F_PKEY_GOST_EC_DERIVE, GOST_R_UKM_NOT_SET);
197         return 0;
198     }
199
200     /* VKO */
201     if (data->vko_dgst_nid) {
202         if (!key) {
203             *keylen = data->vko_dgst_nid == NID_id_GostR3411_2012_256? 32 : 64;
204             return 1;
205         }
206         *keylen = VKO_compute_key(key,
207                                   EC_KEY_get0_public_key(EVP_PKEY_get0(peer_key)),
208                                   (EC_KEY *)EVP_PKEY_get0(my_key),
209                                   data->shared_ukm, data->shared_ukm_size,
210                                   data->vko_dgst_nid);
211         return (*keylen) ? 1 : 0;
212     }
213
214     /*
215      * shared_ukm_size = 8 stands for pre-2018 cipher suites
216      * It means 32 bytes of key length, 8 byte UKM, 32-bytes hash
217      *
218      * shared_ukm_size = 32 stands for post-2018 cipher suites
219      * It means 64 bytes of shared_key, 16 bytes of UKM and either
220      * 64 bytes of hash or 64 bytes of TLSTREE output
221      * */
222
223     switch (data->shared_ukm_size) {
224     case 8:
225         {
226             if (key == NULL) {
227                 *keylen = 32;
228                 return 1;
229             }
230             EVP_PKEY_get_default_digest_nid(my_key, &dgst_nid);
231             if (dgst_nid == NID_id_GostR3411_2012_512)
232                 dgst_nid = NID_id_GostR3411_2012_256;
233
234             *keylen =
235                 VKO_compute_key(key,
236                                 EC_KEY_get0_public_key(EVP_PKEY_get0(peer_key)),
237                                 (EC_KEY *)EVP_PKEY_get0(my_key),
238                                 data->shared_ukm, 8, dgst_nid);
239             return (*keylen) ? 1 : 0;
240         }
241         break;
242     case 32:
243         {
244             if (key == NULL) {
245                 *keylen = 64;
246                 return 1;
247             }
248
249             *keylen = gost_keg(data->shared_ukm, EVP_PKEY_id(my_key),
250                                EC_KEY_get0_public_key(EVP_PKEY_get0(peer_key)),
251                                (EC_KEY *)EVP_PKEY_get0(my_key), key);
252             return (*keylen) ? 1 : 0;
253         }
254
255         break;
256     default:
257         return 0;
258     }
259 }
260
261 /*
262  * Generates ephemeral key based on pubk algorithm computes shared key using
263  * VKO and returns filled up GOST_KEY_TRANSPORT structure
264  */
265
266 /*
267  * EVP_PKEY_METHOD callback encrypt
268  * Implementation of GOST2001/12 key transport, cryptopro variation
269  */
270
271 static int pkey_GOST_ECcp_encrypt(EVP_PKEY_CTX *pctx, unsigned char *out,
272                            size_t *out_len, const unsigned char *key,
273                            size_t key_len)
274 {
275     GOST_KEY_TRANSPORT *gkt = NULL;
276     EVP_PKEY *pubk = EVP_PKEY_CTX_get0_pkey(pctx);
277     struct gost_pmeth_data *data = EVP_PKEY_CTX_get_data(pctx);
278     int pkey_nid = EVP_PKEY_base_id(pubk);
279     ASN1_OBJECT *crypt_params_obj = (pkey_nid == NID_id_GostR3410_2001 || pkey_nid == NID_id_GostR3410_2001DH) ?
280         OBJ_nid2obj(NID_id_Gost28147_89_CryptoPro_A_ParamSet) :
281         OBJ_nid2obj(NID_id_tc26_gost_28147_param_Z);
282     const struct gost_cipher_info *param =
283         get_encryption_params(crypt_params_obj);
284     unsigned char ukm[8], shared_key[32], crypted_key[44];
285     int ret = 0;
286     int key_is_ephemeral = 1;
287     gost_ctx cctx;
288     EVP_PKEY *sec_key = EVP_PKEY_CTX_get0_peerkey(pctx);
289     if (data->shared_ukm_size) {
290         memcpy(ukm, data->shared_ukm, 8);
291     } else {
292         if (RAND_bytes(ukm, 8) <= 0) {
293             GOSTerr(GOST_F_PKEY_GOST_ECCP_ENCRYPT, GOST_R_RNG_ERROR);
294             return 0;
295         }
296     }
297     if (!param)
298         goto err;
299     /* Check for private key in the peer_key of context */
300     if (sec_key) {
301         key_is_ephemeral = 0;
302         if (!gost_get0_priv_key(sec_key)) {
303             GOSTerr(GOST_F_PKEY_GOST_ECCP_ENCRYPT,
304                     GOST_R_NO_PRIVATE_PART_OF_NON_EPHEMERAL_KEYPAIR);
305             goto err;
306         }
307     } else {
308         key_is_ephemeral = 1;
309         if (out) {
310             sec_key = EVP_PKEY_new();
311             if (!EVP_PKEY_assign(sec_key, EVP_PKEY_base_id(pubk), EC_KEY_new())
312                 || !EVP_PKEY_copy_parameters(sec_key, pubk)
313                 || !gost_ec_keygen(EVP_PKEY_get0(sec_key))) {
314                 GOSTerr(GOST_F_PKEY_GOST_ECCP_ENCRYPT,
315                         GOST_R_ERROR_COMPUTING_SHARED_KEY);
316                 goto err;
317             }
318         }
319     }
320     if (out) {
321         int dgst_nid = NID_undef;
322         EVP_PKEY_get_default_digest_nid(pubk, &dgst_nid);
323         if (dgst_nid == NID_id_GostR3411_2012_512)
324             dgst_nid = NID_id_GostR3411_2012_256;
325
326         if (!VKO_compute_key(shared_key,
327                              EC_KEY_get0_public_key(EVP_PKEY_get0(pubk)),
328                              EVP_PKEY_get0(sec_key), ukm, 8, dgst_nid)) {
329             GOSTerr(GOST_F_PKEY_GOST_ECCP_ENCRYPT,
330                     GOST_R_ERROR_COMPUTING_SHARED_KEY);
331             goto err;
332         }
333         gost_init(&cctx, param->sblock);
334         keyWrapCryptoPro(&cctx, shared_key, ukm, key, crypted_key);
335     }
336     gkt = GOST_KEY_TRANSPORT_new();
337     if (!gkt) {
338         goto err;
339     }
340     if (!ASN1_OCTET_STRING_set(gkt->key_agreement_info->eph_iv, ukm, 8)) {
341         goto err;
342     }
343     if (!ASN1_OCTET_STRING_set(gkt->key_info->imit, crypted_key + 40, 4)) {
344         goto err;
345     }
346     if (!ASN1_OCTET_STRING_set
347         (gkt->key_info->encrypted_key, crypted_key + 8, 32)) {
348         goto err;
349     }
350     if (key_is_ephemeral) {
351         if (!X509_PUBKEY_set
352             (&gkt->key_agreement_info->ephem_key, out ? sec_key : pubk)) {
353             GOSTerr(GOST_F_PKEY_GOST_ECCP_ENCRYPT,
354                     GOST_R_CANNOT_PACK_EPHEMERAL_KEY);
355             goto err;
356         }
357     }
358     ASN1_OBJECT_free(gkt->key_agreement_info->cipher);
359     gkt->key_agreement_info->cipher = OBJ_nid2obj(param->nid);
360     if (key_is_ephemeral)
361         EVP_PKEY_free(sec_key);
362     if (!key_is_ephemeral) {
363         /* Set control "public key from client certificate used" */
364         if (EVP_PKEY_CTX_ctrl(pctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 3, NULL)
365             <= 0) {
366             GOSTerr(GOST_F_PKEY_GOST_ECCP_ENCRYPT, GOST_R_CTRL_CALL_FAILED);
367             goto err;
368         }
369     }
370     if ((*out_len = i2d_GOST_KEY_TRANSPORT(gkt, out ? &out : NULL)) > 0)
371         ret = 1;
372     OPENSSL_cleanse(shared_key, sizeof(shared_key));
373     GOST_KEY_TRANSPORT_free(gkt);
374     return ret;
375  err:
376     OPENSSL_cleanse(shared_key, sizeof(shared_key));
377     if (key_is_ephemeral)
378         EVP_PKEY_free(sec_key);
379     GOST_KEY_TRANSPORT_free(gkt);
380     return -1;
381 }
382
383 /*
384  * EVP_PKEY_METHOD callback decrypt
385  * Implementation of GOST2018 key transport
386  */
387 static int pkey_gost2018_encrypt(EVP_PKEY_CTX *pctx, unsigned char *out,
388                           size_t *out_len, const unsigned char *key,
389                           size_t key_len)
390 {
391     PSKeyTransport_gost *pst = NULL;
392     EVP_PKEY *pubk = EVP_PKEY_CTX_get0_pkey(pctx);
393     struct gost_pmeth_data *data = EVP_PKEY_CTX_get_data(pctx);
394     int pkey_nid = EVP_PKEY_base_id(pubk);
395     unsigned char expkeys[64];
396     EVP_PKEY *sec_key = NULL;
397     int ret = 0;
398     int mac_nid = NID_undef;
399     size_t mac_len = 0;
400     int exp_len = 0, iv_len = 0;
401     unsigned char *exp_buf = NULL;
402     int key_is_ephemeral = 0;
403
404     switch (data->cipher_nid) {
405     case NID_magma_ctr:
406         mac_nid = NID_magma_mac;
407         mac_len = 8;
408         iv_len = 4;
409         break;
410     case NID_grasshopper_ctr:
411         mac_nid = NID_grasshopper_mac;
412         mac_len = 16;
413         iv_len = 8;
414         break;
415     default:
416         GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, GOST_R_INVALID_CIPHER);
417         return -1;
418         break;
419     }
420     exp_len = key_len + mac_len;
421     exp_buf = OPENSSL_malloc(exp_len);
422     if (!exp_buf) {
423         GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_MALLOC_FAILURE);
424         return -1;
425     }
426
427     sec_key = EVP_PKEY_CTX_get0_peerkey(pctx);
428     if (!sec_key)
429     {
430       sec_key = EVP_PKEY_new();
431       if (sec_key == NULL) {
432         GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_MALLOC_FAILURE );
433         goto err;
434       }
435
436       if (!EVP_PKEY_assign(sec_key, EVP_PKEY_base_id(pubk), EC_KEY_new())
437           || !EVP_PKEY_copy_parameters(sec_key, pubk)
438           || !gost_ec_keygen(EVP_PKEY_get0(sec_key))) {
439         GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT,
440             GOST_R_ERROR_COMPUTING_SHARED_KEY);
441         goto err;
442       }
443       key_is_ephemeral = 1;
444     }
445
446     if (data->shared_ukm_size == 0) {
447         if (RAND_bytes(data->shared_ukm, 32) <= 0) {
448             GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_INTERNAL_ERROR);
449             goto err;
450         }
451         data->shared_ukm_size = 32;
452     }
453
454     if (gost_keg(data->shared_ukm, pkey_nid,
455                  EC_KEY_get0_public_key(EVP_PKEY_get0(pubk)),
456                  EVP_PKEY_get0(sec_key), expkeys) <= 0) {
457         GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT,
458                 GOST_R_ERROR_COMPUTING_EXPORT_KEYS);
459         goto err;
460     }
461
462     if (gost_kexp15(key, key_len, data->cipher_nid, expkeys + 32,
463                     mac_nid, expkeys + 0, data->shared_ukm + 24, iv_len,
464                     exp_buf, &exp_len) <= 0) {
465         GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, GOST_R_CANNOT_PACK_EPHEMERAL_KEY);
466         goto err;
467     }
468
469     pst = PSKeyTransport_gost_new();
470     if (!pst) {
471         GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_MALLOC_FAILURE);
472         goto err;
473     }
474
475     pst->ukm = ASN1_OCTET_STRING_new();
476     if (pst->ukm == NULL) {
477         GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_MALLOC_FAILURE);
478         goto err;
479     }
480
481     if (!ASN1_OCTET_STRING_set(pst->ukm, data->shared_ukm, data->shared_ukm_size)) {
482         GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_MALLOC_FAILURE);
483         goto err;
484     }
485
486     if (!ASN1_OCTET_STRING_set(pst->psexp, exp_buf, exp_len)) {
487         GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_MALLOC_FAILURE);
488         goto err;
489     }
490
491     if (!X509_PUBKEY_set(&pst->ephem_key, out ? sec_key : pubk)) {
492         GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, GOST_R_CANNOT_PACK_EPHEMERAL_KEY);
493         goto err;
494     }
495
496     if ((*out_len = i2d_PSKeyTransport_gost(pst, out ? &out : NULL)) > 0)
497         ret = 1;
498  err:
499     OPENSSL_cleanse(expkeys, sizeof(expkeys));
500     if (key_is_ephemeral)
501         EVP_PKEY_free(sec_key);
502
503     PSKeyTransport_gost_free(pst);
504     OPENSSL_free(exp_buf);
505     return ret;
506 }
507
508 int pkey_gost_encrypt(EVP_PKEY_CTX *pctx, unsigned char *out,
509                       size_t *out_len, const unsigned char *key, size_t key_len)
510 {
511   struct gost_pmeth_data *gctx = EVP_PKEY_CTX_get_data(pctx);
512   switch (gctx->cipher_nid)
513   {
514     case NID_id_Gost28147_89:
515     case NID_undef: /* FIXME */
516       return pkey_GOST_ECcp_encrypt(pctx, out, out_len, key, key_len);
517       break;
518     case NID_kuznyechik_ctr:
519     case NID_magma_ctr:
520       return pkey_gost2018_encrypt(pctx, out, out_len, key, key_len);
521       break;
522     default:
523       GOSTerr(GOST_F_PKEY_GOST_ENCRYPT, ERR_R_INTERNAL_ERROR);
524       return -1;
525   }
526 }
527
528 /*
529  * EVP_PKEY_METHOD callback decrypt
530  * Implementation of GOST2001/12 key transport, cryptopro variation
531  */
532 static int pkey_GOST_ECcp_decrypt(EVP_PKEY_CTX *pctx, unsigned char *key,
533                            size_t *key_len, const unsigned char *in,
534                            size_t in_len)
535 {
536     const unsigned char *p = in;
537     EVP_PKEY *priv = EVP_PKEY_CTX_get0_pkey(pctx);
538     GOST_KEY_TRANSPORT *gkt = NULL;
539     int ret = 0;
540     unsigned char wrappedKey[44];
541     unsigned char sharedKey[32];
542     gost_ctx ctx;
543     const struct gost_cipher_info *param = NULL;
544     EVP_PKEY *eph_key = NULL, *peerkey = NULL;
545     int dgst_nid = NID_undef;
546
547     if (!key) {
548         *key_len = 32;
549         return 1;
550     }
551     gkt = d2i_GOST_KEY_TRANSPORT(NULL, (const unsigned char **)&p, in_len);
552     if (!gkt) {
553         GOSTerr(GOST_F_PKEY_GOST_ECCP_DECRYPT,
554                 GOST_R_ERROR_PARSING_KEY_TRANSPORT_INFO);
555         return -1;
556     }
557
558     /* If key transport structure contains public key, use it */
559     eph_key = X509_PUBKEY_get(gkt->key_agreement_info->ephem_key);
560     if (eph_key) {
561         if (EVP_PKEY_derive_set_peer(pctx, eph_key) <= 0) {
562             GOSTerr(GOST_F_PKEY_GOST_ECCP_DECRYPT,
563                     GOST_R_INCOMPATIBLE_PEER_KEY);
564             goto err;
565         }
566     } else {
567         /* Set control "public key from client certificate used" */
568         if (EVP_PKEY_CTX_ctrl(pctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 3, NULL)
569             <= 0) {
570             GOSTerr(GOST_F_PKEY_GOST_ECCP_DECRYPT, GOST_R_CTRL_CALL_FAILED);
571             goto err;
572         }
573     }
574     peerkey = EVP_PKEY_CTX_get0_peerkey(pctx);
575     if (!peerkey) {
576         GOSTerr(GOST_F_PKEY_GOST_ECCP_DECRYPT, GOST_R_NO_PEER_KEY);
577         goto err;
578     }
579
580     param = get_encryption_params(gkt->key_agreement_info->cipher);
581     if (!param) {
582         goto err;
583     }
584
585     gost_init(&ctx, param->sblock);
586     OPENSSL_assert(gkt->key_agreement_info->eph_iv->length == 8);
587     memcpy(wrappedKey, gkt->key_agreement_info->eph_iv->data, 8);
588     OPENSSL_assert(gkt->key_info->encrypted_key->length == 32);
589     memcpy(wrappedKey + 8, gkt->key_info->encrypted_key->data, 32);
590     OPENSSL_assert(gkt->key_info->imit->length == 4);
591     memcpy(wrappedKey + 40, gkt->key_info->imit->data, 4);
592
593     EVP_PKEY_get_default_digest_nid(priv, &dgst_nid);
594     if (dgst_nid == NID_id_GostR3411_2012_512)
595         dgst_nid = NID_id_GostR3411_2012_256;
596
597     if (!VKO_compute_key(sharedKey,
598                          EC_KEY_get0_public_key(EVP_PKEY_get0(peerkey)),
599                          EVP_PKEY_get0(priv), wrappedKey, 8, dgst_nid)) {
600         GOSTerr(GOST_F_PKEY_GOST_ECCP_DECRYPT,
601                 GOST_R_ERROR_COMPUTING_SHARED_KEY);
602         goto err;
603     }
604     if (!keyUnwrapCryptoPro(&ctx, sharedKey, wrappedKey, key)) {
605         GOSTerr(GOST_F_PKEY_GOST_ECCP_DECRYPT,
606                 GOST_R_ERROR_COMPUTING_SHARED_KEY);
607         goto err;
608     }
609
610     ret = 1;
611  err:
612     OPENSSL_cleanse(sharedKey, sizeof(sharedKey));
613     EVP_PKEY_free(eph_key);
614     GOST_KEY_TRANSPORT_free(gkt);
615     return ret;
616 }
617
618 /*
619  * EVP_PKEY_METHOD callback decrypt
620  * Implementation of GOST2018 key transport
621  */
622 static int pkey_gost2018_decrypt(EVP_PKEY_CTX *pctx, unsigned char *key,
623                           size_t *key_len, const unsigned char *in,
624                           size_t in_len)
625 {
626     const unsigned char *p = in;
627     struct gost_pmeth_data *data = EVP_PKEY_CTX_get_data(pctx);
628     EVP_PKEY *priv = EVP_PKEY_CTX_get0_pkey(pctx);
629     PSKeyTransport_gost *pst = NULL;
630     int ret = 0;
631     unsigned char expkeys[64];
632     EVP_PKEY *eph_key = NULL;
633     int pkey_nid = EVP_PKEY_base_id(priv);
634     int mac_nid = NID_undef;
635     int iv_len = 0;
636
637     switch (data->cipher_nid) {
638     case NID_magma_ctr:
639         mac_nid = NID_magma_mac;
640         iv_len = 4;
641         break;
642     case NID_grasshopper_ctr:
643         mac_nid = NID_grasshopper_mac;
644         iv_len = 8;
645         break;
646     default:
647         GOSTerr(GOST_F_PKEY_GOST2018_DECRYPT, GOST_R_INVALID_CIPHER);
648         return -1;
649         break;
650     }
651     if (!key) {
652         *key_len = 32;
653         return 1;
654     }
655
656     pst = d2i_PSKeyTransport_gost(NULL, (const unsigned char **)&p, in_len);
657     if (!pst) {
658         GOSTerr(GOST_F_PKEY_GOST2018_DECRYPT,
659                 GOST_R_ERROR_PARSING_KEY_TRANSPORT_INFO);
660         return -1;
661     }
662
663     eph_key = X509_PUBKEY_get(pst->ephem_key);
664 /*
665  * TODO beldmit
666    1.  Checks the next three conditions fulfilling and terminates the
667    connection with fatal error if not.
668
669    o  Q_eph is on the same curve as server public key;
670
671    o  Q_eph is not equal to zero point;
672
673    o  q * Q_eph is not equal to zero point.
674 */
675     if (data->shared_ukm_size == 0 && pst->ukm != NULL) {
676         if (EVP_PKEY_CTX_ctrl(pctx, -1, -1, EVP_PKEY_CTRL_SET_IV,
677         ASN1_STRING_length(pst->ukm), (void *)ASN1_STRING_get0_data(pst->ukm)) < 0) {
678             GOSTerr(GOST_F_PKEY_GOST2018_DECRYPT, GOST_R_UKM_NOT_SET);
679             goto err;
680         }
681     }
682
683     if (gost_keg(data->shared_ukm, pkey_nid,
684                  EC_KEY_get0_public_key(EVP_PKEY_get0(eph_key)),
685                  EVP_PKEY_get0(priv), expkeys) <= 0) {
686         GOSTerr(GOST_F_PKEY_GOST2018_DECRYPT,
687                 GOST_R_ERROR_COMPUTING_EXPORT_KEYS);
688         goto err;
689     }
690
691     if (gost_kimp15(ASN1_STRING_get0_data(pst->psexp),
692                     ASN1_STRING_length(pst->psexp), data->cipher_nid,
693                     expkeys + 32, mac_nid, expkeys + 0, data->shared_ukm + 24,
694                     iv_len, key) <= 0) {
695         GOSTerr(GOST_F_PKEY_GOST2018_DECRYPT, GOST_R_CANNOT_UNPACK_EPHEMERAL_KEY);
696         goto err;
697     }
698
699     ret = 1;
700  err:
701     OPENSSL_cleanse(expkeys, sizeof(expkeys));
702     EVP_PKEY_free(eph_key);
703     PSKeyTransport_gost_free(pst);
704     return ret;
705 }
706
707 int pkey_gost_decrypt(EVP_PKEY_CTX *pctx, unsigned char *key,
708                       size_t *key_len, const unsigned char *in, size_t in_len)
709 {
710     struct gost_pmeth_data *gctx = EVP_PKEY_CTX_get_data(pctx);
711     switch (gctx->cipher_nid)
712     {
713         case NID_id_Gost28147_89:
714         case NID_undef: /* FIXME */
715             return pkey_GOST_ECcp_decrypt(pctx, key, key_len, in, in_len);
716         case NID_kuznyechik_ctr:
717         case NID_magma_ctr:
718             return pkey_gost2018_decrypt(pctx, key, key_len, in, in_len);
719         default:
720       GOSTerr(GOST_F_PKEY_GOST_DECRYPT, ERR_R_INTERNAL_ERROR);
721       return -1;
722     }
723 }
724 /* vim: set expandtab cinoptions=\:0,l1,t0,g0,(0 sw=4 : */