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