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