]> www.wagner.pp.ru Git - openssl-gost/engine.git/blob - gost_crypt.c
CI: copy GitHub Actions files from master
[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     if (iv) {
482         memcpy((unsigned char *)EVP_CIPHER_CTX_original_iv(ctx), iv,
483                EVP_CIPHER_CTX_iv_length(ctx));
484     }
485     memcpy(EVP_CIPHER_CTX_iv_noconst(ctx),
486            EVP_CIPHER_CTX_original_iv(ctx), EVP_CIPHER_CTX_iv_length(ctx));
487
488     if (EVP_CIPHER_CTX_nid(ctx) == NID_magma_ctr_acpkm
489      || EVP_CIPHER_CTX_nid(ctx) == NID_magma_ctr_acpkm_omac) {
490        c->key_meshing = 1024;
491     } else {
492        c->key_meshing = 0;
493     }
494
495     return 1;
496 }
497
498 /* Initializes EVP_CIPHER_CTX with default values */
499 static int magma_cipher_init_ctr_acpkm_omac(EVP_CIPHER_CTX *ctx, const unsigned char *key,
500                       const unsigned char *iv, int enc)
501 {
502         if (key) {
503     struct ossl_gost_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
504                 unsigned char cipher_key[32];
505                 c->omac_ctx = EVP_MD_CTX_new();
506
507                 if (c->omac_ctx == NULL) {
508                     GOSTerr(GOST_F_MAGMA_CIPHER_INIT_CTR_ACPKM_OMAC, ERR_R_MALLOC_FAILURE);
509                                 return 0;
510                 }
511
512                 if (gost2015_acpkm_omac_init(NID_magma_mac, enc, key,
513                                  c->omac_ctx, cipher_key, c->kdf_seed) != 1) {
514                     EVP_MD_CTX_free(c->omac_ctx);
515                                 c->omac_ctx = NULL;
516                     return 0;
517                 }
518
519                 return magma_cipher_init(ctx, cipher_key, iv, enc);
520         }
521
522         return magma_cipher_init(ctx, key, iv, enc);
523 }
524
525 void gost_magma_encrypt_wrap(unsigned char *in, unsigned char *out,
526                    struct ossl_gost_cipher_ctx *c) {
527     int i;
528     unsigned char b[8];
529     unsigned char d[8];
530     for (i = 0; i < 8; i++) {
531         b[7 - i] = in[i];
532     }
533     gostcrypt(&(c->cctx), b, d);
534     for (i = 0; i < 8; i++) {
535         out[7 - i] = d[i];
536     }
537 }
538
539 /* ----------------------------------------------------------------------------------------------- */
540 /*! Функция реализует операцию умножения двух элементов конечного поля \f$ \mathbb F_{2^{64}}\f$,
541     порожденного неприводимым многочленом
542     \f$ f(x) = x^{64} + x^4 + x^3 + x + 1 \in \mathbb F_2[x]\f$. Для умножения используется
543     простейшая реализация, основанная на приведении по модулю после каждого шага алгоритма.        */
544 /* ----------------------------------------------------------------------------------------------- */
545 static void gf64_mul (uint64_t *result, uint64_t *arg1, uint64_t *arg2)
546 {
547         int i = 0;
548         register uint64_t t, X0;
549         uint64_t Z0 = 0;
550  
551 #ifdef L_ENDIAN
552         X0 = BSWAP64(*arg1);
553 #else
554         X0 = *arg1;
555 #endif
556
557 #ifdef L_ENDIAN
558         t = BSWAP64(*(arg2));
559 #else
560         t = *(arg2);
561 #endif
562
563         for (i = 0; i < 63; i++) {
564                 if (t & 0x1) {
565                         Z0 ^= X0;
566                 }
567                 t >>= 1;
568                 if (X0 & 0x8000000000000000) {
569                         X0 <<= 1;
570                         X0 ^= 0x1b;
571                 }
572                 else {
573                         X0 <<= 1;
574                 }
575         }
576
577         if (t & 0x1) {
578                 Z0 ^= X0;
579         }
580
581 #ifdef L_ENDIAN
582         *(result) = BSWAP64(Z0);
583 #else
584         *(result) = Z0;
585 #endif
586 }
587
588 static int gost_magma_cipher_init_mgm(EVP_CIPHER_CTX *ctx, const unsigned char *key,
589                                  const unsigned char *iv, int enc)
590 {
591     gost_mgm_ctx *mctx = 
592         (gost_mgm_ctx *)EVP_CIPHER_CTX_get_cipher_data(ctx);
593     int bl;
594
595     if (!iv && !key)
596         return 1;
597     if (key) {
598         bl = EVP_CIPHER_CTX_iv_length(ctx);
599         if (!gost_cipher_set_param(&mctx->ks.g_ks, NID_id_tc26_gost_28147_param_Z))
600             return 0;
601         magma_key(&(mctx->ks.g_ks.cctx), key);
602         gost_mgm128_init(&mctx->mgm, &mctx->ks, 
603                          (block128_f) gost_magma_encrypt_wrap, gf64_mul, bl);
604
605         /*
606          * If we have an iv can set it directly, otherwise use saved IV.
607          */
608         if (iv == NULL && mctx->iv_set)
609             iv = mctx->iv;
610         if (iv) {
611             if (gost_mgm128_setiv(&mctx->mgm, iv, mctx->ivlen) != 1)
612                 return 0;
613             mctx->iv_set = 1;
614         }
615         mctx->key_set = 1;
616     } else {
617         /* If key set use IV, otherwise copy */
618         if (mctx->key_set) {
619             if (gost_mgm128_setiv(&mctx->mgm, iv, mctx->ivlen) != 1)
620                 return 0;
621         }
622         else
623             memcpy(mctx->iv, iv, mctx->ivlen);
624         mctx->iv_set = 1;
625     }
626     return 1;
627 }
628
629 /*
630  * Wrapper around gostcrypt function from gost89.c which perform key meshing
631  * when nesseccary
632  */
633 static void gost_crypt_mesh(void *ctx, unsigned char *iv, unsigned char *buf)
634 {
635     struct ossl_gost_cipher_ctx *c = ctx;
636     assert(c->count % 8 == 0 && c->count <= 1024);
637     if (c->key_meshing && c->count == 1024) {
638         cryptopro_key_meshing(&(c->cctx), iv);
639     }
640     gostcrypt(&(c->cctx), iv, buf);
641     c->count = c->count % 1024 + 8;
642 }
643
644 static void gost_cnt_next(void *ctx, unsigned char *iv, unsigned char *buf)
645 {
646     struct ossl_gost_cipher_ctx *c = ctx;
647     word32 g, go;
648     unsigned char buf1[8];
649     assert(c->count % 8 == 0 && c->count <= 1024);
650     if (c->key_meshing && c->count == 1024) {
651         cryptopro_key_meshing(&(c->cctx), iv);
652     }
653     if (c->count == 0) {
654         gostcrypt(&(c->cctx), iv, buf1);
655     } else {
656         memcpy(buf1, iv, 8);
657     }
658     g = buf1[0] | (buf1[1] << 8) | (buf1[2] << 16) | ((word32) buf1[3] << 24);
659     g += 0x01010101;
660     buf1[0] = (unsigned char)(g & 0xff);
661     buf1[1] = (unsigned char)((g >> 8) & 0xff);
662     buf1[2] = (unsigned char)((g >> 16) & 0xff);
663     buf1[3] = (unsigned char)((g >> 24) & 0xff);
664     g = buf1[4] | (buf1[5] << 8) | (buf1[6] << 16) | ((word32) buf1[7] << 24);
665     go = g;
666     g += 0x01010104;
667     if (go > g)                 /* overflow */
668         g++;
669     buf1[4] = (unsigned char)(g & 0xff);
670     buf1[5] = (unsigned char)((g >> 8) & 0xff);
671     buf1[6] = (unsigned char)((g >> 16) & 0xff);
672     buf1[7] = (unsigned char)((g >> 24) & 0xff);
673     memcpy(iv, buf1, 8);
674     gostcrypt(&(c->cctx), buf1, buf);
675     c->count = c->count % 1024 + 8;
676 }
677
678 /* GOST encryption in CBC mode */
679 static int gost_cipher_do_cbc(EVP_CIPHER_CTX *ctx, unsigned char *out,
680                        const unsigned char *in, size_t inl)
681 {
682     unsigned char b[8];
683     const unsigned char *in_ptr = in;
684     unsigned char *out_ptr = out;
685     int i;
686     struct ossl_gost_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
687     unsigned char *iv = EVP_CIPHER_CTX_iv_noconst(ctx);
688     if (EVP_CIPHER_CTX_encrypting(ctx)) {
689         while (inl > 0) {
690
691             for (i = 0; i < 8; i++) {
692                 b[i] = iv[i] ^ in_ptr[i];
693             }
694             gostcrypt(&(c->cctx), b, out_ptr);
695             memcpy(iv, out_ptr, 8);
696             out_ptr += 8;
697             in_ptr += 8;
698             inl -= 8;
699         }
700     } else {
701         while (inl > 0) {
702             unsigned char tmpiv[8];
703             gostdecrypt(&(c->cctx), in_ptr, b);
704             memcpy(tmpiv, in_ptr, 8);
705             for (i = 0; i < 8; i++) {
706                 out_ptr[i] = iv[i] ^ b[i];
707             }
708             memcpy(iv, tmpiv, 8);
709             out_ptr += 8;
710             in_ptr += 8;
711             inl -= 8;
712         }
713     }
714     return 1;
715 }
716
717 /* MAGMA encryption in CBC mode */
718 static int magma_cipher_do_cbc(EVP_CIPHER_CTX *ctx, unsigned char *out,
719                         const unsigned char *in, size_t inl)
720 {
721     unsigned char b[8];
722     unsigned char d[8];
723     const unsigned char *in_ptr = in;
724     unsigned char *out_ptr = out;
725     int i;
726     struct ossl_gost_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
727     unsigned char *iv = EVP_CIPHER_CTX_iv_noconst(ctx);
728     if (EVP_CIPHER_CTX_encrypting(ctx)) {
729         while (inl > 0) {
730
731             for (i = 0; i < 8; i++) {
732                 b[7 - i] = iv[i] ^ in_ptr[i];
733             }
734             gostcrypt(&(c->cctx), b, d);
735
736             for (i = 0; i < 8; i++) {
737                 out_ptr[7 - i] = d[i];
738             }
739             memcpy(iv, out_ptr, 8);
740             out_ptr += 8;
741             in_ptr += 8;
742             inl -= 8;
743         }
744     } else {
745         while (inl > 0) {
746             for (i = 0; i < 8; i++) {
747                 d[7 - i] = in_ptr[i];
748             }
749             gostdecrypt(&(c->cctx), d, b);
750             memcpy(d, in_ptr, 8);
751             for (i = 0; i < 8; i++) {
752                 out_ptr[i] = iv[i] ^ b[7 - i];
753             }
754             memcpy(iv, d, 8);
755             out_ptr += 8;
756             in_ptr += 8;
757             inl -= 8;
758         }
759     }
760     return 1;
761 }
762
763 /* increment counter (64-bit int) by 1 */
764 static void ctr64_inc(unsigned char *counter)
765 {
766     inc_counter(counter, 8);
767 }
768
769 #define MAGMA_BLOCK_SIZE 8
770 #define MAGMA_BLOCK_MASK (MAGMA_BLOCK_SIZE - 1)
771 static inline void apply_acpkm_magma(struct ossl_gost_cipher_ctx *
772                                            ctx, unsigned int *num)
773 {
774     if (!ctx->key_meshing || (*num < ctx->key_meshing))
775         return;
776     acpkm_magma_key_meshing(&ctx->cctx);
777     *num &= MAGMA_BLOCK_MASK;
778 }
779
780 /* MAGMA encryption in CTR mode */
781 static int magma_cipher_do_ctr(EVP_CIPHER_CTX *ctx, unsigned char *out,
782                                const unsigned char *in, size_t inl)
783 {
784     const unsigned char *in_ptr = in;
785     unsigned char *out_ptr = out;
786     size_t j;
787     struct ossl_gost_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
788     unsigned char *buf = EVP_CIPHER_CTX_buf_noconst(ctx);
789     unsigned char *iv = EVP_CIPHER_CTX_iv_noconst(ctx);
790     unsigned int num = EVP_CIPHER_CTX_num(ctx);
791     size_t blocks, i, lasted = inl;
792     unsigned char b[8];
793 /* Process partial blocks */
794     while ((num & MAGMA_BLOCK_MASK) && lasted) {
795         *out_ptr++ = *in_ptr++ ^ buf[7 - (num & MAGMA_BLOCK_MASK)];
796         --lasted;
797         num++;
798     }
799     blocks = lasted / MAGMA_BLOCK_SIZE;
800
801 /* Process full blocks */
802     for (i = 0; i < blocks; i++) {
803         apply_acpkm_magma(c, &num);
804         for (j = 0; j < 8; j++) {
805             b[7 - j] = iv[j];
806         }
807         gostcrypt(&(c->cctx), b, buf);
808         for (j = 0; j < 8; j++) {
809             out_ptr[j] = buf[7 - j] ^ in_ptr[j];
810         }
811         ctr64_inc(iv);
812         c->count += MAGMA_BLOCK_SIZE;
813         in_ptr += MAGMA_BLOCK_SIZE;
814         out_ptr += MAGMA_BLOCK_SIZE;
815         num += MAGMA_BLOCK_SIZE;
816         lasted -= MAGMA_BLOCK_SIZE;
817     }
818
819 /* Process the rest of plaintext */
820     if (lasted > 0) {
821         apply_acpkm_magma(c, &num);
822         for (j = 0; j < 8; j++) {
823             b[7 - j] = iv[j];
824         }
825         gostcrypt(&(c->cctx), b, buf);
826
827         for (i = 0; i < lasted; i++)
828             out_ptr[i] = buf[7 - i] ^ in_ptr[i];
829         ctr64_inc(iv);
830         c->count += j;
831         num += lasted;
832     }
833     EVP_CIPHER_CTX_set_num(ctx, num);
834
835     return inl;
836 }
837
838 /* MAGMA encryption in CTR mode */
839 static int magma_cipher_do_ctr_acpkm_omac(EVP_CIPHER_CTX *ctx, unsigned char *out,
840                                const unsigned char *in, size_t inl)
841 {
842   struct ossl_gost_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
843
844         if (in == NULL && inl == 0) /* Final call */
845                 return gost2015_final_call(ctx, c->omac_ctx, MAGMA_MAC_MAX_SIZE, c->tag, magma_cipher_do_ctr);
846
847   if (in == NULL)
848       return -1;
849
850         /* As in and out can be the same pointer, process unencrypted here */
851         if (EVP_CIPHER_CTX_encrypting(ctx))
852                 EVP_DigestSignUpdate(c->omac_ctx, in, inl);
853
854   if (magma_cipher_do_ctr(ctx, out, in, inl) != inl)
855       return -1;
856
857         /* As in and out can be the same pointer, process decrypted here */
858         if (!EVP_CIPHER_CTX_encrypting(ctx))
859                 EVP_DigestSignUpdate(c->omac_ctx, out, inl);
860
861         return inl;
862 }
863
864 static int gost_magma_cipher_do_mgm(EVP_CIPHER_CTX *ctx, unsigned char *out,
865                                    const unsigned char *in, size_t len)
866 {
867     gost_mgm_ctx *mctx = 
868         (gost_mgm_ctx *)EVP_CIPHER_CTX_get_cipher_data(ctx);
869     int enc = EVP_CIPHER_CTX_encrypting(ctx);
870
871     /* If not set up, return error */
872     if (!mctx->key_set) {
873         GOSTerr(GOST_F_GOST_MAGMA_CIPHER_DO_MGM,
874                 GOST_R_BAD_ORDER);
875         return -1;
876     }
877
878     if (!mctx->iv_set) {
879         GOSTerr(GOST_F_GOST_MAGMA_CIPHER_DO_MGM,
880                 GOST_R_BAD_ORDER);
881         return -1;
882     }
883     if (in) {
884         if (out == NULL) {
885             if (gost_mgm128_aad(&mctx->mgm, in, len))
886                 return -1;            
887         } else if (enc) {
888             if (gost_mgm128_encrypt(&mctx->mgm, in, out, len))
889                 return -1;
890         } else {
891             if (gost_mgm128_decrypt(&mctx->mgm, in, out, len))
892                 return -1;
893         }
894         return len;
895     } else {
896         if (!enc) {
897             if (mctx->taglen < 0)
898                 return -1;
899             if (gost_mgm128_finish(&mctx->mgm,
900                                    EVP_CIPHER_CTX_buf_noconst(ctx),
901                                    mctx->taglen) != 0)
902                 return -1;
903             mctx->iv_set = 0;
904             return 0;
905         }
906         gost_mgm128_tag(&mctx->mgm, EVP_CIPHER_CTX_buf_noconst(ctx), 8);
907         mctx->taglen = 8;
908         /* Don't reuse the IV */
909         mctx->iv_set = 0;
910         return 0;
911     }
912
913 }
914
915 /* GOST encryption in CFB mode */
916 static int gost_cipher_do_cfb(EVP_CIPHER_CTX *ctx, unsigned char *out,
917                        const unsigned char *in, size_t inl)
918 {
919     const unsigned char *in_ptr = in;
920     unsigned char *out_ptr = out;
921     size_t i = 0;
922     size_t j = 0;
923     unsigned char *buf = EVP_CIPHER_CTX_buf_noconst(ctx);
924     unsigned char *iv = EVP_CIPHER_CTX_iv_noconst(ctx);
925 /* process partial block if any */
926     if (EVP_CIPHER_CTX_num(ctx)) {
927         for (j = EVP_CIPHER_CTX_num(ctx), i = 0; j < 8 && i < inl;
928              j++, i++, in_ptr++, out_ptr++) {
929             if (!EVP_CIPHER_CTX_encrypting(ctx))
930                 buf[j + 8] = *in_ptr;
931             *out_ptr = buf[j] ^ (*in_ptr);
932             if (EVP_CIPHER_CTX_encrypting(ctx))
933                 buf[j + 8] = *out_ptr;
934         }
935         if (j == 8) {
936             memcpy(iv, buf + 8, 8);
937             EVP_CIPHER_CTX_set_num(ctx, 0);
938         } else {
939             EVP_CIPHER_CTX_set_num(ctx, j);
940             return 1;
941         }
942     }
943
944     for (; (inl - i) >= 8; i += 8, in_ptr += 8, out_ptr += 8) {
945         /*
946          * block cipher current iv
947          */
948         gost_crypt_mesh(EVP_CIPHER_CTX_get_cipher_data(ctx), iv, buf);
949         /*
950          * xor next block of input text with it and output it
951          */
952         /*
953          * output this block
954          */
955         if (!EVP_CIPHER_CTX_encrypting(ctx))
956             memcpy(iv, in_ptr, 8);
957         for (j = 0; j < 8; j++) {
958             out_ptr[j] = buf[j] ^ in_ptr[j];
959         }
960         /* Encrypt */
961         /* Next iv is next block of cipher text */
962         if (EVP_CIPHER_CTX_encrypting(ctx))
963             memcpy(iv, out_ptr, 8);
964     }
965 /* Process rest of buffer */
966     if (i < inl) {
967         gost_crypt_mesh(EVP_CIPHER_CTX_get_cipher_data(ctx), iv, buf);
968         if (!EVP_CIPHER_CTX_encrypting(ctx))
969             memcpy(buf + 8, in_ptr, inl - i);
970         for (j = 0; i < inl; j++, i++) {
971             out_ptr[j] = buf[j] ^ in_ptr[j];
972         }
973         EVP_CIPHER_CTX_set_num(ctx, j);
974         if (EVP_CIPHER_CTX_encrypting(ctx))
975             memcpy(buf + 8, out_ptr, j);
976     } else {
977         EVP_CIPHER_CTX_set_num(ctx, 0);
978     }
979     return 1;
980 }
981
982 static int gost_cipher_do_cnt(EVP_CIPHER_CTX *ctx, unsigned char *out,
983                               const unsigned char *in, size_t inl)
984 {
985     const unsigned char *in_ptr = in;
986     unsigned char *out_ptr = out;
987     size_t i = 0;
988     size_t j;
989     unsigned char *buf = EVP_CIPHER_CTX_buf_noconst(ctx);
990     unsigned char *iv = EVP_CIPHER_CTX_iv_noconst(ctx);
991 /* process partial block if any */
992     if (EVP_CIPHER_CTX_num(ctx)) {
993         for (j = EVP_CIPHER_CTX_num(ctx), i = 0; j < 8 && i < inl;
994              j++, i++, in_ptr++, out_ptr++) {
995             *out_ptr = buf[j] ^ (*in_ptr);
996         }
997         if (j == 8) {
998             EVP_CIPHER_CTX_set_num(ctx, 0);
999         } else {
1000             EVP_CIPHER_CTX_set_num(ctx, j);
1001             return 1;
1002         }
1003     }
1004
1005     for (; (inl - i) >= 8; i += 8, in_ptr += 8, out_ptr += 8) {
1006         /*
1007          * block cipher current iv
1008          */
1009         /* Encrypt */
1010         gost_cnt_next(EVP_CIPHER_CTX_get_cipher_data(ctx), iv, buf);
1011         /*
1012          * xor next block of input text with it and output it
1013          */
1014         /*
1015          * output this block
1016          */
1017         for (j = 0; j < 8; j++) {
1018             out_ptr[j] = buf[j] ^ in_ptr[j];
1019         }
1020     }
1021 /* Process rest of buffer */
1022     if (i < inl) {
1023         gost_cnt_next(EVP_CIPHER_CTX_get_cipher_data(ctx), iv, buf);
1024         for (j = 0; i < inl; j++, i++) {
1025             out_ptr[j] = buf[j] ^ in_ptr[j];
1026         }
1027         EVP_CIPHER_CTX_set_num(ctx, j);
1028     } else {
1029         EVP_CIPHER_CTX_set_num(ctx, 0);
1030     }
1031     return 1;
1032 }
1033
1034 /* Cleaning up of EVP_CIPHER_CTX */
1035 static int gost_cipher_cleanup(EVP_CIPHER_CTX *ctx)
1036 {
1037     struct ossl_gost_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
1038                 EVP_MD_CTX_free(c->omac_ctx);
1039     gost_destroy(&(c->cctx));
1040     EVP_CIPHER_CTX_set_app_data(ctx, NULL);
1041     return 1;
1042 }
1043
1044 static int gost_magma_mgm_cleanup(EVP_CIPHER_CTX *c)
1045 {
1046     gost_mgm_ctx *mctx = 
1047         (gost_mgm_ctx *)EVP_CIPHER_CTX_get_cipher_data(c);
1048     if (mctx == NULL)
1049         return 0;
1050     gost_destroy(&mctx->ks.g_ks.cctx);
1051     OPENSSL_cleanse(&mctx->mgm, sizeof(mctx->mgm));
1052     EVP_CIPHER_CTX_set_app_data(c, NULL);
1053     return 1;
1054 }
1055
1056 static int gost_magma_mgm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr)
1057 {
1058     gost_mgm_ctx *mctx = 
1059         (gost_mgm_ctx *)EVP_CIPHER_CTX_get_cipher_data(c);
1060     unsigned char *buf, *iv;
1061     int ivlen, enc;
1062
1063     switch (type) {
1064     case EVP_CTRL_INIT:
1065         ivlen = EVP_CIPHER_iv_length(EVP_CIPHER_CTX_cipher(c));
1066         iv = EVP_CIPHER_CTX_iv_noconst(c);
1067         mctx->key_set = 0;
1068         mctx->iv_set = 0;
1069         mctx->ivlen = ivlen;
1070         mctx->iv = iv;
1071         mctx->taglen = -1;
1072         return 1;
1073     
1074     case EVP_CTRL_GET_IVLEN:
1075         *(int *)ptr = mctx->ivlen;
1076         return 1;
1077
1078     case EVP_CTRL_AEAD_SET_IVLEN:
1079         if (arg <= 0)
1080             return 0;
1081         if ((arg > EVP_MAX_IV_LENGTH) && (arg > mctx->ivlen)) {
1082             // TODO: Allocate memory for IV or set error
1083             return 0;
1084         }
1085         mctx->ivlen = arg;
1086         return 1;
1087
1088     case EVP_CTRL_AEAD_SET_TAG:
1089         buf = EVP_CIPHER_CTX_buf_noconst(c);
1090         enc = EVP_CIPHER_CTX_encrypting(c);
1091         if (arg <= 0 || arg != 8 || enc) {
1092             GOSTerr(GOST_F_GOST_MAGMA_MGM_CTRL,
1093                     GOST_R_INVALID_TAG_LENGTH);
1094             return 0;
1095         }
1096         memcpy(buf, ptr, arg);
1097         mctx->taglen = arg;    
1098         return 1;
1099
1100     case EVP_CTRL_AEAD_GET_TAG:
1101         buf = EVP_CIPHER_CTX_buf_noconst(c);
1102         enc = EVP_CIPHER_CTX_encrypting(c);
1103         if (arg <= 0 || arg > 8 || !enc || mctx->taglen < 0) {
1104             GOSTerr(GOST_F_GOST_MAGMA_MGM_CTRL,
1105                     GOST_R_INVALID_TAG_LENGTH);
1106             return 0;
1107         }
1108         memcpy(ptr, buf, arg);
1109         return 1;
1110
1111     default:
1112         return -1;
1113     }
1114 }
1115
1116 /* Control function for gost cipher */
1117 static int gost_cipher_ctl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr)
1118 {
1119     switch (type) {
1120     case EVP_CTRL_RAND_KEY:
1121         {
1122             if (RAND_priv_bytes
1123                 ((unsigned char *)ptr, EVP_CIPHER_CTX_key_length(ctx)) <= 0) {
1124                 GOSTerr(GOST_F_GOST_CIPHER_CTL, GOST_R_RNG_ERROR);
1125                 return -1;
1126             }
1127             break;
1128         }
1129     case EVP_CTRL_PBE_PRF_NID:
1130         if (ptr) {
1131             const char *params = get_gost_engine_param(GOST_PARAM_PBE_PARAMS);
1132             int nid = NID_id_tc26_hmac_gost_3411_2012_512;
1133
1134             if (params) {
1135                 if (!strcmp("md_gost12_256", params))
1136                     nid = NID_id_tc26_hmac_gost_3411_2012_256;
1137                 else if (!strcmp("md_gost12_512", params))
1138                     nid = NID_id_tc26_hmac_gost_3411_2012_512;
1139                 else if (!strcmp("md_gost94", params))
1140                     nid = NID_id_HMACGostR3411_94;
1141             }
1142             *((int *)ptr) = nid;
1143             return 1;
1144         } else {
1145             return 0;
1146         }
1147
1148     case EVP_CTRL_SET_SBOX:
1149         if (ptr) {
1150             struct ossl_gost_cipher_ctx *c =
1151                 EVP_CIPHER_CTX_get_cipher_data(ctx);
1152             int nid;
1153             int cur_meshing;
1154             int ret;
1155
1156             if (c == NULL) {
1157                 return -1;
1158             }
1159
1160             if (c->count != 0) {
1161                 return -1;
1162             }
1163
1164             nid = OBJ_txt2nid(ptr);
1165             if (nid == NID_undef) {
1166                 return 0;
1167             }
1168
1169             cur_meshing = c->key_meshing;
1170             ret = gost_cipher_set_param(c, nid);
1171             c->key_meshing = cur_meshing;
1172             return ret;
1173         } else {
1174             return 0;
1175         }
1176     case EVP_CTRL_KEY_MESH:
1177         {
1178             struct ossl_gost_cipher_ctx *c =
1179                 EVP_CIPHER_CTX_get_cipher_data(ctx);
1180
1181             if (c == NULL) {
1182                 return -1;
1183             }
1184
1185             if (c->count != 0) {
1186                 return -1;
1187             }
1188
1189             c->key_meshing = arg;
1190             return 1;
1191         }
1192     default:
1193         GOSTerr(GOST_F_GOST_CIPHER_CTL, GOST_R_UNSUPPORTED_CIPHER_CTL_COMMAND);
1194         return -1;
1195     }
1196     return 1;
1197 }
1198
1199 /* Control function for gost cipher */
1200 static int magma_cipher_ctl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr)
1201 {
1202     switch (type) {
1203     case EVP_CTRL_RAND_KEY:
1204             if (RAND_priv_bytes
1205                 ((unsigned char *)ptr, EVP_CIPHER_CTX_key_length(ctx)) <= 0) {
1206                 GOSTerr(GOST_F_MAGMA_CIPHER_CTL, GOST_R_RNG_ERROR);
1207                 return -1;
1208             }
1209             break;
1210     case EVP_CTRL_KEY_MESH:
1211         {
1212             struct ossl_gost_cipher_ctx *c =
1213                 EVP_CIPHER_CTX_get_cipher_data(ctx);
1214
1215             if (c == NULL) {
1216                 return -1;
1217             }
1218
1219             if (c->count != 0) {
1220                 return -1;
1221             }
1222
1223             c->key_meshing = arg;
1224             return 1;
1225         }
1226     default:
1227         GOSTerr(GOST_F_MAGMA_CIPHER_CTL, GOST_R_UNSUPPORTED_CIPHER_CTL_COMMAND);
1228         return -1;
1229     }
1230     return 1;
1231 }
1232
1233 static int magma_cipher_ctl_acpkm_omac(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr)
1234 {
1235         switch (type)
1236         {
1237                 case EVP_CTRL_PROCESS_UNPROTECTED:
1238                 {
1239                         struct ossl_gost_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
1240                         STACK_OF(X509_ATTRIBUTE) *x = ptr;
1241       return gost2015_process_unprotected_attributes(x, arg, MAGMA_MAC_MAX_SIZE, c->tag);
1242                 }
1243     case EVP_CTRL_COPY: {
1244                         EVP_CIPHER_CTX *out = ptr;
1245       struct ossl_gost_cipher_ctx *in_cctx  = EVP_CIPHER_CTX_get_cipher_data(ctx);
1246       struct ossl_gost_cipher_ctx *out_cctx = EVP_CIPHER_CTX_get_cipher_data(out);
1247
1248                         if (in_cctx->omac_ctx == out_cctx->omac_ctx) {
1249                                 out_cctx->omac_ctx = EVP_MD_CTX_new();
1250                                 if (out_cctx->omac_ctx == NULL) {
1251                                         GOSTerr(GOST_F_MAGMA_CIPHER_CTL_ACPKM_OMAC, ERR_R_MALLOC_FAILURE);
1252                                         return -1;
1253                                 }
1254                         }
1255                         return EVP_MD_CTX_copy(out_cctx->omac_ctx, in_cctx->omac_ctx);
1256                 }
1257                 default:
1258                         return magma_cipher_ctl(ctx, type, arg, ptr);
1259                         break;
1260         }
1261 }
1262
1263 /* Set cipher parameters from ASN1 structure */
1264 static int gost89_set_asn1_parameters(EVP_CIPHER_CTX *ctx, ASN1_TYPE *params)
1265 {
1266     int len = 0;
1267     unsigned char *buf = NULL;
1268     unsigned char *p = NULL;
1269     struct ossl_gost_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
1270     GOST_CIPHER_PARAMS *gcp = GOST_CIPHER_PARAMS_new();
1271     ASN1_OCTET_STRING *os = NULL;
1272     if (!gcp) {
1273         GOSTerr(GOST_F_GOST89_SET_ASN1_PARAMETERS, ERR_R_MALLOC_FAILURE);
1274         return 0;
1275     }
1276     if (!ASN1_OCTET_STRING_set
1277         (gcp->iv, EVP_CIPHER_CTX_iv(ctx), EVP_CIPHER_CTX_iv_length(ctx))) {
1278         GOST_CIPHER_PARAMS_free(gcp);
1279         GOSTerr(GOST_F_GOST89_SET_ASN1_PARAMETERS, ERR_R_MALLOC_FAILURE);
1280         return 0;
1281     }
1282     ASN1_OBJECT_free(gcp->enc_param_set);
1283     gcp->enc_param_set = OBJ_nid2obj(c->paramNID);
1284
1285     len = i2d_GOST_CIPHER_PARAMS(gcp, NULL);
1286     p = buf = OPENSSL_malloc(len);
1287     if (!buf) {
1288         GOST_CIPHER_PARAMS_free(gcp);
1289         GOSTerr(GOST_F_GOST89_SET_ASN1_PARAMETERS, ERR_R_MALLOC_FAILURE);
1290         return 0;
1291     }
1292     i2d_GOST_CIPHER_PARAMS(gcp, &p);
1293     GOST_CIPHER_PARAMS_free(gcp);
1294
1295     os = ASN1_OCTET_STRING_new();
1296
1297     if (!os || !ASN1_OCTET_STRING_set(os, buf, len)) {
1298         OPENSSL_free(buf);
1299         GOSTerr(GOST_F_GOST89_SET_ASN1_PARAMETERS, ERR_R_MALLOC_FAILURE);
1300         return 0;
1301     }
1302     OPENSSL_free(buf);
1303
1304     ASN1_TYPE_set(params, V_ASN1_SEQUENCE, os);
1305     return 1;
1306 }
1307
1308 /* Store parameters into ASN1 structure */
1309 static int gost89_get_asn1_parameters(EVP_CIPHER_CTX *ctx, ASN1_TYPE *params)
1310 {
1311     int len;
1312     GOST_CIPHER_PARAMS *gcp = NULL;
1313     unsigned char *p;
1314     struct ossl_gost_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
1315     int nid;
1316
1317     if (ASN1_TYPE_get(params) != V_ASN1_SEQUENCE) {
1318         return -1;
1319     }
1320
1321     p = params->value.sequence->data;
1322
1323     gcp = d2i_GOST_CIPHER_PARAMS(NULL, (const unsigned char **)&p,
1324                                  params->value.sequence->length);
1325
1326     len = gcp->iv->length;
1327     if (len != EVP_CIPHER_CTX_iv_length(ctx)) {
1328         GOST_CIPHER_PARAMS_free(gcp);
1329         GOSTerr(GOST_F_GOST89_GET_ASN1_PARAMETERS, GOST_R_INVALID_IV_LENGTH);
1330         return -1;
1331     }
1332
1333     nid = OBJ_obj2nid(gcp->enc_param_set);
1334     if (nid == NID_undef) {
1335         GOST_CIPHER_PARAMS_free(gcp);
1336         GOSTerr(GOST_F_GOST89_GET_ASN1_PARAMETERS,
1337                 GOST_R_INVALID_CIPHER_PARAM_OID);
1338         return -1;
1339     }
1340
1341     if (!gost_cipher_set_param(c, nid)) {
1342         GOST_CIPHER_PARAMS_free(gcp);
1343         return -1;
1344     }
1345     /*XXX missing non-const accessor */
1346     memcpy((unsigned char *)EVP_CIPHER_CTX_original_iv(ctx), gcp->iv->data,
1347            EVP_CIPHER_CTX_iv_length(ctx));
1348
1349     GOST_CIPHER_PARAMS_free(gcp);
1350
1351     return 1;
1352 }
1353
1354 #define MAGMA_UKM_LEN 12
1355 static int magma_set_asn1_parameters (EVP_CIPHER_CTX *ctx, ASN1_TYPE *params)
1356 {
1357   struct ossl_gost_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
1358         c->key_meshing = 8192;
1359
1360         return gost2015_set_asn1_params(params, EVP_CIPHER_CTX_original_iv(ctx), 4,
1361                 c->kdf_seed);
1362 }
1363
1364 static int magma_get_asn1_parameters(EVP_CIPHER_CTX *ctx, ASN1_TYPE *params)
1365 {
1366   struct ossl_gost_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
1367         unsigned char iv[16];
1368
1369         c->key_meshing = 8192;
1370
1371         if (gost2015_get_asn1_params(params, MAGMA_UKM_LEN, iv, 4, c->kdf_seed) < 0)
1372             return -1;
1373
1374         memcpy(EVP_CIPHER_CTX_iv_noconst(ctx), iv, sizeof(iv));
1375         memcpy((unsigned char *)EVP_CIPHER_CTX_original_iv(ctx), iv, sizeof(iv));
1376         /* Key meshing 8 kb*/
1377         c->key_meshing = 8192;
1378
1379         return 1;
1380 }
1381
1382 static int gost_imit_init(EVP_MD_CTX *ctx, gost_subst_block * block)
1383 {
1384     struct ossl_gost_imit_ctx *c = EVP_MD_CTX_md_data(ctx);
1385     memset(c->buffer, 0, sizeof(c->buffer));
1386     memset(c->partial_block, 0, sizeof(c->partial_block));
1387     c->count = 0;
1388     c->bytes_left = 0;
1389     c->key_meshing = 1;
1390     c->dgst_size = 4;
1391     gost_init(&(c->cctx), block);
1392     return 1;
1393 }
1394
1395 static int gost_imit_init_cpa(EVP_MD_CTX *ctx)
1396 {
1397     return gost_imit_init(ctx, &Gost28147_CryptoProParamSetA);
1398 }
1399
1400 static int gost_imit_init_cp_12(EVP_MD_CTX *ctx)
1401 {
1402     return gost_imit_init(ctx, &Gost28147_TC26ParamSetZ);
1403 }
1404
1405 static void mac_block_mesh(struct ossl_gost_imit_ctx *c,
1406                            const unsigned char *data)
1407 {
1408     /*
1409      * We are using NULL for iv because CryptoPro doesn't interpret
1410      * internal state of MAC algorithm as iv during keymeshing (but does
1411      * initialize internal state from iv in key transport
1412      */
1413     assert(c->count % 8 == 0 && c->count <= 1024);
1414     if (c->key_meshing && c->count == 1024) {
1415         cryptopro_key_meshing(&(c->cctx), NULL);
1416     }
1417     mac_block(&(c->cctx), c->buffer, data);
1418     c->count = c->count % 1024 + 8;
1419 }
1420
1421 static int gost_imit_update(EVP_MD_CTX *ctx, const void *data, size_t count)
1422 {
1423     struct ossl_gost_imit_ctx *c = EVP_MD_CTX_md_data(ctx);
1424     const unsigned char *p = data;
1425     size_t bytes = count;
1426     if (!(c->key_set)) {
1427         GOSTerr(GOST_F_GOST_IMIT_UPDATE, GOST_R_MAC_KEY_NOT_SET);
1428         return 0;
1429     }
1430     if (c->bytes_left) {
1431         size_t i;
1432         for (i = c->bytes_left; i < 8 && bytes > 0; bytes--, i++, p++) {
1433             c->partial_block[i] = *p;
1434         }
1435         if (i == 8) {
1436             mac_block_mesh(c, c->partial_block);
1437         } else {
1438             c->bytes_left = i;
1439             return 1;
1440         }
1441     }
1442     while (bytes > 8) {
1443         mac_block_mesh(c, p);
1444         p += 8;
1445         bytes -= 8;
1446     }
1447     if (bytes > 0) {
1448         memcpy(c->partial_block, p, bytes);
1449     }
1450     c->bytes_left = bytes;
1451     return 1;
1452 }
1453
1454 static int gost_imit_final(EVP_MD_CTX *ctx, unsigned char *md)
1455 {
1456     struct ossl_gost_imit_ctx *c = EVP_MD_CTX_md_data(ctx);
1457     if (!c->key_set) {
1458         GOSTerr(GOST_F_GOST_IMIT_FINAL, GOST_R_MAC_KEY_NOT_SET);
1459         return 0;
1460     }
1461     if (c->count == 0 && c->bytes_left) {
1462         unsigned char buffer[8];
1463         memset(buffer, 0, 8);
1464         gost_imit_update(ctx, buffer, 8);
1465     }
1466     if (c->bytes_left) {
1467         int i;
1468         for (i = c->bytes_left; i < 8; i++) {
1469             c->partial_block[i] = 0;
1470         }
1471         mac_block_mesh(c, c->partial_block);
1472     }
1473     get_mac(c->buffer, 8 * c->dgst_size, md);
1474     return 1;
1475 }
1476
1477 static int gost_imit_ctrl(EVP_MD_CTX *ctx, int type, int arg, void *ptr)
1478 {
1479     switch (type) {
1480     case EVP_MD_CTRL_KEY_LEN:
1481         *((unsigned int *)(ptr)) = 32;
1482         return 1;
1483     case EVP_MD_CTRL_SET_KEY:
1484         {
1485             struct ossl_gost_imit_ctx *gost_imit_ctx = EVP_MD_CTX_md_data(ctx);
1486
1487             if (EVP_MD_meth_get_init(EVP_MD_CTX_md(ctx)) (ctx) <= 0) {
1488                 GOSTerr(GOST_F_GOST_IMIT_CTRL, GOST_R_MAC_KEY_NOT_SET);
1489                 return 0;
1490             }
1491             EVP_MD_CTX_set_flags(ctx, EVP_MD_CTX_FLAG_NO_INIT);
1492
1493             if (arg == 0) {
1494                 struct gost_mac_key *key = (struct gost_mac_key *)ptr;
1495                 if (key->mac_param_nid != NID_undef) {
1496                     const struct gost_cipher_info *param =
1497                         get_encryption_params(OBJ_nid2obj(key->mac_param_nid));
1498                     if (param == NULL) {
1499                         GOSTerr(GOST_F_GOST_IMIT_CTRL,
1500                                 GOST_R_INVALID_MAC_PARAMS);
1501                         return 0;
1502                     }
1503                     gost_init(&(gost_imit_ctx->cctx), param->sblock);
1504                 }
1505                 gost_key(&(gost_imit_ctx->cctx), key->key);
1506                 gost_imit_ctx->key_set = 1;
1507
1508                 return 1;
1509             } else if (arg == 32) {
1510                 gost_key(&(gost_imit_ctx->cctx), ptr);
1511                 gost_imit_ctx->key_set = 1;
1512                 return 1;
1513             }
1514             GOSTerr(GOST_F_GOST_IMIT_CTRL, GOST_R_INVALID_MAC_KEY_SIZE);
1515             return 0;
1516         }
1517     case EVP_MD_CTRL_XOF_LEN:
1518         {
1519             struct ossl_gost_imit_ctx *c = EVP_MD_CTX_md_data(ctx);
1520             if (arg < 1 || arg > 8) {
1521                 GOSTerr(GOST_F_GOST_IMIT_CTRL, GOST_R_INVALID_MAC_SIZE);
1522                 return 0;
1523             }
1524             c->dgst_size = arg;
1525             return 1;
1526         }
1527
1528     default:
1529         return 0;
1530     }
1531 }
1532
1533 static int gost_imit_copy(EVP_MD_CTX *to, const EVP_MD_CTX *from)
1534 {
1535     if (EVP_MD_CTX_md_data(to) && EVP_MD_CTX_md_data(from)) {
1536         memcpy(EVP_MD_CTX_md_data(to), EVP_MD_CTX_md_data(from),
1537                sizeof(struct ossl_gost_imit_ctx));
1538     }
1539     return 1;
1540 }
1541
1542 /* Clean up imit ctx */
1543 static int gost_imit_cleanup(EVP_MD_CTX *ctx)
1544 {
1545     memset(EVP_MD_CTX_md_data(ctx), 0, sizeof(struct ossl_gost_imit_ctx));
1546     return 1;
1547 }
1548 /* vim: set expandtab cinoptions=\:0,l1,t0,g0,(0 sw=4 : */