]> www.wagner.pp.ru Git - openssl-gost/engine.git/blob - gost_crypt.c
Add TLS 1.3 new modes for TLSTREE algorithm
[openssl-gost/engine.git] / gost_crypt.c
1 /**********************************************************************
2  *             gost_crypt.c - Initialize all ciphers                  *
3  *                                                                    *
4  *             Copyright (c) 2005-2006 Cryptocom LTD                  *
5  *             Copyright (c) 2020 Chikunov Vitaly <vt@altlinux.org>   *
6  *         This file is distributed under the same license as OpenSSL *
7  *                                                                    *
8  *       OpenSSL interface to GOST 28147-89 cipher functions          *
9  *          Requires OpenSSL 0.9.9 for compilation                    *
10  **********************************************************************/
11 #include <string.h>
12 #include "gost89.h"
13 #include <openssl/err.h>
14 #include <openssl/rand.h>
15 #include "e_gost_err.h"
16 #include "gost_lcl.h"
17 #include "gost_gost2015.h"
18
19 #if !defined(CCGOST_DEBUG) && !defined(DEBUG)
20 # ifndef NDEBUG
21 #  define NDEBUG
22 # endif
23 #endif
24 #include <assert.h>
25
26 static int gost_cipher_init(EVP_CIPHER_CTX *ctx, const unsigned char *key,
27                             const unsigned char *iv, int enc);
28 static int gost_cipher_init_cbc(EVP_CIPHER_CTX *ctx, const unsigned char *key,
29                                 const unsigned char *iv, int enc);
30 static int gost_cipher_init_cpa(EVP_CIPHER_CTX *ctx, const unsigned char *key,
31                                 const unsigned char *iv, int enc);
32 static int gost_cipher_init_cp_12(EVP_CIPHER_CTX *ctx,
33                                   const unsigned char *key,
34                                   const unsigned char *iv, int enc);
35 /* Handles block of data in CFB mode */
36 static int gost_cipher_do_cfb(EVP_CIPHER_CTX *ctx, unsigned char *out,
37                               const unsigned char *in, size_t inl);
38 /* Handles block of data in CBC mode */
39 static int gost_cipher_do_cbc(EVP_CIPHER_CTX *ctx, unsigned char *out,
40                               const unsigned char *in, size_t inl);
41 /* Handles block of data in CNT mode */
42 static int gost_cipher_do_cnt(EVP_CIPHER_CTX *ctx, unsigned char *out,
43                               const unsigned char *in, size_t inl);
44 /* Cleanup function */
45 static int gost_cipher_cleanup(EVP_CIPHER_CTX *);
46 static int gost_magma_mgm_cleanup(EVP_CIPHER_CTX *c);
47 /* set/get cipher parameters */
48 static int gost89_set_asn1_parameters(EVP_CIPHER_CTX *ctx, ASN1_TYPE *params);
49 static int gost89_get_asn1_parameters(EVP_CIPHER_CTX *ctx, ASN1_TYPE *params);
50 /* Control function */
51 static int gost_cipher_ctl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr);
52
53 static int magma_cipher_init(EVP_CIPHER_CTX *ctx, const unsigned char *key,
54                              const unsigned char *iv, int enc);
55 static int magma_cipher_init_ctr_acpkm_omac(EVP_CIPHER_CTX *ctx, const unsigned char *key,
56                              const unsigned char *iv, int enc);
57 static int gost_magma_cipher_init_mgm(EVP_CIPHER_CTX *ctx, const unsigned char *key,
58                                  const unsigned char *iv, int enc);
59 /* Handles block of data in CBC mode */
60 static int magma_cipher_do_cbc(EVP_CIPHER_CTX *ctx, unsigned char *out,
61                                const unsigned char *in, size_t inl);
62 static int magma_cipher_do_ctr(EVP_CIPHER_CTX *ctx, unsigned char *out,
63                                const unsigned char *in, size_t inl);
64
65 static int magma_cipher_do_ctr_acpkm_omac(EVP_CIPHER_CTX *ctx, unsigned char *out,
66                                const unsigned char *in, size_t inl);
67 static int gost_magma_cipher_do_mgm(EVP_CIPHER_CTX *ctx, unsigned char *out,
68                                    const unsigned char *in, size_t len);
69 /* set/get cipher parameters */
70 static int magma_set_asn1_parameters(EVP_CIPHER_CTX *ctx, ASN1_TYPE *params);
71 static int magma_get_asn1_parameters(EVP_CIPHER_CTX *ctx, ASN1_TYPE *params);
72 /* Control function */
73 static int magma_cipher_ctl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr);
74 static int magma_cipher_ctl_acpkm_omac(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr);
75 static int gost_magma_mgm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr);
76
77 /*
78  * Single level template accessor.
79  * Note: that you cannot template 0 value.
80  */
81 #define TPL(st,field) ( \
82     ((st)->field) ?: TPL_VAL(st,field) \
83 )
84
85 #define TPL_VAL(st,field) ( \
86     ((st)->template ? (st)->template->field : 0) \
87 )
88
89 EVP_CIPHER *GOST_init_cipher(GOST_cipher *c)
90 {
91     if (c->cipher)
92         return c->cipher;
93
94     /* Some sanity checking. */
95     int flags = c->flags | TPL_VAL(c, flags);
96     int block_size = TPL(c, block_size);
97     switch (flags & EVP_CIPH_MODE) {
98     case EVP_CIPH_CBC_MODE:
99     case EVP_CIPH_ECB_MODE:
100     case EVP_CIPH_WRAP_MODE:
101         OPENSSL_assert(block_size != 1);
102         OPENSSL_assert(!(flags & EVP_CIPH_NO_PADDING));
103         break;
104     default:
105         OPENSSL_assert(block_size == 1);
106         OPENSSL_assert(flags & EVP_CIPH_NO_PADDING);
107     }
108
109     if (TPL(c, iv_len))
110         OPENSSL_assert(flags & EVP_CIPH_CUSTOM_IV);
111     else
112         OPENSSL_assert(!(flags & EVP_CIPH_CUSTOM_IV));
113
114     EVP_CIPHER *cipher;
115     if (!(cipher = EVP_CIPHER_meth_new(c->nid, block_size, TPL(c, key_len)))
116         || !EVP_CIPHER_meth_set_iv_length(cipher, TPL(c, iv_len))
117         || !EVP_CIPHER_meth_set_flags(cipher, flags)
118         || !EVP_CIPHER_meth_set_init(cipher, TPL(c, init))
119         || !EVP_CIPHER_meth_set_do_cipher(cipher, TPL(c, do_cipher))
120         || !EVP_CIPHER_meth_set_cleanup(cipher, TPL(c, cleanup))
121         || !EVP_CIPHER_meth_set_impl_ctx_size(cipher, TPL(c, ctx_size))
122         || !EVP_CIPHER_meth_set_set_asn1_params(cipher, TPL(c, set_asn1_parameters))
123         || !EVP_CIPHER_meth_set_get_asn1_params(cipher, TPL(c, get_asn1_parameters))
124         || !EVP_CIPHER_meth_set_ctrl(cipher, TPL(c, ctrl))) {
125         EVP_CIPHER_meth_free(cipher);
126         cipher = NULL;
127     }
128     c->cipher = cipher;
129     return c->cipher;
130 }
131
132 void GOST_deinit_cipher(GOST_cipher *c)
133 {
134     if (c->cipher) {
135         EVP_CIPHER_meth_free(c->cipher);
136         c->cipher = NULL;
137     }
138 }
139
140 static GOST_cipher gost_template_cipher = {
141     .block_size = 8,
142     .key_len = 32,
143     .iv_len = 8,
144     .flags = EVP_CIPH_CUSTOM_IV |
145         EVP_CIPH_RAND_KEY |
146         EVP_CIPH_ALWAYS_CALL_INIT,
147     .cleanup = gost_cipher_cleanup,
148     .ctx_size = sizeof(struct ossl_gost_cipher_ctx),
149     .set_asn1_parameters = gost89_set_asn1_parameters,
150     .get_asn1_parameters = gost89_get_asn1_parameters,
151     .ctrl = gost_cipher_ctl,
152 };
153
154 GOST_cipher Gost28147_89_cipher = {
155     .nid = NID_id_Gost28147_89,
156     .template = &gost_template_cipher,
157     .block_size = 1,
158     .flags = EVP_CIPH_CFB_MODE |
159         EVP_CIPH_NO_PADDING,
160     .init = gost_cipher_init,
161     .do_cipher = gost_cipher_do_cfb,
162 };
163
164 GOST_cipher Gost28147_89_cbc_cipher = {
165     .nid = NID_gost89_cbc,
166     .template = &gost_template_cipher,
167     .flags = EVP_CIPH_CBC_MODE,
168     .init = gost_cipher_init_cbc,
169     .do_cipher = gost_cipher_do_cbc,
170 };
171
172 GOST_cipher Gost28147_89_cnt_cipher = {
173     .nid = NID_gost89_cnt,
174     .template = &gost_template_cipher,
175     .block_size = 1,
176     .flags = EVP_CIPH_OFB_MODE |
177         EVP_CIPH_NO_PADDING,
178     .init = gost_cipher_init_cpa,
179     .do_cipher = gost_cipher_do_cnt,
180 };
181
182 GOST_cipher Gost28147_89_cnt_12_cipher = {
183     .nid = NID_gost89_cnt_12,
184     .template = &gost_template_cipher,
185     .block_size = 1,
186     .flags = EVP_CIPH_OFB_MODE |
187         EVP_CIPH_NO_PADDING,
188     .init = gost_cipher_init_cp_12,
189     .do_cipher = gost_cipher_do_cnt,
190 };
191
192 static GOST_cipher magma_template_cipher = {
193     .block_size = 8,
194     .key_len = 32,
195     .iv_len = 8,
196     .flags = EVP_CIPH_CUSTOM_IV |
197         EVP_CIPH_RAND_KEY |
198         EVP_CIPH_ALWAYS_CALL_INIT,
199     .cleanup = gost_cipher_cleanup,
200     .ctx_size = sizeof(struct ossl_gost_cipher_ctx),
201     .set_asn1_parameters = magma_set_asn1_parameters,
202     .get_asn1_parameters = magma_get_asn1_parameters,
203     .do_cipher = magma_cipher_do_ctr,
204     .ctrl = magma_cipher_ctl,
205 };
206
207 GOST_cipher magma_ctr_cipher = {
208     .nid = NID_magma_ctr,
209     .template = &magma_template_cipher,
210     .block_size = 1,
211     .iv_len = 4,
212     .flags = EVP_CIPH_CTR_MODE |
213         EVP_CIPH_NO_PADDING,
214     .init = magma_cipher_init,
215 };
216
217 GOST_cipher magma_ctr_acpkm_cipher = {
218     .nid = NID_magma_ctr_acpkm,
219     .template = &magma_template_cipher,
220     .block_size = 1,
221     .iv_len = 4,
222     .flags = EVP_CIPH_CTR_MODE |
223         EVP_CIPH_NO_PADDING,
224     .init = magma_cipher_init,
225 };
226
227 GOST_cipher magma_ctr_acpkm_omac_cipher = {
228     .nid = NID_magma_ctr_acpkm_omac,
229     .template = &magma_template_cipher,
230     .block_size = 1,
231     .iv_len = 4,
232     .flags = EVP_CIPH_CTR_MODE |
233         EVP_CIPH_NO_PADDING |
234         EVP_CIPH_CUSTOM_COPY |
235         EVP_CIPH_FLAG_CUSTOM_CIPHER |
236         EVP_CIPH_FLAG_CIPHER_WITH_MAC,
237     .init = magma_cipher_init_ctr_acpkm_omac,
238     .do_cipher = magma_cipher_do_ctr_acpkm_omac,
239     .ctrl = magma_cipher_ctl_acpkm_omac,
240 };
241
242  GOST_cipher magma_mgm_cipher = {
243     .nid = NID_magma_mgm,
244     .template = &magma_template_cipher,
245     .block_size = 1,
246     .iv_len = 8,
247     .flags = EVP_CIPH_NO_PADDING |
248         EVP_CIPH_CUSTOM_IV | EVP_CIPH_FLAG_CUSTOM_CIPHER | 
249         EVP_CIPH_CTRL_INIT | EVP_CIPH_FLAG_AEAD_CIPHER,
250     .init = gost_magma_cipher_init_mgm,
251     .do_cipher = gost_magma_cipher_do_mgm,
252     .ctrl = gost_magma_mgm_ctrl,
253     .cleanup = gost_magma_mgm_cleanup,
254     .ctx_size = sizeof(gost_mgm_ctx)
255  };
256
257 GOST_cipher magma_cbc_cipher = {
258     .nid = NID_magma_cbc,
259     .template = &gost_template_cipher,
260     .flags = EVP_CIPH_CBC_MODE,
261     .init = magma_cipher_init,
262     .do_cipher = magma_cipher_do_cbc,
263 };
264
265 /* Implementation of GOST 28147-89 in MAC (imitovstavka) mode */
266 /* Init functions which set specific parameters */
267 static int gost_imit_init_cpa(EVP_MD_CTX *ctx);
268 static int gost_imit_init_cp_12(EVP_MD_CTX *ctx);
269 /* process block of data */
270 static int gost_imit_update(EVP_MD_CTX *ctx, const void *data, size_t count);
271 /* Return computed value */
272 static int gost_imit_final(EVP_MD_CTX *ctx, unsigned char *md);
273 /* Copies context */
274 static int gost_imit_copy(EVP_MD_CTX *to, const EVP_MD_CTX *from);
275 static int gost_imit_cleanup(EVP_MD_CTX *ctx);
276 /* Control function, knows how to set MAC key.*/
277 static int gost_imit_ctrl(EVP_MD_CTX *ctx, int type, int arg, void *ptr);
278
279 GOST_digest Gost28147_89_MAC_digest = {
280     .nid = NID_id_Gost28147_89_MAC,
281     .result_size = 4,
282     .input_blocksize = 8,
283     .app_datasize = sizeof(struct ossl_gost_imit_ctx),
284     .flags = EVP_MD_FLAG_XOF,
285     .init = gost_imit_init_cpa,
286     .update = gost_imit_update,
287     .final = gost_imit_final,
288     .copy = gost_imit_copy,
289     .cleanup = gost_imit_cleanup,
290     .ctrl = gost_imit_ctrl,
291 };
292
293 GOST_digest Gost28147_89_mac_12_digest = {
294     .nid = NID_gost_mac_12,
295     .result_size = 4,
296     .input_blocksize = 8,
297     .app_datasize = sizeof(struct ossl_gost_imit_ctx),
298     .flags = EVP_MD_FLAG_XOF,
299     .init = gost_imit_init_cp_12,
300     .update = gost_imit_update,
301     .final = gost_imit_final,
302     .copy = gost_imit_copy,
303     .cleanup = gost_imit_cleanup,
304     .ctrl = gost_imit_ctrl,
305 };
306
307 /*
308  * Correspondence between gost parameter OIDs and substitution blocks
309  * NID field is filed by register_gost_NID function in engine.c
310  * upon engine initialization
311  */
312
313 static struct gost_cipher_info gost_cipher_list[] = {
314     /*- NID *//*
315      * Subst block
316      *//*
317      * Key meshing
318      */
319     /*
320      * {NID_id_GostR3411_94_CryptoProParamSet,&GostR3411_94_CryptoProParamSet,0},
321      */
322     {NID_id_Gost28147_89_CryptoPro_A_ParamSet, &Gost28147_CryptoProParamSetA,
323      1},
324     {NID_id_Gost28147_89_CryptoPro_B_ParamSet, &Gost28147_CryptoProParamSetB,
325      1},
326     {NID_id_Gost28147_89_CryptoPro_C_ParamSet, &Gost28147_CryptoProParamSetC,
327      1},
328     {NID_id_Gost28147_89_CryptoPro_D_ParamSet, &Gost28147_CryptoProParamSetD,
329      1},
330     {NID_id_tc26_gost_28147_param_Z, &Gost28147_TC26ParamSetZ, 1},
331     {NID_id_Gost28147_89_TestParamSet, &Gost28147_TestParamSet, 1},
332     {NID_undef, NULL, 0}
333 };
334
335 /*
336  * get encryption parameters from crypto network settings FIXME For now we
337  * use environment var CRYPT_PARAMS as place to store these settings.
338  * Actually, it is better to use engine control command, read from
339  * configuration file to set them
340  */
341 const struct gost_cipher_info *get_encryption_params(ASN1_OBJECT *obj)
342 {
343     int nid;
344     struct gost_cipher_info *param;
345     if (!obj) {
346         const char *params = get_gost_engine_param(GOST_PARAM_CRYPT_PARAMS);
347         if (!params || !strlen(params)) {
348             int i;
349             for (i = 0; gost_cipher_list[i].nid != NID_undef; i++)
350                 if (gost_cipher_list[i].nid == NID_id_tc26_gost_28147_param_Z)
351                     return &gost_cipher_list[i];
352             return &gost_cipher_list[0];
353         }
354
355         nid = OBJ_txt2nid(params);
356         if (nid == NID_undef) {
357             GOSTerr(GOST_F_GET_ENCRYPTION_PARAMS,
358                     GOST_R_INVALID_CIPHER_PARAM_OID);
359             ERR_add_error_data(3, "Unsupported CRYPT_PARAMS='",
360                 params, "' specified in environment or in config");
361             return NULL;
362         }
363     } else {
364         nid = OBJ_obj2nid(obj);
365     }
366     for (param = gost_cipher_list; param->sblock != NULL && param->nid != nid;
367          param++) ;
368     if (!param->sblock) {
369         GOSTerr(GOST_F_GET_ENCRYPTION_PARAMS, GOST_R_INVALID_CIPHER_PARAMS);
370         return NULL;
371     }
372     return param;
373 }
374
375 /* Sets cipher param from paramset NID. */
376 static int gost_cipher_set_param(struct ossl_gost_cipher_ctx *c, int nid)
377 {
378     const struct gost_cipher_info *param;
379     param = get_encryption_params((nid == NID_undef ? NULL : OBJ_nid2obj(nid)));
380     if (!param)
381         return 0;
382
383     c->paramNID = param->nid;
384     c->key_meshing = param->key_meshing;
385     c->count = 0;
386     gost_init(&(c->cctx), param->sblock);
387     return 1;
388 }
389
390 /* Initializes EVP_CIPHER_CTX by paramset NID */
391 static int gost_cipher_init_param(EVP_CIPHER_CTX *ctx,
392                                   const unsigned char *key,
393                                   const unsigned char *iv, int enc,
394                                   int paramNID, int mode)
395 {
396     struct ossl_gost_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
397     if (EVP_CIPHER_CTX_get_app_data(ctx) == NULL) {
398         if (!gost_cipher_set_param(c, paramNID))
399             return 0;
400         EVP_CIPHER_CTX_set_app_data(ctx, EVP_CIPHER_CTX_get_cipher_data(ctx));
401     }
402     if (key)
403         gost_key(&(c->cctx), key);
404     if (iv) {
405         memcpy((unsigned char *)EVP_CIPHER_CTX_original_iv(ctx), iv,
406                EVP_CIPHER_CTX_iv_length(ctx));
407     }
408     memcpy(EVP_CIPHER_CTX_iv_noconst(ctx),
409            EVP_CIPHER_CTX_original_iv(ctx), EVP_CIPHER_CTX_iv_length(ctx));
410     return 1;
411 }
412
413 static int gost_cipher_init_cnt(EVP_CIPHER_CTX *ctx,
414                                 const unsigned char *key,
415                                 const unsigned char *iv,
416                                 gost_subst_block * block)
417 {
418     struct ossl_gost_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
419     gost_init(&(c->cctx), block);
420     c->key_meshing = 1;
421     c->count = 0;
422     if (key)
423         gost_key(&(c->cctx), key);
424     if (iv) {
425         memcpy((unsigned char *)EVP_CIPHER_CTX_original_iv(ctx), iv,
426                EVP_CIPHER_CTX_iv_length(ctx));
427     }
428     memcpy(EVP_CIPHER_CTX_iv_noconst(ctx),
429            EVP_CIPHER_CTX_original_iv(ctx), EVP_CIPHER_CTX_iv_length(ctx));
430     return 1;
431 }
432
433 static int gost_cipher_init_cpa(EVP_CIPHER_CTX *ctx, const unsigned char *key,
434                                 const unsigned char *iv, int enc)
435 {
436     return gost_cipher_init_cnt(ctx, key, iv, &Gost28147_CryptoProParamSetA);
437 }
438
439 static int gost_cipher_init_cp_12(EVP_CIPHER_CTX *ctx,
440                                   const unsigned char *key,
441                                   const unsigned char *iv, int enc)
442 {
443     return gost_cipher_init_cnt(ctx, key, iv, &Gost28147_TC26ParamSetZ);
444 }
445
446 /* Initializes EVP_CIPHER_CTX with default values */
447 static int gost_cipher_init(EVP_CIPHER_CTX *ctx, const unsigned char *key,
448                      const unsigned char *iv, int enc)
449 {
450     return gost_cipher_init_param(ctx, key, iv, enc, NID_undef,
451                                   EVP_CIPH_CFB_MODE);
452 }
453
454 /* Initializes EVP_CIPHER_CTX with default values */
455 static int gost_cipher_init_cbc(EVP_CIPHER_CTX *ctx, const unsigned char *key,
456                          const unsigned char *iv, int enc)
457 {
458     return gost_cipher_init_param(ctx, key, iv, enc, NID_undef,
459                                   EVP_CIPH_CBC_MODE);
460 }
461
462 /* Initializes EVP_CIPHER_CTX with default values */
463 static int magma_cipher_init(EVP_CIPHER_CTX *ctx, const unsigned char *key,
464                       const unsigned char *iv, int enc)
465 {
466     struct ossl_gost_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
467     /* FIXME this is just initializtion check */
468     if (EVP_CIPHER_CTX_get_app_data(ctx) == NULL) {
469         if (!gost_cipher_set_param(c, NID_id_tc26_gost_28147_param_Z))
470             return 0;
471         EVP_CIPHER_CTX_set_app_data(ctx, EVP_CIPHER_CTX_get_cipher_data(ctx));
472
473         if (enc) {
474             if (init_zero_kdf_seed(c->kdf_seed) == 0)
475                 return -1;
476         }
477     }
478
479     if (key) {
480         magma_key(&(c->cctx), key);
481         magma_master_key(&(c->cctx), key);
482     }
483     if (iv) {
484         memcpy((unsigned char *)EVP_CIPHER_CTX_original_iv(ctx), iv,
485                EVP_CIPHER_CTX_iv_length(ctx));
486     }
487     memcpy(EVP_CIPHER_CTX_iv_noconst(ctx),
488            EVP_CIPHER_CTX_original_iv(ctx), EVP_CIPHER_CTX_iv_length(ctx));
489
490     if (EVP_CIPHER_CTX_nid(ctx) == NID_magma_ctr_acpkm
491      || EVP_CIPHER_CTX_nid(ctx) == NID_magma_ctr_acpkm_omac) {
492        c->key_meshing = 1024;
493     } else {
494        c->key_meshing = 0;
495     }
496
497     return 1;
498 }
499
500 /* Initializes EVP_CIPHER_CTX with default values */
501 static int magma_cipher_init_ctr_acpkm_omac(EVP_CIPHER_CTX *ctx, const unsigned char *key,
502                       const unsigned char *iv, int enc)
503 {
504         if (key) {
505     struct ossl_gost_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
506                 unsigned char cipher_key[32];
507                 c->omac_ctx = EVP_MD_CTX_new();
508
509                 if (c->omac_ctx == NULL) {
510                     GOSTerr(GOST_F_MAGMA_CIPHER_INIT_CTR_ACPKM_OMAC, ERR_R_MALLOC_FAILURE);
511                                 return 0;
512                 }
513
514                 if (gost2015_acpkm_omac_init(NID_magma_mac, enc, key,
515                                  c->omac_ctx, cipher_key, c->kdf_seed) != 1) {
516                     EVP_MD_CTX_free(c->omac_ctx);
517                                 c->omac_ctx = NULL;
518                     return 0;
519                 }
520
521                 return magma_cipher_init(ctx, cipher_key, iv, enc);
522         }
523
524         return magma_cipher_init(ctx, key, iv, enc);
525 }
526
527 void gost_magma_encrypt_wrap(unsigned char *in, unsigned char *out,
528                    struct ossl_gost_cipher_ctx *c) {
529     int i;
530     unsigned char b[8];
531     unsigned char d[8];
532     for (i = 0; i < 8; i++) {
533         b[7 - i] = in[i];
534     }
535     gostcrypt(&(c->cctx), b, d);
536     for (i = 0; i < 8; i++) {
537         out[7 - i] = d[i];
538     }
539 }
540
541 /* ----------------------------------------------------------------------------------------------- */
542 /*! Функция реализует операцию умножения двух элементов конечного поля \f$ \mathbb F_{2^{64}}\f$,
543     порожденного неприводимым многочленом
544     \f$ f(x) = x^{64} + x^4 + x^3 + x + 1 \in \mathbb F_2[x]\f$. Для умножения используется
545     простейшая реализация, основанная на приведении по модулю после каждого шага алгоритма.        */
546 /* ----------------------------------------------------------------------------------------------- */
547 static void gf64_mul (uint64_t *result, uint64_t *arg1, uint64_t *arg2)
548 {
549         int i = 0;
550         register uint64_t t, X0;
551         uint64_t Z0 = 0;
552  
553 #ifdef L_ENDIAN
554         X0 = BSWAP64(*arg1);
555 #else
556         X0 = *arg1;
557 #endif
558
559 #ifdef L_ENDIAN
560         t = BSWAP64(*(arg2));
561 #else
562         t = *(arg2);
563 #endif
564
565         for (i = 0; i < 63; i++) {
566                 if (t & 0x1) {
567                         Z0 ^= X0;
568                 }
569                 t >>= 1;
570                 if (X0 & 0x8000000000000000) {
571                         X0 <<= 1;
572                         X0 ^= 0x1b;
573                 }
574                 else {
575                         X0 <<= 1;
576                 }
577         }
578
579         if (t & 0x1) {
580                 Z0 ^= X0;
581         }
582
583 #ifdef L_ENDIAN
584         *(result) = BSWAP64(Z0);
585 #else
586         *(result) = Z0;
587 #endif
588 }
589
590 static int gost_magma_cipher_init_mgm(EVP_CIPHER_CTX *ctx, const unsigned char *key,
591                                  const unsigned char *iv, int enc)
592 {
593     gost_mgm_ctx *mctx = 
594         (gost_mgm_ctx *)EVP_CIPHER_CTX_get_cipher_data(ctx);
595     int bl;
596
597     if (!iv && !key)
598         return 1;
599     if (key) {
600         bl = EVP_CIPHER_CTX_iv_length(ctx);
601         if (!gost_cipher_set_param(&mctx->ks.g_ks, NID_id_tc26_gost_28147_param_Z))
602             return 0;
603         magma_key(&(mctx->ks.g_ks.cctx), key);
604         magma_master_key(&(mctx->ks.g_ks.cctx), key);
605         gost_mgm128_init(&mctx->mgm, &mctx->ks, 
606                          (block128_f) gost_magma_encrypt_wrap, gf64_mul, bl);
607
608         /*
609          * If we have an iv can set it directly, otherwise use saved IV.
610          */
611         if (iv == NULL && mctx->iv_set)
612             iv = mctx->iv;
613         if (iv) {
614             if (gost_mgm128_setiv(&mctx->mgm, iv, mctx->ivlen) != 1)
615                 return 0;
616             mctx->iv_set = 1;
617         }
618         mctx->key_set = 1;
619     } else {
620         /* If key set use IV, otherwise copy */
621         if (mctx->key_set) {
622             if (gost_mgm128_setiv(&mctx->mgm, iv, mctx->ivlen) != 1)
623                 return 0;
624         }
625         else
626             memcpy(mctx->iv, iv, mctx->ivlen);
627         mctx->iv_set = 1;
628     }
629     return 1;
630 }
631
632 /*
633  * Wrapper around gostcrypt function from gost89.c which perform key meshing
634  * when nesseccary
635  */
636 static void gost_crypt_mesh(void *ctx, unsigned char *iv, unsigned char *buf)
637 {
638     struct ossl_gost_cipher_ctx *c = ctx;
639     assert(c->count % 8 == 0 && c->count <= 1024);
640     if (c->key_meshing && c->count == 1024) {
641         cryptopro_key_meshing(&(c->cctx), iv);
642     }
643     gostcrypt(&(c->cctx), iv, buf);
644     c->count = c->count % 1024 + 8;
645 }
646
647 static void gost_cnt_next(void *ctx, unsigned char *iv, unsigned char *buf)
648 {
649     struct ossl_gost_cipher_ctx *c = ctx;
650     word32 g, go;
651     unsigned char buf1[8];
652     assert(c->count % 8 == 0 && c->count <= 1024);
653     if (c->key_meshing && c->count == 1024) {
654         cryptopro_key_meshing(&(c->cctx), iv);
655     }
656     if (c->count == 0) {
657         gostcrypt(&(c->cctx), iv, buf1);
658     } else {
659         memcpy(buf1, iv, 8);
660     }
661     g = buf1[0] | (buf1[1] << 8) | (buf1[2] << 16) | ((word32) buf1[3] << 24);
662     g += 0x01010101;
663     buf1[0] = (unsigned char)(g & 0xff);
664     buf1[1] = (unsigned char)((g >> 8) & 0xff);
665     buf1[2] = (unsigned char)((g >> 16) & 0xff);
666     buf1[3] = (unsigned char)((g >> 24) & 0xff);
667     g = buf1[4] | (buf1[5] << 8) | (buf1[6] << 16) | ((word32) buf1[7] << 24);
668     go = g;
669     g += 0x01010104;
670     if (go > g)                 /* overflow */
671         g++;
672     buf1[4] = (unsigned char)(g & 0xff);
673     buf1[5] = (unsigned char)((g >> 8) & 0xff);
674     buf1[6] = (unsigned char)((g >> 16) & 0xff);
675     buf1[7] = (unsigned char)((g >> 24) & 0xff);
676     memcpy(iv, buf1, 8);
677     gostcrypt(&(c->cctx), buf1, buf);
678     c->count = c->count % 1024 + 8;
679 }
680
681 /* GOST encryption in CBC mode */
682 static int gost_cipher_do_cbc(EVP_CIPHER_CTX *ctx, unsigned char *out,
683                        const unsigned char *in, size_t inl)
684 {
685     unsigned char b[8];
686     const unsigned char *in_ptr = in;
687     unsigned char *out_ptr = out;
688     int i;
689     struct ossl_gost_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
690     unsigned char *iv = EVP_CIPHER_CTX_iv_noconst(ctx);
691     if (EVP_CIPHER_CTX_encrypting(ctx)) {
692         while (inl > 0) {
693
694             for (i = 0; i < 8; i++) {
695                 b[i] = iv[i] ^ in_ptr[i];
696             }
697             gostcrypt(&(c->cctx), b, out_ptr);
698             memcpy(iv, out_ptr, 8);
699             out_ptr += 8;
700             in_ptr += 8;
701             inl -= 8;
702         }
703     } else {
704         while (inl > 0) {
705             unsigned char tmpiv[8];
706             gostdecrypt(&(c->cctx), in_ptr, b);
707             memcpy(tmpiv, in_ptr, 8);
708             for (i = 0; i < 8; i++) {
709                 out_ptr[i] = iv[i] ^ b[i];
710             }
711             memcpy(iv, tmpiv, 8);
712             out_ptr += 8;
713             in_ptr += 8;
714             inl -= 8;
715         }
716     }
717     return 1;
718 }
719
720 /* MAGMA encryption in CBC mode */
721 static int magma_cipher_do_cbc(EVP_CIPHER_CTX *ctx, unsigned char *out,
722                         const unsigned char *in, size_t inl)
723 {
724     unsigned char b[8];
725     unsigned char d[8];
726     const unsigned char *in_ptr = in;
727     unsigned char *out_ptr = out;
728     int i;
729     struct ossl_gost_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
730     unsigned char *iv = EVP_CIPHER_CTX_iv_noconst(ctx);
731     if (EVP_CIPHER_CTX_encrypting(ctx)) {
732         while (inl > 0) {
733
734             for (i = 0; i < 8; i++) {
735                 b[7 - i] = iv[i] ^ in_ptr[i];
736             }
737             gostcrypt(&(c->cctx), b, d);
738
739             for (i = 0; i < 8; i++) {
740                 out_ptr[7 - i] = d[i];
741             }
742             memcpy(iv, out_ptr, 8);
743             out_ptr += 8;
744             in_ptr += 8;
745             inl -= 8;
746         }
747     } else {
748         while (inl > 0) {
749             for (i = 0; i < 8; i++) {
750                 d[7 - i] = in_ptr[i];
751             }
752             gostdecrypt(&(c->cctx), d, b);
753             memcpy(d, in_ptr, 8);
754             for (i = 0; i < 8; i++) {
755                 out_ptr[i] = iv[i] ^ b[7 - i];
756             }
757             memcpy(iv, d, 8);
758             out_ptr += 8;
759             in_ptr += 8;
760             inl -= 8;
761         }
762     }
763     return 1;
764 }
765
766 /* increment counter (64-bit int) by 1 */
767 static void ctr64_inc(unsigned char *counter)
768 {
769     inc_counter(counter, 8);
770 }
771
772 #define MAGMA_BLOCK_SIZE 8
773 #define MAGMA_BLOCK_MASK (MAGMA_BLOCK_SIZE - 1)
774 static inline void apply_acpkm_magma(struct ossl_gost_cipher_ctx *
775                                            ctx, unsigned int *num)
776 {
777     if (!ctx->key_meshing || (*num < ctx->key_meshing))
778         return;
779     acpkm_magma_key_meshing(&ctx->cctx);
780     *num &= MAGMA_BLOCK_MASK;
781 }
782
783 /* MAGMA encryption in CTR mode */
784 static int magma_cipher_do_ctr(EVP_CIPHER_CTX *ctx, unsigned char *out,
785                                const unsigned char *in, size_t inl)
786 {
787     const unsigned char *in_ptr = in;
788     unsigned char *out_ptr = out;
789     size_t j;
790     struct ossl_gost_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
791     unsigned char *buf = EVP_CIPHER_CTX_buf_noconst(ctx);
792     unsigned char *iv = EVP_CIPHER_CTX_iv_noconst(ctx);
793     unsigned int num = EVP_CIPHER_CTX_num(ctx);
794     size_t blocks, i, lasted = inl;
795     unsigned char b[8];
796 /* Process partial blocks */
797     while ((num & MAGMA_BLOCK_MASK) && lasted) {
798         *out_ptr++ = *in_ptr++ ^ buf[7 - (num & MAGMA_BLOCK_MASK)];
799         --lasted;
800         num++;
801     }
802     blocks = lasted / MAGMA_BLOCK_SIZE;
803
804 /* Process full blocks */
805     for (i = 0; i < blocks; i++) {
806         apply_acpkm_magma(c, &num);
807         for (j = 0; j < 8; j++) {
808             b[7 - j] = iv[j];
809         }
810         gostcrypt(&(c->cctx), b, buf);
811         for (j = 0; j < 8; j++) {
812             out_ptr[j] = buf[7 - j] ^ in_ptr[j];
813         }
814         ctr64_inc(iv);
815         c->count += MAGMA_BLOCK_SIZE;
816         in_ptr += MAGMA_BLOCK_SIZE;
817         out_ptr += MAGMA_BLOCK_SIZE;
818         num += MAGMA_BLOCK_SIZE;
819         lasted -= MAGMA_BLOCK_SIZE;
820     }
821
822 /* Process the rest of plaintext */
823     if (lasted > 0) {
824         apply_acpkm_magma(c, &num);
825         for (j = 0; j < 8; j++) {
826             b[7 - j] = iv[j];
827         }
828         gostcrypt(&(c->cctx), b, buf);
829
830         for (i = 0; i < lasted; i++)
831             out_ptr[i] = buf[7 - i] ^ in_ptr[i];
832         ctr64_inc(iv);
833         c->count += j;
834         num += lasted;
835     }
836     EVP_CIPHER_CTX_set_num(ctx, num);
837
838     return inl;
839 }
840
841 /* MAGMA encryption in CTR mode */
842 static int magma_cipher_do_ctr_acpkm_omac(EVP_CIPHER_CTX *ctx, unsigned char *out,
843                                const unsigned char *in, size_t inl)
844 {
845   struct ossl_gost_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
846
847         if (in == NULL && inl == 0) /* Final call */
848                 return gost2015_final_call(ctx, c->omac_ctx, MAGMA_MAC_MAX_SIZE, c->tag, magma_cipher_do_ctr);
849
850   if (in == NULL)
851       return -1;
852
853         /* As in and out can be the same pointer, process unencrypted here */
854         if (EVP_CIPHER_CTX_encrypting(ctx))
855                 EVP_DigestSignUpdate(c->omac_ctx, in, inl);
856
857   if (magma_cipher_do_ctr(ctx, out, in, inl) != inl)
858       return -1;
859
860         /* As in and out can be the same pointer, process decrypted here */
861         if (!EVP_CIPHER_CTX_encrypting(ctx))
862                 EVP_DigestSignUpdate(c->omac_ctx, out, inl);
863
864         return inl;
865 }
866
867 static int gost_magma_cipher_do_mgm(EVP_CIPHER_CTX *ctx, unsigned char *out,
868                                    const unsigned char *in, size_t len)
869 {
870     gost_mgm_ctx *mctx = 
871         (gost_mgm_ctx *)EVP_CIPHER_CTX_get_cipher_data(ctx);
872     int enc = EVP_CIPHER_CTX_encrypting(ctx);
873
874     /* If not set up, return error */
875     if (!mctx->key_set) {
876         GOSTerr(GOST_F_GOST_MAGMA_CIPHER_DO_MGM,
877                 GOST_R_BAD_ORDER);
878         return -1;
879     }
880
881     if (!mctx->iv_set) {
882         GOSTerr(GOST_F_GOST_MAGMA_CIPHER_DO_MGM,
883                 GOST_R_BAD_ORDER);
884         return -1;
885     }
886     if (in) {
887         if (out == NULL) {
888             if (gost_mgm128_aad(&mctx->mgm, in, len))
889                 return -1;            
890         } else if (enc) {
891             if (gost_mgm128_encrypt(&mctx->mgm, in, out, len))
892                 return -1;
893         } else {
894             if (gost_mgm128_decrypt(&mctx->mgm, in, out, len))
895                 return -1;
896         }
897         return len;
898     } else {
899         if (!enc) {
900             if (mctx->taglen < 0)
901                 return -1;
902             if (gost_mgm128_finish(&mctx->mgm,
903                                    EVP_CIPHER_CTX_buf_noconst(ctx),
904                                    mctx->taglen) != 0)
905                 return -1;
906             mctx->iv_set = 0;
907             return 0;
908         }
909         gost_mgm128_tag(&mctx->mgm, EVP_CIPHER_CTX_buf_noconst(ctx), 8);
910         mctx->taglen = 8;
911         /* Don't reuse the IV */
912         mctx->iv_set = 0;
913         return 0;
914     }
915
916 }
917
918 /* GOST encryption in CFB mode */
919 static int gost_cipher_do_cfb(EVP_CIPHER_CTX *ctx, unsigned char *out,
920                        const unsigned char *in, size_t inl)
921 {
922     const unsigned char *in_ptr = in;
923     unsigned char *out_ptr = out;
924     size_t i = 0;
925     size_t j = 0;
926     unsigned char *buf = EVP_CIPHER_CTX_buf_noconst(ctx);
927     unsigned char *iv = EVP_CIPHER_CTX_iv_noconst(ctx);
928 /* process partial block if any */
929     if (EVP_CIPHER_CTX_num(ctx)) {
930         for (j = EVP_CIPHER_CTX_num(ctx), i = 0; j < 8 && i < inl;
931              j++, i++, in_ptr++, out_ptr++) {
932             if (!EVP_CIPHER_CTX_encrypting(ctx))
933                 buf[j + 8] = *in_ptr;
934             *out_ptr = buf[j] ^ (*in_ptr);
935             if (EVP_CIPHER_CTX_encrypting(ctx))
936                 buf[j + 8] = *out_ptr;
937         }
938         if (j == 8) {
939             memcpy(iv, buf + 8, 8);
940             EVP_CIPHER_CTX_set_num(ctx, 0);
941         } else {
942             EVP_CIPHER_CTX_set_num(ctx, j);
943             return 1;
944         }
945     }
946
947     for (; (inl - i) >= 8; i += 8, in_ptr += 8, out_ptr += 8) {
948         /*
949          * block cipher current iv
950          */
951         gost_crypt_mesh(EVP_CIPHER_CTX_get_cipher_data(ctx), iv, buf);
952         /*
953          * xor next block of input text with it and output it
954          */
955         /*
956          * output this block
957          */
958         if (!EVP_CIPHER_CTX_encrypting(ctx))
959             memcpy(iv, in_ptr, 8);
960         for (j = 0; j < 8; j++) {
961             out_ptr[j] = buf[j] ^ in_ptr[j];
962         }
963         /* Encrypt */
964         /* Next iv is next block of cipher text */
965         if (EVP_CIPHER_CTX_encrypting(ctx))
966             memcpy(iv, out_ptr, 8);
967     }
968 /* Process rest of buffer */
969     if (i < inl) {
970         gost_crypt_mesh(EVP_CIPHER_CTX_get_cipher_data(ctx), iv, buf);
971         if (!EVP_CIPHER_CTX_encrypting(ctx))
972             memcpy(buf + 8, in_ptr, inl - i);
973         for (j = 0; i < inl; j++, i++) {
974             out_ptr[j] = buf[j] ^ in_ptr[j];
975         }
976         EVP_CIPHER_CTX_set_num(ctx, j);
977         if (EVP_CIPHER_CTX_encrypting(ctx))
978             memcpy(buf + 8, out_ptr, j);
979     } else {
980         EVP_CIPHER_CTX_set_num(ctx, 0);
981     }
982     return 1;
983 }
984
985 static int gost_cipher_do_cnt(EVP_CIPHER_CTX *ctx, unsigned char *out,
986                               const unsigned char *in, size_t inl)
987 {
988     const unsigned char *in_ptr = in;
989     unsigned char *out_ptr = out;
990     size_t i = 0;
991     size_t j;
992     unsigned char *buf = EVP_CIPHER_CTX_buf_noconst(ctx);
993     unsigned char *iv = EVP_CIPHER_CTX_iv_noconst(ctx);
994 /* process partial block if any */
995     if (EVP_CIPHER_CTX_num(ctx)) {
996         for (j = EVP_CIPHER_CTX_num(ctx), i = 0; j < 8 && i < inl;
997              j++, i++, in_ptr++, out_ptr++) {
998             *out_ptr = buf[j] ^ (*in_ptr);
999         }
1000         if (j == 8) {
1001             EVP_CIPHER_CTX_set_num(ctx, 0);
1002         } else {
1003             EVP_CIPHER_CTX_set_num(ctx, j);
1004             return 1;
1005         }
1006     }
1007
1008     for (; (inl - i) >= 8; i += 8, in_ptr += 8, out_ptr += 8) {
1009         /*
1010          * block cipher current iv
1011          */
1012         /* Encrypt */
1013         gost_cnt_next(EVP_CIPHER_CTX_get_cipher_data(ctx), iv, buf);
1014         /*
1015          * xor next block of input text with it and output it
1016          */
1017         /*
1018          * output this block
1019          */
1020         for (j = 0; j < 8; j++) {
1021             out_ptr[j] = buf[j] ^ in_ptr[j];
1022         }
1023     }
1024 /* Process rest of buffer */
1025     if (i < inl) {
1026         gost_cnt_next(EVP_CIPHER_CTX_get_cipher_data(ctx), iv, buf);
1027         for (j = 0; i < inl; j++, i++) {
1028             out_ptr[j] = buf[j] ^ in_ptr[j];
1029         }
1030         EVP_CIPHER_CTX_set_num(ctx, j);
1031     } else {
1032         EVP_CIPHER_CTX_set_num(ctx, 0);
1033     }
1034     return 1;
1035 }
1036
1037 /* Cleaning up of EVP_CIPHER_CTX */
1038 static int gost_cipher_cleanup(EVP_CIPHER_CTX *ctx)
1039 {
1040     struct ossl_gost_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
1041                 EVP_MD_CTX_free(c->omac_ctx);
1042     gost_destroy(&(c->cctx));
1043     EVP_CIPHER_CTX_set_app_data(ctx, NULL);
1044     return 1;
1045 }
1046
1047 static int gost_magma_mgm_cleanup(EVP_CIPHER_CTX *c)
1048 {
1049     gost_mgm_ctx *mctx = 
1050         (gost_mgm_ctx *)EVP_CIPHER_CTX_get_cipher_data(c);
1051     if (mctx == NULL)
1052         return 0;
1053     gost_destroy(&mctx->ks.g_ks.cctx);
1054     OPENSSL_cleanse(&mctx->mgm, sizeof(mctx->mgm));
1055     EVP_CIPHER_CTX_set_app_data(c, NULL);
1056     return 1;
1057 }
1058
1059 static int gost_magma_mgm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr)
1060 {
1061     gost_mgm_ctx *mctx = 
1062         (gost_mgm_ctx *)EVP_CIPHER_CTX_get_cipher_data(c);
1063     unsigned char *buf, *iv;
1064     int ivlen, enc;
1065
1066     switch (type) {
1067     case EVP_CTRL_INIT:
1068         ivlen = EVP_CIPHER_iv_length(EVP_CIPHER_CTX_cipher(c));
1069         iv = EVP_CIPHER_CTX_iv_noconst(c);
1070         mctx->key_set = 0;
1071         mctx->iv_set = 0;
1072         mctx->ivlen = ivlen;
1073         mctx->iv = iv;
1074         mctx->taglen = -1;
1075         mctx->tlstree_mode = TLSTREE_MODE_NONE;
1076         return 1;
1077     
1078     case EVP_CTRL_GET_IVLEN:
1079         *(int *)ptr = mctx->ivlen;
1080         return 1;
1081
1082     case EVP_CTRL_AEAD_SET_IVLEN:
1083         if (arg <= 0)
1084             return 0;
1085         if ((arg > EVP_MAX_IV_LENGTH) && (arg > mctx->ivlen)) {
1086             // TODO: Allocate memory for IV or set error
1087             return 0;
1088         }
1089         mctx->ivlen = arg;
1090         return 1;
1091
1092     case EVP_CTRL_AEAD_SET_TAG:
1093         buf = EVP_CIPHER_CTX_buf_noconst(c);
1094         enc = EVP_CIPHER_CTX_encrypting(c);
1095         if (arg <= 0 || arg != 8 || enc) {
1096             GOSTerr(GOST_F_GOST_MAGMA_MGM_CTRL,
1097                     GOST_R_INVALID_TAG_LENGTH);
1098             return 0;
1099         }
1100         memcpy(buf, ptr, arg);
1101         mctx->taglen = arg;    
1102         return 1;
1103
1104     case EVP_CTRL_AEAD_GET_TAG:
1105         buf = EVP_CIPHER_CTX_buf_noconst(c);
1106         enc = EVP_CIPHER_CTX_encrypting(c);
1107         if (arg <= 0 || arg > 8 || !enc || mctx->taglen < 0) {
1108             GOSTerr(GOST_F_GOST_MAGMA_MGM_CTRL,
1109                     GOST_R_INVALID_TAG_LENGTH);
1110             return 0;
1111         }
1112         memcpy(ptr, buf, arg);
1113         return 1;
1114
1115     case EVP_CTRL_SET_TLSTREE_PARAMS:
1116         if (strcmp((char *)ptr, "short") == 0)
1117             mctx->tlstree_mode = TLSTREE_MODE_S;
1118         else if (strcmp((char *)ptr, "long") == 0)
1119             mctx->tlstree_mode = TLSTREE_MODE_L;
1120         else {
1121             // TODO: set err
1122             return 0;
1123         }
1124         return 1;
1125
1126     case EVP_CTRL_TLSTREE:
1127         {
1128             unsigned char newkey[32];
1129             if (gost_tlstree(NID_magma_mgm, 
1130                     (const unsigned char *)mctx->ks.g_ks.cctx.master_key, 
1131                     newkey, (const unsigned char *)ptr, mctx->tlstree_mode) 
1132                   > 0) {
1133                 magma_key(&mctx->ks.g_ks.cctx, newkey);
1134                 memset(newkey, 0, sizeof(newkey));
1135             }
1136         }
1137         return 1;
1138
1139     default:
1140         return -1;
1141     }
1142 }
1143
1144 /* Control function for gost cipher */
1145 static int gost_cipher_ctl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr)
1146 {
1147     switch (type) {
1148     case EVP_CTRL_RAND_KEY:
1149         {
1150             if (RAND_priv_bytes
1151                 ((unsigned char *)ptr, EVP_CIPHER_CTX_key_length(ctx)) <= 0) {
1152                 GOSTerr(GOST_F_GOST_CIPHER_CTL, GOST_R_RNG_ERROR);
1153                 return -1;
1154             }
1155             break;
1156         }
1157     case EVP_CTRL_PBE_PRF_NID:
1158         if (ptr) {
1159             const char *params = get_gost_engine_param(GOST_PARAM_PBE_PARAMS);
1160             int nid = NID_id_tc26_hmac_gost_3411_2012_512;
1161
1162             if (params) {
1163                 if (!strcmp("md_gost12_256", params))
1164                     nid = NID_id_tc26_hmac_gost_3411_2012_256;
1165                 else if (!strcmp("md_gost12_512", params))
1166                     nid = NID_id_tc26_hmac_gost_3411_2012_512;
1167                 else if (!strcmp("md_gost94", params))
1168                     nid = NID_id_HMACGostR3411_94;
1169             }
1170             *((int *)ptr) = nid;
1171             return 1;
1172         } else {
1173             return 0;
1174         }
1175
1176     case EVP_CTRL_SET_SBOX:
1177         if (ptr) {
1178             struct ossl_gost_cipher_ctx *c =
1179                 EVP_CIPHER_CTX_get_cipher_data(ctx);
1180             int nid;
1181             int cur_meshing;
1182             int ret;
1183
1184             if (c == NULL) {
1185                 return -1;
1186             }
1187
1188             if (c->count != 0) {
1189                 return -1;
1190             }
1191
1192             nid = OBJ_txt2nid(ptr);
1193             if (nid == NID_undef) {
1194                 return 0;
1195             }
1196
1197             cur_meshing = c->key_meshing;
1198             ret = gost_cipher_set_param(c, nid);
1199             c->key_meshing = cur_meshing;
1200             return ret;
1201         } else {
1202             return 0;
1203         }
1204     case EVP_CTRL_KEY_MESH:
1205         {
1206             struct ossl_gost_cipher_ctx *c =
1207                 EVP_CIPHER_CTX_get_cipher_data(ctx);
1208
1209             if (c == NULL) {
1210                 return -1;
1211             }
1212
1213             if (c->count != 0) {
1214                 return -1;
1215             }
1216
1217             c->key_meshing = arg;
1218             return 1;
1219         }
1220     default:
1221         GOSTerr(GOST_F_GOST_CIPHER_CTL, GOST_R_UNSUPPORTED_CIPHER_CTL_COMMAND);
1222         return -1;
1223     }
1224     return 1;
1225 }
1226
1227 /* Control function for gost cipher */
1228 static int magma_cipher_ctl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr)
1229 {
1230     switch (type) {
1231     case EVP_CTRL_RAND_KEY:
1232             if (RAND_priv_bytes
1233                 ((unsigned char *)ptr, EVP_CIPHER_CTX_key_length(ctx)) <= 0) {
1234                 GOSTerr(GOST_F_MAGMA_CIPHER_CTL, GOST_R_RNG_ERROR);
1235                 return -1;
1236             }
1237             break;
1238     case EVP_CTRL_KEY_MESH:
1239         {
1240             struct ossl_gost_cipher_ctx *c =
1241                 EVP_CIPHER_CTX_get_cipher_data(ctx);
1242
1243             if (c == NULL) {
1244                 return -1;
1245             }
1246
1247             if (c->count != 0) {
1248                 return -1;
1249             }
1250
1251             c->key_meshing = arg;
1252             return 1;
1253         }
1254     default:
1255         GOSTerr(GOST_F_MAGMA_CIPHER_CTL, GOST_R_UNSUPPORTED_CIPHER_CTL_COMMAND);
1256         return -1;
1257     }
1258     return 1;
1259 }
1260
1261 static int magma_cipher_ctl_acpkm_omac(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr)
1262 {
1263         switch (type)
1264         {
1265                 case EVP_CTRL_PROCESS_UNPROTECTED:
1266                 {
1267                         struct ossl_gost_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
1268                         STACK_OF(X509_ATTRIBUTE) *x = ptr;
1269       return gost2015_process_unprotected_attributes(x, arg, MAGMA_MAC_MAX_SIZE, c->tag);
1270                 }
1271     case EVP_CTRL_COPY: {
1272                         EVP_CIPHER_CTX *out = ptr;
1273       struct ossl_gost_cipher_ctx *in_cctx  = EVP_CIPHER_CTX_get_cipher_data(ctx);
1274       struct ossl_gost_cipher_ctx *out_cctx = EVP_CIPHER_CTX_get_cipher_data(out);
1275
1276                         if (in_cctx->omac_ctx == out_cctx->omac_ctx) {
1277                                 out_cctx->omac_ctx = EVP_MD_CTX_new();
1278                                 if (out_cctx->omac_ctx == NULL) {
1279                                         GOSTerr(GOST_F_MAGMA_CIPHER_CTL_ACPKM_OMAC, ERR_R_MALLOC_FAILURE);
1280                                         return -1;
1281                                 }
1282                         }
1283                         return EVP_MD_CTX_copy(out_cctx->omac_ctx, in_cctx->omac_ctx);
1284                 }
1285                 default:
1286                         return magma_cipher_ctl(ctx, type, arg, ptr);
1287                         break;
1288         }
1289 }
1290
1291 /* Set cipher parameters from ASN1 structure */
1292 static int gost89_set_asn1_parameters(EVP_CIPHER_CTX *ctx, ASN1_TYPE *params)
1293 {
1294     int len = 0;
1295     unsigned char *buf = NULL;
1296     unsigned char *p = NULL;
1297     struct ossl_gost_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
1298     GOST_CIPHER_PARAMS *gcp = GOST_CIPHER_PARAMS_new();
1299     ASN1_OCTET_STRING *os = NULL;
1300     if (!gcp) {
1301         GOSTerr(GOST_F_GOST89_SET_ASN1_PARAMETERS, ERR_R_MALLOC_FAILURE);
1302         return 0;
1303     }
1304     if (!ASN1_OCTET_STRING_set
1305         (gcp->iv, EVP_CIPHER_CTX_iv(ctx), EVP_CIPHER_CTX_iv_length(ctx))) {
1306         GOST_CIPHER_PARAMS_free(gcp);
1307         GOSTerr(GOST_F_GOST89_SET_ASN1_PARAMETERS, ERR_R_MALLOC_FAILURE);
1308         return 0;
1309     }
1310     ASN1_OBJECT_free(gcp->enc_param_set);
1311     gcp->enc_param_set = OBJ_nid2obj(c->paramNID);
1312
1313     len = i2d_GOST_CIPHER_PARAMS(gcp, NULL);
1314     p = buf = OPENSSL_malloc(len);
1315     if (!buf) {
1316         GOST_CIPHER_PARAMS_free(gcp);
1317         GOSTerr(GOST_F_GOST89_SET_ASN1_PARAMETERS, ERR_R_MALLOC_FAILURE);
1318         return 0;
1319     }
1320     i2d_GOST_CIPHER_PARAMS(gcp, &p);
1321     GOST_CIPHER_PARAMS_free(gcp);
1322
1323     os = ASN1_OCTET_STRING_new();
1324
1325     if (!os || !ASN1_OCTET_STRING_set(os, buf, len)) {
1326         OPENSSL_free(buf);
1327         GOSTerr(GOST_F_GOST89_SET_ASN1_PARAMETERS, ERR_R_MALLOC_FAILURE);
1328         return 0;
1329     }
1330     OPENSSL_free(buf);
1331
1332     ASN1_TYPE_set(params, V_ASN1_SEQUENCE, os);
1333     return 1;
1334 }
1335
1336 /* Store parameters into ASN1 structure */
1337 static int gost89_get_asn1_parameters(EVP_CIPHER_CTX *ctx, ASN1_TYPE *params)
1338 {
1339     int len;
1340     GOST_CIPHER_PARAMS *gcp = NULL;
1341     unsigned char *p;
1342     struct ossl_gost_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
1343     int nid;
1344
1345     if (ASN1_TYPE_get(params) != V_ASN1_SEQUENCE) {
1346         return -1;
1347     }
1348
1349     p = params->value.sequence->data;
1350
1351     gcp = d2i_GOST_CIPHER_PARAMS(NULL, (const unsigned char **)&p,
1352                                  params->value.sequence->length);
1353
1354     len = gcp->iv->length;
1355     if (len != EVP_CIPHER_CTX_iv_length(ctx)) {
1356         GOST_CIPHER_PARAMS_free(gcp);
1357         GOSTerr(GOST_F_GOST89_GET_ASN1_PARAMETERS, GOST_R_INVALID_IV_LENGTH);
1358         return -1;
1359     }
1360
1361     nid = OBJ_obj2nid(gcp->enc_param_set);
1362     if (nid == NID_undef) {
1363         GOST_CIPHER_PARAMS_free(gcp);
1364         GOSTerr(GOST_F_GOST89_GET_ASN1_PARAMETERS,
1365                 GOST_R_INVALID_CIPHER_PARAM_OID);
1366         return -1;
1367     }
1368
1369     if (!gost_cipher_set_param(c, nid)) {
1370         GOST_CIPHER_PARAMS_free(gcp);
1371         return -1;
1372     }
1373     /*XXX missing non-const accessor */
1374     memcpy((unsigned char *)EVP_CIPHER_CTX_original_iv(ctx), gcp->iv->data,
1375            EVP_CIPHER_CTX_iv_length(ctx));
1376
1377     GOST_CIPHER_PARAMS_free(gcp);
1378
1379     return 1;
1380 }
1381
1382 #define MAGMA_UKM_LEN 12
1383 static int magma_set_asn1_parameters (EVP_CIPHER_CTX *ctx, ASN1_TYPE *params)
1384 {
1385   struct ossl_gost_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
1386         c->key_meshing = 8192;
1387
1388         return gost2015_set_asn1_params(params, EVP_CIPHER_CTX_original_iv(ctx), 4,
1389                 c->kdf_seed);
1390 }
1391
1392 static int magma_get_asn1_parameters(EVP_CIPHER_CTX *ctx, ASN1_TYPE *params)
1393 {
1394   struct ossl_gost_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
1395         unsigned char iv[16];
1396
1397         c->key_meshing = 8192;
1398
1399         if (gost2015_get_asn1_params(params, MAGMA_UKM_LEN, iv, 4, c->kdf_seed) < 0)
1400             return -1;
1401
1402         memcpy(EVP_CIPHER_CTX_iv_noconst(ctx), iv, sizeof(iv));
1403         memcpy((unsigned char *)EVP_CIPHER_CTX_original_iv(ctx), iv, sizeof(iv));
1404         /* Key meshing 8 kb*/
1405         c->key_meshing = 8192;
1406
1407         return 1;
1408 }
1409
1410 static int gost_imit_init(EVP_MD_CTX *ctx, gost_subst_block * block)
1411 {
1412     struct ossl_gost_imit_ctx *c = EVP_MD_CTX_md_data(ctx);
1413     memset(c->buffer, 0, sizeof(c->buffer));
1414     memset(c->partial_block, 0, sizeof(c->partial_block));
1415     c->count = 0;
1416     c->bytes_left = 0;
1417     c->key_meshing = 1;
1418     c->dgst_size = 4;
1419     gost_init(&(c->cctx), block);
1420     return 1;
1421 }
1422
1423 static int gost_imit_init_cpa(EVP_MD_CTX *ctx)
1424 {
1425     return gost_imit_init(ctx, &Gost28147_CryptoProParamSetA);
1426 }
1427
1428 static int gost_imit_init_cp_12(EVP_MD_CTX *ctx)
1429 {
1430     return gost_imit_init(ctx, &Gost28147_TC26ParamSetZ);
1431 }
1432
1433 static void mac_block_mesh(struct ossl_gost_imit_ctx *c,
1434                            const unsigned char *data)
1435 {
1436     /*
1437      * We are using NULL for iv because CryptoPro doesn't interpret
1438      * internal state of MAC algorithm as iv during keymeshing (but does
1439      * initialize internal state from iv in key transport
1440      */
1441     assert(c->count % 8 == 0 && c->count <= 1024);
1442     if (c->key_meshing && c->count == 1024) {
1443         cryptopro_key_meshing(&(c->cctx), NULL);
1444     }
1445     mac_block(&(c->cctx), c->buffer, data);
1446     c->count = c->count % 1024 + 8;
1447 }
1448
1449 static int gost_imit_update(EVP_MD_CTX *ctx, const void *data, size_t count)
1450 {
1451     struct ossl_gost_imit_ctx *c = EVP_MD_CTX_md_data(ctx);
1452     const unsigned char *p = data;
1453     size_t bytes = count;
1454     if (!(c->key_set)) {
1455         GOSTerr(GOST_F_GOST_IMIT_UPDATE, GOST_R_MAC_KEY_NOT_SET);
1456         return 0;
1457     }
1458     if (c->bytes_left) {
1459         size_t i;
1460         for (i = c->bytes_left; i < 8 && bytes > 0; bytes--, i++, p++) {
1461             c->partial_block[i] = *p;
1462         }
1463         if (i == 8) {
1464             mac_block_mesh(c, c->partial_block);
1465         } else {
1466             c->bytes_left = i;
1467             return 1;
1468         }
1469     }
1470     while (bytes > 8) {
1471         mac_block_mesh(c, p);
1472         p += 8;
1473         bytes -= 8;
1474     }
1475     if (bytes > 0) {
1476         memcpy(c->partial_block, p, bytes);
1477     }
1478     c->bytes_left = bytes;
1479     return 1;
1480 }
1481
1482 static int gost_imit_final(EVP_MD_CTX *ctx, unsigned char *md)
1483 {
1484     struct ossl_gost_imit_ctx *c = EVP_MD_CTX_md_data(ctx);
1485     if (!c->key_set) {
1486         GOSTerr(GOST_F_GOST_IMIT_FINAL, GOST_R_MAC_KEY_NOT_SET);
1487         return 0;
1488     }
1489     if (c->count == 0 && c->bytes_left) {
1490         unsigned char buffer[8];
1491         memset(buffer, 0, 8);
1492         gost_imit_update(ctx, buffer, 8);
1493     }
1494     if (c->bytes_left) {
1495         int i;
1496         for (i = c->bytes_left; i < 8; i++) {
1497             c->partial_block[i] = 0;
1498         }
1499         mac_block_mesh(c, c->partial_block);
1500     }
1501     get_mac(c->buffer, 8 * c->dgst_size, md);
1502     return 1;
1503 }
1504
1505 static int gost_imit_ctrl(EVP_MD_CTX *ctx, int type, int arg, void *ptr)
1506 {
1507     switch (type) {
1508     case EVP_MD_CTRL_KEY_LEN:
1509         *((unsigned int *)(ptr)) = 32;
1510         return 1;
1511     case EVP_MD_CTRL_SET_KEY:
1512         {
1513             struct ossl_gost_imit_ctx *gost_imit_ctx = EVP_MD_CTX_md_data(ctx);
1514
1515             if (EVP_MD_meth_get_init(EVP_MD_CTX_md(ctx)) (ctx) <= 0) {
1516                 GOSTerr(GOST_F_GOST_IMIT_CTRL, GOST_R_MAC_KEY_NOT_SET);
1517                 return 0;
1518             }
1519             EVP_MD_CTX_set_flags(ctx, EVP_MD_CTX_FLAG_NO_INIT);
1520
1521             if (arg == 0) {
1522                 struct gost_mac_key *key = (struct gost_mac_key *)ptr;
1523                 if (key->mac_param_nid != NID_undef) {
1524                     const struct gost_cipher_info *param =
1525                         get_encryption_params(OBJ_nid2obj(key->mac_param_nid));
1526                     if (param == NULL) {
1527                         GOSTerr(GOST_F_GOST_IMIT_CTRL,
1528                                 GOST_R_INVALID_MAC_PARAMS);
1529                         return 0;
1530                     }
1531                     gost_init(&(gost_imit_ctx->cctx), param->sblock);
1532                 }
1533                 gost_key(&(gost_imit_ctx->cctx), key->key);
1534                 gost_imit_ctx->key_set = 1;
1535
1536                 return 1;
1537             } else if (arg == 32) {
1538                 gost_key(&(gost_imit_ctx->cctx), ptr);
1539                 gost_imit_ctx->key_set = 1;
1540                 return 1;
1541             }
1542             GOSTerr(GOST_F_GOST_IMIT_CTRL, GOST_R_INVALID_MAC_KEY_SIZE);
1543             return 0;
1544         }
1545     case EVP_MD_CTRL_XOF_LEN:
1546         {
1547             struct ossl_gost_imit_ctx *c = EVP_MD_CTX_md_data(ctx);
1548             if (arg < 1 || arg > 8) {
1549                 GOSTerr(GOST_F_GOST_IMIT_CTRL, GOST_R_INVALID_MAC_SIZE);
1550                 return 0;
1551             }
1552             c->dgst_size = arg;
1553             return 1;
1554         }
1555
1556     default:
1557         return 0;
1558     }
1559 }
1560
1561 static int gost_imit_copy(EVP_MD_CTX *to, const EVP_MD_CTX *from)
1562 {
1563     if (EVP_MD_CTX_md_data(to) && EVP_MD_CTX_md_data(from)) {
1564         memcpy(EVP_MD_CTX_md_data(to), EVP_MD_CTX_md_data(from),
1565                sizeof(struct ossl_gost_imit_ctx));
1566     }
1567     return 1;
1568 }
1569
1570 /* Clean up imit ctx */
1571 static int gost_imit_cleanup(EVP_MD_CTX *ctx)
1572 {
1573     memset(EVP_MD_CTX_md_data(ctx), 0, sizeof(struct ossl_gost_imit_ctx));
1574     return 1;
1575 }
1576 /* vim: set expandtab cinoptions=\:0,l1,t0,g0,(0 sw=4 : */