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