]> www.wagner.pp.ru Git - openssl-gost/engine.git/blob - gost_crypt.c
gost_crypt: Allow templates in GOST_cipher
[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 /* set/get cipher parameters */
47 static int gost89_set_asn1_parameters(EVP_CIPHER_CTX *ctx, ASN1_TYPE *params);
48 static int gost89_get_asn1_parameters(EVP_CIPHER_CTX *ctx, ASN1_TYPE *params);
49 /* Control function */
50 static int gost_cipher_ctl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr);
51
52 static int magma_cipher_init(EVP_CIPHER_CTX *ctx, const unsigned char *key,
53                              const unsigned char *iv, int enc);
54 static int magma_cipher_init_ctr_acpkm_omac(EVP_CIPHER_CTX *ctx, const unsigned char *key,
55                              const unsigned char *iv, int enc);
56 /* Handles block of data in CBC mode */
57 static int magma_cipher_do_cbc(EVP_CIPHER_CTX *ctx, unsigned char *out,
58                                const unsigned char *in, size_t inl);
59 static int magma_cipher_do_ctr(EVP_CIPHER_CTX *ctx, unsigned char *out,
60                                const unsigned char *in, size_t inl);
61
62 static int magma_cipher_do_ctr_acpkm_omac(EVP_CIPHER_CTX *ctx, unsigned char *out,
63                                const unsigned char *in, size_t inl);
64
65 /* set/get cipher parameters */
66 static int magma_set_asn1_parameters(EVP_CIPHER_CTX *ctx, ASN1_TYPE *params);
67 static int magma_get_asn1_parameters(EVP_CIPHER_CTX *ctx, ASN1_TYPE *params);
68 /* Control function */
69 static int magma_cipher_ctl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr);
70 static int magma_cipher_ctl_acpkm_omac(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr);
71
72 /*
73  * Single level template accessor.
74  * Note: that you cannot template 0 value.
75  */
76 #define TPL(st,field) ( \
77     ((st)->field) ?: TPL_VAL(st,field) \
78 )
79
80 #define TPL_VAL(st,field) ( \
81     ((st)->template ? (st)->template->field : 0) \
82 )
83
84 EVP_CIPHER *GOST_init_cipher(GOST_cipher *c)
85 {
86     if (c->cipher)
87         return c->cipher;
88
89     EVP_CIPHER *cipher;
90     if (!(cipher = EVP_CIPHER_meth_new(c->nid, TPL(c, block_size), TPL(c, key_len)))
91         || !EVP_CIPHER_meth_set_iv_length(cipher, TPL(c, iv_len))
92         || !EVP_CIPHER_meth_set_flags(cipher, c->flags | TPL_VAL(c, flags))
93         || !EVP_CIPHER_meth_set_init(cipher, TPL(c, init))
94         || !EVP_CIPHER_meth_set_do_cipher(cipher, TPL(c, do_cipher))
95         || !EVP_CIPHER_meth_set_cleanup(cipher, TPL(c, cleanup))
96         || !EVP_CIPHER_meth_set_impl_ctx_size(cipher, TPL(c, ctx_size))
97         || !EVP_CIPHER_meth_set_set_asn1_params(cipher, TPL(c, set_asn1_parameters))
98         || !EVP_CIPHER_meth_set_get_asn1_params(cipher, TPL(c, get_asn1_parameters))
99         || !EVP_CIPHER_meth_set_ctrl(cipher, TPL(c, ctrl))) {
100         EVP_CIPHER_meth_free(cipher);
101         cipher = NULL;
102     }
103     c->cipher = cipher;
104     return c->cipher;
105 }
106
107 void GOST_deinit_cipher(GOST_cipher *c)
108 {
109     if (c->cipher) {
110         EVP_CIPHER_meth_free(c->cipher);
111         c->cipher = NULL;
112     }
113 }
114
115 static GOST_cipher gost_template_cipher = {
116     .block_size = 8,
117     .key_len = 32,
118     .iv_len = 8,
119     .flags = EVP_CIPH_CUSTOM_IV |
120         EVP_CIPH_RAND_KEY |
121         EVP_CIPH_ALWAYS_CALL_INIT,
122     .cleanup = gost_cipher_cleanup,
123     .ctx_size = sizeof(struct ossl_gost_cipher_ctx),
124     .set_asn1_parameters = gost89_set_asn1_parameters,
125     .get_asn1_parameters = gost89_get_asn1_parameters,
126     .ctrl = gost_cipher_ctl,
127 };
128
129 GOST_cipher Gost28147_89_cipher = {
130     .nid = NID_id_Gost28147_89,
131     .template = &gost_template_cipher,
132     .block_size = 1,
133     .flags = EVP_CIPH_CFB_MODE |
134         EVP_CIPH_NO_PADDING,
135     .init = gost_cipher_init,
136     .do_cipher = gost_cipher_do_cfb,
137 };
138
139 GOST_cipher Gost28147_89_cbc_cipher = {
140     .nid = NID_gost89_cbc,
141     .template = &gost_template_cipher,
142     .flags = EVP_CIPH_CBC_MODE,
143     .init = gost_cipher_init_cbc,
144     .do_cipher = gost_cipher_do_cbc,
145 };
146
147 GOST_cipher Gost28147_89_cnt_cipher = {
148     .nid = NID_gost89_cnt,
149     .template = &gost_template_cipher,
150     .block_size = 1,
151     .flags = EVP_CIPH_OFB_MODE |
152         EVP_CIPH_NO_PADDING,
153     .init = gost_cipher_init_cpa,
154     .do_cipher = gost_cipher_do_cnt,
155 };
156
157 GOST_cipher Gost28147_89_cnt_12_cipher = {
158     .nid = NID_gost89_cnt_12,
159     .template = &gost_template_cipher,
160     .block_size = 1,
161     .flags = EVP_CIPH_OFB_MODE |
162         EVP_CIPH_NO_PADDING,
163     .init = gost_cipher_init_cp_12,
164     .do_cipher = gost_cipher_do_cnt,
165 };
166
167 static GOST_cipher magma_template_cipher = {
168     .block_size = 8,
169     .key_len = 32,
170     .iv_len = 8,
171     .flags = EVP_CIPH_CUSTOM_IV |
172         EVP_CIPH_RAND_KEY |
173         EVP_CIPH_ALWAYS_CALL_INIT,
174     .cleanup = gost_cipher_cleanup,
175     .ctx_size = sizeof(struct ossl_gost_cipher_ctx),
176     .set_asn1_parameters = magma_set_asn1_parameters,
177     .get_asn1_parameters = magma_get_asn1_parameters,
178     .do_cipher = magma_cipher_do_ctr,
179     .ctrl = magma_cipher_ctl,
180 };
181
182 GOST_cipher magma_ctr_cipher = {
183     .nid = NID_magma_ctr,
184     .template = &magma_template_cipher,
185     .block_size = 1,
186     .iv_len = 4,
187     .flags = EVP_CIPH_CTR_MODE |
188         EVP_CIPH_NO_PADDING,
189     .init = magma_cipher_init,
190 };
191
192 GOST_cipher magma_ctr_acpkm_cipher = {
193     .nid = NID_magma_ctr_acpkm,
194     .template = &magma_template_cipher,
195     .block_size = 1,
196     .iv_len = 4,
197     .flags = EVP_CIPH_CTR_MODE |
198         EVP_CIPH_NO_PADDING,
199     .init = magma_cipher_init,
200 };
201
202 GOST_cipher magma_ctr_acpkm_omac_cipher = {
203     .nid = NID_magma_ctr_acpkm_omac,
204     .template = &magma_template_cipher,
205     .block_size = 1,
206     .iv_len = 4,
207     .flags = EVP_CIPH_CTR_MODE |
208         EVP_CIPH_NO_PADDING |
209         EVP_CIPH_CUSTOM_COPY |
210         EVP_CIPH_FLAG_CUSTOM_CIPHER |
211         EVP_CIPH_FLAG_CIPHER_WITH_MAC,
212     .init = magma_cipher_init_ctr_acpkm_omac,
213     .do_cipher = magma_cipher_do_ctr_acpkm_omac,
214     .ctrl = magma_cipher_ctl_acpkm_omac,
215 };
216
217 GOST_cipher magma_cbc_cipher = {
218     .nid = NID_magma_cbc,
219     .template = &gost_template_cipher,
220     .flags = EVP_CIPH_CBC_MODE,
221     .init = magma_cipher_init,
222     .do_cipher = magma_cipher_do_cbc,
223 };
224
225 /* Implementation of GOST 28147-89 in MAC (imitovstavka) mode */
226 /* Init functions which set specific parameters */
227 static int gost_imit_init_cpa(EVP_MD_CTX *ctx);
228 static int gost_imit_init_cp_12(EVP_MD_CTX *ctx);
229 /* process block of data */
230 static int gost_imit_update(EVP_MD_CTX *ctx, const void *data, size_t count);
231 /* Return computed value */
232 static int gost_imit_final(EVP_MD_CTX *ctx, unsigned char *md);
233 /* Copies context */
234 static int gost_imit_copy(EVP_MD_CTX *to, const EVP_MD_CTX *from);
235 static int gost_imit_cleanup(EVP_MD_CTX *ctx);
236 /* Control function, knows how to set MAC key.*/
237 static int gost_imit_ctrl(EVP_MD_CTX *ctx, int type, int arg, void *ptr);
238
239 static EVP_MD *_hidden_Gost28147_89_MAC_md = NULL;
240 static EVP_MD *_hidden_Gost28147_89_12_MAC_md = NULL;
241
242 EVP_MD *imit_gost_cpa(void)
243 {
244     if (_hidden_Gost28147_89_MAC_md == NULL) {
245         EVP_MD *md;
246
247         if ((md = EVP_MD_meth_new(NID_id_Gost28147_89_MAC, NID_undef)) == NULL
248             || !EVP_MD_meth_set_result_size(md, 4)
249             || !EVP_MD_meth_set_input_blocksize(md, 8)
250             || !EVP_MD_meth_set_app_datasize(md,
251                                              sizeof(struct ossl_gost_imit_ctx))
252             || !EVP_MD_meth_set_flags(md, EVP_MD_FLAG_XOF)
253             || !EVP_MD_meth_set_init(md, gost_imit_init_cpa)
254             || !EVP_MD_meth_set_update(md, gost_imit_update)
255             || !EVP_MD_meth_set_final(md, gost_imit_final)
256             || !EVP_MD_meth_set_copy(md, gost_imit_copy)
257             || !EVP_MD_meth_set_cleanup(md, gost_imit_cleanup)
258             || !EVP_MD_meth_set_ctrl(md, gost_imit_ctrl)) {
259             EVP_MD_meth_free(md);
260             md = NULL;
261         }
262         _hidden_Gost28147_89_MAC_md = md;
263     }
264     return _hidden_Gost28147_89_MAC_md;
265 }
266
267 void imit_gost_cpa_destroy(void)
268 {
269     EVP_MD_meth_free(_hidden_Gost28147_89_MAC_md);
270     _hidden_Gost28147_89_MAC_md = NULL;
271 }
272
273 EVP_MD *imit_gost_cp_12(void)
274 {
275     if (_hidden_Gost28147_89_12_MAC_md == NULL) {
276         EVP_MD *md;
277
278         if ((md = EVP_MD_meth_new(NID_gost_mac_12, NID_undef)) == NULL
279             || !EVP_MD_meth_set_result_size(md, 4)
280             || !EVP_MD_meth_set_input_blocksize(md, 8)
281             || !EVP_MD_meth_set_app_datasize(md,
282                                              sizeof(struct ossl_gost_imit_ctx))
283             || !EVP_MD_meth_set_flags(md, EVP_MD_FLAG_XOF)
284             || !EVP_MD_meth_set_init(md, gost_imit_init_cp_12)
285             || !EVP_MD_meth_set_update(md, gost_imit_update)
286             || !EVP_MD_meth_set_final(md, gost_imit_final)
287             || !EVP_MD_meth_set_copy(md, gost_imit_copy)
288             || !EVP_MD_meth_set_cleanup(md, gost_imit_cleanup)
289             || !EVP_MD_meth_set_ctrl(md, gost_imit_ctrl)) {
290             EVP_MD_meth_free(md);
291             md = NULL;
292         }
293         _hidden_Gost28147_89_12_MAC_md = md;
294     }
295     return _hidden_Gost28147_89_12_MAC_md;
296 }
297
298 void imit_gost_cp_12_destroy(void)
299 {
300     EVP_MD_meth_free(_hidden_Gost28147_89_12_MAC_md);
301     _hidden_Gost28147_89_12_MAC_md = NULL;
302 }
303
304 /*
305  * Correspondence between gost parameter OIDs and substitution blocks
306  * NID field is filed by register_gost_NID function in engine.c
307  * upon engine initialization
308  */
309
310 struct gost_cipher_info gost_cipher_list[] = {
311     /*- NID *//*
312      * Subst block
313      *//*
314      * Key meshing
315      */
316     /*
317      * {NID_id_GostR3411_94_CryptoProParamSet,&GostR3411_94_CryptoProParamSet,0},
318      */
319     {NID_id_Gost28147_89_CryptoPro_A_ParamSet, &Gost28147_CryptoProParamSetA,
320      1},
321     {NID_id_Gost28147_89_CryptoPro_B_ParamSet, &Gost28147_CryptoProParamSetB,
322      1},
323     {NID_id_Gost28147_89_CryptoPro_C_ParamSet, &Gost28147_CryptoProParamSetC,
324      1},
325     {NID_id_Gost28147_89_CryptoPro_D_ParamSet, &Gost28147_CryptoProParamSetD,
326      1},
327     {NID_id_tc26_gost_28147_param_Z, &Gost28147_TC26ParamSetZ, 1},
328     {NID_id_Gost28147_89_TestParamSet, &Gost28147_TestParamSet, 1},
329     {NID_undef, NULL, 0}
330 };
331
332 /*
333  * get encryption parameters from crypto network settings FIXME For now we
334  * use environment var CRYPT_PARAMS as place to store these settings.
335  * Actually, it is better to use engine control command, read from
336  * configuration file to set them
337  */
338 const struct gost_cipher_info *get_encryption_params(ASN1_OBJECT *obj)
339 {
340     int nid;
341     struct gost_cipher_info *param;
342     if (!obj) {
343         const char *params = get_gost_engine_param(GOST_PARAM_CRYPT_PARAMS);
344         if (!params || !strlen(params)) {
345             int i;
346             for (i = 0; gost_cipher_list[i].nid != NID_undef; i++)
347                 if (gost_cipher_list[i].nid == NID_id_tc26_gost_28147_param_Z)
348                     return &gost_cipher_list[i];
349             return &gost_cipher_list[0];
350         }
351
352         nid = OBJ_txt2nid(params);
353         if (nid == NID_undef) {
354             GOSTerr(GOST_F_GET_ENCRYPTION_PARAMS,
355                     GOST_R_INVALID_CIPHER_PARAM_OID);
356             ERR_add_error_data(3, "Unsupported CRYPT_PARAMS='",
357                 params, "' specified in environment or in config");
358             return NULL;
359         }
360     } else {
361         nid = OBJ_obj2nid(obj);
362     }
363     for (param = gost_cipher_list; param->sblock != NULL && param->nid != nid;
364          param++) ;
365     if (!param->sblock) {
366         GOSTerr(GOST_F_GET_ENCRYPTION_PARAMS, GOST_R_INVALID_CIPHER_PARAMS);
367         return NULL;
368     }
369     return param;
370 }
371
372 /* Sets cipher param from paramset NID. */
373 static int gost_cipher_set_param(struct ossl_gost_cipher_ctx *c, int nid)
374 {
375     const struct gost_cipher_info *param;
376     param = get_encryption_params((nid == NID_undef ? NULL : OBJ_nid2obj(nid)));
377     if (!param)
378         return 0;
379
380     c->paramNID = param->nid;
381     c->key_meshing = param->key_meshing;
382     c->count = 0;
383     gost_init(&(c->cctx), param->sblock);
384     return 1;
385 }
386
387 /* Initializes EVP_CIPHER_CTX by paramset NID */
388 static int gost_cipher_init_param(EVP_CIPHER_CTX *ctx,
389                                   const unsigned char *key,
390                                   const unsigned char *iv, int enc,
391                                   int paramNID, int mode)
392 {
393     struct ossl_gost_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
394     if (EVP_CIPHER_CTX_get_app_data(ctx) == NULL) {
395         if (!gost_cipher_set_param(c, paramNID))
396             return 0;
397         EVP_CIPHER_CTX_set_app_data(ctx, EVP_CIPHER_CTX_get_cipher_data(ctx));
398     }
399     if (key)
400         gost_key(&(c->cctx), key);
401     if (iv) {
402         memcpy((unsigned char *)EVP_CIPHER_CTX_original_iv(ctx), iv,
403                EVP_CIPHER_CTX_iv_length(ctx));
404     }
405     memcpy(EVP_CIPHER_CTX_iv_noconst(ctx),
406            EVP_CIPHER_CTX_original_iv(ctx), EVP_CIPHER_CTX_iv_length(ctx));
407     return 1;
408 }
409
410 static int gost_cipher_init_cnt(EVP_CIPHER_CTX *ctx,
411                                 const unsigned char *key,
412                                 const unsigned char *iv,
413                                 gost_subst_block * block)
414 {
415     struct ossl_gost_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
416     gost_init(&(c->cctx), block);
417     c->key_meshing = 1;
418     c->count = 0;
419     if (key)
420         gost_key(&(c->cctx), key);
421     if (iv) {
422         memcpy((unsigned char *)EVP_CIPHER_CTX_original_iv(ctx), iv,
423                EVP_CIPHER_CTX_iv_length(ctx));
424     }
425     memcpy(EVP_CIPHER_CTX_iv_noconst(ctx),
426            EVP_CIPHER_CTX_original_iv(ctx), EVP_CIPHER_CTX_iv_length(ctx));
427     return 1;
428 }
429
430 static int gost_cipher_init_cpa(EVP_CIPHER_CTX *ctx, const unsigned char *key,
431                                 const unsigned char *iv, int enc)
432 {
433     return gost_cipher_init_cnt(ctx, key, iv, &Gost28147_CryptoProParamSetA);
434 }
435
436 static int gost_cipher_init_cp_12(EVP_CIPHER_CTX *ctx,
437                                   const unsigned char *key,
438                                   const unsigned char *iv, int enc)
439 {
440     return gost_cipher_init_cnt(ctx, key, iv, &Gost28147_TC26ParamSetZ);
441 }
442
443 /* Initializes EVP_CIPHER_CTX with default values */
444 int gost_cipher_init(EVP_CIPHER_CTX *ctx, const unsigned char *key,
445                      const unsigned char *iv, int enc)
446 {
447     return gost_cipher_init_param(ctx, key, iv, enc, NID_undef,
448                                   EVP_CIPH_CFB_MODE);
449 }
450
451 /* Initializes EVP_CIPHER_CTX with default values */
452 int gost_cipher_init_cbc(EVP_CIPHER_CTX *ctx, const unsigned char *key,
453                          const unsigned char *iv, int enc)
454 {
455     return gost_cipher_init_param(ctx, key, iv, enc, NID_undef,
456                                   EVP_CIPH_CBC_MODE);
457 }
458
459 /* Initializes EVP_CIPHER_CTX with default values */
460 int magma_cipher_init(EVP_CIPHER_CTX *ctx, const unsigned char *key,
461                       const unsigned char *iv, int enc)
462 {
463     struct ossl_gost_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
464     /* FIXME this is just initializtion check */
465     if (EVP_CIPHER_CTX_get_app_data(ctx) == NULL) {
466         if (!gost_cipher_set_param(c, NID_id_tc26_gost_28147_param_Z))
467             return 0;
468         EVP_CIPHER_CTX_set_app_data(ctx, EVP_CIPHER_CTX_get_cipher_data(ctx));
469
470         if (enc) {
471             if (init_zero_kdf_seed(c->kdf_seed) == 0)
472                 return -1;
473         }
474     }
475
476     if (key)
477         magma_key(&(c->cctx), key);
478     if (iv) {
479         memcpy((unsigned char *)EVP_CIPHER_CTX_original_iv(ctx), iv,
480                EVP_CIPHER_CTX_iv_length(ctx));
481     }
482     memcpy(EVP_CIPHER_CTX_iv_noconst(ctx),
483            EVP_CIPHER_CTX_original_iv(ctx), EVP_CIPHER_CTX_iv_length(ctx));
484
485     if (EVP_CIPHER_CTX_nid(ctx) == NID_magma_ctr_acpkm
486      || EVP_CIPHER_CTX_nid(ctx) == NID_magma_ctr_acpkm_omac) {
487        c->key_meshing = 1024;
488     } else {
489        c->key_meshing = 0;
490     }
491
492     return 1;
493 }
494
495 /* Initializes EVP_CIPHER_CTX with default values */
496 int magma_cipher_init_ctr_acpkm_omac(EVP_CIPHER_CTX *ctx, const unsigned char *key,
497                       const unsigned char *iv, int enc)
498 {
499         if (key) {
500     struct ossl_gost_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
501                 unsigned char cipher_key[32];
502                 c->omac_ctx = EVP_MD_CTX_new();
503
504                 if (c->omac_ctx == NULL) {
505                     GOSTerr(GOST_F_MAGMA_CIPHER_INIT_CTR_ACPKM_OMAC, ERR_R_MALLOC_FAILURE);
506                                 return 0;
507                 }
508
509                 if (gost2015_acpkm_omac_init(NID_magma_mac, enc, key,
510                                  c->omac_ctx, cipher_key, c->kdf_seed) != 1) {
511                     EVP_MD_CTX_free(c->omac_ctx);
512                                 c->omac_ctx = NULL;
513                     return 0;
514                 }
515
516                 return magma_cipher_init(ctx, cipher_key, iv, enc);
517         }
518
519         return magma_cipher_init(ctx, key, iv, enc);
520 }
521
522 /*
523  * Wrapper around gostcrypt function from gost89.c which perform key meshing
524  * when nesseccary
525  */
526 static void gost_crypt_mesh(void *ctx, unsigned char *iv, unsigned char *buf)
527 {
528     struct ossl_gost_cipher_ctx *c = ctx;
529     assert(c->count % 8 == 0 && c->count <= 1024);
530     if (c->key_meshing && c->count == 1024) {
531         cryptopro_key_meshing(&(c->cctx), iv);
532     }
533     gostcrypt(&(c->cctx), iv, buf);
534     c->count = c->count % 1024 + 8;
535 }
536
537 static void gost_cnt_next(void *ctx, unsigned char *iv, unsigned char *buf)
538 {
539     struct ossl_gost_cipher_ctx *c = ctx;
540     word32 g, go;
541     unsigned char buf1[8];
542     assert(c->count % 8 == 0 && c->count <= 1024);
543     if (c->key_meshing && c->count == 1024) {
544         cryptopro_key_meshing(&(c->cctx), iv);
545     }
546     if (c->count == 0) {
547         gostcrypt(&(c->cctx), iv, buf1);
548     } else {
549         memcpy(buf1, iv, 8);
550     }
551     g = buf1[0] | (buf1[1] << 8) | (buf1[2] << 16) | ((word32) buf1[3] << 24);
552     g += 0x01010101;
553     buf1[0] = (unsigned char)(g & 0xff);
554     buf1[1] = (unsigned char)((g >> 8) & 0xff);
555     buf1[2] = (unsigned char)((g >> 16) & 0xff);
556     buf1[3] = (unsigned char)((g >> 24) & 0xff);
557     g = buf1[4] | (buf1[5] << 8) | (buf1[6] << 16) | ((word32) buf1[7] << 24);
558     go = g;
559     g += 0x01010104;
560     if (go > g)                 /* overflow */
561         g++;
562     buf1[4] = (unsigned char)(g & 0xff);
563     buf1[5] = (unsigned char)((g >> 8) & 0xff);
564     buf1[6] = (unsigned char)((g >> 16) & 0xff);
565     buf1[7] = (unsigned char)((g >> 24) & 0xff);
566     memcpy(iv, buf1, 8);
567     gostcrypt(&(c->cctx), buf1, buf);
568     c->count = c->count % 1024 + 8;
569 }
570
571 /* GOST encryption in CBC mode */
572 int gost_cipher_do_cbc(EVP_CIPHER_CTX *ctx, unsigned char *out,
573                        const unsigned char *in, size_t inl)
574 {
575     unsigned char b[8];
576     const unsigned char *in_ptr = in;
577     unsigned char *out_ptr = out;
578     int i;
579     struct ossl_gost_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
580     unsigned char *iv = EVP_CIPHER_CTX_iv_noconst(ctx);
581     if (EVP_CIPHER_CTX_encrypting(ctx)) {
582         while (inl > 0) {
583
584             for (i = 0; i < 8; i++) {
585                 b[i] = iv[i] ^ in_ptr[i];
586             }
587             gostcrypt(&(c->cctx), b, out_ptr);
588             memcpy(iv, out_ptr, 8);
589             out_ptr += 8;
590             in_ptr += 8;
591             inl -= 8;
592         }
593     } else {
594         while (inl > 0) {
595             gostdecrypt(&(c->cctx), in_ptr, b);
596             for (i = 0; i < 8; i++) {
597                 out_ptr[i] = iv[i] ^ b[i];
598             }
599             memcpy(iv, in_ptr, 8);
600             out_ptr += 8;
601             in_ptr += 8;
602             inl -= 8;
603         }
604     }
605     return 1;
606 }
607
608 /* MAGMA encryption in CBC mode */
609 int magma_cipher_do_cbc(EVP_CIPHER_CTX *ctx, unsigned char *out,
610                         const unsigned char *in, size_t inl)
611 {
612     unsigned char b[8];
613     unsigned char d[8];
614     const unsigned char *in_ptr = in;
615     unsigned char *out_ptr = out;
616     int i;
617     struct ossl_gost_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
618     unsigned char *iv = EVP_CIPHER_CTX_iv_noconst(ctx);
619     if (EVP_CIPHER_CTX_encrypting(ctx)) {
620         while (inl > 0) {
621
622             for (i = 0; i < 8; i++) {
623                 b[7 - i] = iv[i] ^ in_ptr[i];
624             }
625             gostcrypt(&(c->cctx), b, d);
626
627             for (i = 0; i < 8; i++) {
628                 out_ptr[7 - i] = d[i];
629             }
630             memcpy(iv, out_ptr, 8);
631             out_ptr += 8;
632             in_ptr += 8;
633             inl -= 8;
634         }
635     } else {
636         while (inl > 0) {
637             for (i = 0; i < 8; i++) {
638                 d[7 - i] = in_ptr[i];
639             }
640             gostdecrypt(&(c->cctx), d, b);
641             memcpy(d, in_ptr, 8);
642             for (i = 0; i < 8; i++) {
643                 out_ptr[i] = iv[i] ^ b[7 - i];
644             }
645             memcpy(iv, d, 8);
646             out_ptr += 8;
647             in_ptr += 8;
648             inl -= 8;
649         }
650     }
651     return 1;
652 }
653
654 /* increment counter (64-bit int) by 1 */
655 static void ctr64_inc(unsigned char *counter)
656 {
657     inc_counter(counter, 8);
658 }
659
660 /* MAGMA encryption in CTR mode */
661 static int magma_cipher_do_ctr(EVP_CIPHER_CTX *ctx, unsigned char *out,
662                                const unsigned char *in, size_t inl)
663 {
664     const unsigned char *in_ptr = in;
665     unsigned char *out_ptr = out;
666     size_t i = 0;
667     size_t j;
668     struct ossl_gost_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
669     unsigned char *buf = EVP_CIPHER_CTX_buf_noconst(ctx);
670     unsigned char *iv = EVP_CIPHER_CTX_iv_noconst(ctx);
671     unsigned char b[8];
672 /* Process partial blocks */
673     if (EVP_CIPHER_CTX_num(ctx)) {
674         for (j = EVP_CIPHER_CTX_num(ctx), i = 0; j < 8 && i < inl;
675              j++, i++, in_ptr++, out_ptr++) {
676             *out_ptr = buf[7 - j] ^ (*in_ptr);
677         }
678         if (j == 8) {
679             EVP_CIPHER_CTX_set_num(ctx, 0);
680         } else {
681             EVP_CIPHER_CTX_set_num(ctx, j);
682             return inl;
683         }
684     }
685
686 /* Process full blocks */
687     for (; i + 8 <= inl; i += 8, in_ptr += 8, out_ptr += 8) {
688         for (j = 0; j < 8; j++) {
689             b[7 - j] = iv[j];
690         }
691         gostcrypt(&(c->cctx), b, buf);
692         for (j = 0; j < 8; j++) {
693             out_ptr[j] = buf[7 - j] ^ in_ptr[j];
694         }
695         ctr64_inc(iv);
696         c->count += 8;
697         if (c->key_meshing && (c->count % c->key_meshing == 0))
698             acpkm_magma_key_meshing(&(c->cctx));
699     }
700
701 /* Process the rest of plaintext */
702     if (i < inl) {
703         for (j = 0; j < 8; j++) {
704             b[7 - j] = iv[j];
705         }
706         gostcrypt(&(c->cctx), b, buf);
707
708         for (j = 0; i < inl; j++, i++) {
709             out_ptr[j] = buf[7 - j] ^ in_ptr[j];
710         }
711
712         ctr64_inc(iv);
713         c->count += 8;
714         if (c->key_meshing && (c->count % c->key_meshing == 0))
715             acpkm_magma_key_meshing(&(c->cctx));
716
717         EVP_CIPHER_CTX_set_num(ctx, j);
718     } else {
719         EVP_CIPHER_CTX_set_num(ctx, 0);
720     }
721
722     return inl;
723 }
724
725 /* MAGMA encryption in CTR mode */
726 static int magma_cipher_do_ctr_acpkm_omac(EVP_CIPHER_CTX *ctx, unsigned char *out,
727                                const unsigned char *in, size_t inl)
728 {
729   struct ossl_gost_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
730
731         if (in == NULL && inl == 0) /* Final call */
732                 return gost2015_final_call(ctx, c->omac_ctx, MAGMA_MAC_MAX_SIZE, c->tag, magma_cipher_do_ctr);
733
734   if (in == NULL)
735       return -1;
736
737         /* As in and out can be the same pointer, process unencrypted here */
738         if (EVP_CIPHER_CTX_encrypting(ctx))
739                 EVP_DigestSignUpdate(c->omac_ctx, in, inl);
740
741   if (magma_cipher_do_ctr(ctx, out, in, inl) != inl)
742       return -1;
743
744         /* As in and out can be the same pointer, process decrypted here */
745         if (!EVP_CIPHER_CTX_encrypting(ctx))
746                 EVP_DigestSignUpdate(c->omac_ctx, out, inl);
747
748         return inl;
749 }
750 /* GOST encryption in CFB mode */
751 int gost_cipher_do_cfb(EVP_CIPHER_CTX *ctx, unsigned char *out,
752                        const unsigned char *in, size_t inl)
753 {
754     const unsigned char *in_ptr = in;
755     unsigned char *out_ptr = out;
756     size_t i = 0;
757     size_t j = 0;
758     unsigned char *buf = EVP_CIPHER_CTX_buf_noconst(ctx);
759     unsigned char *iv = EVP_CIPHER_CTX_iv_noconst(ctx);
760 /* process partial block if any */
761     if (EVP_CIPHER_CTX_num(ctx)) {
762         for (j = EVP_CIPHER_CTX_num(ctx), i = 0; j < 8 && i < inl;
763              j++, i++, in_ptr++, out_ptr++) {
764             if (!EVP_CIPHER_CTX_encrypting(ctx))
765                 buf[j + 8] = *in_ptr;
766             *out_ptr = buf[j] ^ (*in_ptr);
767             if (EVP_CIPHER_CTX_encrypting(ctx))
768                 buf[j + 8] = *out_ptr;
769         }
770         if (j == 8) {
771             memcpy(iv, buf + 8, 8);
772             EVP_CIPHER_CTX_set_num(ctx, 0);
773         } else {
774             EVP_CIPHER_CTX_set_num(ctx, j);
775             return 1;
776         }
777     }
778
779     for (; i + 8 < inl; i += 8, in_ptr += 8, out_ptr += 8) {
780         /*
781          * block cipher current iv
782          */
783         gost_crypt_mesh(EVP_CIPHER_CTX_get_cipher_data(ctx), iv, buf);
784         /*
785          * xor next block of input text with it and output it
786          */
787         /*
788          * output this block
789          */
790         if (!EVP_CIPHER_CTX_encrypting(ctx))
791             memcpy(iv, in_ptr, 8);
792         for (j = 0; j < 8; j++) {
793             out_ptr[j] = buf[j] ^ in_ptr[j];
794         }
795         /* Encrypt */
796         /* Next iv is next block of cipher text */
797         if (EVP_CIPHER_CTX_encrypting(ctx))
798             memcpy(iv, out_ptr, 8);
799     }
800 /* Process rest of buffer */
801     if (i < inl) {
802         gost_crypt_mesh(EVP_CIPHER_CTX_get_cipher_data(ctx), iv, buf);
803         if (!EVP_CIPHER_CTX_encrypting(ctx))
804             memcpy(buf + 8, in_ptr, inl - i);
805         for (j = 0; i < inl; j++, i++) {
806             out_ptr[j] = buf[j] ^ in_ptr[j];
807         }
808         EVP_CIPHER_CTX_set_num(ctx, j);
809         if (EVP_CIPHER_CTX_encrypting(ctx))
810             memcpy(buf + 8, out_ptr, j);
811     } else {
812         EVP_CIPHER_CTX_set_num(ctx, 0);
813     }
814     return 1;
815 }
816
817 static int gost_cipher_do_cnt(EVP_CIPHER_CTX *ctx, unsigned char *out,
818                               const unsigned char *in, size_t inl)
819 {
820     const unsigned char *in_ptr = in;
821     unsigned char *out_ptr = out;
822     size_t i = 0;
823     size_t j;
824     unsigned char *buf = EVP_CIPHER_CTX_buf_noconst(ctx);
825     unsigned char *iv = EVP_CIPHER_CTX_iv_noconst(ctx);
826 /* process partial block if any */
827     if (EVP_CIPHER_CTX_num(ctx)) {
828         for (j = EVP_CIPHER_CTX_num(ctx), i = 0; j < 8 && i < inl;
829              j++, i++, in_ptr++, out_ptr++) {
830             *out_ptr = buf[j] ^ (*in_ptr);
831         }
832         if (j == 8) {
833             EVP_CIPHER_CTX_set_num(ctx, 0);
834         } else {
835             EVP_CIPHER_CTX_set_num(ctx, j);
836             return 1;
837         }
838     }
839
840     for (; i + 8 < inl; i += 8, in_ptr += 8, out_ptr += 8) {
841         /*
842          * block cipher current iv
843          */
844         /* Encrypt */
845         gost_cnt_next(EVP_CIPHER_CTX_get_cipher_data(ctx), iv, buf);
846         /*
847          * xor next block of input text with it and output it
848          */
849         /*
850          * output this block
851          */
852         for (j = 0; j < 8; j++) {
853             out_ptr[j] = buf[j] ^ in_ptr[j];
854         }
855     }
856 /* Process rest of buffer */
857     if (i < inl) {
858         gost_cnt_next(EVP_CIPHER_CTX_get_cipher_data(ctx), iv, buf);
859         for (j = 0; i < inl; j++, i++) {
860             out_ptr[j] = buf[j] ^ in_ptr[j];
861         }
862         EVP_CIPHER_CTX_set_num(ctx, j);
863     } else {
864         EVP_CIPHER_CTX_set_num(ctx, 0);
865     }
866     return 1;
867 }
868
869 /* Cleaning up of EVP_CIPHER_CTX */
870 int gost_cipher_cleanup(EVP_CIPHER_CTX *ctx)
871 {
872     struct ossl_gost_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
873                 EVP_MD_CTX_free(c->omac_ctx);
874     gost_destroy(&(c->cctx));
875     EVP_CIPHER_CTX_set_app_data(ctx, NULL);
876     return 1;
877 }
878
879 /* Control function for gost cipher */
880 int gost_cipher_ctl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr)
881 {
882     switch (type) {
883     case EVP_CTRL_RAND_KEY:
884         {
885             if (RAND_priv_bytes
886                 ((unsigned char *)ptr, EVP_CIPHER_CTX_key_length(ctx)) <= 0) {
887                 GOSTerr(GOST_F_GOST_CIPHER_CTL, GOST_R_RNG_ERROR);
888                 return -1;
889             }
890             break;
891         }
892     case EVP_CTRL_PBE_PRF_NID:
893         if (ptr) {
894             const char *params = get_gost_engine_param(GOST_PARAM_PBE_PARAMS);
895             int nid = NID_id_tc26_hmac_gost_3411_2012_512;
896
897             if (params) {
898                 if (!strcmp("md_gost12_256", params))
899                     nid = NID_id_tc26_hmac_gost_3411_2012_256;
900                 else if (!strcmp("md_gost12_512", params))
901                     nid = NID_id_tc26_hmac_gost_3411_2012_512;
902                 else if (!strcmp("md_gost94", params))
903                     nid = NID_id_HMACGostR3411_94;
904             }
905             *((int *)ptr) = nid;
906             return 1;
907         } else {
908             return 0;
909         }
910
911     case EVP_CTRL_SET_SBOX:
912         if (ptr) {
913             struct ossl_gost_cipher_ctx *c =
914                 EVP_CIPHER_CTX_get_cipher_data(ctx);
915             int nid;
916             int cur_meshing;
917             int ret;
918
919             if (c == NULL) {
920                 return -1;
921             }
922
923             if (c->count != 0) {
924                 return -1;
925             }
926
927             nid = OBJ_txt2nid(ptr);
928             if (nid == NID_undef) {
929                 return 0;
930             }
931
932             cur_meshing = c->key_meshing;
933             ret = gost_cipher_set_param(c, nid);
934             c->key_meshing = cur_meshing;
935             return ret;
936         } else {
937             return 0;
938         }
939     case EVP_CTRL_KEY_MESH:
940         {
941             struct ossl_gost_cipher_ctx *c =
942                 EVP_CIPHER_CTX_get_cipher_data(ctx);
943
944             if (c == NULL) {
945                 return -1;
946             }
947
948             if (c->count != 0) {
949                 return -1;
950             }
951
952             c->key_meshing = arg;
953             return 1;
954         }
955     default:
956         GOSTerr(GOST_F_GOST_CIPHER_CTL, GOST_R_UNSUPPORTED_CIPHER_CTL_COMMAND);
957         return -1;
958     }
959     return 1;
960 }
961
962 /* Control function for gost cipher */
963 int magma_cipher_ctl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr)
964 {
965     switch (type) {
966     case EVP_CTRL_RAND_KEY:
967             if (RAND_priv_bytes
968                 ((unsigned char *)ptr, EVP_CIPHER_CTX_key_length(ctx)) <= 0) {
969                 GOSTerr(GOST_F_GOST_CIPHER_CTL, GOST_R_RNG_ERROR);
970                 return -1;
971             }
972             break;
973     case EVP_CTRL_KEY_MESH:
974         {
975             struct ossl_gost_cipher_ctx *c =
976                 EVP_CIPHER_CTX_get_cipher_data(ctx);
977
978             if (c == NULL) {
979                 return -1;
980             }
981
982             if (c->count != 0) {
983                 return -1;
984             }
985
986             c->key_meshing = arg;
987             return 1;
988         }
989     default:
990         GOSTerr(GOST_F_MAGMA_CIPHER_CTL, GOST_R_UNSUPPORTED_CIPHER_CTL_COMMAND);
991         return -1;
992     }
993     return 1;
994 }
995
996 static int magma_cipher_ctl_acpkm_omac(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr)
997 {
998         switch (type)
999         {
1000                 case EVP_CTRL_PROCESS_UNPROTECTED:
1001                 {
1002                         struct ossl_gost_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
1003                         STACK_OF(X509_ATTRIBUTE) *x = ptr;
1004       return gost2015_process_unprotected_attributes(x, arg, MAGMA_MAC_MAX_SIZE, c->tag);
1005                 }
1006     case EVP_CTRL_COPY: {
1007                         EVP_CIPHER_CTX *out = ptr;
1008       struct ossl_gost_cipher_ctx *in_cctx  = EVP_CIPHER_CTX_get_cipher_data(ctx);
1009       struct ossl_gost_cipher_ctx *out_cctx = EVP_CIPHER_CTX_get_cipher_data(out);
1010
1011                         if (in_cctx->omac_ctx == out_cctx->omac_ctx) {
1012                                 out_cctx->omac_ctx = EVP_MD_CTX_new();
1013                                 if (out_cctx->omac_ctx == NULL) {
1014                                         GOSTerr(GOST_F_MAGMA_CIPHER_CTL_ACPKM_OMAC, ERR_R_MALLOC_FAILURE);
1015                                         return -1;
1016                                 }
1017                         }
1018                         return EVP_MD_CTX_copy(out_cctx->omac_ctx, in_cctx->omac_ctx);
1019                 }
1020                 default:
1021                         return magma_cipher_ctl(ctx, type, arg, ptr);
1022                         break;
1023         }
1024 }
1025
1026 /* Set cipher parameters from ASN1 structure */
1027 int gost89_set_asn1_parameters(EVP_CIPHER_CTX *ctx, ASN1_TYPE *params)
1028 {
1029     int len = 0;
1030     unsigned char *buf = NULL;
1031     unsigned char *p = NULL;
1032     struct ossl_gost_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
1033     GOST_CIPHER_PARAMS *gcp = GOST_CIPHER_PARAMS_new();
1034     ASN1_OCTET_STRING *os = NULL;
1035     if (!gcp) {
1036         GOSTerr(GOST_F_GOST89_SET_ASN1_PARAMETERS, ERR_R_MALLOC_FAILURE);
1037         return 0;
1038     }
1039     if (!ASN1_OCTET_STRING_set
1040         (gcp->iv, EVP_CIPHER_CTX_iv(ctx), EVP_CIPHER_CTX_iv_length(ctx))) {
1041         GOST_CIPHER_PARAMS_free(gcp);
1042         GOSTerr(GOST_F_GOST89_SET_ASN1_PARAMETERS, ERR_R_MALLOC_FAILURE);
1043         return 0;
1044     }
1045     ASN1_OBJECT_free(gcp->enc_param_set);
1046     gcp->enc_param_set = OBJ_nid2obj(c->paramNID);
1047
1048     len = i2d_GOST_CIPHER_PARAMS(gcp, NULL);
1049     p = buf = OPENSSL_malloc(len);
1050     if (!buf) {
1051         GOST_CIPHER_PARAMS_free(gcp);
1052         GOSTerr(GOST_F_GOST89_SET_ASN1_PARAMETERS, ERR_R_MALLOC_FAILURE);
1053         return 0;
1054     }
1055     i2d_GOST_CIPHER_PARAMS(gcp, &p);
1056     GOST_CIPHER_PARAMS_free(gcp);
1057
1058     os = ASN1_OCTET_STRING_new();
1059
1060     if (!os || !ASN1_OCTET_STRING_set(os, buf, len)) {
1061         OPENSSL_free(buf);
1062         GOSTerr(GOST_F_GOST89_SET_ASN1_PARAMETERS, ERR_R_MALLOC_FAILURE);
1063         return 0;
1064     }
1065     OPENSSL_free(buf);
1066
1067     ASN1_TYPE_set(params, V_ASN1_SEQUENCE, os);
1068     return 1;
1069 }
1070
1071 /* Store parameters into ASN1 structure */
1072 int gost89_get_asn1_parameters(EVP_CIPHER_CTX *ctx, ASN1_TYPE *params)
1073 {
1074     int len;
1075     GOST_CIPHER_PARAMS *gcp = NULL;
1076     unsigned char *p;
1077     struct ossl_gost_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
1078     int nid;
1079
1080     if (ASN1_TYPE_get(params) != V_ASN1_SEQUENCE) {
1081         return -1;
1082     }
1083
1084     p = params->value.sequence->data;
1085
1086     gcp = d2i_GOST_CIPHER_PARAMS(NULL, (const unsigned char **)&p,
1087                                  params->value.sequence->length);
1088
1089     len = gcp->iv->length;
1090     if (len != EVP_CIPHER_CTX_iv_length(ctx)) {
1091         GOST_CIPHER_PARAMS_free(gcp);
1092         GOSTerr(GOST_F_GOST89_GET_ASN1_PARAMETERS, GOST_R_INVALID_IV_LENGTH);
1093         return -1;
1094     }
1095
1096     nid = OBJ_obj2nid(gcp->enc_param_set);
1097     if (nid == NID_undef) {
1098         GOST_CIPHER_PARAMS_free(gcp);
1099         GOSTerr(GOST_F_GOST89_GET_ASN1_PARAMETERS,
1100                 GOST_R_INVALID_CIPHER_PARAM_OID);
1101         return -1;
1102     }
1103
1104     if (!gost_cipher_set_param(c, nid)) {
1105         GOST_CIPHER_PARAMS_free(gcp);
1106         return -1;
1107     }
1108     /*XXX missing non-const accessor */
1109     memcpy((unsigned char *)EVP_CIPHER_CTX_original_iv(ctx), gcp->iv->data,
1110            EVP_CIPHER_CTX_iv_length(ctx));
1111
1112     GOST_CIPHER_PARAMS_free(gcp);
1113
1114     return 1;
1115 }
1116
1117 #define MAGMA_UKM_LEN 12
1118 static int magma_set_asn1_parameters (EVP_CIPHER_CTX *ctx, ASN1_TYPE *params)
1119 {
1120   struct ossl_gost_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
1121         c->key_meshing = 8192;
1122
1123         return gost2015_set_asn1_params(params, EVP_CIPHER_CTX_original_iv(ctx), 4,
1124                 c->kdf_seed);
1125 }
1126
1127 static int magma_get_asn1_parameters(EVP_CIPHER_CTX *ctx, ASN1_TYPE *params)
1128 {
1129   struct ossl_gost_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
1130         unsigned char iv[16];
1131
1132         c->key_meshing = 8192;
1133
1134         if (gost2015_get_asn1_params(params, MAGMA_UKM_LEN, iv, 4, c->kdf_seed) < 0)
1135             return -1;
1136
1137         memcpy(EVP_CIPHER_CTX_iv_noconst(ctx), iv, sizeof(iv));
1138         memcpy((unsigned char *)EVP_CIPHER_CTX_original_iv(ctx), iv, sizeof(iv));
1139         /* Key meshing 8 kb*/
1140         c->key_meshing = 8192;
1141
1142         return 1;
1143 }
1144
1145 static int gost_imit_init(EVP_MD_CTX *ctx, gost_subst_block * block)
1146 {
1147     struct ossl_gost_imit_ctx *c = EVP_MD_CTX_md_data(ctx);
1148     memset(c->buffer, 0, sizeof(c->buffer));
1149     memset(c->partial_block, 0, sizeof(c->partial_block));
1150     c->count = 0;
1151     c->bytes_left = 0;
1152     c->key_meshing = 1;
1153     c->dgst_size = 4;
1154     gost_init(&(c->cctx), block);
1155     return 1;
1156 }
1157
1158 static int gost_imit_init_cpa(EVP_MD_CTX *ctx)
1159 {
1160     return gost_imit_init(ctx, &Gost28147_CryptoProParamSetA);
1161 }
1162
1163 static int gost_imit_init_cp_12(EVP_MD_CTX *ctx)
1164 {
1165     return gost_imit_init(ctx, &Gost28147_TC26ParamSetZ);
1166 }
1167
1168 static void mac_block_mesh(struct ossl_gost_imit_ctx *c,
1169                            const unsigned char *data)
1170 {
1171     /*
1172      * We are using NULL for iv because CryptoPro doesn't interpret
1173      * internal state of MAC algorithm as iv during keymeshing (but does
1174      * initialize internal state from iv in key transport
1175      */
1176     assert(c->count % 8 == 0 && c->count <= 1024);
1177     if (c->key_meshing && c->count == 1024) {
1178         cryptopro_key_meshing(&(c->cctx), NULL);
1179     }
1180     mac_block(&(c->cctx), c->buffer, data);
1181     c->count = c->count % 1024 + 8;
1182 }
1183
1184 int gost_imit_update(EVP_MD_CTX *ctx, const void *data, size_t count)
1185 {
1186     struct ossl_gost_imit_ctx *c = EVP_MD_CTX_md_data(ctx);
1187     const unsigned char *p = data;
1188     size_t bytes = count;
1189     if (!(c->key_set)) {
1190         GOSTerr(GOST_F_GOST_IMIT_UPDATE, GOST_R_MAC_KEY_NOT_SET);
1191         return 0;
1192     }
1193     if (c->bytes_left) {
1194         size_t i;
1195         for (i = c->bytes_left; i < 8 && bytes > 0; bytes--, i++, p++) {
1196             c->partial_block[i] = *p;
1197         }
1198         if (i == 8) {
1199             mac_block_mesh(c, c->partial_block);
1200         } else {
1201             c->bytes_left = i;
1202             return 1;
1203         }
1204     }
1205     while (bytes > 8) {
1206         mac_block_mesh(c, p);
1207         p += 8;
1208         bytes -= 8;
1209     }
1210     if (bytes > 0) {
1211         memcpy(c->partial_block, p, bytes);
1212     }
1213     c->bytes_left = bytes;
1214     return 1;
1215 }
1216
1217 int gost_imit_final(EVP_MD_CTX *ctx, unsigned char *md)
1218 {
1219     struct ossl_gost_imit_ctx *c = EVP_MD_CTX_md_data(ctx);
1220     if (!c->key_set) {
1221         GOSTerr(GOST_F_GOST_IMIT_FINAL, GOST_R_MAC_KEY_NOT_SET);
1222         return 0;
1223     }
1224     if (c->count == 0 && c->bytes_left) {
1225         unsigned char buffer[8];
1226         memset(buffer, 0, 8);
1227         gost_imit_update(ctx, buffer, 8);
1228     }
1229     if (c->bytes_left) {
1230         int i;
1231         for (i = c->bytes_left; i < 8; i++) {
1232             c->partial_block[i] = 0;
1233         }
1234         mac_block_mesh(c, c->partial_block);
1235     }
1236     get_mac(c->buffer, 8 * c->dgst_size, md);
1237     return 1;
1238 }
1239
1240 int gost_imit_ctrl(EVP_MD_CTX *ctx, int type, int arg, void *ptr)
1241 {
1242     switch (type) {
1243     case EVP_MD_CTRL_KEY_LEN:
1244         *((unsigned int *)(ptr)) = 32;
1245         return 1;
1246     case EVP_MD_CTRL_SET_KEY:
1247         {
1248             struct ossl_gost_imit_ctx *gost_imit_ctx = EVP_MD_CTX_md_data(ctx);
1249
1250             if (EVP_MD_meth_get_init(EVP_MD_CTX_md(ctx)) (ctx) <= 0) {
1251                 GOSTerr(GOST_F_GOST_IMIT_CTRL, GOST_R_MAC_KEY_NOT_SET);
1252                 return 0;
1253             }
1254             EVP_MD_CTX_set_flags(ctx, EVP_MD_CTX_FLAG_NO_INIT);
1255
1256             if (arg == 0) {
1257                 struct gost_mac_key *key = (struct gost_mac_key *)ptr;
1258                 if (key->mac_param_nid != NID_undef) {
1259                     const struct gost_cipher_info *param =
1260                         get_encryption_params(OBJ_nid2obj(key->mac_param_nid));
1261                     if (param == NULL) {
1262                         GOSTerr(GOST_F_GOST_IMIT_CTRL,
1263                                 GOST_R_INVALID_MAC_PARAMS);
1264                         return 0;
1265                     }
1266                     gost_init(&(gost_imit_ctx->cctx), param->sblock);
1267                 }
1268                 gost_key(&(gost_imit_ctx->cctx), key->key);
1269                 gost_imit_ctx->key_set = 1;
1270
1271                 return 1;
1272             } else if (arg == 32) {
1273                 gost_key(&(gost_imit_ctx->cctx), ptr);
1274                 gost_imit_ctx->key_set = 1;
1275                 return 1;
1276             }
1277             GOSTerr(GOST_F_GOST_IMIT_CTRL, GOST_R_INVALID_MAC_KEY_SIZE);
1278             return 0;
1279         }
1280     case EVP_MD_CTRL_XOF_LEN:
1281         {
1282             struct ossl_gost_imit_ctx *c = EVP_MD_CTX_md_data(ctx);
1283             if (arg < 1 || arg > 8) {
1284                 GOSTerr(GOST_F_GOST_IMIT_CTRL, GOST_R_INVALID_MAC_SIZE);
1285                 return 0;
1286             }
1287             c->dgst_size = arg;
1288             return 1;
1289         }
1290
1291     default:
1292         return 0;
1293     }
1294 }
1295
1296 int gost_imit_copy(EVP_MD_CTX *to, const EVP_MD_CTX *from)
1297 {
1298     if (EVP_MD_CTX_md_data(to) && EVP_MD_CTX_md_data(from)) {
1299         memcpy(EVP_MD_CTX_md_data(to), EVP_MD_CTX_md_data(from),
1300                sizeof(struct ossl_gost_imit_ctx));
1301     }
1302     return 1;
1303 }
1304
1305 /* Clean up imit ctx */
1306 int gost_imit_cleanup(EVP_MD_CTX *ctx)
1307 {
1308     memset(EVP_MD_CTX_md_data(ctx), 0, sizeof(struct ossl_gost_imit_ctx));
1309     return 1;
1310 }
1311 /* vim: set expandtab cinoptions=\:0,l1,t0,g0,(0 sw=4 : */