]> www.wagner.pp.ru Git - openssl-gost/engine.git/blob - gost_ec_keyx.c
GOST ECC optimizations (#263)
[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  * keyout expected to be 64 bytes
124  * */
125 static int gost_keg(const unsigned char *ukm_source, int pkey_nid,
126                     const EC_POINT *pub_key, const EC_KEY *priv_key,
127                     unsigned char *keyout)
128 {
129 /* Adjust UKM */
130     unsigned char real_ukm[16];
131     size_t keylen = 0;
132
133     memset(real_ukm, 0, 16);
134     if (memcmp(ukm_source, real_ukm, 16) == 0)
135         real_ukm[15] = 1;
136     else {
137         memcpy(real_ukm, ukm_source, 16);
138         BUF_reverse(real_ukm, NULL, 16);
139     }
140
141     switch (pkey_nid) {
142     case NID_id_GostR3410_2012_512:
143         keylen =
144             VKO_compute_key(keyout, pub_key, priv_key, real_ukm, 16,
145                             NID_id_GostR3411_2012_512);
146         return (keylen) ? keylen : 0;
147         break;
148
149     case NID_id_GostR3410_2012_256:
150         {
151             unsigned char tmpkey[32];
152             keylen =
153               VKO_compute_key(tmpkey, pub_key, priv_key, real_ukm, 16,
154                   NID_id_GostR3411_2012_256);
155
156             if (keylen == 0)
157                 return 0;
158
159             if (gost_kdftree2012_256
160                 (keyout, 64, tmpkey, 32, (const unsigned char *)"kdf tree", 8,
161                  ukm_source + 16, 8, 1) > 0)
162                 keylen = 64;
163             else
164                 keylen = 0;
165
166             OPENSSL_cleanse(tmpkey, 32);
167             return (keylen) ? keylen : 0;
168         }
169     default:
170         return 0;
171     }
172 }
173
174 /*
175  * EVP_PKEY_METHOD callback derive.
176  * Implements VKO R 34.10-2001/2012 algorithms
177  */
178 int pkey_gost_ec_derive(EVP_PKEY_CTX *ctx, unsigned char *key, size_t *keylen)
179 {
180     /*
181      * Public key of peer in the ctx field peerkey
182      * Our private key in the ctx pkey
183      * ukm is in the algorithm specific context data
184      */
185     EVP_PKEY *my_key = EVP_PKEY_CTX_get0_pkey(ctx);
186     EVP_PKEY *peer_key = EVP_PKEY_CTX_get0_peerkey(ctx);
187     struct gost_pmeth_data *data = EVP_PKEY_CTX_get_data(ctx);
188     int dgst_nid = NID_undef;
189
190     if (!data || data->shared_ukm_size == 0) {
191         GOSTerr(GOST_F_PKEY_GOST_EC_DERIVE, GOST_R_UKM_NOT_SET);
192         return 0;
193     }
194     /*
195      * shared_ukm_size = 8 stands for pre-2018 cipher suites
196      * It means 32 bytes of key length, 8 byte UKM, 32-bytes hash
197      *
198      * shared_ukm_size = 32 stands for pre-2018 cipher suites
199      * It means 64 bytes of shared_key, 16 bytes of UKM and either
200      * 64 bytes of hash or 64 bytes of TLSTREE output
201      * */
202
203     switch (data->shared_ukm_size) {
204     case 8:
205         {
206             if (key == NULL) {
207                 *keylen = 32;
208                 return 1;
209             }
210
211             EVP_PKEY_get_default_digest_nid(my_key, &dgst_nid);
212             if (dgst_nid == NID_id_GostR3411_2012_512)
213                 dgst_nid = NID_id_GostR3411_2012_256;
214
215             *keylen =
216                 VKO_compute_key(key,
217                                 EC_KEY_get0_public_key(EVP_PKEY_get0(peer_key)),
218                                 (EC_KEY *)EVP_PKEY_get0(my_key),
219                                 data->shared_ukm, 8, dgst_nid);
220             return (*keylen) ? 1 : 0;
221         }
222         break;
223     case 32:
224         {
225             if (key == NULL) {
226                 *keylen = 64;
227                 return 1;
228             }
229
230             *keylen = gost_keg(data->shared_ukm, EVP_PKEY_id(my_key),
231                                EC_KEY_get0_public_key(EVP_PKEY_get0(peer_key)),
232                                (EC_KEY *)EVP_PKEY_get0(my_key), key);
233             return (*keylen) ? 1 : 0;
234         }
235
236         break;
237     default:
238         return 0;
239     }
240 }
241
242 /*
243  * Generates ephemeral key based on pubk algorithm computes shared key using
244  * VKO and returns filled up GOST_KEY_TRANSPORT structure
245  */
246
247 /*
248  * EVP_PKEY_METHOD callback encrypt
249  * Implementation of GOST2001/12 key transport, cryptopro variation
250  */
251
252 static int pkey_GOST_ECcp_encrypt(EVP_PKEY_CTX *pctx, unsigned char *out,
253                            size_t *out_len, const unsigned char *key,
254                            size_t key_len)
255 {
256     GOST_KEY_TRANSPORT *gkt = NULL;
257     EVP_PKEY *pubk = EVP_PKEY_CTX_get0_pkey(pctx);
258     struct gost_pmeth_data *data = EVP_PKEY_CTX_get_data(pctx);
259     int pkey_nid = EVP_PKEY_base_id(pubk);
260     ASN1_OBJECT *crypt_params_obj = (pkey_nid == NID_id_GostR3410_2001) ?
261         OBJ_nid2obj(NID_id_Gost28147_89_CryptoPro_A_ParamSet) :
262         OBJ_nid2obj(NID_id_tc26_gost_28147_param_Z);
263     const struct gost_cipher_info *param =
264         get_encryption_params(crypt_params_obj);
265     unsigned char ukm[8], shared_key[32], crypted_key[44];
266     int ret = 0;
267     int key_is_ephemeral = 1;
268     gost_ctx cctx;
269     EVP_PKEY *sec_key = EVP_PKEY_CTX_get0_peerkey(pctx);
270     if (data->shared_ukm_size) {
271         memcpy(ukm, data->shared_ukm, 8);
272     } else {
273         if (RAND_bytes(ukm, 8) <= 0) {
274             GOSTerr(GOST_F_PKEY_GOST_ECCP_ENCRYPT, GOST_R_RNG_ERROR);
275             return 0;
276         }
277     }
278     if (!param)
279         goto err;
280     /* Check for private key in the peer_key of context */
281     if (sec_key) {
282         key_is_ephemeral = 0;
283         if (!gost_get0_priv_key(sec_key)) {
284             GOSTerr(GOST_F_PKEY_GOST_ECCP_ENCRYPT,
285                     GOST_R_NO_PRIVATE_PART_OF_NON_EPHEMERAL_KEYPAIR);
286             goto err;
287         }
288     } else {
289         key_is_ephemeral = 1;
290         if (out) {
291             sec_key = EVP_PKEY_new();
292             if (!EVP_PKEY_assign(sec_key, EVP_PKEY_base_id(pubk), EC_KEY_new())
293                 || !EVP_PKEY_copy_parameters(sec_key, pubk)
294                 || !gost_ec_keygen(EVP_PKEY_get0(sec_key))) {
295                 GOSTerr(GOST_F_PKEY_GOST_ECCP_ENCRYPT,
296                         GOST_R_ERROR_COMPUTING_SHARED_KEY);
297                 goto err;
298             }
299         }
300     }
301     if (out) {
302         int dgst_nid = NID_undef;
303         EVP_PKEY_get_default_digest_nid(pubk, &dgst_nid);
304         if (dgst_nid == NID_id_GostR3411_2012_512)
305             dgst_nid = NID_id_GostR3411_2012_256;
306
307         if (!VKO_compute_key(shared_key,
308                              EC_KEY_get0_public_key(EVP_PKEY_get0(pubk)),
309                              EVP_PKEY_get0(sec_key), ukm, 8, dgst_nid)) {
310             GOSTerr(GOST_F_PKEY_GOST_ECCP_ENCRYPT,
311                     GOST_R_ERROR_COMPUTING_SHARED_KEY);
312             goto err;
313         }
314         gost_init(&cctx, param->sblock);
315         keyWrapCryptoPro(&cctx, shared_key, ukm, key, crypted_key);
316     }
317     gkt = GOST_KEY_TRANSPORT_new();
318     if (!gkt) {
319         goto err;
320     }
321     if (!ASN1_OCTET_STRING_set(gkt->key_agreement_info->eph_iv, ukm, 8)) {
322         goto err;
323     }
324     if (!ASN1_OCTET_STRING_set(gkt->key_info->imit, crypted_key + 40, 4)) {
325         goto err;
326     }
327     if (!ASN1_OCTET_STRING_set
328         (gkt->key_info->encrypted_key, crypted_key + 8, 32)) {
329         goto err;
330     }
331     if (key_is_ephemeral) {
332         if (!X509_PUBKEY_set
333             (&gkt->key_agreement_info->ephem_key, out ? sec_key : pubk)) {
334             GOSTerr(GOST_F_PKEY_GOST_ECCP_ENCRYPT,
335                     GOST_R_CANNOT_PACK_EPHEMERAL_KEY);
336             goto err;
337         }
338     }
339     ASN1_OBJECT_free(gkt->key_agreement_info->cipher);
340     gkt->key_agreement_info->cipher = OBJ_nid2obj(param->nid);
341     if (key_is_ephemeral)
342         EVP_PKEY_free(sec_key);
343     if (!key_is_ephemeral) {
344         /* Set control "public key from client certificate used" */
345         if (EVP_PKEY_CTX_ctrl(pctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 3, NULL)
346             <= 0) {
347             GOSTerr(GOST_F_PKEY_GOST_ECCP_ENCRYPT, GOST_R_CTRL_CALL_FAILED);
348             goto err;
349         }
350     }
351     if ((*out_len = i2d_GOST_KEY_TRANSPORT(gkt, out ? &out : NULL)) > 0)
352         ret = 1;
353     OPENSSL_cleanse(shared_key, sizeof(shared_key));
354     GOST_KEY_TRANSPORT_free(gkt);
355     return ret;
356  err:
357     OPENSSL_cleanse(shared_key, sizeof(shared_key));
358     if (key_is_ephemeral)
359         EVP_PKEY_free(sec_key);
360     GOST_KEY_TRANSPORT_free(gkt);
361     return -1;
362 }
363
364 /*
365  * EVP_PKEY_METHOD callback decrypt
366  * Implementation of GOST2018 key transport
367  */
368 static int pkey_gost2018_encrypt(EVP_PKEY_CTX *pctx, unsigned char *out,
369                           size_t *out_len, const unsigned char *key,
370                           size_t key_len)
371 {
372     PSKeyTransport_gost *pst = NULL;
373     EVP_PKEY *pubk = EVP_PKEY_CTX_get0_pkey(pctx);
374     struct gost_pmeth_data *data = EVP_PKEY_CTX_get_data(pctx);
375     int pkey_nid = EVP_PKEY_base_id(pubk);
376     unsigned char expkeys[64];
377     EVP_PKEY *sec_key = NULL;
378     int ret = 0;
379     int mac_nid = NID_undef;
380     size_t mac_len = 0;
381     int exp_len = 0, iv_len = 0;
382     unsigned char *exp_buf = NULL;
383     int key_is_ephemeral = 0;
384
385     switch (data->cipher_nid) {
386     case NID_magma_ctr:
387         mac_nid = NID_magma_mac;
388         mac_len = 8;
389         iv_len = 4;
390         break;
391     case NID_grasshopper_ctr:
392         mac_nid = NID_grasshopper_mac;
393         mac_len = 16;
394         iv_len = 8;
395         break;
396     default:
397         GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, GOST_R_INVALID_CIPHER);
398         return -1;
399         break;
400     }
401     exp_len = key_len + mac_len;
402     exp_buf = OPENSSL_malloc(exp_len);
403     if (!exp_buf) {
404         GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_MALLOC_FAILURE);
405         return -1;
406     }
407
408     sec_key = EVP_PKEY_CTX_get0_peerkey(pctx);
409     if (!sec_key)
410     {
411       sec_key = EVP_PKEY_new();
412       if (sec_key == NULL) {
413         GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_MALLOC_FAILURE );
414         goto err;
415       }
416
417       if (!EVP_PKEY_assign(sec_key, EVP_PKEY_base_id(pubk), EC_KEY_new())
418           || !EVP_PKEY_copy_parameters(sec_key, pubk)
419           || !gost_ec_keygen(EVP_PKEY_get0(sec_key))) {
420         GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT,
421             GOST_R_ERROR_COMPUTING_SHARED_KEY);
422         goto err;
423       }
424       key_is_ephemeral = 1;
425     }
426
427     if (data->shared_ukm_size == 0) {
428         if (RAND_bytes(data->shared_ukm, 32) <= 0) {
429             GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_INTERNAL_ERROR);
430             goto err;
431         }
432         data->shared_ukm_size = 32;
433     }
434
435     if (gost_keg(data->shared_ukm, pkey_nid,
436                  EC_KEY_get0_public_key(EVP_PKEY_get0(pubk)),
437                  EVP_PKEY_get0(sec_key), expkeys) <= 0) {
438         GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT,
439                 GOST_R_ERROR_COMPUTING_EXPORT_KEYS);
440         goto err;
441     }
442
443     if (gost_kexp15(key, key_len, data->cipher_nid, expkeys + 32,
444                     mac_nid, expkeys + 0, data->shared_ukm + 24, iv_len,
445                     exp_buf, &exp_len) <= 0) {
446         GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, GOST_R_CANNOT_PACK_EPHEMERAL_KEY);
447         goto err;
448     }
449
450     pst = PSKeyTransport_gost_new();
451     if (!pst) {
452         GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_MALLOC_FAILURE);
453         goto err;
454     }
455
456     pst->ukm = ASN1_OCTET_STRING_new();
457     if (pst->ukm == NULL) {
458         GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_MALLOC_FAILURE);
459         goto err;
460     }
461
462     if (!ASN1_OCTET_STRING_set(pst->ukm, data->shared_ukm, data->shared_ukm_size)) {
463         GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_MALLOC_FAILURE);
464         goto err;
465     }
466
467     if (!ASN1_OCTET_STRING_set(pst->psexp, exp_buf, exp_len)) {
468         GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_MALLOC_FAILURE);
469         goto err;
470     }
471
472     if (!X509_PUBKEY_set(&pst->ephem_key, out ? sec_key : pubk)) {
473         GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, GOST_R_CANNOT_PACK_EPHEMERAL_KEY);
474         goto err;
475     }
476
477     if ((*out_len = i2d_PSKeyTransport_gost(pst, out ? &out : NULL)) > 0)
478         ret = 1;
479  err:
480     OPENSSL_cleanse(expkeys, sizeof(expkeys));
481     if (key_is_ephemeral)
482         EVP_PKEY_free(sec_key);
483
484     PSKeyTransport_gost_free(pst);
485     OPENSSL_free(exp_buf);
486     return ret;
487 }
488
489 int pkey_gost_encrypt(EVP_PKEY_CTX *pctx, unsigned char *out,
490                       size_t *out_len, const unsigned char *key, size_t key_len)
491 {
492   struct gost_pmeth_data *gctx = EVP_PKEY_CTX_get_data(pctx);
493   switch (gctx->cipher_nid)
494   {
495     case NID_id_Gost28147_89:
496     case NID_undef: /* FIXME */
497       return pkey_GOST_ECcp_encrypt(pctx, out, out_len, key, key_len);
498       break;
499     case NID_kuznyechik_ctr:
500     case NID_magma_ctr:
501       return pkey_gost2018_encrypt(pctx, out, out_len, key, key_len);
502       break;
503     default:
504       GOSTerr(GOST_F_PKEY_GOST_ENCRYPT, ERR_R_INTERNAL_ERROR);
505       return -1;
506   }
507 }
508
509 /*
510  * EVP_PKEY_METHOD callback decrypt
511  * Implementation of GOST2001/12 key transport, cryptopro variation
512  */
513 static int pkey_GOST_ECcp_decrypt(EVP_PKEY_CTX *pctx, unsigned char *key,
514                            size_t *key_len, const unsigned char *in,
515                            size_t in_len)
516 {
517     const unsigned char *p = in;
518     EVP_PKEY *priv = EVP_PKEY_CTX_get0_pkey(pctx);
519     GOST_KEY_TRANSPORT *gkt = NULL;
520     int ret = 0;
521     unsigned char wrappedKey[44];
522     unsigned char sharedKey[32];
523     gost_ctx ctx;
524     const struct gost_cipher_info *param = NULL;
525     EVP_PKEY *eph_key = NULL, *peerkey = NULL;
526     int dgst_nid = NID_undef;
527
528     if (!key) {
529         *key_len = 32;
530         return 1;
531     }
532     gkt = d2i_GOST_KEY_TRANSPORT(NULL, (const unsigned char **)&p, in_len);
533     if (!gkt) {
534         GOSTerr(GOST_F_PKEY_GOST_ECCP_DECRYPT,
535                 GOST_R_ERROR_PARSING_KEY_TRANSPORT_INFO);
536         return -1;
537     }
538
539     /* If key transport structure contains public key, use it */
540     eph_key = X509_PUBKEY_get(gkt->key_agreement_info->ephem_key);
541     if (eph_key) {
542         if (EVP_PKEY_derive_set_peer(pctx, eph_key) <= 0) {
543             GOSTerr(GOST_F_PKEY_GOST_ECCP_DECRYPT,
544                     GOST_R_INCOMPATIBLE_PEER_KEY);
545             goto err;
546         }
547     } else {
548         /* Set control "public key from client certificate used" */
549         if (EVP_PKEY_CTX_ctrl(pctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 3, NULL)
550             <= 0) {
551             GOSTerr(GOST_F_PKEY_GOST_ECCP_DECRYPT, GOST_R_CTRL_CALL_FAILED);
552             goto err;
553         }
554     }
555     peerkey = EVP_PKEY_CTX_get0_peerkey(pctx);
556     if (!peerkey) {
557         GOSTerr(GOST_F_PKEY_GOST_ECCP_DECRYPT, GOST_R_NO_PEER_KEY);
558         goto err;
559     }
560
561     param = get_encryption_params(gkt->key_agreement_info->cipher);
562     if (!param) {
563         goto err;
564     }
565
566     gost_init(&ctx, param->sblock);
567     OPENSSL_assert(gkt->key_agreement_info->eph_iv->length == 8);
568     memcpy(wrappedKey, gkt->key_agreement_info->eph_iv->data, 8);
569     OPENSSL_assert(gkt->key_info->encrypted_key->length == 32);
570     memcpy(wrappedKey + 8, gkt->key_info->encrypted_key->data, 32);
571     OPENSSL_assert(gkt->key_info->imit->length == 4);
572     memcpy(wrappedKey + 40, gkt->key_info->imit->data, 4);
573
574     EVP_PKEY_get_default_digest_nid(priv, &dgst_nid);
575     if (dgst_nid == NID_id_GostR3411_2012_512)
576         dgst_nid = NID_id_GostR3411_2012_256;
577
578     if (!VKO_compute_key(sharedKey,
579                          EC_KEY_get0_public_key(EVP_PKEY_get0(peerkey)),
580                          EVP_PKEY_get0(priv), wrappedKey, 8, dgst_nid)) {
581         GOSTerr(GOST_F_PKEY_GOST_ECCP_DECRYPT,
582                 GOST_R_ERROR_COMPUTING_SHARED_KEY);
583         goto err;
584     }
585     if (!keyUnwrapCryptoPro(&ctx, sharedKey, wrappedKey, key)) {
586         GOSTerr(GOST_F_PKEY_GOST_ECCP_DECRYPT,
587                 GOST_R_ERROR_COMPUTING_SHARED_KEY);
588         goto err;
589     }
590
591     ret = 1;
592  err:
593     OPENSSL_cleanse(sharedKey, sizeof(sharedKey));
594     EVP_PKEY_free(eph_key);
595     GOST_KEY_TRANSPORT_free(gkt);
596     return ret;
597 }
598
599 /*
600  * EVP_PKEY_METHOD callback decrypt
601  * Implementation of GOST2018 key transport
602  */
603 static int pkey_gost2018_decrypt(EVP_PKEY_CTX *pctx, unsigned char *key,
604                           size_t *key_len, const unsigned char *in,
605                           size_t in_len)
606 {
607     const unsigned char *p = in;
608     struct gost_pmeth_data *data = EVP_PKEY_CTX_get_data(pctx);
609     EVP_PKEY *priv = EVP_PKEY_CTX_get0_pkey(pctx);
610     PSKeyTransport_gost *pst = NULL;
611     int ret = 0;
612     unsigned char expkeys[64];
613     EVP_PKEY *eph_key = NULL;
614     int pkey_nid = EVP_PKEY_base_id(priv);
615     int mac_nid = NID_undef;
616     int iv_len = 0;
617
618     switch (data->cipher_nid) {
619     case NID_magma_ctr:
620         mac_nid = NID_magma_mac;
621         iv_len = 4;
622         break;
623     case NID_grasshopper_ctr:
624         mac_nid = NID_grasshopper_mac;
625         iv_len = 8;
626         break;
627     default:
628         GOSTerr(GOST_F_PKEY_GOST2018_DECRYPT, GOST_R_INVALID_CIPHER);
629         return -1;
630         break;
631     }
632     if (!key) {
633         *key_len = 32;
634         return 1;
635     }
636
637     pst = d2i_PSKeyTransport_gost(NULL, (const unsigned char **)&p, in_len);
638     if (!pst) {
639         GOSTerr(GOST_F_PKEY_GOST2018_DECRYPT,
640                 GOST_R_ERROR_PARSING_KEY_TRANSPORT_INFO);
641         return -1;
642     }
643
644     eph_key = X509_PUBKEY_get(pst->ephem_key);
645 /*
646  * TODO beldmit
647    1.  Checks the next three conditions fulfilling and terminates the
648    connection with fatal error if not.
649
650    o  Q_eph is on the same curve as server public key;
651
652    o  Q_eph is not equal to zero point;
653
654    o  q * Q_eph is not equal to zero point.
655 */
656     if (data->shared_ukm_size == 0 && pst->ukm != NULL) {
657         if (EVP_PKEY_CTX_ctrl(pctx, -1, -1, EVP_PKEY_CTRL_SET_IV,
658         ASN1_STRING_length(pst->ukm), (void *)ASN1_STRING_get0_data(pst->ukm)) < 0) {
659             GOSTerr(GOST_F_PKEY_GOST2018_DECRYPT, GOST_R_UKM_NOT_SET);
660             goto err;
661         }
662     }
663
664     if (gost_keg(data->shared_ukm, pkey_nid,
665                  EC_KEY_get0_public_key(EVP_PKEY_get0(eph_key)),
666                  EVP_PKEY_get0(priv), expkeys) <= 0) {
667         GOSTerr(GOST_F_PKEY_GOST2018_DECRYPT,
668                 GOST_R_ERROR_COMPUTING_EXPORT_KEYS);
669         goto err;
670     }
671
672     if (gost_kimp15(ASN1_STRING_get0_data(pst->psexp),
673                     ASN1_STRING_length(pst->psexp), data->cipher_nid,
674                     expkeys + 32, mac_nid, expkeys + 0, data->shared_ukm + 24,
675                     iv_len, key) <= 0) {
676         GOSTerr(GOST_F_PKEY_GOST2018_DECRYPT, GOST_R_CANNOT_UNPACK_EPHEMERAL_KEY);
677         goto err;
678     }
679
680     ret = 1;
681  err:
682     OPENSSL_cleanse(expkeys, sizeof(expkeys));
683     EVP_PKEY_free(eph_key);
684     PSKeyTransport_gost_free(pst);
685     return ret;
686 }
687
688 int pkey_gost_decrypt(EVP_PKEY_CTX *pctx, unsigned char *key,
689                       size_t *key_len, const unsigned char *in, size_t in_len)
690 {
691     struct gost_pmeth_data *gctx = EVP_PKEY_CTX_get_data(pctx);
692     switch (gctx->cipher_nid)
693     {
694         case NID_id_Gost28147_89:
695         case NID_undef: /* FIXME */
696             return pkey_GOST_ECcp_decrypt(pctx, key, key_len, in, in_len);
697         case NID_kuznyechik_ctr:
698         case NID_magma_ctr:
699             return pkey_gost2018_decrypt(pctx, key, key_len, in, in_len);
700         default:
701       GOSTerr(GOST_F_PKEY_GOST_DECRYPT, ERR_R_INTERNAL_ERROR);
702       return -1;
703     }
704 }