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