]> www.wagner.pp.ru Git - openssl-gost/engine.git/blob - gost_grasshopper_cipher.c
Refactoring unprotected attributes processing
[openssl-gost/engine.git] / gost_grasshopper_cipher.c
1 /*
2  * Maxim Tishkov 2016
3  * This file is distributed under the same license as OpenSSL
4  */
5
6 #include "gost_grasshopper_cipher.h"
7 #include "gost_grasshopper_defines.h"
8 #include "gost_grasshopper_math.h"
9 #include "gost_grasshopper_core.h"
10 #include "gost_gost2015.h"
11
12 #include <openssl/evp.h>
13 #include <openssl/rand.h>
14 #include <openssl/err.h>
15 #include <string.h>
16
17 #include "gost_lcl.h"
18 #include "e_gost_err.h"
19
20 enum GRASSHOPPER_CIPHER_TYPE {
21     GRASSHOPPER_CIPHER_ECB = 0,
22     GRASSHOPPER_CIPHER_CBC,
23     GRASSHOPPER_CIPHER_OFB,
24     GRASSHOPPER_CIPHER_CFB,
25     GRASSHOPPER_CIPHER_CTR,
26     GRASSHOPPER_CIPHER_CTRACPKM,
27     GRASSHOPPER_CIPHER_CTRACPKMOMAC,
28 };
29
30 static EVP_CIPHER *gost_grasshopper_ciphers[7] = {
31     NULL, NULL, NULL, NULL, NULL, NULL, NULL
32 };
33
34 static GRASSHOPPER_INLINE void
35 gost_grasshopper_cipher_destroy_ctr(gost_grasshopper_cipher_ctx * c);
36
37 struct GRASSHOPPER_CIPHER_PARAMS {
38     int nid;
39     grasshopper_init_cipher_func init_cipher;
40     grasshopper_do_cipher_func do_cipher;
41     grasshopper_destroy_cipher_func destroy_cipher;
42     int block_size;
43     int ctx_size;
44     int iv_size;
45     bool padding;
46     int extra_flags;
47 };
48
49 static struct GRASSHOPPER_CIPHER_PARAMS gost_cipher_params[7] = {
50         {
51                 NID_grasshopper_ecb,
52                 gost_grasshopper_cipher_init_ecb,
53                 gost_grasshopper_cipher_do_ecb,
54                 NULL,
55                 16,
56                 sizeof(gost_grasshopper_cipher_ctx),
57                 0,
58                 true,
59                 0
60         },
61         {
62                 NID_grasshopper_cbc,
63                 gost_grasshopper_cipher_init_cbc,
64                 gost_grasshopper_cipher_do_cbc,
65                 NULL,
66                 16,
67                 sizeof(gost_grasshopper_cipher_ctx),
68                 16,
69                 true,
70                 0
71         },
72         {
73                 NID_grasshopper_ofb,
74                 gost_grasshopper_cipher_init_ofb,
75                 gost_grasshopper_cipher_do_ofb,
76                 NULL,
77                 1,
78                 sizeof(gost_grasshopper_cipher_ctx),
79                 16,
80                 false,
81                 0
82         },
83         {
84                 NID_grasshopper_cfb,
85                 gost_grasshopper_cipher_init_cfb,
86                 gost_grasshopper_cipher_do_cfb,
87                 NULL,
88                 1,
89                 sizeof(gost_grasshopper_cipher_ctx),
90                 16,
91                 false,
92                 0
93         },
94         {
95                 NID_grasshopper_ctr,
96                 gost_grasshopper_cipher_init_ctr,
97                 gost_grasshopper_cipher_do_ctr,
98                 gost_grasshopper_cipher_destroy_ctr,
99                 1,
100                 sizeof(gost_grasshopper_cipher_ctx_ctr),
101                 8,
102                 false,
103                 0
104         },
105         {
106                 NID_kuznyechik_ctr_acpkm,
107                 gost_grasshopper_cipher_init_ctracpkm,
108                 gost_grasshopper_cipher_do_ctracpkm,
109                 gost_grasshopper_cipher_destroy_ctr,
110                 1,
111                 sizeof(gost_grasshopper_cipher_ctx_ctr),
112                 8,
113                 false,
114                 0
115         },
116         {
117                 NID_kuznyechik_ctr_acpkm_omac,
118                 gost_grasshopper_cipher_init_ctracpkm_omac,
119                 gost_grasshopper_cipher_do_ctracpkm_omac,
120                 gost_grasshopper_cipher_destroy_ctr,
121                 1,
122                 sizeof(gost_grasshopper_cipher_ctx_ctr),
123                 8,
124                 false,
125                 EVP_CIPH_FLAG_CUSTOM_CIPHER|EVP_CIPH_FLAG_CIPHER_WITH_MAC|EVP_CIPH_CUSTOM_COPY
126         },
127 };
128
129 /* first 256 bit of D from draft-irtf-cfrg-re-keying-12 */
130 static const unsigned char ACPKM_D_2018[] = {
131     0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, /*  64 bit */
132     0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, /* 128 bit */
133     0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
134     0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, /* 256 bit */
135 };
136
137 static void acpkm_next(gost_grasshopper_cipher_ctx * c)
138 {
139     unsigned char newkey[GRASSHOPPER_KEY_SIZE];
140     const int J = GRASSHOPPER_KEY_SIZE / GRASSHOPPER_BLOCK_SIZE;
141     int n;
142
143     for (n = 0; n < J; n++) {
144         const unsigned char *D_n = &ACPKM_D_2018[n * GRASSHOPPER_BLOCK_SIZE];
145
146         grasshopper_encrypt_block(&c->encrypt_round_keys,
147                                   (grasshopper_w128_t *) D_n,
148                                   (grasshopper_w128_t *) & newkey[n *
149                                                                   GRASSHOPPER_BLOCK_SIZE],
150                                   &c->buffer);
151     }
152     gost_grasshopper_cipher_key(c, newkey);
153 }
154
155 /* Set 256 bit  key into context */
156 GRASSHOPPER_INLINE void
157 gost_grasshopper_cipher_key(gost_grasshopper_cipher_ctx * c, const uint8_t *k)
158 {
159     int i;
160     for (i = 0; i < 2; i++) {
161         grasshopper_copy128(&c->key.k.k[i],
162                             (const grasshopper_w128_t *)(k + i * 16));
163     }
164
165     grasshopper_set_encrypt_key(&c->encrypt_round_keys, &c->key);
166     grasshopper_set_decrypt_key(&c->decrypt_round_keys, &c->key);
167 }
168
169 /* Set master 256-bit key to be used in TLSTREE calculation into context */
170 GRASSHOPPER_INLINE void
171 gost_grasshopper_master_key(gost_grasshopper_cipher_ctx * c, const uint8_t *k)
172 {
173     int i;
174     for (i = 0; i < 2; i++) {
175         grasshopper_copy128(&c->master_key.k.k[i],
176                             (const grasshopper_w128_t *)(k + i * 16));
177     }
178 }
179
180 /* Cleans up key from context */
181 GRASSHOPPER_INLINE void
182 gost_grasshopper_cipher_destroy(gost_grasshopper_cipher_ctx * c)
183 {
184     int i;
185     for (i = 0; i < 2; i++) {
186         grasshopper_zero128(&c->key.k.k[i]);
187         grasshopper_zero128(&c->master_key.k.k[i]);
188     }
189     for (i = 0; i < GRASSHOPPER_ROUND_KEYS_COUNT; i++) {
190         grasshopper_zero128(&c->encrypt_round_keys.k[i]);
191     }
192     for (i = 0; i < GRASSHOPPER_ROUND_KEYS_COUNT; i++) {
193         grasshopper_zero128(&c->decrypt_round_keys.k[i]);
194     }
195     grasshopper_zero128(&c->buffer);
196 }
197
198 static GRASSHOPPER_INLINE void
199 gost_grasshopper_cipher_destroy_ctr(gost_grasshopper_cipher_ctx * c)
200 {
201     gost_grasshopper_cipher_ctx_ctr *ctx =
202         (gost_grasshopper_cipher_ctx_ctr *) c;
203
204     if (ctx->omac_ctx)
205         EVP_MD_CTX_free(ctx->omac_ctx);
206
207     grasshopper_zero128(&ctx->partial_buffer);
208 }
209
210 int gost_grasshopper_cipher_init(EVP_CIPHER_CTX *ctx,
211                                  const unsigned char *key,
212                                  const unsigned char *iv, int enc)
213 {
214     gost_grasshopper_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
215
216     if (EVP_CIPHER_CTX_get_app_data(ctx) == NULL) {
217         EVP_CIPHER_CTX_set_app_data(ctx, EVP_CIPHER_CTX_get_cipher_data(ctx));
218     }
219
220     if (key != NULL) {
221         gost_grasshopper_cipher_key(c, key);
222         gost_grasshopper_master_key(c, key);
223     }
224
225     if (iv != NULL) {
226         memcpy((unsigned char *)EVP_CIPHER_CTX_original_iv(ctx), iv,
227                EVP_CIPHER_CTX_iv_length(ctx));
228     }
229
230     memcpy(EVP_CIPHER_CTX_iv_noconst(ctx),
231            EVP_CIPHER_CTX_original_iv(ctx), EVP_CIPHER_CTX_iv_length(ctx));
232
233     grasshopper_zero128(&c->buffer);
234
235     return 1;
236 }
237
238 GRASSHOPPER_INLINE int gost_grasshopper_cipher_init_ecb(EVP_CIPHER_CTX *ctx, const unsigned char
239                                                         *key, const unsigned char
240                                                         *iv, int enc)
241 {
242     gost_grasshopper_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
243     c->type = GRASSHOPPER_CIPHER_ECB;
244     return gost_grasshopper_cipher_init(ctx, key, iv, enc);
245 }
246
247 GRASSHOPPER_INLINE int gost_grasshopper_cipher_init_cbc(EVP_CIPHER_CTX *ctx, const unsigned char
248                                                         *key, const unsigned char
249                                                         *iv, int enc)
250 {
251     gost_grasshopper_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
252     c->type = GRASSHOPPER_CIPHER_CBC;
253     return gost_grasshopper_cipher_init(ctx, key, iv, enc);
254 }
255
256 GRASSHOPPER_INLINE int gost_grasshopper_cipher_init_ofb(EVP_CIPHER_CTX *ctx, const unsigned char
257                                                         *key, const unsigned char
258                                                         *iv, int enc)
259 {
260     gost_grasshopper_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
261     c->type = GRASSHOPPER_CIPHER_OFB;
262     return gost_grasshopper_cipher_init(ctx, key, iv, enc);
263 }
264
265 GRASSHOPPER_INLINE int gost_grasshopper_cipher_init_cfb(EVP_CIPHER_CTX *ctx, const unsigned char
266                                                         *key, const unsigned char
267                                                         *iv, int enc)
268 {
269     gost_grasshopper_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
270     c->type = GRASSHOPPER_CIPHER_CFB;
271     return gost_grasshopper_cipher_init(ctx, key, iv, enc);
272 }
273
274 GRASSHOPPER_INLINE int gost_grasshopper_cipher_init_ctr(EVP_CIPHER_CTX *ctx, const unsigned char
275                                                         *key, const unsigned char
276                                                         *iv, int enc)
277 {
278     gost_grasshopper_cipher_ctx_ctr *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
279
280     c->c.type = GRASSHOPPER_CIPHER_CTR;
281     EVP_CIPHER_CTX_set_num(ctx, 0);
282
283     grasshopper_zero128(&c->partial_buffer);
284
285     return gost_grasshopper_cipher_init(ctx, key, iv, enc);
286 }
287
288 GRASSHOPPER_INLINE int gost_grasshopper_cipher_init_ctracpkm(EVP_CIPHER_CTX
289                                                              *ctx, const unsigned
290                                                              char *key, const unsigned
291                                                              char *iv, int enc)
292 {
293     gost_grasshopper_cipher_ctx_ctr *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
294
295     /* NB: setting type makes EVP do_cipher callback useless */
296     c->c.type = GRASSHOPPER_CIPHER_CTRACPKM;
297     EVP_CIPHER_CTX_set_num(ctx, 0);
298     c->section_size = 4096;
299
300     return gost_grasshopper_cipher_init(ctx, key, iv, enc);
301 }
302
303 GRASSHOPPER_INLINE int gost_grasshopper_cipher_init_ctracpkm_omac(EVP_CIPHER_CTX
304                                                              *ctx, const unsigned
305                                                              char *key, const unsigned
306                                                              char *iv, int enc)
307 {
308         gost_grasshopper_cipher_ctx_ctr *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
309
310         /* NB: setting type makes EVP do_cipher callback useless */
311         c->c.type = GRASSHOPPER_CIPHER_CTRACPKMOMAC;
312         EVP_CIPHER_CTX_set_num(ctx, 0);
313         c->section_size = 4096;
314
315         if (key) {
316                 unsigned char keys[64];
317                 const EVP_MD *md = EVP_get_digestbynid(NID_kuznyechik_mac);
318                 EVP_PKEY *mac_key;
319
320                 if (md == NULL)
321                         return 0;
322
323                 if (enc) {
324                         if (RAND_bytes(c->kdf_seed, 8) != 1)
325                                 return 0;
326                 }
327
328                 if (gost_kdftree2012_256(keys, 64, key, 32, (const unsigned char *)"kdf tree", 8, c->kdf_seed, 8, 1) <= 0)
329                         return 0;
330
331                 c->omac_ctx = EVP_MD_CTX_new();
332                 mac_key = EVP_PKEY_new_mac_key(NID_kuznyechik_mac, NULL, keys+32, 32);
333
334                 if (mac_key == NULL || c->omac_ctx == NULL) {
335                         EVP_PKEY_free(mac_key);
336                         return 0;
337                 }
338
339                 if (EVP_DigestInit_ex(c->omac_ctx, md, NULL) <= 0 ||
340                                 EVP_DigestSignInit(c->omac_ctx, NULL, md, NULL, mac_key) <= 0) {
341                         EVP_PKEY_free(mac_key);
342                         return 0;
343                 }
344                 EVP_PKEY_free(mac_key);
345
346                 return gost_grasshopper_cipher_init(ctx, keys, iv, enc);
347         }
348         return gost_grasshopper_cipher_init(ctx, key, iv, enc);
349 }
350
351 GRASSHOPPER_INLINE int gost_grasshopper_cipher_do(EVP_CIPHER_CTX *ctx,
352                                                   unsigned char *out,
353                                                   const unsigned char *in,
354                                                   size_t inl)
355 {
356     gost_grasshopper_cipher_ctx *c =
357         (gost_grasshopper_cipher_ctx *) EVP_CIPHER_CTX_get_cipher_data(ctx);
358     struct GRASSHOPPER_CIPHER_PARAMS *params = &gost_cipher_params[c->type];
359
360     return params->do_cipher(ctx, out, in, inl);
361 }
362
363 int gost_grasshopper_cipher_do_ecb(EVP_CIPHER_CTX *ctx, unsigned char *out,
364                                    const unsigned char *in, size_t inl)
365 {
366     gost_grasshopper_cipher_ctx *c =
367         (gost_grasshopper_cipher_ctx *) EVP_CIPHER_CTX_get_cipher_data(ctx);
368     bool encrypting = (bool) EVP_CIPHER_CTX_encrypting(ctx);
369     const unsigned char *current_in = in;
370     unsigned char *current_out = out;
371     size_t blocks = inl / GRASSHOPPER_BLOCK_SIZE;
372     size_t i;
373
374     for (i = 0; i < blocks;
375          i++, current_in += GRASSHOPPER_BLOCK_SIZE, current_out +=
376          GRASSHOPPER_BLOCK_SIZE) {
377         if (encrypting) {
378             grasshopper_encrypt_block(&c->encrypt_round_keys,
379                                       (grasshopper_w128_t *) current_in,
380                                       (grasshopper_w128_t *) current_out,
381                                       &c->buffer);
382         } else {
383             grasshopper_decrypt_block(&c->decrypt_round_keys,
384                                       (grasshopper_w128_t *) current_in,
385                                       (grasshopper_w128_t *) current_out,
386                                       &c->buffer);
387         }
388     }
389
390     return 1;
391 }
392
393 int gost_grasshopper_cipher_do_cbc(EVP_CIPHER_CTX *ctx, unsigned char *out,
394                                    const unsigned char *in, size_t inl)
395 {
396     gost_grasshopper_cipher_ctx *c =
397         (gost_grasshopper_cipher_ctx *) EVP_CIPHER_CTX_get_cipher_data(ctx);
398     unsigned char *iv = EVP_CIPHER_CTX_iv_noconst(ctx);
399     bool encrypting = (bool) EVP_CIPHER_CTX_encrypting(ctx);
400     const unsigned char *current_in = in;
401     unsigned char *current_out = out;
402     size_t blocks = inl / GRASSHOPPER_BLOCK_SIZE;
403     size_t i;
404     grasshopper_w128_t *currentBlock;
405
406     currentBlock = (grasshopper_w128_t *) iv;
407
408     for (i = 0; i < blocks;
409          i++, current_in += GRASSHOPPER_BLOCK_SIZE, current_out +=
410          GRASSHOPPER_BLOCK_SIZE) {
411         grasshopper_w128_t *currentInputBlock = (grasshopper_w128_t *) current_in;
412         grasshopper_w128_t *currentOutputBlock = (grasshopper_w128_t *) current_out;
413         if (encrypting) {
414             grasshopper_append128(currentBlock, currentInputBlock);
415             grasshopper_encrypt_block(&c->encrypt_round_keys, currentBlock,
416                                       currentOutputBlock, &c->buffer);
417             grasshopper_copy128(currentBlock, currentOutputBlock);
418         } else {
419             grasshopper_w128_t tmp;
420
421             grasshopper_copy128(&tmp, currentInputBlock);
422             grasshopper_decrypt_block(&c->decrypt_round_keys,
423                                       currentInputBlock, currentOutputBlock,
424                                       &c->buffer);
425             grasshopper_append128(currentOutputBlock, currentBlock);
426             grasshopper_copy128(currentBlock, &tmp);
427         }
428     }
429
430     return 1;
431 }
432
433 void inc_counter(unsigned char *counter, size_t counter_bytes)
434 {
435     unsigned int n = counter_bytes;
436
437     do {
438         unsigned char c;
439         --n;
440         c = counter[n];
441         ++c;
442         counter[n] = c;
443         if (c)
444             return;
445     } while (n);
446 }
447
448 /* increment counter (128-bit int) by 1 */
449 static void ctr128_inc(unsigned char *counter)
450 {
451     inc_counter(counter, 16);
452 }
453
454 int gost_grasshopper_cipher_do_ctr(EVP_CIPHER_CTX *ctx, unsigned char *out,
455                                    const unsigned char *in, size_t inl)
456 {
457     gost_grasshopper_cipher_ctx_ctr *c = (gost_grasshopper_cipher_ctx_ctr *)
458         EVP_CIPHER_CTX_get_cipher_data(ctx);
459     unsigned char *iv = EVP_CIPHER_CTX_iv_noconst(ctx);
460     const unsigned char *current_in = in;
461     unsigned char *current_out = out;
462     grasshopper_w128_t *currentInputBlock;
463     grasshopper_w128_t *currentOutputBlock;
464     unsigned int n = EVP_CIPHER_CTX_num(ctx);
465     size_t lasted = inl;
466     size_t i;
467     size_t blocks;
468     grasshopper_w128_t *iv_buffer;
469     grasshopper_w128_t tmp;
470
471     while (n && lasted) {
472         *(current_out++) = *(current_in++) ^ c->partial_buffer.b[n];
473         --lasted;
474         n = (n + 1) % GRASSHOPPER_BLOCK_SIZE;
475     }
476     EVP_CIPHER_CTX_set_num(ctx, n);
477     blocks = lasted / GRASSHOPPER_BLOCK_SIZE;
478
479     iv_buffer = (grasshopper_w128_t *) iv;
480
481     // full parts
482     for (i = 0; i < blocks; i++) {
483         currentInputBlock = (grasshopper_w128_t *) current_in;
484         currentOutputBlock = (grasshopper_w128_t *) current_out;
485         grasshopper_encrypt_block(&c->c.encrypt_round_keys, iv_buffer,
486                                   &c->partial_buffer, &c->c.buffer);
487         grasshopper_plus128(&tmp, &c->partial_buffer, currentInputBlock);
488         grasshopper_copy128(currentOutputBlock, &tmp);
489         ctr128_inc(iv_buffer->b);
490         current_in += GRASSHOPPER_BLOCK_SIZE;
491         current_out += GRASSHOPPER_BLOCK_SIZE;
492                                 lasted -= GRASSHOPPER_BLOCK_SIZE;
493     }
494
495     if (lasted > 0) {
496         currentInputBlock = (grasshopper_w128_t *) current_in;
497         currentOutputBlock = (grasshopper_w128_t *) current_out;
498         grasshopper_encrypt_block(&c->c.encrypt_round_keys, iv_buffer,
499                                   &c->partial_buffer, &c->c.buffer);
500         for (i = 0; i < lasted; i++) {
501             currentOutputBlock->b[i] =
502                 c->partial_buffer.b[i] ^ currentInputBlock->b[i];
503         }
504         EVP_CIPHER_CTX_set_num(ctx, i);
505         ctr128_inc(iv_buffer->b);
506     }
507
508     return inl;
509 }
510
511 #define GRASSHOPPER_BLOCK_MASK (GRASSHOPPER_BLOCK_SIZE - 1)
512 static inline void apply_acpkm_grasshopper(gost_grasshopper_cipher_ctx_ctr *
513                                            ctx, unsigned int *num)
514 {
515     if (!ctx->section_size || (*num < ctx->section_size))
516         return;
517     acpkm_next(&ctx->c);
518     *num &= GRASSHOPPER_BLOCK_MASK;
519 }
520
521 /* If meshing is not configured via ctrl (setting section_size)
522  * this function works exactly like plain ctr */
523 int gost_grasshopper_cipher_do_ctracpkm(EVP_CIPHER_CTX *ctx,
524                                         unsigned char *out,
525                                         const unsigned char *in, size_t inl)
526 {
527     gost_grasshopper_cipher_ctx_ctr *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
528     unsigned char *iv = EVP_CIPHER_CTX_iv_noconst(ctx);
529     unsigned int num = EVP_CIPHER_CTX_num(ctx);
530     size_t blocks, i, lasted = inl;
531     grasshopper_w128_t tmp;
532
533     while ((num & GRASSHOPPER_BLOCK_MASK) && lasted) {
534         *out++ = *in++ ^ c->partial_buffer.b[num & GRASSHOPPER_BLOCK_MASK];
535         --lasted;
536         num++;
537     }
538     blocks = lasted / GRASSHOPPER_BLOCK_SIZE;
539
540     // full parts
541     for (i = 0; i < blocks; i++) {
542         apply_acpkm_grasshopper(c, &num);
543         grasshopper_encrypt_block(&c->c.encrypt_round_keys,
544                                   (grasshopper_w128_t *) iv,
545                                   (grasshopper_w128_t *) & c->partial_buffer,
546                                   &c->c.buffer);
547         grasshopper_plus128(&tmp, &c->partial_buffer,
548                             (grasshopper_w128_t *) in);
549         grasshopper_copy128((grasshopper_w128_t *) out, &tmp);
550         ctr128_inc(iv);
551         in += GRASSHOPPER_BLOCK_SIZE;
552         out += GRASSHOPPER_BLOCK_SIZE;
553         num += GRASSHOPPER_BLOCK_SIZE;
554                                 lasted -= GRASSHOPPER_BLOCK_SIZE;
555     }
556
557     // last part
558     if (lasted > 0) {
559         apply_acpkm_grasshopper(c, &num);
560         grasshopper_encrypt_block(&c->c.encrypt_round_keys,
561                                   (grasshopper_w128_t *) iv,
562                                   &c->partial_buffer, &c->c.buffer);
563         for (i = 0; i < lasted; i++)
564             out[i] = c->partial_buffer.b[i] ^ in[i];
565         ctr128_inc(iv);
566         num += lasted;
567     }
568     EVP_CIPHER_CTX_set_num(ctx, num);
569
570     return inl;
571 }
572
573 int gost_grasshopper_cipher_do_ctracpkm_omac(EVP_CIPHER_CTX *ctx,
574                                         unsigned char *out,
575                                         const unsigned char *in, size_t inl)
576 {
577         int result;
578   gost_grasshopper_cipher_ctx_ctr *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
579         /* As in and out can be the same pointer, process unencrypted here */
580         if (EVP_CIPHER_CTX_encrypting(ctx))
581                 EVP_DigestSignUpdate(c->omac_ctx, in, inl);
582
583         if (in == NULL && inl == 0) { /* Final call */
584                 return gost2015_final_call(ctx, c->omac_ctx, KUZNYECHIK_MAC_MAX_SIZE, c->tag, gost_grasshopper_cipher_do_ctracpkm);
585         }
586
587   if (in == NULL) {
588       GOSTerr(GOST_F_GOST_GRASSHOPPER_CIPHER_DO_CTRACPKM_OMAC, ERR_R_EVP_LIB);
589       return -1;
590   }
591         result = gost_grasshopper_cipher_do_ctracpkm(ctx, out, in, inl);
592
593         /* As in and out can be the same pointer, process decrypted here */
594         if (!EVP_CIPHER_CTX_encrypting(ctx))
595                 EVP_DigestSignUpdate(c->omac_ctx, out, inl);
596
597         return result;
598 }
599 /*
600  * Fixed 128-bit IV implementation make shift regiser redundant.
601  */
602 static void gost_grasshopper_cnt_next(gost_grasshopper_cipher_ctx * ctx,
603                                       grasshopper_w128_t * iv,
604                                       grasshopper_w128_t * buf)
605 {
606     grasshopper_w128_t tmp;
607     memcpy(&tmp, iv, 16);
608     grasshopper_encrypt_block(&ctx->encrypt_round_keys, &tmp,
609                               buf, &ctx->buffer);
610     memcpy(iv, buf, 16);
611 }
612
613 int gost_grasshopper_cipher_do_ofb(EVP_CIPHER_CTX *ctx, unsigned char *out,
614                                    const unsigned char *in, size_t inl)
615 {
616     gost_grasshopper_cipher_ctx *c = (gost_grasshopper_cipher_ctx *)
617         EVP_CIPHER_CTX_get_cipher_data(ctx);
618     const unsigned char *in_ptr = in;
619     unsigned char *out_ptr = out;
620     unsigned char *buf = EVP_CIPHER_CTX_buf_noconst(ctx);
621     unsigned char *iv = EVP_CIPHER_CTX_iv_noconst(ctx);
622     int num = EVP_CIPHER_CTX_num(ctx);
623     size_t i = 0;
624     size_t j;
625
626     /* process partial block if any */
627     if (num > 0) {
628         for (j = (size_t)num, i = 0; j < GRASSHOPPER_BLOCK_SIZE && i < inl;
629              j++, i++, in_ptr++, out_ptr++) {
630             *out_ptr = buf[j] ^ (*in_ptr);
631         }
632         if (j == GRASSHOPPER_BLOCK_SIZE) {
633             EVP_CIPHER_CTX_set_num(ctx, 0);
634         } else {
635             EVP_CIPHER_CTX_set_num(ctx, (int)j);
636             return 1;
637         }
638     }
639
640     for (; i + GRASSHOPPER_BLOCK_SIZE <
641          inl;
642          i += GRASSHOPPER_BLOCK_SIZE, in_ptr +=
643          GRASSHOPPER_BLOCK_SIZE, out_ptr += GRASSHOPPER_BLOCK_SIZE) {
644         /*
645          * block cipher current iv
646          */
647         /* Encrypt */
648         gost_grasshopper_cnt_next(c, (grasshopper_w128_t *) iv,
649                                   (grasshopper_w128_t *) buf);
650
651         /*
652          * xor next block of input text with it and output it
653          */
654         /*
655          * output this block
656          */
657         for (j = 0; j < GRASSHOPPER_BLOCK_SIZE; j++) {
658             out_ptr[j] = buf[j] ^ in_ptr[j];
659         }
660     }
661
662     /* Process rest of buffer */
663     if (i < inl) {
664         gost_grasshopper_cnt_next(c, (grasshopper_w128_t *) iv,
665                                   (grasshopper_w128_t *) buf);
666         for (j = 0; i < inl; j++, i++) {
667             out_ptr[j] = buf[j] ^ in_ptr[j];
668         }
669         EVP_CIPHER_CTX_set_num(ctx, (int)j);
670     } else {
671         EVP_CIPHER_CTX_set_num(ctx, 0);
672     }
673
674     return 1;
675 }
676
677 int gost_grasshopper_cipher_do_cfb(EVP_CIPHER_CTX *ctx, unsigned char *out,
678                                    const unsigned char *in, size_t inl)
679 {
680     gost_grasshopper_cipher_ctx *c =
681         (gost_grasshopper_cipher_ctx *) EVP_CIPHER_CTX_get_cipher_data(ctx);
682     const unsigned char *in_ptr = in;
683     unsigned char *out_ptr = out;
684     unsigned char *buf = EVP_CIPHER_CTX_buf_noconst(ctx);
685     unsigned char *iv = EVP_CIPHER_CTX_iv_noconst(ctx);
686     bool encrypting = (bool) EVP_CIPHER_CTX_encrypting(ctx);
687     int num = EVP_CIPHER_CTX_num(ctx);
688     size_t i = 0;
689     size_t j = 0;
690
691     /* process partial block if any */
692     if (num > 0) {
693         for (j = (size_t)num, i = 0; j < GRASSHOPPER_BLOCK_SIZE && i < inl;
694              j++, i++, in_ptr++, out_ptr++) {
695             if (!encrypting) {
696                 buf[j + GRASSHOPPER_BLOCK_SIZE] = *in_ptr;
697             }
698             *out_ptr = buf[j] ^ (*in_ptr);
699             if (encrypting) {
700                 buf[j + GRASSHOPPER_BLOCK_SIZE] = *out_ptr;
701             }
702         }
703         if (j == GRASSHOPPER_BLOCK_SIZE) {
704             memcpy(iv, buf + GRASSHOPPER_BLOCK_SIZE, GRASSHOPPER_BLOCK_SIZE);
705             EVP_CIPHER_CTX_set_num(ctx, 0);
706         } else {
707             EVP_CIPHER_CTX_set_num(ctx, (int)j);
708             return 1;
709         }
710     }
711
712     for (; i + GRASSHOPPER_BLOCK_SIZE <
713          inl;
714          i += GRASSHOPPER_BLOCK_SIZE, in_ptr +=
715          GRASSHOPPER_BLOCK_SIZE, out_ptr += GRASSHOPPER_BLOCK_SIZE) {
716         /*
717          * block cipher current iv
718          */
719         grasshopper_encrypt_block(&c->encrypt_round_keys,
720                                   (grasshopper_w128_t *) iv,
721                                   (grasshopper_w128_t *) buf, &c->buffer);
722         /*
723          * xor next block of input text with it and output it
724          */
725         /*
726          * output this block
727          */
728         if (!encrypting) {
729             memcpy(iv, in_ptr, GRASSHOPPER_BLOCK_SIZE);
730         }
731         for (j = 0; j < GRASSHOPPER_BLOCK_SIZE; j++) {
732             out_ptr[j] = buf[j] ^ in_ptr[j];
733         }
734         /* Encrypt */
735         /* Next iv is next block of cipher text */
736         if (encrypting) {
737             memcpy(iv, out_ptr, GRASSHOPPER_BLOCK_SIZE);
738         }
739     }
740
741     /* Process rest of buffer */
742     if (i < inl) {
743         grasshopper_encrypt_block(&c->encrypt_round_keys,
744                                   (grasshopper_w128_t *) iv,
745                                   (grasshopper_w128_t *) buf, &c->buffer);
746         if (!encrypting) {
747             memcpy(buf + GRASSHOPPER_BLOCK_SIZE, in_ptr, inl - i);
748         }
749         for (j = 0; i < inl; j++, i++) {
750             out_ptr[j] = buf[j] ^ in_ptr[j];
751         }
752         EVP_CIPHER_CTX_set_num(ctx, (int)j);
753         if (encrypting) {
754             memcpy(buf + GRASSHOPPER_BLOCK_SIZE, out_ptr, j);
755         }
756     } else {
757         EVP_CIPHER_CTX_set_num(ctx, 0);
758     }
759
760     return 1;
761 }
762
763 int gost_grasshopper_cipher_cleanup(EVP_CIPHER_CTX *ctx)
764 {
765     struct GRASSHOPPER_CIPHER_PARAMS *params;
766     gost_grasshopper_cipher_ctx *c =
767         (gost_grasshopper_cipher_ctx *) EVP_CIPHER_CTX_get_cipher_data(ctx);
768
769     if (!c)
770         return 1;
771
772     params = &gost_cipher_params[c->type];
773
774     gost_grasshopper_cipher_destroy(c);
775     if (params->destroy_cipher != NULL) {
776         params->destroy_cipher(c);
777     }
778
779     EVP_CIPHER_CTX_set_app_data(ctx, NULL);
780
781     return 1;
782 }
783
784 int gost_grasshopper_set_asn1_parameters(EVP_CIPHER_CTX *ctx, ASN1_TYPE *params)
785 {
786         if (EVP_CIPHER_CTX_mode(ctx) == EVP_CIPH_CTR_MODE) {
787                 gost_grasshopper_cipher_ctx_ctr *ctr = EVP_CIPHER_CTX_get_cipher_data(ctx);
788
789                 /* CMS implies 256kb section_size */
790                 ctr->section_size = 256*1024;
791
792                 return gost2015_set_asn1_params(params, EVP_CIPHER_CTX_original_iv(ctx), 8,
793                                 ctr->kdf_seed);
794         }
795         return 0;
796 }
797
798 GRASSHOPPER_INLINE int gost_grasshopper_get_asn1_parameters(EVP_CIPHER_CTX
799                                                             *ctx, ASN1_TYPE
800                                                             *params)
801 {
802         if (EVP_CIPHER_CTX_mode(ctx) == EVP_CIPH_CTR_MODE) {
803                 gost_grasshopper_cipher_ctx_ctr *ctr = EVP_CIPHER_CTX_get_cipher_data(ctx);
804
805                 int iv_len = 16;
806                 unsigned char iv[16];
807
808                 if (gost2015_get_asn1_params(params, 16, iv, 8, ctr->kdf_seed) == 0) {
809                         return 0;
810                 }
811
812                 memcpy(EVP_CIPHER_CTX_iv_noconst(ctx), iv, iv_len);
813                 memcpy((unsigned char *)EVP_CIPHER_CTX_original_iv(ctx), iv, iv_len);
814
815                 /* CMS implies 256kb section_size */
816                 ctr->section_size = 256*1024;
817                 return 1;
818         }
819         return 0;
820 }
821
822 int gost_grasshopper_cipher_ctl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr)
823 {
824     switch (type) {
825     case EVP_CTRL_RAND_KEY:{
826             if (RAND_priv_bytes
827                 ((unsigned char *)ptr, EVP_CIPHER_CTX_key_length(ctx)) <= 0) {
828                 GOSTerr(GOST_F_GOST_GRASSHOPPER_CIPHER_CTL, GOST_R_RNG_ERROR);
829                 return -1;
830             }
831             break;
832         }
833     case EVP_CTRL_KEY_MESH:{
834             gost_grasshopper_cipher_ctx_ctr *c =
835                 EVP_CIPHER_CTX_get_cipher_data(ctx);
836             if ((c->c.type != GRASSHOPPER_CIPHER_CTRACPKM &&
837                                                     c->c.type != GRASSHOPPER_CIPHER_CTRACPKMOMAC)
838                                                     || (arg == 0)
839                 || (arg % GRASSHOPPER_BLOCK_SIZE))
840                 return -1;
841             c->section_size = arg;
842             break;
843         }
844 #ifdef EVP_CTRL_TLS1_2_TLSTREE
845     case EVP_CTRL_TLS1_2_TLSTREE:
846         {
847           unsigned char newkey[32];
848           int mode = EVP_CIPHER_CTX_mode(ctx);
849           static const unsigned char zeroseq[8];
850           gost_grasshopper_cipher_ctx_ctr *ctr_ctx = NULL;
851           gost_grasshopper_cipher_ctx *c = NULL;
852
853           unsigned char adjusted_iv[16];
854           unsigned char seq[8];
855           int j, carry;
856           if (mode != EVP_CIPH_CTR_MODE)
857             return -1;
858
859           ctr_ctx = (gost_grasshopper_cipher_ctx_ctr *)
860             EVP_CIPHER_CTX_get_cipher_data(ctx);
861           c = &(ctr_ctx->c);
862
863           memcpy(seq, ptr, 8);
864           if (EVP_CIPHER_CTX_encrypting(ctx)) {
865             /*
866              * OpenSSL increments seq after mac calculation.
867              * As we have Mac-Then-Encrypt, we need decrement it here on encryption
868              * to derive the key correctly.
869              * */
870             if (memcmp(seq, zeroseq, 8) != 0)
871             {
872               for(j=7; j>=0; j--)
873               {
874                 if (seq[j] != 0) {seq[j]--; break;}
875                 else seq[j]  = 0xFF;
876               }
877             }
878           }
879           if (gost_tlstree(NID_grasshopper_cbc, c->master_key.k.b, newkey,
880                 (const unsigned char *)seq) > 0) {
881             memset(adjusted_iv, 0, 16);
882             memcpy(adjusted_iv, EVP_CIPHER_CTX_original_iv(ctx), 8);
883             for(j=7,carry=0; j>=0; j--)
884             {
885               int adj_byte = adjusted_iv[j]+seq[j]+carry;
886               carry = (adj_byte > 255) ? 1 : 0;
887               adjusted_iv[j] = adj_byte & 0xFF;
888             }
889             EVP_CIPHER_CTX_set_num(ctx, 0);
890             memcpy(EVP_CIPHER_CTX_iv_noconst(ctx), adjusted_iv, 16);
891
892             gost_grasshopper_cipher_key(c, newkey);
893             return 1;
894           }
895         }
896         return -1;
897 #endif
898 #if 0
899     case EVP_CTRL_AEAD_GET_TAG:
900     case EVP_CTRL_AEAD_SET_TAG:
901         {
902             int taglen = arg;
903             unsigned char *tag = ptr;
904
905             gost_grasshopper_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
906             if (c->c.type != GRASSHOPPER_CIPHER_MGM)
907                 return -1;
908
909             if (taglen > KUZNYECHIK_MAC_MAX_SIZE) {
910                 CRYPTOCOMerr(CRYPTOCOM_F_GOST_GRASSHOPPER_CIPHER_CTL,
911                         CRYPTOCOM_R_INVALID_TAG_LENGTH);
912                 return -1;
913             }
914
915             if (type == EVP_CTRL_AEAD_GET_TAG)
916                 memcpy(tag, c->final_tag, taglen);
917             else
918                 memcpy(c->final_tag, tag, taglen);
919
920             return 1;
921         }
922 #endif
923                 case EVP_CTRL_PROCESS_UNPROTECTED:
924     {
925       STACK_OF(X509_ATTRIBUTE) *x = ptr;
926       gost_grasshopper_cipher_ctx_ctr *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
927
928       if (c->c.type != GRASSHOPPER_CIPHER_CTRACPKMOMAC)
929         return -1;
930
931       return gost2015_process_unprotected_attributes(x, arg, KUZNYECHIK_MAC_MAX_SIZE, c->tag);
932     }
933     return 1;
934     case EVP_CTRL_COPY: {
935                         EVP_CIPHER_CTX *out = ptr;
936
937       gost_grasshopper_cipher_ctx_ctr *out_cctx = EVP_CIPHER_CTX_get_cipher_data(out);
938       gost_grasshopper_cipher_ctx_ctr *in_cctx  = EVP_CIPHER_CTX_get_cipher_data(ctx);
939
940       if (in_cctx->c.type != GRASSHOPPER_CIPHER_CTRACPKMOMAC)
941           return -1;
942
943                         if (in_cctx->omac_ctx == out_cctx->omac_ctx) {
944                                 out_cctx->omac_ctx = EVP_MD_CTX_new();
945                                 if (out_cctx->omac_ctx == NULL) {
946                                         GOSTerr(GOST_F_GOST_GRASSHOPPER_CIPHER_CTL, ERR_R_MALLOC_FAILURE);
947                                         return -1;
948                                 }
949                         }
950                         return EVP_MD_CTX_copy(out_cctx->omac_ctx, in_cctx->omac_ctx);
951                 }
952     default:
953         GOSTerr(GOST_F_GOST_GRASSHOPPER_CIPHER_CTL,
954                 GOST_R_UNSUPPORTED_CIPHER_CTL_COMMAND);
955         return -1;
956     }
957     return 1;
958 }
959
960 GRASSHOPPER_INLINE EVP_CIPHER *cipher_gost_grasshopper_create(int
961                                                               cipher_type, int
962                                                               block_size)
963 {
964     return EVP_CIPHER_meth_new(cipher_type, block_size /* block_size */ ,
965                                GRASSHOPPER_KEY_SIZE /* key_size */ );
966 }
967
968 const int cipher_gost_grasshopper_setup(EVP_CIPHER *cipher, uint8_t mode,
969                                         int iv_size, bool padding, int extra_flags)
970 {
971         unsigned long flags = (unsigned long)(mode
972                  | ((!padding) ?  EVP_CIPH_NO_PADDING : 0)
973                                          | ((iv_size >  0) ?  EVP_CIPH_CUSTOM_IV : 0)
974                                          | EVP_CIPH_RAND_KEY |  EVP_CIPH_ALWAYS_CALL_INIT
975                                          | extra_flags);
976
977     return EVP_CIPHER_meth_set_iv_length(cipher, iv_size)
978         && EVP_CIPHER_meth_set_flags(cipher, flags)
979         && EVP_CIPHER_meth_set_cleanup(cipher, gost_grasshopper_cipher_cleanup)
980         && EVP_CIPHER_meth_set_set_asn1_params(cipher,
981                                                gost_grasshopper_set_asn1_parameters)
982         && EVP_CIPHER_meth_set_get_asn1_params(cipher,
983                                                gost_grasshopper_get_asn1_parameters)
984         && EVP_CIPHER_meth_set_ctrl(cipher, gost_grasshopper_cipher_ctl)
985         && EVP_CIPHER_meth_set_do_cipher(cipher, gost_grasshopper_cipher_do);
986 }
987
988 const GRASSHOPPER_INLINE EVP_CIPHER *cipher_gost_grasshopper(uint8_t mode,
989                                                              uint8_t num)
990 {
991     EVP_CIPHER **cipher;
992     struct GRASSHOPPER_CIPHER_PARAMS *params;
993
994     cipher = &gost_grasshopper_ciphers[num];
995
996     if (*cipher == NULL) {
997         grasshopper_init_cipher_func init_cipher;
998         int nid, block_size, ctx_size, iv_size, extra_flags;
999         bool padding;
1000
1001         params = &gost_cipher_params[num];
1002
1003         nid = params->nid;
1004         init_cipher = params->init_cipher;
1005         block_size = params->block_size;
1006         ctx_size = params->ctx_size;
1007         iv_size = params->iv_size;
1008         padding = params->padding;
1009                                 extra_flags = params->extra_flags;
1010
1011         *cipher = cipher_gost_grasshopper_create(nid, block_size);
1012         if (*cipher == NULL) {
1013             return NULL;
1014         }
1015
1016         if (!cipher_gost_grasshopper_setup(*cipher, mode, iv_size, padding, extra_flags)
1017             || !EVP_CIPHER_meth_set_init(*cipher, init_cipher)
1018             || !EVP_CIPHER_meth_set_impl_ctx_size(*cipher, ctx_size)) {
1019             EVP_CIPHER_meth_free(*cipher);
1020             *cipher = NULL;
1021         }
1022     }
1023
1024     return *cipher;
1025 }
1026
1027 const GRASSHOPPER_INLINE EVP_CIPHER *cipher_gost_grasshopper_ecb()
1028 {
1029     return cipher_gost_grasshopper(EVP_CIPH_ECB_MODE, GRASSHOPPER_CIPHER_ECB);
1030 }
1031
1032 const GRASSHOPPER_INLINE EVP_CIPHER *cipher_gost_grasshopper_cbc()
1033 {
1034     return cipher_gost_grasshopper(EVP_CIPH_CBC_MODE, GRASSHOPPER_CIPHER_CBC);
1035 }
1036
1037 const GRASSHOPPER_INLINE EVP_CIPHER *cipher_gost_grasshopper_ofb()
1038 {
1039     return cipher_gost_grasshopper(EVP_CIPH_OFB_MODE, GRASSHOPPER_CIPHER_OFB);
1040 }
1041
1042 const GRASSHOPPER_INLINE EVP_CIPHER *cipher_gost_grasshopper_cfb()
1043 {
1044     return cipher_gost_grasshopper(EVP_CIPH_CFB_MODE, GRASSHOPPER_CIPHER_CFB);
1045 }
1046
1047 const GRASSHOPPER_INLINE EVP_CIPHER *cipher_gost_grasshopper_ctr()
1048 {
1049     return cipher_gost_grasshopper(EVP_CIPH_CTR_MODE, GRASSHOPPER_CIPHER_CTR);
1050 }
1051
1052 const GRASSHOPPER_INLINE EVP_CIPHER *cipher_gost_grasshopper_ctracpkm()
1053 {
1054     return cipher_gost_grasshopper(EVP_CIPH_CTR_MODE,
1055                                    GRASSHOPPER_CIPHER_CTRACPKM);
1056 }
1057
1058 const GRASSHOPPER_INLINE EVP_CIPHER *cipher_gost_grasshopper_ctracpkm_omac()
1059 {
1060     return cipher_gost_grasshopper(EVP_CIPH_CTR_MODE,
1061                                    GRASSHOPPER_CIPHER_CTRACPKMOMAC);
1062 }
1063
1064 void cipher_gost_grasshopper_destroy(void)
1065 {
1066     EVP_CIPHER_meth_free(gost_grasshopper_ciphers[GRASSHOPPER_CIPHER_ECB]);
1067     gost_grasshopper_ciphers[GRASSHOPPER_CIPHER_ECB] = NULL;
1068     EVP_CIPHER_meth_free(gost_grasshopper_ciphers[GRASSHOPPER_CIPHER_CBC]);
1069     gost_grasshopper_ciphers[GRASSHOPPER_CIPHER_CBC] = NULL;
1070     EVP_CIPHER_meth_free(gost_grasshopper_ciphers[GRASSHOPPER_CIPHER_OFB]);
1071     gost_grasshopper_ciphers[GRASSHOPPER_CIPHER_OFB] = NULL;
1072     EVP_CIPHER_meth_free(gost_grasshopper_ciphers[GRASSHOPPER_CIPHER_CFB]);
1073     gost_grasshopper_ciphers[GRASSHOPPER_CIPHER_CFB] = NULL;
1074     EVP_CIPHER_meth_free(gost_grasshopper_ciphers[GRASSHOPPER_CIPHER_CTR]);
1075     gost_grasshopper_ciphers[GRASSHOPPER_CIPHER_CTR] = NULL;
1076     EVP_CIPHER_meth_free(gost_grasshopper_ciphers[GRASSHOPPER_CIPHER_CTRACPKM]);
1077     gost_grasshopper_ciphers[GRASSHOPPER_CIPHER_CTRACPKM] = NULL;
1078     EVP_CIPHER_meth_free(gost_grasshopper_ciphers[GRASSHOPPER_CIPHER_CTRACPKMOMAC]);
1079     gost_grasshopper_ciphers[GRASSHOPPER_CIPHER_CTRACPKMOMAC] = NULL;
1080 }