]> www.wagner.pp.ru Git - openssl-gost/engine.git/blob - gost_gost2015.c
initial unified impl magma/kuznetchik MGM mode
[openssl-gost/engine.git] / gost_gost2015.c
1 /*
2  * Copyright (c) 2020 Dmitry Belyavskiy <beldmit@gmail.com>
3  *
4  * Contents licensed under the terms of the OpenSSL license
5  * See https://www.openssl.org/source/license.html for details
6  */
7 #include "gost_lcl.h"
8 #include "gost_gost2015.h"
9 #include "gost_grasshopper_defines.h"
10 #include "gost_grasshopper_math.h"
11 #include "e_gost_err.h"
12 #include <string.h>
13 #include <openssl/rand.h>
14
15 int gost2015_final_call(EVP_CIPHER_CTX *ctx, EVP_MD_CTX *omac_ctx, size_t mac_size,
16     unsigned char *encrypted_mac,
17     int (*do_cipher) (EVP_CIPHER_CTX *ctx,
18     unsigned char *out,
19     const unsigned char *in,
20     size_t inl))
21 {
22     unsigned char calculated_mac[KUZNYECHIK_MAC_MAX_SIZE];
23     memset(calculated_mac, 0, KUZNYECHIK_MAC_MAX_SIZE);
24
25     if (EVP_CIPHER_CTX_encrypting(ctx)) {
26         EVP_DigestSignFinal(omac_ctx, calculated_mac, &mac_size);
27
28         if (do_cipher(ctx, encrypted_mac, calculated_mac, mac_size) <= 0) {
29             return -1;
30         }
31     } else {
32         unsigned char expected_mac[KUZNYECHIK_MAC_MAX_SIZE];
33
34         memset(expected_mac, 0, KUZNYECHIK_MAC_MAX_SIZE);
35         EVP_DigestSignFinal(omac_ctx, calculated_mac, &mac_size);
36
37         if (do_cipher(ctx, expected_mac, encrypted_mac, mac_size) <= 0) {
38             return -1;
39         }
40
41         if (CRYPTO_memcmp(expected_mac, calculated_mac, mac_size) != 0)
42             return -1;
43     }
44     return 0;
45 }
46
47 /*
48  * UKM = iv|kdf_seed
49  * */
50 #define MAX_GOST2015_UKM_SIZE 16
51 #define KDF_SEED_SIZE 8
52 int gost2015_get_asn1_params(const ASN1_TYPE *params, size_t ukm_size,
53     unsigned char *iv, size_t ukm_offset, unsigned char *kdf_seed)
54 {
55     int iv_len = 16;
56     GOST2015_CIPHER_PARAMS *gcp = NULL;
57
58     unsigned char *p = NULL;
59
60     memset(iv, 0, iv_len);
61
62     /* Проверяем тип params */
63     if (ASN1_TYPE_get(params) != V_ASN1_SEQUENCE) {
64         GOSTerr(GOST_F_GOST2015_GET_ASN1_PARAMS, GOST_R_INVALID_CIPHER_PARAMS);
65         return 0;
66     }
67
68     p = params->value.sequence->data;
69     /* Извлекаем структуру параметров */
70     gcp = d2i_GOST2015_CIPHER_PARAMS(NULL, (const unsigned char **)&p, params->value.sequence->length);
71     if (gcp == NULL) {
72         GOSTerr(GOST_F_GOST2015_GET_ASN1_PARAMS, GOST_R_INVALID_CIPHER_PARAMS);
73         return 0;
74     }
75
76     /* Проверяем длину синхропосылки */
77     if (gcp->ukm->length != (int)ukm_size) {
78         GOSTerr(GOST_F_GOST2015_GET_ASN1_PARAMS, GOST_R_INVALID_CIPHER_PARAMS);
79         GOST2015_CIPHER_PARAMS_free(gcp);
80         return 0;
81     }
82
83     memcpy(iv, gcp->ukm->data, ukm_offset);
84     memcpy(kdf_seed, gcp->ukm->data+ukm_offset, KDF_SEED_SIZE);
85
86     GOST2015_CIPHER_PARAMS_free(gcp);
87     return 1;
88 }
89
90 int gost2015_set_asn1_params(ASN1_TYPE *params,
91     const unsigned char *iv, size_t iv_size, const unsigned char *kdf_seed)
92 {
93     GOST2015_CIPHER_PARAMS *gcp = GOST2015_CIPHER_PARAMS_new();
94     int ret = 0, len = 0;
95
96     ASN1_OCTET_STRING *os = NULL;
97     unsigned char ukm_buf[MAX_GOST2015_UKM_SIZE];
98     unsigned char *buf = NULL;
99
100     if (gcp == NULL) {
101         GOSTerr(GOST_F_GOST2015_SET_ASN1_PARAMS, ERR_R_MALLOC_FAILURE);
102         return 0;
103     }
104
105     memcpy(ukm_buf, iv, iv_size);
106     memcpy(ukm_buf+iv_size, kdf_seed, KDF_SEED_SIZE);
107
108     if (ASN1_STRING_set(gcp->ukm, ukm_buf, iv_size + KDF_SEED_SIZE) == 0) {
109         GOSTerr(GOST_F_GOST2015_SET_ASN1_PARAMS, ERR_R_MALLOC_FAILURE);
110         goto end;
111     }
112
113     len = i2d_GOST2015_CIPHER_PARAMS(gcp, &buf);
114
115     if (len <= 0
116        || (os = ASN1_OCTET_STRING_new()) == NULL
117        || ASN1_OCTET_STRING_set(os, buf, len) == 0) {
118         goto end;
119   }
120
121     ASN1_TYPE_set(params, V_ASN1_SEQUENCE, os);
122     ret = 1;
123
124 end:
125     OPENSSL_free(buf);
126     if (ret <= 0 && os)
127         ASN1_OCTET_STRING_free(os);
128
129     GOST2015_CIPHER_PARAMS_free(gcp);
130     return ret;
131 }
132
133 int gost2015_process_unprotected_attributes(
134     STACK_OF(X509_ATTRIBUTE) *attrs,
135     int encryption, size_t mac_len, unsigned char *final_tag)
136 {
137     if (encryption == 0) /*Decrypting*/ {
138         ASN1_OCTET_STRING *osExpectedMac = X509at_get0_data_by_OBJ(attrs,
139             OBJ_txt2obj(OID_GOST_CMS_MAC, 1), -3, V_ASN1_OCTET_STRING);
140
141         if (!osExpectedMac || osExpectedMac->length != (int)mac_len)
142             return -1;
143
144         memcpy(final_tag, osExpectedMac->data, osExpectedMac->length);
145     } else {
146         if (attrs == NULL)
147             return -1;
148         return (X509at_add1_attr_by_OBJ(&attrs,
149                OBJ_txt2obj(OID_GOST_CMS_MAC, 1),
150                V_ASN1_OCTET_STRING, final_tag,
151                mac_len) == NULL) ? -1 : 1;
152     }
153     return 1;
154 }
155
156 int gost2015_acpkm_omac_init(int nid, int enc, const unsigned char *inkey,
157                              EVP_MD_CTX *omac_ctx,
158                              unsigned char *outkey, unsigned char *kdf_seed)
159 {
160     int ret = 0;
161     unsigned char keys[64];
162     const EVP_MD *md = EVP_get_digestbynid(nid);
163     EVP_PKEY *mac_key;
164
165     if (md == NULL)
166         return 0;
167
168     if (enc) {
169         if (RAND_bytes(kdf_seed, 8) != 1)
170             return 0;
171     }
172
173     if (gost_kdftree2012_256(keys, 64, inkey, 32,
174        (const unsigned char *)"kdf tree", 8, kdf_seed, 8, 1) <= 0)
175         return 0;
176
177     mac_key = EVP_PKEY_new_mac_key(nid, NULL, keys+32, 32);
178
179     if (mac_key == NULL)
180         goto end;
181
182     if (EVP_DigestInit_ex(omac_ctx, md, NULL) <= 0 ||
183        EVP_DigestSignInit(omac_ctx, NULL, md, NULL, mac_key) <= 0)
184         goto end;
185
186     memcpy(outkey, keys, 32);
187
188     ret = 1;
189 end:
190     EVP_PKEY_free(mac_key);
191     OPENSSL_cleanse(keys, sizeof(keys));
192
193     return ret;
194 }
195
196 int init_zero_kdf_seed(unsigned char *kdf_seed)
197 {
198     int is_zero_kdfseed = 1, i;
199     for (i = 0; i < 8; i++) {
200         if (kdf_seed[i] != 0)
201             is_zero_kdfseed = 0;
202     }
203
204     return is_zero_kdfseed ? RAND_bytes(kdf_seed, 8) : 1;
205 }
206
207 void gost_mgm128_init(mgm128_context *ctx, void *key, block128_f block, mul128_f mul_gf, int blen)
208 {
209     memset(ctx, 0, sizeof(*ctx));
210     ctx->block = block;
211     ctx->mul_gf = mul_gf;
212     ctx->key = key;
213     ctx->blocklen = blen;
214
215     /* some precalculations place here
216      *
217      */
218 }
219
220 int gost_mgm128_setiv(mgm128_context *ctx, const unsigned char *iv,
221                          size_t len)
222 {
223     ctx->len.u[0] = 0;          /* AAD length */
224     ctx->len.u[1] = 0;          /* message length */
225     ctx->ares = 0;
226     ctx->mres = 0;
227
228     ctx->ACi.u[0] = 0;
229     ctx->ACi.u[1] = 0;
230
231     memcpy(ctx->nonce.c, iv, ctx->blocklen);
232     ctx->nonce.c[0] &= 0x7f;    /* IV - random vector, but 1st bit should be 0 */
233     return 1;
234 }
235
236 int gost_mgm128_aad(mgm128_context *ctx, const unsigned char *aad,
237                       size_t len)
238 {
239     size_t i;
240     unsigned int n;
241     uint64_t alen = ctx->len.u[0];
242     block128_f block = ctx->block;
243     mul128_f mul_gf = ctx->mul_gf;
244     void *key = ctx->key;
245     int bl = ctx->blocklen;
246
247     if (ctx->len.u[1]) {
248         GOSTerr(GOST_F_GOST_MGM128_AAD,
249                 GOST_R_BAD_ORDER);
250         return -2;
251     }
252
253     if (alen == 0) {
254         ctx->nonce.c[0] |= 0x80;
255         (*block) (ctx->nonce.c, ctx->Zi.c, key);    // Z_1 = E_K(1 || nonce)
256     }
257     
258     alen += len;
259     if (alen > (U64(1) << (bl * 4 - 3)) ||      // < 2^(n/2)  (len stores in bytes)
260         (sizeof(len) == 8 && alen < len)) {
261             GOSTerr(GOST_F_GOST_MGM128_AAD,
262                     GOST_R_DATA_TOO_LARGE);
263             return -1;
264         }
265     ctx->len.u[0] = alen;
266
267     n = ctx->ares;
268     if (n) {
269         /* Finalize partial_data */
270         while (n && len) {
271             ctx->ACi.c[n] = *(aad++);
272             --len;
273             n = (n + 1) % bl;
274         }
275         if (n == 0) {
276             (*block) (ctx->Zi.c, ctx->Hi.c, key);                   // H_i = E_K(Z_i)
277             mul_gf(ctx->mul.u, ctx->Hi.u, ctx->ACi.u);              // H_i (x) A_i
278             grasshopper_plus128((grasshopper_w128_t*)ctx->sum.u,    // acc XOR
279               (grasshopper_w128_t*)ctx->sum.u, (grasshopper_w128_t*)ctx->mul.u);
280             inc_counter(ctx->Zi.c, bl / 2);                              // Z_{i+1} = incr_l(Z_i)
281         } else {
282             ctx->ares = n;
283             return 0;
284         }
285     }
286     while (len >= bl) {
287         (*block) (ctx->Zi.c, ctx->Hi.c, key);                       // H_i = E_K(Z_i)
288         mul_gf(ctx->mul.u, ctx->Hi.u, (uint64_t *)aad);             // H_i (x) A_i
289         grasshopper_plus128((grasshopper_w128_t*)ctx->sum.u,        // acc XOR
290             (grasshopper_w128_t*)ctx->sum.u, (grasshopper_w128_t*)ctx->mul.u);
291         inc_counter(ctx->Zi.c, bl / 2);                                  // Z_{i+1} = incr_l(Z_i)
292         aad += bl;
293         len -= bl;
294     }
295     if (len) {
296         n = (unsigned int)len;
297         for (i = 0; i < len; ++i)
298             ctx->ACi.c[i] = aad[i];
299     }
300
301     ctx->ares = n;
302     return 0;
303 }
304
305 int gost_mgm128_encrypt(mgm128_context *ctx, const unsigned char *in, 
306                           unsigned char *out, size_t len)
307 {
308     size_t i;
309     unsigned int n, mres;
310     uint64_t alen = ctx->len.u[0];
311     uint64_t mlen = ctx->len.u[1];
312     block128_f block = ctx->block;
313     mul128_f mul_gf = ctx->mul_gf;
314     void *key = ctx->key;
315     int bl = ctx->blocklen;
316
317     if (mlen == 0) {
318         ctx->nonce.c[0] &= 0x7f;
319         (*block) (ctx->nonce.c, ctx->Yi.c, key);    // Y_1 = E_K(0 || nonce)
320     }
321
322     mlen += len;
323     
324     if (mlen > (U64(1) << (bl * 4 - 3)) ||     // < 2^(n/2)  (len stores in bytes)
325         (sizeof(len) == 8 && mlen < len) ||
326         (mlen + alen) > (U64(1) << (bl * 4 - 3))) {
327             GOSTerr(GOST_F_GOST_MGM128_ENCRYPT,
328                     GOST_R_DATA_TOO_LARGE);
329             return -1;
330         }
331     ctx->len.u[1] = mlen;
332
333     mres = ctx->mres;
334
335     if (ctx->ares) {
336         /* First call to encrypt finalizes AAD */
337         memset(ctx->ACi.c + ctx->ares, 0, bl - ctx->ares);
338         (*block) (ctx->Zi.c, ctx->Hi.c, key);                   // H_i = E_K(Z_i)
339         mul_gf(ctx->mul.u, ctx->Hi.u, ctx->ACi.u);              // H_i (x) A_i
340         grasshopper_plus128((grasshopper_w128_t*)ctx->sum.u,    // acc XOR
341             (grasshopper_w128_t*)ctx->sum.u, (grasshopper_w128_t*)ctx->mul.u);
342         inc_counter(ctx->Zi.c, bl / 2);                         // Z_{i+1} = incr_l(Z_i)
343
344         ctx->ares = 0;
345     }
346
347     n = mres % bl;
348     // TODO: full blocks
349     for (i = 0; i < len; ++i) {
350         if (n == 0) {
351             (*block) (ctx->Yi.c, ctx->EKi.c, key);          // E_K(Y_i)
352             inc_counter(ctx->Yi.c + bl / 2, bl / 2);        // Y_i = incr_r(Y_{i-1})
353         }
354         ctx->ACi.c[n] = out[i] = in[i] ^ ctx->EKi.c[n];     // C_i = P_i (xor) E_K(Y_i)
355         mres = n = (n + 1) % bl;
356         if (n == 0) {
357             (*block) (ctx->Zi.c, ctx->Hi.c, key);                   // H_i = E_K(Z_i)
358             mul_gf(ctx->mul.u, ctx->Hi.u, ctx->ACi.u);              // H_i (x) C_i
359             grasshopper_plus128((grasshopper_w128_t*)ctx->sum.u,    // acc XOR
360                 (grasshopper_w128_t*)ctx->sum.u, (grasshopper_w128_t*)ctx->mul.u);
361             inc_counter(ctx->Zi.c, bl / 2);                         // Z_{i+1} = incr_l(Z_i)
362         }
363     }
364
365     ctx->mres = mres;
366     return 0;  
367 }
368
369 int gost_mgm128_decrypt(mgm128_context *ctx, const unsigned char *in, 
370                           unsigned char *out, size_t len)
371 {
372     size_t i;
373     unsigned int n, mres;
374     uint64_t alen = ctx->len.u[0];
375     uint64_t mlen = ctx->len.u[1];
376     block128_f block = ctx->block;
377     mul128_f mul_gf = ctx->mul_gf;
378     void *key = ctx->key;
379     int bl = ctx->blocklen;
380
381     if (mlen == 0) {
382         ctx->nonce.c[0] &= 0x7f;
383         (*block) (ctx->nonce.c, ctx->Yi.c, key);  // Y_1 = E_K(0 || nonce)
384     }
385
386     mlen += len;
387     if (mlen > (U64(1) << (bl * 4 - 3)) ||     // < 2^(n/2)  (len stores in bytes)
388         (sizeof(len) == 8 && mlen < len) ||
389         (mlen + alen) > (U64(1) << (bl * 4 - 3))) {
390             GOSTerr(GOST_F_GOST_MGM128_DECRYPT,
391                     GOST_R_DATA_TOO_LARGE);
392             return -1;
393         }
394     ctx->len.u[1] = mlen;
395
396     mres = ctx->mres;
397
398     if (ctx->ares) {
399         /* First call to encrypt finalizes AAD */
400         memset(ctx->ACi.c + ctx->ares, 0, bl - ctx->ares);
401         (*block) (ctx->Zi.c, ctx->Hi.c, key);                   // H_i = E_K(Z_i)
402         mul_gf(ctx->mul.u, ctx->Hi.u, ctx->ACi.u);              // H_i (x) A_i
403         grasshopper_plus128((grasshopper_w128_t*)ctx->sum.u,    // acc XOR
404             (grasshopper_w128_t*)ctx->sum.u, (grasshopper_w128_t*)ctx->mul.u);
405         inc_counter(ctx->Zi.c, bl / 2);                         // Z_{i+1} = incr_l(Z_i)
406
407         ctx->ares = 0;
408     }
409
410     n = mres % bl;
411     // TODO: full blocks
412     for (i = 0; i < len; ++i) {
413         uint8_t c;
414         if (n == 0) {
415             (*block) (ctx->Yi.c, ctx->EKi.c, key);      // E_K(Y_i)
416             inc_counter(ctx->Yi.c + bl / 2, bl / 2);    // Y_i = incr_r(Y_{i-1})
417         }
418         ctx->ACi.c[n] = c = in[i];       
419         out[i] = c ^ ctx->EKi.c[n];             // P_i = C_i (xor) E_K(Y_i)
420         mres = n = (n + 1) % bl;
421         if (n == 0) {
422             (*block) (ctx->Zi.c, ctx->Hi.c, key);                   // H_i = E_K(Z_i)
423             mul_gf(ctx->mul.u, ctx->Hi.u, ctx->ACi.u);              // H_i (x) C_i
424             grasshopper_plus128((grasshopper_w128_t*)ctx->sum.u,    // acc XOR
425                 (grasshopper_w128_t*)ctx->sum.u, (grasshopper_w128_t*)ctx->mul.u);
426             inc_counter(ctx->Zi.c, bl / 2);                         // Z_{i+1} = incr_l(Z_i)
427         }
428     }
429
430     ctx->mres = mres;
431     return 0;  
432 }
433
434 int gost_mgm128_finish(mgm128_context *ctx, const unsigned char *tag,
435                          size_t len)
436 {
437     uint64_t alen = ctx->len.u[0] << 3;
438     uint64_t clen = ctx->len.u[1] << 3;
439     block128_f block = ctx->block;
440     mul128_f mul_gf = ctx->mul_gf;
441     void *key = ctx->key;
442     int bl = ctx->blocklen;
443
444     if (ctx->mres || ctx->ares) {
445         /* First call to encrypt finalizes AAD/ENC */
446         memset(ctx->ACi.c + ctx->ares + ctx->mres, 0, bl - (ctx->ares + ctx->mres));
447         (*block) (ctx->Zi.c, ctx->Hi.c, key);                   // H_i = E_K(Z_i)
448         mul_gf(ctx->mul.u, ctx->Hi.u, ctx->ACi.u);              // H_i (x) [A_i or C_i]
449         grasshopper_plus128((grasshopper_w128_t*)ctx->sum.u,    // acc XOR
450             (grasshopper_w128_t*)ctx->sum.u, (grasshopper_w128_t*)ctx->mul.u);
451         inc_counter(ctx->Zi.c, bl / 2);                         // Z_{i+1} = incr_l(Z_i)
452     }
453
454 #ifdef L_ENDIAN
455     alen = BSWAP64(alen);
456     clen = BSWAP64(clen);
457 #endif
458     if (bl == 16) {
459         ctx->len.u[0] = alen;
460         ctx->len.u[1] = clen;
461     } else {
462         // TODO: check for big-endian
463         ctx->len.u[0] = (alen >> 32) | clen;
464         ctx->len.u[1] = 0;
465     }
466
467     (*block) (ctx->Zi.c, ctx->Hi.c, key);                   // H_i = E_K(Z_i)
468     mul_gf(ctx->mul.u, ctx->Hi.u, ctx->len.u);              // H_i (x) (len(A) || len(C))
469     grasshopper_plus128((grasshopper_w128_t*)ctx->sum.u,    // acc XOR
470             (grasshopper_w128_t*)ctx->sum.u, (grasshopper_w128_t*)ctx->mul.u);
471     (*block) (ctx->sum.c, ctx->tag.c, key);                 // E_K(sum)
472
473     if (tag && len <= sizeof(ctx->tag))
474         return CRYPTO_memcmp(ctx->tag.c, tag, len);         // MSB_S(E_K(sum))
475     else
476         return -1;
477 }
478
479 void gost_mgm128_tag(mgm128_context *ctx, unsigned char *tag, size_t len)
480 {
481     gost_mgm128_finish(ctx, NULL, 0);
482     memcpy(tag, ctx->tag.c,
483            len <= sizeof(ctx->tag.c) ? len : sizeof(ctx->tag.c));
484 }