]> www.wagner.pp.ru Git - openssl-gost/engine.git/blob - gost_grasshopper_cipher.c
GOST CMS encryption implementation.
[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         if (enc && c->type == GRASSHOPPER_CIPHER_CTRACPKM) {
219             gost_grasshopper_cipher_ctx_ctr *ctr = EVP_CIPHER_CTX_get_cipher_data(ctx);
220             if (init_zero_kdf_seed(ctr->kdf_seed) == 0)
221                 return -1;
222         }
223     }
224
225     if (key != NULL) {
226         gost_grasshopper_cipher_key(c, key);
227         gost_grasshopper_master_key(c, key);
228     }
229
230     if (iv != NULL) {
231         memcpy((unsigned char *)EVP_CIPHER_CTX_original_iv(ctx), iv,
232                EVP_CIPHER_CTX_iv_length(ctx));
233     }
234
235     memcpy(EVP_CIPHER_CTX_iv_noconst(ctx),
236            EVP_CIPHER_CTX_original_iv(ctx), EVP_CIPHER_CTX_iv_length(ctx));
237
238     grasshopper_zero128(&c->buffer);
239
240     return 1;
241 }
242
243 GRASSHOPPER_INLINE int gost_grasshopper_cipher_init_ecb(EVP_CIPHER_CTX *ctx, const unsigned char
244                                                         *key, const unsigned char
245                                                         *iv, int enc)
246 {
247     gost_grasshopper_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
248     c->type = GRASSHOPPER_CIPHER_ECB;
249     return gost_grasshopper_cipher_init(ctx, key, iv, enc);
250 }
251
252 GRASSHOPPER_INLINE int gost_grasshopper_cipher_init_cbc(EVP_CIPHER_CTX *ctx, const unsigned char
253                                                         *key, const unsigned char
254                                                         *iv, int enc)
255 {
256     gost_grasshopper_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
257     c->type = GRASSHOPPER_CIPHER_CBC;
258     return gost_grasshopper_cipher_init(ctx, key, iv, enc);
259 }
260
261 GRASSHOPPER_INLINE int gost_grasshopper_cipher_init_ofb(EVP_CIPHER_CTX *ctx, const unsigned char
262                                                         *key, const unsigned char
263                                                         *iv, int enc)
264 {
265     gost_grasshopper_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
266     c->type = GRASSHOPPER_CIPHER_OFB;
267     return gost_grasshopper_cipher_init(ctx, key, iv, enc);
268 }
269
270 GRASSHOPPER_INLINE int gost_grasshopper_cipher_init_cfb(EVP_CIPHER_CTX *ctx, const unsigned char
271                                                         *key, const unsigned char
272                                                         *iv, int enc)
273 {
274     gost_grasshopper_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
275     c->type = GRASSHOPPER_CIPHER_CFB;
276     return gost_grasshopper_cipher_init(ctx, key, iv, enc);
277 }
278
279 GRASSHOPPER_INLINE int gost_grasshopper_cipher_init_ctr(EVP_CIPHER_CTX *ctx, const unsigned char
280                                                         *key, const unsigned char
281                                                         *iv, int enc)
282 {
283     gost_grasshopper_cipher_ctx_ctr *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
284
285     c->c.type = GRASSHOPPER_CIPHER_CTR;
286     EVP_CIPHER_CTX_set_num(ctx, 0);
287
288     grasshopper_zero128(&c->partial_buffer);
289
290     return gost_grasshopper_cipher_init(ctx, key, iv, enc);
291 }
292
293 GRASSHOPPER_INLINE int gost_grasshopper_cipher_init_ctracpkm(EVP_CIPHER_CTX
294                                                              *ctx, const unsigned
295                                                              char *key, const unsigned
296                                                              char *iv, int enc)
297 {
298     gost_grasshopper_cipher_ctx_ctr *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
299
300     /* NB: setting type makes EVP do_cipher callback useless */
301     c->c.type = GRASSHOPPER_CIPHER_CTRACPKM;
302     EVP_CIPHER_CTX_set_num(ctx, 0);
303     c->section_size = 4096;
304
305     return gost_grasshopper_cipher_init(ctx, key, iv, enc);
306 }
307
308 GRASSHOPPER_INLINE int gost_grasshopper_cipher_init_ctracpkm_omac(EVP_CIPHER_CTX
309                                                              *ctx, const unsigned
310                                                              char *key, const unsigned
311                                                              char *iv, int enc)
312 {
313         gost_grasshopper_cipher_ctx_ctr *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
314
315         /* NB: setting type makes EVP do_cipher callback useless */
316         c->c.type = GRASSHOPPER_CIPHER_CTRACPKMOMAC;
317         EVP_CIPHER_CTX_set_num(ctx, 0);
318         c->section_size = 4096;
319
320         if (key) {
321                 unsigned char cipher_key[32];
322                 c->omac_ctx = EVP_MD_CTX_new();
323
324                 if (c->omac_ctx == NULL) {
325                     GOSTerr(GOST_F_GOST_GRASSHOPPER_CIPHER_INIT_CTRACPKM_OMAC, ERR_R_MALLOC_FAILURE);
326                                 return 0;
327                 }
328
329                 if (gost2015_acpkm_omac_init(NID_kuznyechik_mac, enc, key,
330                                  c->omac_ctx, cipher_key, c->kdf_seed) != 1) {
331                     EVP_MD_CTX_free(c->omac_ctx);
332                                 c->omac_ctx = NULL;
333                     return 0;
334                 }
335
336                 return gost_grasshopper_cipher_init(ctx, cipher_key, iv, enc);
337         }
338
339         return gost_grasshopper_cipher_init(ctx, key, iv, enc);
340 }
341
342 GRASSHOPPER_INLINE int gost_grasshopper_cipher_do(EVP_CIPHER_CTX *ctx,
343                                                   unsigned char *out,
344                                                   const unsigned char *in,
345                                                   size_t inl)
346 {
347     gost_grasshopper_cipher_ctx *c =
348         (gost_grasshopper_cipher_ctx *) EVP_CIPHER_CTX_get_cipher_data(ctx);
349     struct GRASSHOPPER_CIPHER_PARAMS *params = &gost_cipher_params[c->type];
350
351     return params->do_cipher(ctx, out, in, inl);
352 }
353
354 int gost_grasshopper_cipher_do_ecb(EVP_CIPHER_CTX *ctx, unsigned char *out,
355                                    const unsigned char *in, size_t inl)
356 {
357     gost_grasshopper_cipher_ctx *c =
358         (gost_grasshopper_cipher_ctx *) EVP_CIPHER_CTX_get_cipher_data(ctx);
359     bool encrypting = (bool) EVP_CIPHER_CTX_encrypting(ctx);
360     const unsigned char *current_in = in;
361     unsigned char *current_out = out;
362     size_t blocks = inl / GRASSHOPPER_BLOCK_SIZE;
363     size_t i;
364
365     for (i = 0; i < blocks;
366          i++, current_in += GRASSHOPPER_BLOCK_SIZE, current_out +=
367          GRASSHOPPER_BLOCK_SIZE) {
368         if (encrypting) {
369             grasshopper_encrypt_block(&c->encrypt_round_keys,
370                                       (grasshopper_w128_t *) current_in,
371                                       (grasshopper_w128_t *) current_out,
372                                       &c->buffer);
373         } else {
374             grasshopper_decrypt_block(&c->decrypt_round_keys,
375                                       (grasshopper_w128_t *) current_in,
376                                       (grasshopper_w128_t *) current_out,
377                                       &c->buffer);
378         }
379     }
380
381     return 1;
382 }
383
384 int gost_grasshopper_cipher_do_cbc(EVP_CIPHER_CTX *ctx, unsigned char *out,
385                                    const unsigned char *in, size_t inl)
386 {
387     gost_grasshopper_cipher_ctx *c =
388         (gost_grasshopper_cipher_ctx *) EVP_CIPHER_CTX_get_cipher_data(ctx);
389     unsigned char *iv = EVP_CIPHER_CTX_iv_noconst(ctx);
390     bool encrypting = (bool) EVP_CIPHER_CTX_encrypting(ctx);
391     const unsigned char *current_in = in;
392     unsigned char *current_out = out;
393     size_t blocks = inl / GRASSHOPPER_BLOCK_SIZE;
394     size_t i;
395     grasshopper_w128_t *currentBlock;
396
397     currentBlock = (grasshopper_w128_t *) iv;
398
399     for (i = 0; i < blocks;
400          i++, current_in += GRASSHOPPER_BLOCK_SIZE, current_out +=
401          GRASSHOPPER_BLOCK_SIZE) {
402         grasshopper_w128_t *currentInputBlock = (grasshopper_w128_t *) current_in;
403         grasshopper_w128_t *currentOutputBlock = (grasshopper_w128_t *) current_out;
404         if (encrypting) {
405             grasshopper_append128(currentBlock, currentInputBlock);
406             grasshopper_encrypt_block(&c->encrypt_round_keys, currentBlock,
407                                       currentOutputBlock, &c->buffer);
408             grasshopper_copy128(currentBlock, currentOutputBlock);
409         } else {
410             grasshopper_w128_t tmp;
411
412             grasshopper_copy128(&tmp, currentInputBlock);
413             grasshopper_decrypt_block(&c->decrypt_round_keys,
414                                       currentInputBlock, currentOutputBlock,
415                                       &c->buffer);
416             grasshopper_append128(currentOutputBlock, currentBlock);
417             grasshopper_copy128(currentBlock, &tmp);
418         }
419     }
420
421     return 1;
422 }
423
424 void inc_counter(unsigned char *counter, size_t counter_bytes)
425 {
426     unsigned int n = counter_bytes;
427
428     do {
429         unsigned char c;
430         --n;
431         c = counter[n];
432         ++c;
433         counter[n] = c;
434         if (c)
435             return;
436     } while (n);
437 }
438
439 /* increment counter (128-bit int) by 1 */
440 static void ctr128_inc(unsigned char *counter)
441 {
442     inc_counter(counter, 16);
443 }
444
445 int gost_grasshopper_cipher_do_ctr(EVP_CIPHER_CTX *ctx, unsigned char *out,
446                                    const unsigned char *in, size_t inl)
447 {
448     gost_grasshopper_cipher_ctx_ctr *c = (gost_grasshopper_cipher_ctx_ctr *)
449         EVP_CIPHER_CTX_get_cipher_data(ctx);
450     unsigned char *iv = EVP_CIPHER_CTX_iv_noconst(ctx);
451     const unsigned char *current_in = in;
452     unsigned char *current_out = out;
453     grasshopper_w128_t *currentInputBlock;
454     grasshopper_w128_t *currentOutputBlock;
455     unsigned int n = EVP_CIPHER_CTX_num(ctx);
456     size_t lasted = inl;
457     size_t i;
458     size_t blocks;
459     grasshopper_w128_t *iv_buffer;
460     grasshopper_w128_t tmp;
461
462     while (n && lasted) {
463         *(current_out++) = *(current_in++) ^ c->partial_buffer.b[n];
464         --lasted;
465         n = (n + 1) % GRASSHOPPER_BLOCK_SIZE;
466     }
467     EVP_CIPHER_CTX_set_num(ctx, n);
468     blocks = lasted / GRASSHOPPER_BLOCK_SIZE;
469
470     iv_buffer = (grasshopper_w128_t *) iv;
471
472     // full parts
473     for (i = 0; i < blocks; i++) {
474         currentInputBlock = (grasshopper_w128_t *) current_in;
475         currentOutputBlock = (grasshopper_w128_t *) current_out;
476         grasshopper_encrypt_block(&c->c.encrypt_round_keys, iv_buffer,
477                                   &c->partial_buffer, &c->c.buffer);
478         grasshopper_plus128(&tmp, &c->partial_buffer, currentInputBlock);
479         grasshopper_copy128(currentOutputBlock, &tmp);
480         ctr128_inc(iv_buffer->b);
481         current_in += GRASSHOPPER_BLOCK_SIZE;
482         current_out += GRASSHOPPER_BLOCK_SIZE;
483                                 lasted -= GRASSHOPPER_BLOCK_SIZE;
484     }
485
486     if (lasted > 0) {
487         currentInputBlock = (grasshopper_w128_t *) current_in;
488         currentOutputBlock = (grasshopper_w128_t *) current_out;
489         grasshopper_encrypt_block(&c->c.encrypt_round_keys, iv_buffer,
490                                   &c->partial_buffer, &c->c.buffer);
491         for (i = 0; i < lasted; i++) {
492             currentOutputBlock->b[i] =
493                 c->partial_buffer.b[i] ^ currentInputBlock->b[i];
494         }
495         EVP_CIPHER_CTX_set_num(ctx, i);
496         ctr128_inc(iv_buffer->b);
497     }
498
499     return inl;
500 }
501
502 #define GRASSHOPPER_BLOCK_MASK (GRASSHOPPER_BLOCK_SIZE - 1)
503 static inline void apply_acpkm_grasshopper(gost_grasshopper_cipher_ctx_ctr *
504                                            ctx, unsigned int *num)
505 {
506     if (!ctx->section_size || (*num < ctx->section_size))
507         return;
508     acpkm_next(&ctx->c);
509     *num &= GRASSHOPPER_BLOCK_MASK;
510 }
511
512 /* If meshing is not configured via ctrl (setting section_size)
513  * this function works exactly like plain ctr */
514 int gost_grasshopper_cipher_do_ctracpkm(EVP_CIPHER_CTX *ctx,
515                                         unsigned char *out,
516                                         const unsigned char *in, size_t inl)
517 {
518     gost_grasshopper_cipher_ctx_ctr *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
519     unsigned char *iv = EVP_CIPHER_CTX_iv_noconst(ctx);
520     unsigned int num = EVP_CIPHER_CTX_num(ctx);
521     size_t blocks, i, lasted = inl;
522     grasshopper_w128_t tmp;
523
524     while ((num & GRASSHOPPER_BLOCK_MASK) && lasted) {
525         *out++ = *in++ ^ c->partial_buffer.b[num & GRASSHOPPER_BLOCK_MASK];
526         --lasted;
527         num++;
528     }
529     blocks = lasted / GRASSHOPPER_BLOCK_SIZE;
530
531     // full parts
532     for (i = 0; i < blocks; i++) {
533         apply_acpkm_grasshopper(c, &num);
534         grasshopper_encrypt_block(&c->c.encrypt_round_keys,
535                                   (grasshopper_w128_t *) iv,
536                                   (grasshopper_w128_t *) & c->partial_buffer,
537                                   &c->c.buffer);
538         grasshopper_plus128(&tmp, &c->partial_buffer,
539                             (grasshopper_w128_t *) in);
540         grasshopper_copy128((grasshopper_w128_t *) out, &tmp);
541         ctr128_inc(iv);
542         in += GRASSHOPPER_BLOCK_SIZE;
543         out += GRASSHOPPER_BLOCK_SIZE;
544         num += GRASSHOPPER_BLOCK_SIZE;
545                                 lasted -= GRASSHOPPER_BLOCK_SIZE;
546     }
547
548     // last part
549     if (lasted > 0) {
550         apply_acpkm_grasshopper(c, &num);
551         grasshopper_encrypt_block(&c->c.encrypt_round_keys,
552                                   (grasshopper_w128_t *) iv,
553                                   &c->partial_buffer, &c->c.buffer);
554         for (i = 0; i < lasted; i++)
555             out[i] = c->partial_buffer.b[i] ^ in[i];
556         ctr128_inc(iv);
557         num += lasted;
558     }
559     EVP_CIPHER_CTX_set_num(ctx, num);
560
561     return inl;
562 }
563
564 int gost_grasshopper_cipher_do_ctracpkm_omac(EVP_CIPHER_CTX *ctx,
565                                         unsigned char *out,
566                                         const unsigned char *in, size_t inl)
567 {
568         int result;
569   gost_grasshopper_cipher_ctx_ctr *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
570         /* As in and out can be the same pointer, process unencrypted here */
571         if (EVP_CIPHER_CTX_encrypting(ctx))
572                 EVP_DigestSignUpdate(c->omac_ctx, in, inl);
573
574         if (in == NULL && inl == 0) { /* Final call */
575                 return gost2015_final_call(ctx, c->omac_ctx, KUZNYECHIK_MAC_MAX_SIZE, c->tag, gost_grasshopper_cipher_do_ctracpkm);
576         }
577
578   if (in == NULL) {
579       GOSTerr(GOST_F_GOST_GRASSHOPPER_CIPHER_DO_CTRACPKM_OMAC, ERR_R_EVP_LIB);
580       return -1;
581   }
582         result = gost_grasshopper_cipher_do_ctracpkm(ctx, out, in, inl);
583
584         /* As in and out can be the same pointer, process decrypted here */
585         if (!EVP_CIPHER_CTX_encrypting(ctx))
586                 EVP_DigestSignUpdate(c->omac_ctx, out, inl);
587
588         return result;
589 }
590 /*
591  * Fixed 128-bit IV implementation make shift regiser redundant.
592  */
593 static void gost_grasshopper_cnt_next(gost_grasshopper_cipher_ctx * ctx,
594                                       grasshopper_w128_t * iv,
595                                       grasshopper_w128_t * buf)
596 {
597     grasshopper_w128_t tmp;
598     memcpy(&tmp, iv, 16);
599     grasshopper_encrypt_block(&ctx->encrypt_round_keys, &tmp,
600                               buf, &ctx->buffer);
601     memcpy(iv, buf, 16);
602 }
603
604 int gost_grasshopper_cipher_do_ofb(EVP_CIPHER_CTX *ctx, unsigned char *out,
605                                    const unsigned char *in, size_t inl)
606 {
607     gost_grasshopper_cipher_ctx *c = (gost_grasshopper_cipher_ctx *)
608         EVP_CIPHER_CTX_get_cipher_data(ctx);
609     const unsigned char *in_ptr = in;
610     unsigned char *out_ptr = out;
611     unsigned char *buf = EVP_CIPHER_CTX_buf_noconst(ctx);
612     unsigned char *iv = EVP_CIPHER_CTX_iv_noconst(ctx);
613     int num = EVP_CIPHER_CTX_num(ctx);
614     size_t i = 0;
615     size_t j;
616
617     /* process partial block if any */
618     if (num > 0) {
619         for (j = (size_t)num, i = 0; j < GRASSHOPPER_BLOCK_SIZE && i < inl;
620              j++, i++, in_ptr++, out_ptr++) {
621             *out_ptr = buf[j] ^ (*in_ptr);
622         }
623         if (j == GRASSHOPPER_BLOCK_SIZE) {
624             EVP_CIPHER_CTX_set_num(ctx, 0);
625         } else {
626             EVP_CIPHER_CTX_set_num(ctx, (int)j);
627             return 1;
628         }
629     }
630
631     for (; i + GRASSHOPPER_BLOCK_SIZE <
632          inl;
633          i += GRASSHOPPER_BLOCK_SIZE, in_ptr +=
634          GRASSHOPPER_BLOCK_SIZE, out_ptr += GRASSHOPPER_BLOCK_SIZE) {
635         /*
636          * block cipher current iv
637          */
638         /* Encrypt */
639         gost_grasshopper_cnt_next(c, (grasshopper_w128_t *) iv,
640                                   (grasshopper_w128_t *) buf);
641
642         /*
643          * xor next block of input text with it and output it
644          */
645         /*
646          * output this block
647          */
648         for (j = 0; j < GRASSHOPPER_BLOCK_SIZE; j++) {
649             out_ptr[j] = buf[j] ^ in_ptr[j];
650         }
651     }
652
653     /* Process rest of buffer */
654     if (i < inl) {
655         gost_grasshopper_cnt_next(c, (grasshopper_w128_t *) iv,
656                                   (grasshopper_w128_t *) buf);
657         for (j = 0; i < inl; j++, i++) {
658             out_ptr[j] = buf[j] ^ in_ptr[j];
659         }
660         EVP_CIPHER_CTX_set_num(ctx, (int)j);
661     } else {
662         EVP_CIPHER_CTX_set_num(ctx, 0);
663     }
664
665     return 1;
666 }
667
668 int gost_grasshopper_cipher_do_cfb(EVP_CIPHER_CTX *ctx, unsigned char *out,
669                                    const unsigned char *in, size_t inl)
670 {
671     gost_grasshopper_cipher_ctx *c =
672         (gost_grasshopper_cipher_ctx *) EVP_CIPHER_CTX_get_cipher_data(ctx);
673     const unsigned char *in_ptr = in;
674     unsigned char *out_ptr = out;
675     unsigned char *buf = EVP_CIPHER_CTX_buf_noconst(ctx);
676     unsigned char *iv = EVP_CIPHER_CTX_iv_noconst(ctx);
677     bool encrypting = (bool) EVP_CIPHER_CTX_encrypting(ctx);
678     int num = EVP_CIPHER_CTX_num(ctx);
679     size_t i = 0;
680     size_t j = 0;
681
682     /* process partial block if any */
683     if (num > 0) {
684         for (j = (size_t)num, i = 0; j < GRASSHOPPER_BLOCK_SIZE && i < inl;
685              j++, i++, in_ptr++, out_ptr++) {
686             if (!encrypting) {
687                 buf[j + GRASSHOPPER_BLOCK_SIZE] = *in_ptr;
688             }
689             *out_ptr = buf[j] ^ (*in_ptr);
690             if (encrypting) {
691                 buf[j + GRASSHOPPER_BLOCK_SIZE] = *out_ptr;
692             }
693         }
694         if (j == GRASSHOPPER_BLOCK_SIZE) {
695             memcpy(iv, buf + GRASSHOPPER_BLOCK_SIZE, GRASSHOPPER_BLOCK_SIZE);
696             EVP_CIPHER_CTX_set_num(ctx, 0);
697         } else {
698             EVP_CIPHER_CTX_set_num(ctx, (int)j);
699             return 1;
700         }
701     }
702
703     for (; i + GRASSHOPPER_BLOCK_SIZE <
704          inl;
705          i += GRASSHOPPER_BLOCK_SIZE, in_ptr +=
706          GRASSHOPPER_BLOCK_SIZE, out_ptr += GRASSHOPPER_BLOCK_SIZE) {
707         /*
708          * block cipher current iv
709          */
710         grasshopper_encrypt_block(&c->encrypt_round_keys,
711                                   (grasshopper_w128_t *) iv,
712                                   (grasshopper_w128_t *) buf, &c->buffer);
713         /*
714          * xor next block of input text with it and output it
715          */
716         /*
717          * output this block
718          */
719         if (!encrypting) {
720             memcpy(iv, in_ptr, GRASSHOPPER_BLOCK_SIZE);
721         }
722         for (j = 0; j < GRASSHOPPER_BLOCK_SIZE; j++) {
723             out_ptr[j] = buf[j] ^ in_ptr[j];
724         }
725         /* Encrypt */
726         /* Next iv is next block of cipher text */
727         if (encrypting) {
728             memcpy(iv, out_ptr, GRASSHOPPER_BLOCK_SIZE);
729         }
730     }
731
732     /* Process rest of buffer */
733     if (i < inl) {
734         grasshopper_encrypt_block(&c->encrypt_round_keys,
735                                   (grasshopper_w128_t *) iv,
736                                   (grasshopper_w128_t *) buf, &c->buffer);
737         if (!encrypting) {
738             memcpy(buf + GRASSHOPPER_BLOCK_SIZE, in_ptr, inl - i);
739         }
740         for (j = 0; i < inl; j++, i++) {
741             out_ptr[j] = buf[j] ^ in_ptr[j];
742         }
743         EVP_CIPHER_CTX_set_num(ctx, (int)j);
744         if (encrypting) {
745             memcpy(buf + GRASSHOPPER_BLOCK_SIZE, out_ptr, j);
746         }
747     } else {
748         EVP_CIPHER_CTX_set_num(ctx, 0);
749     }
750
751     return 1;
752 }
753
754 int gost_grasshopper_cipher_cleanup(EVP_CIPHER_CTX *ctx)
755 {
756     struct GRASSHOPPER_CIPHER_PARAMS *params;
757     gost_grasshopper_cipher_ctx *c =
758         (gost_grasshopper_cipher_ctx *) EVP_CIPHER_CTX_get_cipher_data(ctx);
759
760     if (!c)
761         return 1;
762
763     params = &gost_cipher_params[c->type];
764
765     gost_grasshopper_cipher_destroy(c);
766     if (params->destroy_cipher != NULL) {
767         params->destroy_cipher(c);
768     }
769
770     EVP_CIPHER_CTX_set_app_data(ctx, NULL);
771
772     return 1;
773 }
774
775 int gost_grasshopper_set_asn1_parameters(EVP_CIPHER_CTX *ctx, ASN1_TYPE *params)
776 {
777         if (EVP_CIPHER_CTX_mode(ctx) == EVP_CIPH_CTR_MODE) {
778                 gost_grasshopper_cipher_ctx_ctr *ctr = EVP_CIPHER_CTX_get_cipher_data(ctx);
779
780                 /* CMS implies 256kb section_size */
781                 ctr->section_size = 256*1024;
782
783                 return gost2015_set_asn1_params(params, EVP_CIPHER_CTX_original_iv(ctx), 8,
784                                 ctr->kdf_seed);
785         }
786         return 0;
787 }
788
789 GRASSHOPPER_INLINE int gost_grasshopper_get_asn1_parameters(EVP_CIPHER_CTX
790                                                             *ctx, ASN1_TYPE
791                                                             *params)
792 {
793         if (EVP_CIPHER_CTX_mode(ctx) == EVP_CIPH_CTR_MODE) {
794                 gost_grasshopper_cipher_ctx_ctr *ctr = EVP_CIPHER_CTX_get_cipher_data(ctx);
795
796                 int iv_len = 16;
797                 unsigned char iv[16];
798
799                 if (gost2015_get_asn1_params(params, 16, iv, 8, ctr->kdf_seed) == 0) {
800                         return 0;
801                 }
802
803                 memcpy(EVP_CIPHER_CTX_iv_noconst(ctx), iv, iv_len);
804                 memcpy((unsigned char *)EVP_CIPHER_CTX_original_iv(ctx), iv, iv_len);
805
806                 /* CMS implies 256kb section_size */
807                 ctr->section_size = 256*1024;
808                 return 1;
809         }
810         return 0;
811 }
812
813 int gost_grasshopper_cipher_ctl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr)
814 {
815     switch (type) {
816     case EVP_CTRL_RAND_KEY:{
817             if (RAND_priv_bytes
818                 ((unsigned char *)ptr, EVP_CIPHER_CTX_key_length(ctx)) <= 0) {
819                 GOSTerr(GOST_F_GOST_GRASSHOPPER_CIPHER_CTL, GOST_R_RNG_ERROR);
820                 return -1;
821             }
822             break;
823         }
824     case EVP_CTRL_KEY_MESH:{
825             gost_grasshopper_cipher_ctx_ctr *c =
826                 EVP_CIPHER_CTX_get_cipher_data(ctx);
827             if ((c->c.type != GRASSHOPPER_CIPHER_CTRACPKM &&
828                                                     c->c.type != GRASSHOPPER_CIPHER_CTRACPKMOMAC)
829                                                     || (arg == 0)
830                 || (arg % GRASSHOPPER_BLOCK_SIZE))
831                 return -1;
832             c->section_size = arg;
833             break;
834         }
835 #ifdef EVP_CTRL_TLS1_2_TLSTREE
836     case EVP_CTRL_TLS1_2_TLSTREE:
837         {
838           unsigned char newkey[32];
839           int mode = EVP_CIPHER_CTX_mode(ctx);
840           static const unsigned char zeroseq[8];
841           gost_grasshopper_cipher_ctx_ctr *ctr_ctx = NULL;
842           gost_grasshopper_cipher_ctx *c = NULL;
843
844           unsigned char adjusted_iv[16];
845           unsigned char seq[8];
846           int j, carry;
847           if (mode != EVP_CIPH_CTR_MODE)
848             return -1;
849
850           ctr_ctx = (gost_grasshopper_cipher_ctx_ctr *)
851             EVP_CIPHER_CTX_get_cipher_data(ctx);
852           c = &(ctr_ctx->c);
853
854           memcpy(seq, ptr, 8);
855           if (EVP_CIPHER_CTX_encrypting(ctx)) {
856             /*
857              * OpenSSL increments seq after mac calculation.
858              * As we have Mac-Then-Encrypt, we need decrement it here on encryption
859              * to derive the key correctly.
860              * */
861             if (memcmp(seq, zeroseq, 8) != 0)
862             {
863               for(j=7; j>=0; j--)
864               {
865                 if (seq[j] != 0) {seq[j]--; break;}
866                 else seq[j]  = 0xFF;
867               }
868             }
869           }
870           if (gost_tlstree(NID_grasshopper_cbc, c->master_key.k.b, newkey,
871                 (const unsigned char *)seq) > 0) {
872             memset(adjusted_iv, 0, 16);
873             memcpy(adjusted_iv, EVP_CIPHER_CTX_original_iv(ctx), 8);
874             for(j=7,carry=0; j>=0; j--)
875             {
876               int adj_byte = adjusted_iv[j]+seq[j]+carry;
877               carry = (adj_byte > 255) ? 1 : 0;
878               adjusted_iv[j] = adj_byte & 0xFF;
879             }
880             EVP_CIPHER_CTX_set_num(ctx, 0);
881             memcpy(EVP_CIPHER_CTX_iv_noconst(ctx), adjusted_iv, 16);
882
883             gost_grasshopper_cipher_key(c, newkey);
884             return 1;
885           }
886         }
887         return -1;
888 #endif
889 #if 0
890     case EVP_CTRL_AEAD_GET_TAG:
891     case EVP_CTRL_AEAD_SET_TAG:
892         {
893             int taglen = arg;
894             unsigned char *tag = ptr;
895
896             gost_grasshopper_cipher_ctx *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
897             if (c->c.type != GRASSHOPPER_CIPHER_MGM)
898                 return -1;
899
900             if (taglen > KUZNYECHIK_MAC_MAX_SIZE) {
901                 CRYPTOCOMerr(CRYPTOCOM_F_GOST_GRASSHOPPER_CIPHER_CTL,
902                         CRYPTOCOM_R_INVALID_TAG_LENGTH);
903                 return -1;
904             }
905
906             if (type == EVP_CTRL_AEAD_GET_TAG)
907                 memcpy(tag, c->final_tag, taglen);
908             else
909                 memcpy(c->final_tag, tag, taglen);
910
911             return 1;
912         }
913 #endif
914                 case EVP_CTRL_PROCESS_UNPROTECTED:
915     {
916       STACK_OF(X509_ATTRIBUTE) *x = ptr;
917       gost_grasshopper_cipher_ctx_ctr *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
918
919       if (c->c.type != GRASSHOPPER_CIPHER_CTRACPKMOMAC)
920         return -1;
921
922       return gost2015_process_unprotected_attributes(x, arg, KUZNYECHIK_MAC_MAX_SIZE, c->tag);
923     }
924     return 1;
925     case EVP_CTRL_COPY: {
926                         EVP_CIPHER_CTX *out = ptr;
927
928       gost_grasshopper_cipher_ctx_ctr *out_cctx = EVP_CIPHER_CTX_get_cipher_data(out);
929       gost_grasshopper_cipher_ctx_ctr *in_cctx  = EVP_CIPHER_CTX_get_cipher_data(ctx);
930
931       if (in_cctx->c.type != GRASSHOPPER_CIPHER_CTRACPKMOMAC)
932           return -1;
933
934                         if (in_cctx->omac_ctx == out_cctx->omac_ctx) {
935                                 out_cctx->omac_ctx = EVP_MD_CTX_new();
936                                 if (out_cctx->omac_ctx == NULL) {
937                                         GOSTerr(GOST_F_GOST_GRASSHOPPER_CIPHER_CTL, ERR_R_MALLOC_FAILURE);
938                                         return -1;
939                                 }
940                         }
941                         return EVP_MD_CTX_copy(out_cctx->omac_ctx, in_cctx->omac_ctx);
942                 }
943     default:
944         GOSTerr(GOST_F_GOST_GRASSHOPPER_CIPHER_CTL,
945                 GOST_R_UNSUPPORTED_CIPHER_CTL_COMMAND);
946         return -1;
947     }
948     return 1;
949 }
950
951 GRASSHOPPER_INLINE EVP_CIPHER *cipher_gost_grasshopper_create(int
952                                                               cipher_type, int
953                                                               block_size)
954 {
955     return EVP_CIPHER_meth_new(cipher_type, block_size /* block_size */ ,
956                                GRASSHOPPER_KEY_SIZE /* key_size */ );
957 }
958
959 const int cipher_gost_grasshopper_setup(EVP_CIPHER *cipher, uint8_t mode,
960                                         int iv_size, bool padding, int extra_flags)
961 {
962         unsigned long flags = (unsigned long)(mode
963                  | ((!padding) ?  EVP_CIPH_NO_PADDING : 0)
964                                          | ((iv_size >  0) ?  EVP_CIPH_CUSTOM_IV : 0)
965                                          | EVP_CIPH_RAND_KEY |  EVP_CIPH_ALWAYS_CALL_INIT
966                                          | extra_flags);
967
968     return EVP_CIPHER_meth_set_iv_length(cipher, iv_size)
969         && EVP_CIPHER_meth_set_flags(cipher, flags)
970         && EVP_CIPHER_meth_set_cleanup(cipher, gost_grasshopper_cipher_cleanup)
971         && EVP_CIPHER_meth_set_set_asn1_params(cipher,
972                                                gost_grasshopper_set_asn1_parameters)
973         && EVP_CIPHER_meth_set_get_asn1_params(cipher,
974                                                gost_grasshopper_get_asn1_parameters)
975         && EVP_CIPHER_meth_set_ctrl(cipher, gost_grasshopper_cipher_ctl)
976         && EVP_CIPHER_meth_set_do_cipher(cipher, gost_grasshopper_cipher_do);
977 }
978
979 const GRASSHOPPER_INLINE EVP_CIPHER *cipher_gost_grasshopper(uint8_t mode,
980                                                              uint8_t num)
981 {
982     EVP_CIPHER **cipher;
983     struct GRASSHOPPER_CIPHER_PARAMS *params;
984
985     cipher = &gost_grasshopper_ciphers[num];
986
987     if (*cipher == NULL) {
988         grasshopper_init_cipher_func init_cipher;
989         int nid, block_size, ctx_size, iv_size, extra_flags;
990         bool padding;
991
992         params = &gost_cipher_params[num];
993
994         nid = params->nid;
995         init_cipher = params->init_cipher;
996         block_size = params->block_size;
997         ctx_size = params->ctx_size;
998         iv_size = params->iv_size;
999         padding = params->padding;
1000                                 extra_flags = params->extra_flags;
1001
1002         *cipher = cipher_gost_grasshopper_create(nid, block_size);
1003         if (*cipher == NULL) {
1004             return NULL;
1005         }
1006
1007         if (!cipher_gost_grasshopper_setup(*cipher, mode, iv_size, padding, extra_flags)
1008             || !EVP_CIPHER_meth_set_init(*cipher, init_cipher)
1009             || !EVP_CIPHER_meth_set_impl_ctx_size(*cipher, ctx_size)) {
1010             EVP_CIPHER_meth_free(*cipher);
1011             *cipher = NULL;
1012         }
1013     }
1014
1015     return *cipher;
1016 }
1017
1018 const GRASSHOPPER_INLINE EVP_CIPHER *cipher_gost_grasshopper_ecb()
1019 {
1020     return cipher_gost_grasshopper(EVP_CIPH_ECB_MODE, GRASSHOPPER_CIPHER_ECB);
1021 }
1022
1023 const GRASSHOPPER_INLINE EVP_CIPHER *cipher_gost_grasshopper_cbc()
1024 {
1025     return cipher_gost_grasshopper(EVP_CIPH_CBC_MODE, GRASSHOPPER_CIPHER_CBC);
1026 }
1027
1028 const GRASSHOPPER_INLINE EVP_CIPHER *cipher_gost_grasshopper_ofb()
1029 {
1030     return cipher_gost_grasshopper(EVP_CIPH_OFB_MODE, GRASSHOPPER_CIPHER_OFB);
1031 }
1032
1033 const GRASSHOPPER_INLINE EVP_CIPHER *cipher_gost_grasshopper_cfb()
1034 {
1035     return cipher_gost_grasshopper(EVP_CIPH_CFB_MODE, GRASSHOPPER_CIPHER_CFB);
1036 }
1037
1038 const GRASSHOPPER_INLINE EVP_CIPHER *cipher_gost_grasshopper_ctr()
1039 {
1040     return cipher_gost_grasshopper(EVP_CIPH_CTR_MODE, GRASSHOPPER_CIPHER_CTR);
1041 }
1042
1043 const GRASSHOPPER_INLINE EVP_CIPHER *cipher_gost_grasshopper_ctracpkm()
1044 {
1045     return cipher_gost_grasshopper(EVP_CIPH_CTR_MODE,
1046                                    GRASSHOPPER_CIPHER_CTRACPKM);
1047 }
1048
1049 const GRASSHOPPER_INLINE EVP_CIPHER *cipher_gost_grasshopper_ctracpkm_omac()
1050 {
1051     return cipher_gost_grasshopper(EVP_CIPH_CTR_MODE,
1052                                    GRASSHOPPER_CIPHER_CTRACPKMOMAC);
1053 }
1054
1055 void cipher_gost_grasshopper_destroy(void)
1056 {
1057     EVP_CIPHER_meth_free(gost_grasshopper_ciphers[GRASSHOPPER_CIPHER_ECB]);
1058     gost_grasshopper_ciphers[GRASSHOPPER_CIPHER_ECB] = NULL;
1059     EVP_CIPHER_meth_free(gost_grasshopper_ciphers[GRASSHOPPER_CIPHER_CBC]);
1060     gost_grasshopper_ciphers[GRASSHOPPER_CIPHER_CBC] = NULL;
1061     EVP_CIPHER_meth_free(gost_grasshopper_ciphers[GRASSHOPPER_CIPHER_OFB]);
1062     gost_grasshopper_ciphers[GRASSHOPPER_CIPHER_OFB] = NULL;
1063     EVP_CIPHER_meth_free(gost_grasshopper_ciphers[GRASSHOPPER_CIPHER_CFB]);
1064     gost_grasshopper_ciphers[GRASSHOPPER_CIPHER_CFB] = NULL;
1065     EVP_CIPHER_meth_free(gost_grasshopper_ciphers[GRASSHOPPER_CIPHER_CTR]);
1066     gost_grasshopper_ciphers[GRASSHOPPER_CIPHER_CTR] = NULL;
1067     EVP_CIPHER_meth_free(gost_grasshopper_ciphers[GRASSHOPPER_CIPHER_CTRACPKM]);
1068     gost_grasshopper_ciphers[GRASSHOPPER_CIPHER_CTRACPKM] = NULL;
1069     EVP_CIPHER_meth_free(gost_grasshopper_ciphers[GRASSHOPPER_CIPHER_CTRACPKMOMAC]);
1070     gost_grasshopper_ciphers[GRASSHOPPER_CIPHER_CTRACPKMOMAC] = NULL;
1071 }