]> www.wagner.pp.ru Git - openssl-gost/engine.git/blob - gost_ec_keyx.c
Delete .travis.yml
[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     int res_len = 0;
422
423     if (data->shared_ukm_size) {
424         memcpy(ukm, data->shared_ukm, 8);
425     } else {
426         if (RAND_bytes(ukm, 8) <= 0) {
427             GOSTerr(GOST_F_PKEY_GOST_ECCP_ENCRYPT, GOST_R_RNG_ERROR);
428             return 0;
429         }
430     }
431     if (!param)
432         goto err;
433     /* Check for private key in the peer_key of context */
434     if (sec_key) {
435         key_is_ephemeral = 0;
436         if (!gost_get0_priv_key(sec_key)) {
437             GOSTerr(GOST_F_PKEY_GOST_ECCP_ENCRYPT,
438                     GOST_R_NO_PRIVATE_PART_OF_NON_EPHEMERAL_KEYPAIR);
439             goto err;
440         }
441     } else {
442         key_is_ephemeral = 1;
443         if (out) {
444             sec_key = EVP_PKEY_new();
445             if (!EVP_PKEY_assign(sec_key, EVP_PKEY_base_id(pubk), EC_KEY_new())
446                 || !EVP_PKEY_copy_parameters(sec_key, pubk)
447                 || !gost_ec_keygen(EVP_PKEY_get0(sec_key))) {
448                 GOSTerr(GOST_F_PKEY_GOST_ECCP_ENCRYPT,
449                         GOST_R_ERROR_COMPUTING_SHARED_KEY);
450                 goto err;
451             }
452         }
453     }
454     if (out) {
455         int dgst_nid = NID_undef;
456         EVP_PKEY_get_default_digest_nid(pubk, &dgst_nid);
457         if (dgst_nid == NID_id_GostR3411_2012_512)
458             dgst_nid = NID_id_GostR3411_2012_256;
459
460         if (!VKO_compute_key(shared_key,
461                              EC_KEY_get0_public_key(EVP_PKEY_get0(pubk)),
462                              EVP_PKEY_get0(sec_key), ukm, 8, dgst_nid)) {
463             GOSTerr(GOST_F_PKEY_GOST_ECCP_ENCRYPT,
464                     GOST_R_ERROR_COMPUTING_SHARED_KEY);
465             goto err;
466         }
467         gost_init(&cctx, param->sblock);
468         keyWrapCryptoPro(&cctx, shared_key, ukm, key, crypted_key);
469     }
470     gkt = GOST_KEY_TRANSPORT_new();
471     if (!gkt) {
472         goto err;
473     }
474     if (!ASN1_OCTET_STRING_set(gkt->key_agreement_info->eph_iv, ukm, 8)) {
475         goto err;
476     }
477     if (!ASN1_OCTET_STRING_set(gkt->key_info->imit, crypted_key + 40, 4)) {
478         goto err;
479     }
480     if (!ASN1_OCTET_STRING_set
481         (gkt->key_info->encrypted_key, crypted_key + 8, 32)) {
482         goto err;
483     }
484     if (key_is_ephemeral) {
485         if (!X509_PUBKEY_set
486             (&gkt->key_agreement_info->ephem_key, out ? sec_key : pubk)) {
487             GOSTerr(GOST_F_PKEY_GOST_ECCP_ENCRYPT,
488                     GOST_R_CANNOT_PACK_EPHEMERAL_KEY);
489             goto err;
490         }
491     }
492     ASN1_OBJECT_free(gkt->key_agreement_info->cipher);
493     gkt->key_agreement_info->cipher = OBJ_nid2obj(param->nid);
494     if (key_is_ephemeral)
495         EVP_PKEY_free(sec_key);
496     if (!key_is_ephemeral) {
497         /* Set control "public key from client certificate used" */
498         if (EVP_PKEY_CTX_ctrl(pctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 3, NULL)
499             <= 0) {
500             GOSTerr(GOST_F_PKEY_GOST_ECCP_ENCRYPT, GOST_R_CTRL_CALL_FAILED);
501             goto err;
502         }
503     }
504     res_len = i2d_GOST_KEY_TRANSPORT(gkt, NULL);
505     if (res_len <= 0) {
506         GOSTerr(GOST_F_PKEY_GOST_ECCP_ENCRYPT, ERR_R_ASN1_LIB);
507         goto err;
508     }
509
510     if (out == NULL) {
511         *out_len = res_len;
512         ret = 1;
513     } else {
514         if ((size_t)res_len > *out_len) {
515             GOSTerr(GOST_F_PKEY_GOST_ECCP_ENCRYPT, GOST_R_INVALID_BUFFER_SIZE);
516             goto err;
517         }
518         if ((*out_len = i2d_GOST_KEY_TRANSPORT(gkt, &out)) > 0)
519             ret = 1;
520         else
521             GOSTerr(GOST_F_PKEY_GOST_ECCP_ENCRYPT, ERR_R_ASN1_LIB);
522     }
523
524     OPENSSL_cleanse(shared_key, sizeof(shared_key));
525     GOST_KEY_TRANSPORT_free(gkt);
526     return ret;
527  err:
528     OPENSSL_cleanse(shared_key, sizeof(shared_key));
529     if (key_is_ephemeral)
530         EVP_PKEY_free(sec_key);
531     GOST_KEY_TRANSPORT_free(gkt);
532     return -1;
533 }
534
535 /*
536  * EVP_PKEY_METHOD callback decrypt
537  * Implementation of GOST2018 key transport
538  */
539 static int pkey_gost2018_encrypt(EVP_PKEY_CTX *pctx, unsigned char *out,
540                           size_t *out_len, const unsigned char *key,
541                           size_t key_len)
542 {
543     PSKeyTransport_gost *pst = NULL;
544     EVP_PKEY *pubk = EVP_PKEY_CTX_get0_pkey(pctx);
545     struct gost_pmeth_data *data = EVP_PKEY_CTX_get_data(pctx);
546     int pkey_nid = EVP_PKEY_base_id(pubk);
547     unsigned char expkeys[64];
548     EVP_PKEY *sec_key = NULL;
549     int ret = 0;
550     int mac_nid = NID_undef;
551     size_t mac_len = 0;
552     int exp_len = 0, iv_len = 0;
553     unsigned char *exp_buf = NULL;
554     int key_is_ephemeral = 0;
555     int res_len = 0;
556
557     switch (data->cipher_nid) {
558     case NID_magma_ctr:
559         mac_nid = NID_magma_mac;
560         mac_len = 8;
561         iv_len = 4;
562         break;
563     case NID_grasshopper_ctr:
564         mac_nid = NID_grasshopper_mac;
565         mac_len = 16;
566         iv_len = 8;
567         break;
568     default:
569         GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, GOST_R_INVALID_CIPHER);
570         return -1;
571         break;
572     }
573     exp_len = key_len + mac_len;
574     exp_buf = OPENSSL_malloc(exp_len);
575     if (!exp_buf) {
576         GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_MALLOC_FAILURE);
577         return -1;
578     }
579
580     sec_key = EVP_PKEY_CTX_get0_peerkey(pctx);
581     if (!sec_key)
582     {
583       sec_key = EVP_PKEY_new();
584       if (sec_key == NULL) {
585         GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_MALLOC_FAILURE );
586         goto err;
587       }
588
589       if (!EVP_PKEY_assign(sec_key, EVP_PKEY_base_id(pubk), EC_KEY_new())
590           || !EVP_PKEY_copy_parameters(sec_key, pubk)
591           || !gost_ec_keygen(EVP_PKEY_get0(sec_key))) {
592         GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT,
593             GOST_R_ERROR_COMPUTING_SHARED_KEY);
594         goto err;
595       }
596       key_is_ephemeral = 1;
597     }
598
599     if (data->shared_ukm_size == 0) {
600         if (RAND_bytes(data->shared_ukm, 32) <= 0) {
601             GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_INTERNAL_ERROR);
602             goto err;
603         }
604         data->shared_ukm_size = 32;
605     }
606
607     if (gost_keg(data->shared_ukm, pkey_nid,
608                  EC_KEY_get0_public_key(EVP_PKEY_get0(pubk)),
609                  EVP_PKEY_get0(sec_key), expkeys) <= 0) {
610         GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT,
611                 GOST_R_ERROR_COMPUTING_EXPORT_KEYS);
612         goto err;
613     }
614
615     if (gost_kexp15(key, key_len, data->cipher_nid, expkeys + 32,
616                     mac_nid, expkeys + 0, data->shared_ukm + 24, iv_len,
617                     exp_buf, &exp_len) <= 0) {
618         GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, GOST_R_CANNOT_PACK_EPHEMERAL_KEY);
619         goto err;
620     }
621
622     pst = PSKeyTransport_gost_new();
623     if (!pst) {
624         GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_MALLOC_FAILURE);
625         goto err;
626     }
627
628     pst->ukm = ASN1_OCTET_STRING_new();
629     if (pst->ukm == NULL) {
630         GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_MALLOC_FAILURE);
631         goto err;
632     }
633
634     if (!ASN1_OCTET_STRING_set(pst->ukm, data->shared_ukm, data->shared_ukm_size)) {
635         GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_MALLOC_FAILURE);
636         goto err;
637     }
638
639     if (!ASN1_OCTET_STRING_set(pst->psexp, exp_buf, exp_len)) {
640         GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_MALLOC_FAILURE);
641         goto err;
642     }
643
644     if (!X509_PUBKEY_set(&pst->ephem_key, out ? sec_key : pubk)) {
645         GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, GOST_R_CANNOT_PACK_EPHEMERAL_KEY);
646         goto err;
647     }
648
649     res_len = i2d_PSKeyTransport_gost(pst, NULL);
650     if (res_len <= 0) {
651         GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_ASN1_LIB);
652         goto err;
653     }
654
655     if (out == NULL) {
656         *out_len = res_len;
657         ret = 1;
658     } else {
659         if ((size_t)res_len > *out_len) {
660             GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, GOST_R_INVALID_BUFFER_SIZE);
661             goto err;
662         }
663         if ((*out_len = i2d_PSKeyTransport_gost(pst, &out)) > 0)
664             ret = 1;
665         else
666             GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_ASN1_LIB);
667     }
668
669  err:
670     OPENSSL_cleanse(expkeys, sizeof(expkeys));
671     if (key_is_ephemeral)
672         EVP_PKEY_free(sec_key);
673
674     PSKeyTransport_gost_free(pst);
675     OPENSSL_free(exp_buf);
676     return ret;
677 }
678
679 int pkey_gost_encrypt(EVP_PKEY_CTX *pctx, unsigned char *out,
680                       size_t *out_len, const unsigned char *key, size_t key_len)
681 {
682   struct gost_pmeth_data *gctx = EVP_PKEY_CTX_get_data(pctx);
683   switch (gctx->cipher_nid)
684   {
685     case NID_id_Gost28147_89:
686     case NID_undef: /* FIXME */
687       return pkey_GOST_ECcp_encrypt(pctx, out, out_len, key, key_len);
688       break;
689     case NID_kuznyechik_ctr:
690     case NID_magma_ctr:
691       return pkey_gost2018_encrypt(pctx, out, out_len, key, key_len);
692       break;
693     default:
694       GOSTerr(GOST_F_PKEY_GOST_ENCRYPT, ERR_R_INTERNAL_ERROR);
695       return -1;
696   }
697 }
698
699 /*
700  * EVP_PKEY_METHOD callback decrypt
701  * Implementation of GOST2001/12 key transport, cryptopro variation
702  */
703 static int pkey_GOST_ECcp_decrypt(EVP_PKEY_CTX *pctx, unsigned char *key,
704                            size_t *key_len, const unsigned char *in,
705                            size_t in_len)
706 {
707     const unsigned char *p = in;
708     EVP_PKEY *priv = EVP_PKEY_CTX_get0_pkey(pctx);
709     GOST_KEY_TRANSPORT *gkt = NULL;
710     int ret = 0;
711     unsigned char wrappedKey[44];
712     unsigned char sharedKey[32];
713     gost_ctx ctx;
714     const struct gost_cipher_info *param = NULL;
715     EVP_PKEY *eph_key = NULL, *peerkey = NULL;
716     int dgst_nid = NID_undef;
717
718     gkt = d2i_GOST_KEY_TRANSPORT(NULL, (const unsigned char **)&p, in_len);
719     if (!gkt) {
720         GOSTerr(GOST_F_PKEY_GOST_ECCP_DECRYPT,
721                 GOST_R_ERROR_PARSING_KEY_TRANSPORT_INFO);
722         return -1;
723     }
724
725     /* If key transport structure contains public key, use it */
726     eph_key = X509_PUBKEY_get(gkt->key_agreement_info->ephem_key);
727     if (eph_key) {
728         if (EVP_PKEY_derive_set_peer(pctx, eph_key) <= 0) {
729             GOSTerr(GOST_F_PKEY_GOST_ECCP_DECRYPT,
730                     GOST_R_INCOMPATIBLE_PEER_KEY);
731             goto err;
732         }
733     } else {
734         /* Set control "public key from client certificate used" */
735         if (EVP_PKEY_CTX_ctrl(pctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 3, NULL)
736             <= 0) {
737             GOSTerr(GOST_F_PKEY_GOST_ECCP_DECRYPT, GOST_R_CTRL_CALL_FAILED);
738             goto err;
739         }
740     }
741     peerkey = EVP_PKEY_CTX_get0_peerkey(pctx);
742     if (!peerkey) {
743         GOSTerr(GOST_F_PKEY_GOST_ECCP_DECRYPT, GOST_R_NO_PEER_KEY);
744         goto err;
745     }
746
747     param = get_encryption_params(gkt->key_agreement_info->cipher);
748     if (!param) {
749         goto err;
750     }
751
752     gost_init(&ctx, param->sblock);
753     OPENSSL_assert(gkt->key_agreement_info->eph_iv->length == 8);
754     memcpy(wrappedKey, gkt->key_agreement_info->eph_iv->data, 8);
755     OPENSSL_assert(gkt->key_info->encrypted_key->length == 32);
756     memcpy(wrappedKey + 8, gkt->key_info->encrypted_key->data, 32);
757     OPENSSL_assert(gkt->key_info->imit->length == 4);
758     memcpy(wrappedKey + 40, gkt->key_info->imit->data, 4);
759
760     EVP_PKEY_get_default_digest_nid(priv, &dgst_nid);
761     if (dgst_nid == NID_id_GostR3411_2012_512)
762         dgst_nid = NID_id_GostR3411_2012_256;
763
764     if (!VKO_compute_key(sharedKey,
765                          EC_KEY_get0_public_key(EVP_PKEY_get0(peerkey)),
766                          EVP_PKEY_get0(priv), wrappedKey, 8, dgst_nid)) {
767         GOSTerr(GOST_F_PKEY_GOST_ECCP_DECRYPT,
768                 GOST_R_ERROR_COMPUTING_SHARED_KEY);
769         goto err;
770     }
771     if (!keyUnwrapCryptoPro(&ctx, sharedKey, wrappedKey, key)) {
772         GOSTerr(GOST_F_PKEY_GOST_ECCP_DECRYPT,
773                 GOST_R_ERROR_COMPUTING_SHARED_KEY);
774         goto err;
775     }
776
777     *key_len = 32;
778     ret = 1;
779  err:
780     OPENSSL_cleanse(sharedKey, sizeof(sharedKey));
781     EVP_PKEY_free(eph_key);
782     GOST_KEY_TRANSPORT_free(gkt);
783     return ret;
784 }
785
786 /*
787  * EVP_PKEY_METHOD callback decrypt
788  * Implementation of GOST2018 key transport
789  */
790 static int pkey_gost2018_decrypt(EVP_PKEY_CTX *pctx, unsigned char *key,
791                           size_t *key_len, const unsigned char *in,
792                           size_t in_len)
793 {
794     const unsigned char *p = in;
795     struct gost_pmeth_data *data = EVP_PKEY_CTX_get_data(pctx);
796     EVP_PKEY *priv = EVP_PKEY_CTX_get0_pkey(pctx);
797     PSKeyTransport_gost *pst = NULL;
798     int ret = 0;
799     unsigned char expkeys[64];
800     EVP_PKEY *eph_key = NULL;
801     int pkey_nid = EVP_PKEY_base_id(priv);
802     int mac_nid = NID_undef;
803     int iv_len = 0;
804
805     switch (data->cipher_nid) {
806     case NID_magma_ctr:
807         mac_nid = NID_magma_mac;
808         iv_len = 4;
809         break;
810     case NID_grasshopper_ctr:
811         mac_nid = NID_grasshopper_mac;
812         iv_len = 8;
813         break;
814     default:
815         GOSTerr(GOST_F_PKEY_GOST2018_DECRYPT, GOST_R_INVALID_CIPHER);
816         return -1;
817         break;
818     }
819
820     pst = d2i_PSKeyTransport_gost(NULL, (const unsigned char **)&p, in_len);
821     if (!pst) {
822         GOSTerr(GOST_F_PKEY_GOST2018_DECRYPT,
823                 GOST_R_ERROR_PARSING_KEY_TRANSPORT_INFO);
824         return -1;
825     }
826
827     eph_key = X509_PUBKEY_get(pst->ephem_key);
828 /*
829  * TODO beldmit
830    1.  Checks the next three conditions fulfilling and terminates the
831    connection with fatal error if not.
832
833    o  Q_eph is on the same curve as server public key;
834
835    o  Q_eph is not equal to zero point;
836
837    o  q * Q_eph is not equal to zero point.
838 */
839     if (eph_key == NULL || priv == NULL || data == NULL) {
840        GOSTerr(GOST_F_PKEY_GOST2018_DECRYPT,
841                GOST_R_ERROR_COMPUTING_EXPORT_KEYS);
842        ret = 0;
843        goto err;
844     }
845
846     if (data->shared_ukm_size == 0 && pst->ukm != NULL) {
847         if (EVP_PKEY_CTX_ctrl(pctx, -1, -1, EVP_PKEY_CTRL_SET_IV,
848         ASN1_STRING_length(pst->ukm), (void *)ASN1_STRING_get0_data(pst->ukm)) < 0) {
849             GOSTerr(GOST_F_PKEY_GOST2018_DECRYPT, GOST_R_UKM_NOT_SET);
850             goto err;
851         }
852     }
853
854     if (gost_keg(data->shared_ukm, pkey_nid,
855                  EC_KEY_get0_public_key(EVP_PKEY_get0(eph_key)),
856                  EVP_PKEY_get0(priv), expkeys) <= 0) {
857         GOSTerr(GOST_F_PKEY_GOST2018_DECRYPT,
858                 GOST_R_ERROR_COMPUTING_EXPORT_KEYS);
859         goto err;
860     }
861
862     if (gost_kimp15(ASN1_STRING_get0_data(pst->psexp),
863                     ASN1_STRING_length(pst->psexp), data->cipher_nid,
864                     expkeys + 32, mac_nid, expkeys + 0, data->shared_ukm + 24,
865                     iv_len, key) <= 0) {
866         GOSTerr(GOST_F_PKEY_GOST2018_DECRYPT, GOST_R_CANNOT_UNPACK_EPHEMERAL_KEY);
867         goto err;
868     }
869
870     *key_len = 32;
871     ret = 1;
872  err:
873     OPENSSL_cleanse(expkeys, sizeof(expkeys));
874     EVP_PKEY_free(eph_key);
875     PSKeyTransport_gost_free(pst);
876     return ret;
877 }
878
879 int pkey_gost_decrypt(EVP_PKEY_CTX *pctx, unsigned char *key,
880                       size_t *key_len, const unsigned char *in, size_t in_len)
881 {
882     struct gost_pmeth_data *gctx = EVP_PKEY_CTX_get_data(pctx);
883
884     if (key == NULL) {
885         *key_len = 32;
886         return 1;
887     }
888
889     if (key != NULL && *key_len < 32) {
890         GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, GOST_R_INVALID_BUFFER_SIZE);
891         return 0;
892     }
893
894     switch (gctx->cipher_nid)
895     {
896         case NID_id_Gost28147_89:
897         case NID_undef: /* FIXME */
898             return pkey_GOST_ECcp_decrypt(pctx, key, key_len, in, in_len);
899         case NID_kuznyechik_ctr:
900         case NID_magma_ctr:
901             return pkey_gost2018_decrypt(pctx, key, key_len, in, in_len);
902         default:
903       GOSTerr(GOST_F_PKEY_GOST_DECRYPT, ERR_R_INTERNAL_ERROR);
904       return -1;
905     }
906 }
907 /* vim: set expandtab cinoptions=\:0,l1,t0,g0,(0 sw=4 : */