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