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