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