]> www.wagner.pp.ru Git - openssl-gost/engine.git/blob - gost_ec_keyx.c
Fix buffer overrun in creating key transport blob according to RFC 9189, 4.2.4.1
[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 int pkey_gost_ec_compute_key(void *out, size_t outlen, const EC_POINT *pub_key,
178                              const EC_KEY *eckey)
179 {
180     BN_CTX *ctx;
181     EC_POINT *tmp = NULL;
182     BIGNUM *x = NULL;
183     const BIGNUM *priv_key;
184     const EC_GROUP *group;
185     int ret = 0;
186     size_t buflen,len;
187     unsigned char *buf = NULL;
188     int nid;
189
190     if (outlen > INT_MAX) {
191         GOSTerr(GOST_F_PKEY_GOST_EC_COMPUTE_KEY, EC_R_INVALID_OUTPUT_LENGTH);
192         return 0;
193     }
194
195     if ((ctx = BN_CTX_new()) == NULL)
196         goto err;
197     BN_CTX_start(ctx);
198     x = BN_CTX_get(ctx);
199     if (x == NULL) {
200         GOSTerr(GOST_F_PKEY_GOST_EC_COMPUTE_KEY, ERR_R_MALLOC_FAILURE);
201         goto err;
202     }
203
204     priv_key = EC_KEY_get0_private_key(eckey);
205     if (priv_key == NULL) {
206         GOSTerr(GOST_F_PKEY_GOST_EC_COMPUTE_KEY, EC_R_MISSING_PRIVATE_KEY);
207         goto err;
208     }
209
210     group = EC_KEY_get0_group(eckey);
211
212     nid = EC_GROUP_get_curve_name(group);
213     if (nid == NID_id_tc26_gost_3410_2012_256_paramSetA 
214         || nid == NID_id_tc26_gost_3410_2012_512_paramSetC) {
215         if (!EC_GROUP_get_cofactor(group, x, NULL) ||
216             // or use BN_mul(...)
217             !BN_mod_mul(x, x, priv_key, EC_GROUP_get0_order(group), ctx)) {
218             GOSTerr(GOST_F_PKEY_GOST_EC_COMPUTE_KEY, ERR_R_INTERNAL_ERROR);
219             goto err;
220         }
221         priv_key = x;
222     }
223
224     if ((tmp = EC_POINT_new(group)) == NULL) {
225         GOSTerr(GOST_F_PKEY_GOST_EC_COMPUTE_KEY, ERR_R_MALLOC_FAILURE);
226         goto err;
227     }
228
229     if (!gost_ec_point_mul(group, tmp, NULL, pub_key, priv_key, ctx)) {
230         GOSTerr(GOST_F_PKEY_GOST_EC_COMPUTE_KEY, EC_R_POINT_ARITHMETIC_FAILURE);
231         goto err;
232     }
233
234     if (!EC_POINT_get_affine_coordinates(group, tmp, x, NULL, ctx)) {
235         GOSTerr(GOST_F_PKEY_GOST_EC_COMPUTE_KEY, EC_R_POINT_ARITHMETIC_FAILURE);
236         goto err;
237     }
238
239     buflen = (EC_GROUP_get_degree(group) + 7) / 8;
240     len = BN_num_bytes(x);
241     if (len > buflen) {
242         GOSTerr(GOST_F_PKEY_GOST_EC_COMPUTE_KEY, ERR_R_INTERNAL_ERROR);
243         goto err;
244     }
245     if ((buf = OPENSSL_malloc(buflen)) == NULL) {
246         GOSTerr(GOST_F_PKEY_GOST_EC_COMPUTE_KEY, ERR_R_MALLOC_FAILURE);
247         goto err;
248     }
249     
250     if (buflen != BN_bn2lebinpad(x, buf, buflen)) {
251         GOSTerr(GOST_F_PKEY_GOST_EC_COMPUTE_KEY, ERR_R_BN_LIB);
252         goto err;
253     }
254
255     if (outlen > buflen)
256         outlen = buflen;
257     memcpy(out, buf, outlen);
258     OPENSSL_clear_free(buf, buflen);
259
260     ret = outlen;
261
262  err:
263     EC_POINT_clear_free(tmp);
264     BN_CTX_end(ctx);
265     BN_CTX_free(ctx);
266     return ret;
267 }
268
269 int pkey_gost_ec_2020_derive(EVP_PKEY_CTX *ctx, unsigned char *key, 
270                              size_t *keylen)
271 {
272     int ret;
273     size_t outlen;
274     const EC_POINT *pubkey = NULL;
275     EC_KEY *eckey;
276     EVP_PKEY *my_key = EVP_PKEY_CTX_get0_pkey(ctx);
277     EVP_PKEY *peer_key = EVP_PKEY_CTX_get0_peerkey(ctx);
278
279     if (!my_key || !peer_key) {
280         GOSTerr(GOST_F_PKEY_GOST_EC_2020_DERIVE, EC_R_KEYS_NOT_SET);
281         return 0;
282     }
283
284     eckey = EVP_PKEY_get0(my_key);
285
286     if (!key) {
287         const EC_GROUP *group;
288         group = EC_KEY_get0_group(eckey);
289         *keylen = (EC_GROUP_get_degree(group) + 7) / 8;
290         return 1;
291     }
292     pubkey = EC_KEY_get0_public_key(EVP_PKEY_get0(peer_key));
293
294     /*
295      * if *outlen is less than maximum size, the result is truncated. 
296      * (is it error or not?)
297      */
298     
299     outlen = *keylen;
300
301     ret = pkey_gost_ec_compute_key(key, outlen, pubkey, eckey);
302     if (ret <= 0)
303         return 0;
304     *keylen = ret;
305     return 1;
306 }
307
308 /*
309  * EVP_PKEY_METHOD callback derive.
310  * Implements VKO R 34.10-2001/2012 algorithms
311  */
312 /*
313  * Backend for EVP_PKEY_derive()
314  * It have KEG mode (default) and VKO mode (enable by EVP_PKEY_CTRL_SET_VKO).
315  */
316 int pkey_gost_ec_derive(EVP_PKEY_CTX *ctx, unsigned char *key, size_t *keylen)
317 {
318     /*
319      * Public key of peer in the ctx field peerkey
320      * Our private key in the ctx pkey
321      * ukm is in the algorithm specific context data
322      */
323     EVP_PKEY *my_key = EVP_PKEY_CTX_get0_pkey(ctx);
324     EVP_PKEY *peer_key = EVP_PKEY_CTX_get0_peerkey(ctx);
325     struct gost_pmeth_data *data = EVP_PKEY_CTX_get_data(ctx);
326     int dgst_nid = NID_undef;
327
328     if (!data || data->shared_ukm_size == 0) {
329         return pkey_gost_ec_2020_derive(ctx, key, keylen);
330     }
331
332     /* VKO */
333     if (data->vko_dgst_nid) {
334         if (!key) {
335             *keylen = data->vko_dgst_nid == NID_id_GostR3411_2012_256? 32 : 64;
336             return 1;
337         }
338         *keylen = VKO_compute_key(key,
339                                   EC_KEY_get0_public_key(EVP_PKEY_get0(peer_key)),
340                                   (EC_KEY *)EVP_PKEY_get0(my_key),
341                                   data->shared_ukm, data->shared_ukm_size,
342                                   data->vko_dgst_nid);
343         return (*keylen) ? 1 : 0;
344     }
345
346     /*
347      * shared_ukm_size = 8 stands for pre-2018 cipher suites
348      * It means 32 bytes of key length, 8 byte UKM, 32-bytes hash
349      *
350      * shared_ukm_size = 32 stands for post-2018 cipher suites
351      * It means 64 bytes of shared_key, 16 bytes of UKM and either
352      * 64 bytes of hash or 64 bytes of TLSTREE output
353      * */
354
355     switch (data->shared_ukm_size) {
356     case 8:
357         {
358             if (key == NULL) {
359                 *keylen = 32;
360                 return 1;
361             }
362             EVP_PKEY_get_default_digest_nid(my_key, &dgst_nid);
363             if (dgst_nid == NID_id_GostR3411_2012_512)
364                 dgst_nid = NID_id_GostR3411_2012_256;
365
366             *keylen =
367                 VKO_compute_key(key,
368                                 EC_KEY_get0_public_key(EVP_PKEY_get0(peer_key)),
369                                 (EC_KEY *)EVP_PKEY_get0(my_key),
370                                 data->shared_ukm, 8, dgst_nid);
371             return (*keylen) ? 1 : 0;
372         }
373         break;
374     case 32:
375         {
376             if (key == NULL) {
377                 *keylen = 64;
378                 return 1;
379             }
380
381             *keylen = gost_keg(data->shared_ukm, EVP_PKEY_id(my_key),
382                                EC_KEY_get0_public_key(EVP_PKEY_get0(peer_key)),
383                                (EC_KEY *)EVP_PKEY_get0(my_key), key);
384             return (*keylen) ? 1 : 0;
385         }
386
387         break;
388     default:
389         return 0;
390     }
391 }
392
393 /*
394  * Generates ephemeral key based on pubk algorithm computes shared key using
395  * VKO and returns filled up GOST_KEY_TRANSPORT structure
396  */
397
398 /*
399  * EVP_PKEY_METHOD callback encrypt
400  * Implementation of GOST2001/12 key transport, cryptopro variation
401  */
402
403 static int pkey_GOST_ECcp_encrypt(EVP_PKEY_CTX *pctx, unsigned char *out,
404                            size_t *out_len, const unsigned char *key,
405                            size_t key_len)
406 {
407     GOST_KEY_TRANSPORT *gkt = NULL;
408     EVP_PKEY *pubk = EVP_PKEY_CTX_get0_pkey(pctx);
409     struct gost_pmeth_data *data = EVP_PKEY_CTX_get_data(pctx);
410     int pkey_nid = EVP_PKEY_base_id(pubk);
411     ASN1_OBJECT *crypt_params_obj = (pkey_nid == NID_id_GostR3410_2001 || pkey_nid == NID_id_GostR3410_2001DH) ?
412         OBJ_nid2obj(NID_id_Gost28147_89_CryptoPro_A_ParamSet) :
413         OBJ_nid2obj(NID_id_tc26_gost_28147_param_Z);
414     const struct gost_cipher_info *param =
415         get_encryption_params(crypt_params_obj);
416     unsigned char ukm[8], shared_key[32], crypted_key[44];
417     int ret = 0;
418     int key_is_ephemeral = 1;
419     gost_ctx cctx;
420     EVP_PKEY *sec_key = EVP_PKEY_CTX_get0_peerkey(pctx);
421     if (data->shared_ukm_size) {
422         memcpy(ukm, data->shared_ukm, 8);
423     } else {
424         if (RAND_bytes(ukm, 8) <= 0) {
425             GOSTerr(GOST_F_PKEY_GOST_ECCP_ENCRYPT, GOST_R_RNG_ERROR);
426             return 0;
427         }
428     }
429     if (!param)
430         goto err;
431     /* Check for private key in the peer_key of context */
432     if (sec_key) {
433         key_is_ephemeral = 0;
434         if (!gost_get0_priv_key(sec_key)) {
435             GOSTerr(GOST_F_PKEY_GOST_ECCP_ENCRYPT,
436                     GOST_R_NO_PRIVATE_PART_OF_NON_EPHEMERAL_KEYPAIR);
437             goto err;
438         }
439     } else {
440         key_is_ephemeral = 1;
441         if (out) {
442             sec_key = EVP_PKEY_new();
443             if (!EVP_PKEY_assign(sec_key, EVP_PKEY_base_id(pubk), EC_KEY_new())
444                 || !EVP_PKEY_copy_parameters(sec_key, pubk)
445                 || !gost_ec_keygen(EVP_PKEY_get0(sec_key))) {
446                 GOSTerr(GOST_F_PKEY_GOST_ECCP_ENCRYPT,
447                         GOST_R_ERROR_COMPUTING_SHARED_KEY);
448                 goto err;
449             }
450         }
451     }
452     if (out) {
453         int dgst_nid = NID_undef;
454         EVP_PKEY_get_default_digest_nid(pubk, &dgst_nid);
455         if (dgst_nid == NID_id_GostR3411_2012_512)
456             dgst_nid = NID_id_GostR3411_2012_256;
457
458         if (!VKO_compute_key(shared_key,
459                              EC_KEY_get0_public_key(EVP_PKEY_get0(pubk)),
460                              EVP_PKEY_get0(sec_key), ukm, 8, dgst_nid)) {
461             GOSTerr(GOST_F_PKEY_GOST_ECCP_ENCRYPT,
462                     GOST_R_ERROR_COMPUTING_SHARED_KEY);
463             goto err;
464         }
465         gost_init(&cctx, param->sblock);
466         keyWrapCryptoPro(&cctx, shared_key, ukm, key, crypted_key);
467     }
468     gkt = GOST_KEY_TRANSPORT_new();
469     if (!gkt) {
470         goto err;
471     }
472     if (!ASN1_OCTET_STRING_set(gkt->key_agreement_info->eph_iv, ukm, 8)) {
473         goto err;
474     }
475     if (!ASN1_OCTET_STRING_set(gkt->key_info->imit, crypted_key + 40, 4)) {
476         goto err;
477     }
478     if (!ASN1_OCTET_STRING_set
479         (gkt->key_info->encrypted_key, crypted_key + 8, 32)) {
480         goto err;
481     }
482     if (key_is_ephemeral) {
483         if (!X509_PUBKEY_set
484             (&gkt->key_agreement_info->ephem_key, out ? sec_key : pubk)) {
485             GOSTerr(GOST_F_PKEY_GOST_ECCP_ENCRYPT,
486                     GOST_R_CANNOT_PACK_EPHEMERAL_KEY);
487             goto err;
488         }
489     }
490     ASN1_OBJECT_free(gkt->key_agreement_info->cipher);
491     gkt->key_agreement_info->cipher = OBJ_nid2obj(param->nid);
492     if (key_is_ephemeral)
493         EVP_PKEY_free(sec_key);
494     if (!key_is_ephemeral) {
495         /* Set control "public key from client certificate used" */
496         if (EVP_PKEY_CTX_ctrl(pctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 3, NULL)
497             <= 0) {
498             GOSTerr(GOST_F_PKEY_GOST_ECCP_ENCRYPT, GOST_R_CTRL_CALL_FAILED);
499             goto err;
500         }
501     }
502     if ((*out_len = i2d_GOST_KEY_TRANSPORT(gkt, out ? &out : NULL)) > 0)
503         ret = 1;
504     OPENSSL_cleanse(shared_key, sizeof(shared_key));
505     GOST_KEY_TRANSPORT_free(gkt);
506     return ret;
507  err:
508     OPENSSL_cleanse(shared_key, sizeof(shared_key));
509     if (key_is_ephemeral)
510         EVP_PKEY_free(sec_key);
511     GOST_KEY_TRANSPORT_free(gkt);
512     return -1;
513 }
514
515 /*
516  * EVP_PKEY_METHOD callback decrypt
517  * Implementation of GOST2018 key transport
518  */
519 static int pkey_gost2018_encrypt(EVP_PKEY_CTX *pctx, unsigned char *out,
520                           size_t *out_len, const unsigned char *key,
521                           size_t key_len)
522 {
523     PSKeyTransport_gost *pst = NULL;
524     EVP_PKEY *pubk = EVP_PKEY_CTX_get0_pkey(pctx);
525     struct gost_pmeth_data *data = EVP_PKEY_CTX_get_data(pctx);
526     int pkey_nid = EVP_PKEY_base_id(pubk);
527     unsigned char expkeys[64];
528     EVP_PKEY *sec_key = NULL;
529     int ret = 0;
530     int mac_nid = NID_undef;
531     size_t mac_len = 0;
532     int exp_len = 0, iv_len = 0;
533     unsigned char *exp_buf = NULL;
534     int key_is_ephemeral = 0;
535     int res_len = 0;
536
537     switch (data->cipher_nid) {
538     case NID_magma_ctr:
539         mac_nid = NID_magma_mac;
540         mac_len = 8;
541         iv_len = 4;
542         break;
543     case NID_grasshopper_ctr:
544         mac_nid = NID_grasshopper_mac;
545         mac_len = 16;
546         iv_len = 8;
547         break;
548     default:
549         GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, GOST_R_INVALID_CIPHER);
550         return -1;
551         break;
552     }
553     exp_len = key_len + mac_len;
554     exp_buf = OPENSSL_malloc(exp_len);
555     if (!exp_buf) {
556         GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_MALLOC_FAILURE);
557         return -1;
558     }
559
560     sec_key = EVP_PKEY_CTX_get0_peerkey(pctx);
561     if (!sec_key)
562     {
563       sec_key = EVP_PKEY_new();
564       if (sec_key == NULL) {
565         GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_MALLOC_FAILURE );
566         goto err;
567       }
568
569       if (!EVP_PKEY_assign(sec_key, EVP_PKEY_base_id(pubk), EC_KEY_new())
570           || !EVP_PKEY_copy_parameters(sec_key, pubk)
571           || !gost_ec_keygen(EVP_PKEY_get0(sec_key))) {
572         GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT,
573             GOST_R_ERROR_COMPUTING_SHARED_KEY);
574         goto err;
575       }
576       key_is_ephemeral = 1;
577     }
578
579     if (data->shared_ukm_size == 0) {
580         if (RAND_bytes(data->shared_ukm, 32) <= 0) {
581             GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_INTERNAL_ERROR);
582             goto err;
583         }
584         data->shared_ukm_size = 32;
585     }
586
587     if (gost_keg(data->shared_ukm, pkey_nid,
588                  EC_KEY_get0_public_key(EVP_PKEY_get0(pubk)),
589                  EVP_PKEY_get0(sec_key), expkeys) <= 0) {
590         GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT,
591                 GOST_R_ERROR_COMPUTING_EXPORT_KEYS);
592         goto err;
593     }
594
595     if (gost_kexp15(key, key_len, data->cipher_nid, expkeys + 32,
596                     mac_nid, expkeys + 0, data->shared_ukm + 24, iv_len,
597                     exp_buf, &exp_len) <= 0) {
598         GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, GOST_R_CANNOT_PACK_EPHEMERAL_KEY);
599         goto err;
600     }
601
602     pst = PSKeyTransport_gost_new();
603     if (!pst) {
604         GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_MALLOC_FAILURE);
605         goto err;
606     }
607
608     pst->ukm = ASN1_OCTET_STRING_new();
609     if (pst->ukm == NULL) {
610         GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_MALLOC_FAILURE);
611         goto err;
612     }
613
614     if (!ASN1_OCTET_STRING_set(pst->ukm, data->shared_ukm, data->shared_ukm_size)) {
615         GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_MALLOC_FAILURE);
616         goto err;
617     }
618
619     if (!ASN1_OCTET_STRING_set(pst->psexp, exp_buf, exp_len)) {
620         GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_MALLOC_FAILURE);
621         goto err;
622     }
623
624     if (!X509_PUBKEY_set(&pst->ephem_key, out ? sec_key : pubk)) {
625         GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, GOST_R_CANNOT_PACK_EPHEMERAL_KEY);
626         goto err;
627     }
628
629     res_len = i2d_PSKeyTransport_gost(pst, NULL);
630     if (res_len <= 0) {
631         GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_ASN1_LIB);
632         goto err;
633     }
634
635     if (out == NULL) {
636         *out_len = res_len;
637         ret = 1;
638     } else {
639         if ((size_t)res_len > *out_len) {
640             GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, GOST_R_INVALID_BUFFER_SIZE);
641             goto err;
642         }
643         if ((*out_len = i2d_PSKeyTransport_gost(pst, &out)) > 0)
644             ret = 1;
645         else
646             GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_ASN1_LIB);
647     }
648
649  err:
650     OPENSSL_cleanse(expkeys, sizeof(expkeys));
651     if (key_is_ephemeral)
652         EVP_PKEY_free(sec_key);
653
654     PSKeyTransport_gost_free(pst);
655     OPENSSL_free(exp_buf);
656     return ret;
657 }
658
659 int pkey_gost_encrypt(EVP_PKEY_CTX *pctx, unsigned char *out,
660                       size_t *out_len, const unsigned char *key, size_t key_len)
661 {
662   struct gost_pmeth_data *gctx = EVP_PKEY_CTX_get_data(pctx);
663   switch (gctx->cipher_nid)
664   {
665     case NID_id_Gost28147_89:
666     case NID_undef: /* FIXME */
667       return pkey_GOST_ECcp_encrypt(pctx, out, out_len, key, key_len);
668       break;
669     case NID_kuznyechik_ctr:
670     case NID_magma_ctr:
671       return pkey_gost2018_encrypt(pctx, out, out_len, key, key_len);
672       break;
673     default:
674       GOSTerr(GOST_F_PKEY_GOST_ENCRYPT, ERR_R_INTERNAL_ERROR);
675       return -1;
676   }
677 }
678
679 /*
680  * EVP_PKEY_METHOD callback decrypt
681  * Implementation of GOST2001/12 key transport, cryptopro variation
682  */
683 static int pkey_GOST_ECcp_decrypt(EVP_PKEY_CTX *pctx, unsigned char *key,
684                            size_t *key_len, const unsigned char *in,
685                            size_t in_len)
686 {
687     const unsigned char *p = in;
688     EVP_PKEY *priv = EVP_PKEY_CTX_get0_pkey(pctx);
689     GOST_KEY_TRANSPORT *gkt = NULL;
690     int ret = 0;
691     unsigned char wrappedKey[44];
692     unsigned char sharedKey[32];
693     gost_ctx ctx;
694     const struct gost_cipher_info *param = NULL;
695     EVP_PKEY *eph_key = NULL, *peerkey = NULL;
696     int dgst_nid = NID_undef;
697
698     if (!key) {
699         *key_len = 32;
700         return 1;
701     }
702     gkt = d2i_GOST_KEY_TRANSPORT(NULL, (const unsigned char **)&p, in_len);
703     if (!gkt) {
704         GOSTerr(GOST_F_PKEY_GOST_ECCP_DECRYPT,
705                 GOST_R_ERROR_PARSING_KEY_TRANSPORT_INFO);
706         return -1;
707     }
708
709     /* If key transport structure contains public key, use it */
710     eph_key = X509_PUBKEY_get(gkt->key_agreement_info->ephem_key);
711     if (eph_key) {
712         if (EVP_PKEY_derive_set_peer(pctx, eph_key) <= 0) {
713             GOSTerr(GOST_F_PKEY_GOST_ECCP_DECRYPT,
714                     GOST_R_INCOMPATIBLE_PEER_KEY);
715             goto err;
716         }
717     } else {
718         /* Set control "public key from client certificate used" */
719         if (EVP_PKEY_CTX_ctrl(pctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 3, NULL)
720             <= 0) {
721             GOSTerr(GOST_F_PKEY_GOST_ECCP_DECRYPT, GOST_R_CTRL_CALL_FAILED);
722             goto err;
723         }
724     }
725     peerkey = EVP_PKEY_CTX_get0_peerkey(pctx);
726     if (!peerkey) {
727         GOSTerr(GOST_F_PKEY_GOST_ECCP_DECRYPT, GOST_R_NO_PEER_KEY);
728         goto err;
729     }
730
731     param = get_encryption_params(gkt->key_agreement_info->cipher);
732     if (!param) {
733         goto err;
734     }
735
736     gost_init(&ctx, param->sblock);
737     OPENSSL_assert(gkt->key_agreement_info->eph_iv->length == 8);
738     memcpy(wrappedKey, gkt->key_agreement_info->eph_iv->data, 8);
739     OPENSSL_assert(gkt->key_info->encrypted_key->length == 32);
740     memcpy(wrappedKey + 8, gkt->key_info->encrypted_key->data, 32);
741     OPENSSL_assert(gkt->key_info->imit->length == 4);
742     memcpy(wrappedKey + 40, gkt->key_info->imit->data, 4);
743
744     EVP_PKEY_get_default_digest_nid(priv, &dgst_nid);
745     if (dgst_nid == NID_id_GostR3411_2012_512)
746         dgst_nid = NID_id_GostR3411_2012_256;
747
748     if (!VKO_compute_key(sharedKey,
749                          EC_KEY_get0_public_key(EVP_PKEY_get0(peerkey)),
750                          EVP_PKEY_get0(priv), wrappedKey, 8, dgst_nid)) {
751         GOSTerr(GOST_F_PKEY_GOST_ECCP_DECRYPT,
752                 GOST_R_ERROR_COMPUTING_SHARED_KEY);
753         goto err;
754     }
755     if (!keyUnwrapCryptoPro(&ctx, sharedKey, wrappedKey, key)) {
756         GOSTerr(GOST_F_PKEY_GOST_ECCP_DECRYPT,
757                 GOST_R_ERROR_COMPUTING_SHARED_KEY);
758         goto err;
759     }
760
761     ret = 1;
762  err:
763     OPENSSL_cleanse(sharedKey, sizeof(sharedKey));
764     EVP_PKEY_free(eph_key);
765     GOST_KEY_TRANSPORT_free(gkt);
766     return ret;
767 }
768
769 /*
770  * EVP_PKEY_METHOD callback decrypt
771  * Implementation of GOST2018 key transport
772  */
773 static int pkey_gost2018_decrypt(EVP_PKEY_CTX *pctx, unsigned char *key,
774                           size_t *key_len, const unsigned char *in,
775                           size_t in_len)
776 {
777     const unsigned char *p = in;
778     struct gost_pmeth_data *data = EVP_PKEY_CTX_get_data(pctx);
779     EVP_PKEY *priv = EVP_PKEY_CTX_get0_pkey(pctx);
780     PSKeyTransport_gost *pst = NULL;
781     int ret = 0;
782     unsigned char expkeys[64];
783     EVP_PKEY *eph_key = NULL;
784     int pkey_nid = EVP_PKEY_base_id(priv);
785     int mac_nid = NID_undef;
786     int iv_len = 0;
787
788     switch (data->cipher_nid) {
789     case NID_magma_ctr:
790         mac_nid = NID_magma_mac;
791         iv_len = 4;
792         break;
793     case NID_grasshopper_ctr:
794         mac_nid = NID_grasshopper_mac;
795         iv_len = 8;
796         break;
797     default:
798         GOSTerr(GOST_F_PKEY_GOST2018_DECRYPT, GOST_R_INVALID_CIPHER);
799         return -1;
800         break;
801     }
802     if (!key) {
803         *key_len = 32;
804         return 1;
805     }
806
807     pst = d2i_PSKeyTransport_gost(NULL, (const unsigned char **)&p, in_len);
808     if (!pst) {
809         GOSTerr(GOST_F_PKEY_GOST2018_DECRYPT,
810                 GOST_R_ERROR_PARSING_KEY_TRANSPORT_INFO);
811         return -1;
812     }
813
814     eph_key = X509_PUBKEY_get(pst->ephem_key);
815 /*
816  * TODO beldmit
817    1.  Checks the next three conditions fulfilling and terminates the
818    connection with fatal error if not.
819
820    o  Q_eph is on the same curve as server public key;
821
822    o  Q_eph is not equal to zero point;
823
824    o  q * Q_eph is not equal to zero point.
825 */
826     if (eph_key == NULL || priv == NULL || data == NULL) {
827        GOSTerr(GOST_F_PKEY_GOST2018_DECRYPT,
828                GOST_R_ERROR_COMPUTING_EXPORT_KEYS);
829        ret = 0;
830        goto err;
831     }
832   
833     if (data->shared_ukm_size == 0 && pst->ukm != NULL) {
834         if (EVP_PKEY_CTX_ctrl(pctx, -1, -1, EVP_PKEY_CTRL_SET_IV,
835         ASN1_STRING_length(pst->ukm), (void *)ASN1_STRING_get0_data(pst->ukm)) < 0) {
836             GOSTerr(GOST_F_PKEY_GOST2018_DECRYPT, GOST_R_UKM_NOT_SET);
837             goto err;
838         }
839     }
840
841     if (gost_keg(data->shared_ukm, pkey_nid,
842                  EC_KEY_get0_public_key(EVP_PKEY_get0(eph_key)),
843                  EVP_PKEY_get0(priv), expkeys) <= 0) {
844         GOSTerr(GOST_F_PKEY_GOST2018_DECRYPT,
845                 GOST_R_ERROR_COMPUTING_EXPORT_KEYS);
846         goto err;
847     }
848
849     if (gost_kimp15(ASN1_STRING_get0_data(pst->psexp),
850                     ASN1_STRING_length(pst->psexp), data->cipher_nid,
851                     expkeys + 32, mac_nid, expkeys + 0, data->shared_ukm + 24,
852                     iv_len, key) <= 0) {
853         GOSTerr(GOST_F_PKEY_GOST2018_DECRYPT, GOST_R_CANNOT_UNPACK_EPHEMERAL_KEY);
854         goto err;
855     }
856
857     ret = 1;
858  err:
859     OPENSSL_cleanse(expkeys, sizeof(expkeys));
860     EVP_PKEY_free(eph_key);
861     PSKeyTransport_gost_free(pst);
862     return ret;
863 }
864
865 int pkey_gost_decrypt(EVP_PKEY_CTX *pctx, unsigned char *key,
866                       size_t *key_len, const unsigned char *in, size_t in_len)
867 {
868     struct gost_pmeth_data *gctx = EVP_PKEY_CTX_get_data(pctx);
869     switch (gctx->cipher_nid)
870     {
871         case NID_id_Gost28147_89:
872         case NID_undef: /* FIXME */
873             return pkey_GOST_ECcp_decrypt(pctx, key, key_len, in, in_len);
874         case NID_kuznyechik_ctr:
875         case NID_magma_ctr:
876             return pkey_gost2018_decrypt(pctx, key, key_len, in, in_len);
877         default:
878       GOSTerr(GOST_F_PKEY_GOST_DECRYPT, ERR_R_INTERNAL_ERROR);
879       return -1;
880     }
881 }
882 /* vim: set expandtab cinoptions=\:0,l1,t0,g0,(0 sw=4 : */