Update copyright year
[openssl.git] / crypto / evp / e_aes_cbc_hmac_sha256.c
1 /*
2  * Copyright 2013-2020 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 /*
11  * AES low level APIs are deprecated for public use, but still ok for internal
12  * use where we're using them to implement the higher level EVP interface, as is
13  * the case here.
14  */
15 #include "internal/deprecated.h"
16
17 #include <stdio.h>
18 #include <string.h>
19 #include <openssl/opensslconf.h>
20 #include <openssl/evp.h>
21 #include <openssl/objects.h>
22 #include <openssl/aes.h>
23 #include <openssl/sha.h>
24 #include <openssl/rand.h>
25 #include "internal/cryptlib.h"
26 #include "crypto/modes.h"
27 #include "internal/constant_time.h"
28 #include "crypto/evp.h"
29
30 typedef struct {
31     AES_KEY ks;
32     SHA256_CTX head, tail, md;
33     size_t payload_length;      /* AAD length in decrypt case */
34     union {
35         unsigned int tls_ver;
36         unsigned char tls_aad[16]; /* 13 used */
37     } aux;
38 } EVP_AES_HMAC_SHA256;
39
40 # define NO_PAYLOAD_LENGTH       ((size_t)-1)
41
42 #if     defined(AES_ASM) &&     ( \
43         defined(__x86_64)       || defined(__x86_64__)  || \
44         defined(_M_AMD64)       || defined(_M_X64)      )
45
46 # define AESNI_CAPABLE   (1<<(57-32))
47
48 int aesni_set_encrypt_key(const unsigned char *userKey, int bits,
49                           AES_KEY *key);
50 int aesni_set_decrypt_key(const unsigned char *userKey, int bits,
51                           AES_KEY *key);
52
53 void aesni_cbc_encrypt(const unsigned char *in,
54                        unsigned char *out,
55                        size_t length,
56                        const AES_KEY *key, unsigned char *ivec, int enc);
57
58 int aesni_cbc_sha256_enc(const void *inp, void *out, size_t blocks,
59                          const AES_KEY *key, unsigned char iv[16],
60                          SHA256_CTX *ctx, const void *in0);
61
62 # define data(ctx) ((EVP_AES_HMAC_SHA256 *)EVP_CIPHER_CTX_get_cipher_data(ctx))
63
64 static int aesni_cbc_hmac_sha256_init_key(EVP_CIPHER_CTX *ctx,
65                                           const unsigned char *inkey,
66                                           const unsigned char *iv, int enc)
67 {
68     EVP_AES_HMAC_SHA256 *key = data(ctx);
69     int ret;
70
71     if (enc)
72         ret = aesni_set_encrypt_key(inkey,
73                                     EVP_CIPHER_CTX_key_length(ctx) * 8,
74                                     &key->ks);
75     else
76         ret = aesni_set_decrypt_key(inkey,
77                                     EVP_CIPHER_CTX_key_length(ctx) * 8,
78                                     &key->ks);
79
80     SHA256_Init(&key->head);    /* handy when benchmarking */
81     key->tail = key->head;
82     key->md = key->head;
83
84     key->payload_length = NO_PAYLOAD_LENGTH;
85
86     return ret < 0 ? 0 : 1;
87 }
88
89 # define STITCHED_CALL
90
91 # if !defined(STITCHED_CALL)
92 #  define aes_off 0
93 # endif
94
95 void sha256_block_data_order(void *c, const void *p, size_t len);
96
97 static void sha256_update(SHA256_CTX *c, const void *data, size_t len)
98 {
99     const unsigned char *ptr = data;
100     size_t res;
101
102     if ((res = c->num)) {
103         res = SHA256_CBLOCK - res;
104         if (len < res)
105             res = len;
106         SHA256_Update(c, ptr, res);
107         ptr += res;
108         len -= res;
109     }
110
111     res = len % SHA256_CBLOCK;
112     len -= res;
113
114     if (len) {
115         sha256_block_data_order(c, ptr, len / SHA256_CBLOCK);
116
117         ptr += len;
118         c->Nh += len >> 29;
119         c->Nl += len <<= 3;
120         if (c->Nl < (unsigned int)len)
121             c->Nh++;
122     }
123
124     if (res)
125         SHA256_Update(c, ptr, res);
126 }
127
128 # ifdef SHA256_Update
129 #  undef SHA256_Update
130 # endif
131 # define SHA256_Update sha256_update
132
133 # if !defined(OPENSSL_NO_MULTIBLOCK)
134
135 typedef struct {
136     unsigned int A[8], B[8], C[8], D[8], E[8], F[8], G[8], H[8];
137 } SHA256_MB_CTX;
138 typedef struct {
139     const unsigned char *ptr;
140     int blocks;
141 } HASH_DESC;
142
143 void sha256_multi_block(SHA256_MB_CTX *, const HASH_DESC *, int);
144
145 typedef struct {
146     const unsigned char *inp;
147     unsigned char *out;
148     int blocks;
149     u64 iv[2];
150 } CIPH_DESC;
151
152 void aesni_multi_cbc_encrypt(CIPH_DESC *, void *, int);
153
154 static size_t tls1_1_multi_block_encrypt(EVP_AES_HMAC_SHA256 *key,
155                                          unsigned char *out,
156                                          const unsigned char *inp,
157                                          size_t inp_len, int n4x)
158 {                               /* n4x is 1 or 2 */
159     HASH_DESC hash_d[8], edges[8];
160     CIPH_DESC ciph_d[8];
161     unsigned char storage[sizeof(SHA256_MB_CTX) + 32];
162     union {
163         u64 q[16];
164         u32 d[32];
165         u8 c[128];
166     } blocks[8];
167     SHA256_MB_CTX *ctx;
168     unsigned int frag, last, packlen, i, x4 = 4 * n4x, minblocks, processed =
169         0;
170     size_t ret = 0;
171     u8 *IVs;
172 #  if defined(BSWAP8)
173     u64 seqnum;
174 #  endif
175
176     /* ask for IVs in bulk */
177     if (RAND_bytes((IVs = blocks[0].c), 16 * x4) <= 0)
178         return 0;
179
180     /* align */
181     ctx = (SHA256_MB_CTX *) (storage + 32 - ((size_t)storage % 32));
182
183     frag = (unsigned int)inp_len >> (1 + n4x);
184     last = (unsigned int)inp_len + frag - (frag << (1 + n4x));
185     if (last > frag && ((last + 13 + 9) % 64) < (x4 - 1)) {
186         frag++;
187         last -= x4 - 1;
188     }
189
190     packlen = 5 + 16 + ((frag + 32 + 16) & -16);
191
192     /* populate descriptors with pointers and IVs */
193     hash_d[0].ptr = inp;
194     ciph_d[0].inp = inp;
195     /* 5+16 is place for header and explicit IV */
196     ciph_d[0].out = out + 5 + 16;
197     memcpy(ciph_d[0].out - 16, IVs, 16);
198     memcpy(ciph_d[0].iv, IVs, 16);
199     IVs += 16;
200
201     for (i = 1; i < x4; i++) {
202         ciph_d[i].inp = hash_d[i].ptr = hash_d[i - 1].ptr + frag;
203         ciph_d[i].out = ciph_d[i - 1].out + packlen;
204         memcpy(ciph_d[i].out - 16, IVs, 16);
205         memcpy(ciph_d[i].iv, IVs, 16);
206         IVs += 16;
207     }
208
209 #  if defined(BSWAP8)
210     memcpy(blocks[0].c, key->md.data, 8);
211     seqnum = BSWAP8(blocks[0].q[0]);
212 #  endif
213     for (i = 0; i < x4; i++) {
214         unsigned int len = (i == (x4 - 1) ? last : frag);
215 #  if !defined(BSWAP8)
216         unsigned int carry, j;
217 #  endif
218
219         ctx->A[i] = key->md.h[0];
220         ctx->B[i] = key->md.h[1];
221         ctx->C[i] = key->md.h[2];
222         ctx->D[i] = key->md.h[3];
223         ctx->E[i] = key->md.h[4];
224         ctx->F[i] = key->md.h[5];
225         ctx->G[i] = key->md.h[6];
226         ctx->H[i] = key->md.h[7];
227
228         /* fix seqnum */
229 #  if defined(BSWAP8)
230         blocks[i].q[0] = BSWAP8(seqnum + i);
231 #  else
232         for (carry = i, j = 8; j--;) {
233             blocks[i].c[j] = ((u8 *)key->md.data)[j] + carry;
234             carry = (blocks[i].c[j] - carry) >> (sizeof(carry) * 8 - 1);
235         }
236 #  endif
237         blocks[i].c[8] = ((u8 *)key->md.data)[8];
238         blocks[i].c[9] = ((u8 *)key->md.data)[9];
239         blocks[i].c[10] = ((u8 *)key->md.data)[10];
240         /* fix length */
241         blocks[i].c[11] = (u8)(len >> 8);
242         blocks[i].c[12] = (u8)(len);
243
244         memcpy(blocks[i].c + 13, hash_d[i].ptr, 64 - 13);
245         hash_d[i].ptr += 64 - 13;
246         hash_d[i].blocks = (len - (64 - 13)) / 64;
247
248         edges[i].ptr = blocks[i].c;
249         edges[i].blocks = 1;
250     }
251
252     /* hash 13-byte headers and first 64-13 bytes of inputs */
253     sha256_multi_block(ctx, edges, n4x);
254     /* hash bulk inputs */
255 #  define MAXCHUNKSIZE    2048
256 #  if     MAXCHUNKSIZE%64
257 #   error  "MAXCHUNKSIZE is not divisible by 64"
258 #  elif   MAXCHUNKSIZE
259     /*
260      * goal is to minimize pressure on L1 cache by moving in shorter steps,
261      * so that hashed data is still in the cache by the time we encrypt it
262      */
263     minblocks = ((frag <= last ? frag : last) - (64 - 13)) / 64;
264     if (minblocks > MAXCHUNKSIZE / 64) {
265         for (i = 0; i < x4; i++) {
266             edges[i].ptr = hash_d[i].ptr;
267             edges[i].blocks = MAXCHUNKSIZE / 64;
268             ciph_d[i].blocks = MAXCHUNKSIZE / 16;
269         }
270         do {
271             sha256_multi_block(ctx, edges, n4x);
272             aesni_multi_cbc_encrypt(ciph_d, &key->ks, n4x);
273
274             for (i = 0; i < x4; i++) {
275                 edges[i].ptr = hash_d[i].ptr += MAXCHUNKSIZE;
276                 hash_d[i].blocks -= MAXCHUNKSIZE / 64;
277                 edges[i].blocks = MAXCHUNKSIZE / 64;
278                 ciph_d[i].inp += MAXCHUNKSIZE;
279                 ciph_d[i].out += MAXCHUNKSIZE;
280                 ciph_d[i].blocks = MAXCHUNKSIZE / 16;
281                 memcpy(ciph_d[i].iv, ciph_d[i].out - 16, 16);
282             }
283             processed += MAXCHUNKSIZE;
284             minblocks -= MAXCHUNKSIZE / 64;
285         } while (minblocks > MAXCHUNKSIZE / 64);
286     }
287 #  endif
288 #  undef  MAXCHUNKSIZE
289     sha256_multi_block(ctx, hash_d, n4x);
290
291     memset(blocks, 0, sizeof(blocks));
292     for (i = 0; i < x4; i++) {
293         unsigned int len = (i == (x4 - 1) ? last : frag),
294             off = hash_d[i].blocks * 64;
295         const unsigned char *ptr = hash_d[i].ptr + off;
296
297         off = (len - processed) - (64 - 13) - off; /* remainder actually */
298         memcpy(blocks[i].c, ptr, off);
299         blocks[i].c[off] = 0x80;
300         len += 64 + 13;         /* 64 is HMAC header */
301         len *= 8;               /* convert to bits */
302         if (off < (64 - 8)) {
303 #  ifdef BSWAP4
304             blocks[i].d[15] = BSWAP4(len);
305 #  else
306             PUTU32(blocks[i].c + 60, len);
307 #  endif
308             edges[i].blocks = 1;
309         } else {
310 #  ifdef BSWAP4
311             blocks[i].d[31] = BSWAP4(len);
312 #  else
313             PUTU32(blocks[i].c + 124, len);
314 #  endif
315             edges[i].blocks = 2;
316         }
317         edges[i].ptr = blocks[i].c;
318     }
319
320     /* hash input tails and finalize */
321     sha256_multi_block(ctx, edges, n4x);
322
323     memset(blocks, 0, sizeof(blocks));
324     for (i = 0; i < x4; i++) {
325 #  ifdef BSWAP4
326         blocks[i].d[0] = BSWAP4(ctx->A[i]);
327         ctx->A[i] = key->tail.h[0];
328         blocks[i].d[1] = BSWAP4(ctx->B[i]);
329         ctx->B[i] = key->tail.h[1];
330         blocks[i].d[2] = BSWAP4(ctx->C[i]);
331         ctx->C[i] = key->tail.h[2];
332         blocks[i].d[3] = BSWAP4(ctx->D[i]);
333         ctx->D[i] = key->tail.h[3];
334         blocks[i].d[4] = BSWAP4(ctx->E[i]);
335         ctx->E[i] = key->tail.h[4];
336         blocks[i].d[5] = BSWAP4(ctx->F[i]);
337         ctx->F[i] = key->tail.h[5];
338         blocks[i].d[6] = BSWAP4(ctx->G[i]);
339         ctx->G[i] = key->tail.h[6];
340         blocks[i].d[7] = BSWAP4(ctx->H[i]);
341         ctx->H[i] = key->tail.h[7];
342         blocks[i].c[32] = 0x80;
343         blocks[i].d[15] = BSWAP4((64 + 32) * 8);
344 #  else
345         PUTU32(blocks[i].c + 0, ctx->A[i]);
346         ctx->A[i] = key->tail.h[0];
347         PUTU32(blocks[i].c + 4, ctx->B[i]);
348         ctx->B[i] = key->tail.h[1];
349         PUTU32(blocks[i].c + 8, ctx->C[i]);
350         ctx->C[i] = key->tail.h[2];
351         PUTU32(blocks[i].c + 12, ctx->D[i]);
352         ctx->D[i] = key->tail.h[3];
353         PUTU32(blocks[i].c + 16, ctx->E[i]);
354         ctx->E[i] = key->tail.h[4];
355         PUTU32(blocks[i].c + 20, ctx->F[i]);
356         ctx->F[i] = key->tail.h[5];
357         PUTU32(blocks[i].c + 24, ctx->G[i]);
358         ctx->G[i] = key->tail.h[6];
359         PUTU32(blocks[i].c + 28, ctx->H[i]);
360         ctx->H[i] = key->tail.h[7];
361         blocks[i].c[32] = 0x80;
362         PUTU32(blocks[i].c + 60, (64 + 32) * 8);
363 #  endif
364         edges[i].ptr = blocks[i].c;
365         edges[i].blocks = 1;
366     }
367
368     /* finalize MACs */
369     sha256_multi_block(ctx, edges, n4x);
370
371     for (i = 0; i < x4; i++) {
372         unsigned int len = (i == (x4 - 1) ? last : frag), pad, j;
373         unsigned char *out0 = out;
374
375         memcpy(ciph_d[i].out, ciph_d[i].inp, len - processed);
376         ciph_d[i].inp = ciph_d[i].out;
377
378         out += 5 + 16 + len;
379
380         /* write MAC */
381         PUTU32(out + 0, ctx->A[i]);
382         PUTU32(out + 4, ctx->B[i]);
383         PUTU32(out + 8, ctx->C[i]);
384         PUTU32(out + 12, ctx->D[i]);
385         PUTU32(out + 16, ctx->E[i]);
386         PUTU32(out + 20, ctx->F[i]);
387         PUTU32(out + 24, ctx->G[i]);
388         PUTU32(out + 28, ctx->H[i]);
389         out += 32;
390         len += 32;
391
392         /* pad */
393         pad = 15 - len % 16;
394         for (j = 0; j <= pad; j++)
395             *(out++) = pad;
396         len += pad + 1;
397
398         ciph_d[i].blocks = (len - processed) / 16;
399         len += 16;              /* account for explicit iv */
400
401         /* arrange header */
402         out0[0] = ((u8 *)key->md.data)[8];
403         out0[1] = ((u8 *)key->md.data)[9];
404         out0[2] = ((u8 *)key->md.data)[10];
405         out0[3] = (u8)(len >> 8);
406         out0[4] = (u8)(len);
407
408         ret += len + 5;
409         inp += frag;
410     }
411
412     aesni_multi_cbc_encrypt(ciph_d, &key->ks, n4x);
413
414     OPENSSL_cleanse(blocks, sizeof(blocks));
415     OPENSSL_cleanse(ctx, sizeof(*ctx));
416
417     return ret;
418 }
419 # endif
420
421 static int aesni_cbc_hmac_sha256_cipher(EVP_CIPHER_CTX *ctx,
422                                         unsigned char *out,
423                                         const unsigned char *in, size_t len)
424 {
425     EVP_AES_HMAC_SHA256 *key = data(ctx);
426     unsigned int l;
427     size_t plen = key->payload_length, iv = 0, /* explicit IV in TLS 1.1 and
428                                                 * later */
429         sha_off = 0;
430 # if defined(STITCHED_CALL)
431     size_t aes_off = 0, blocks;
432
433     sha_off = SHA256_CBLOCK - key->md.num;
434 # endif
435
436     key->payload_length = NO_PAYLOAD_LENGTH;
437
438     if (len % AES_BLOCK_SIZE)
439         return 0;
440
441     if (EVP_CIPHER_CTX_encrypting(ctx)) {
442         if (plen == NO_PAYLOAD_LENGTH)
443             plen = len;
444         else if (len !=
445                  ((plen + SHA256_DIGEST_LENGTH +
446                    AES_BLOCK_SIZE) & -AES_BLOCK_SIZE))
447             return 0;
448         else if (key->aux.tls_ver >= TLS1_1_VERSION)
449             iv = AES_BLOCK_SIZE;
450
451 # if defined(STITCHED_CALL)
452         /*
453          * Assembly stitch handles AVX-capable processors, but its
454          * performance is not optimal on AMD Jaguar, ~40% worse, for
455          * unknown reasons. Incidentally processor in question supports
456          * AVX, but not AMD-specific XOP extension, which can be used
457          * to identify it and avoid stitch invocation. So that after we
458          * establish that current CPU supports AVX, we even see if it's
459          * either even XOP-capable Bulldozer-based or GenuineIntel one.
460          * But SHAEXT-capable go ahead...
461          */
462         if (((OPENSSL_ia32cap_P[2] & (1 << 29)) ||         /* SHAEXT? */
463              ((OPENSSL_ia32cap_P[1] & (1 << (60 - 32))) && /* AVX? */
464               ((OPENSSL_ia32cap_P[1] & (1 << (43 - 32)))   /* XOP? */
465                | (OPENSSL_ia32cap_P[0] & (1 << 30))))) &&  /* "Intel CPU"? */
466             plen > (sha_off + iv) &&
467             (blocks = (plen - (sha_off + iv)) / SHA256_CBLOCK)) {
468             SHA256_Update(&key->md, in + iv, sha_off);
469
470             (void)aesni_cbc_sha256_enc(in, out, blocks, &key->ks,
471                                        EVP_CIPHER_CTX_iv_noconst(ctx),
472                                        &key->md, in + iv + sha_off);
473             blocks *= SHA256_CBLOCK;
474             aes_off += blocks;
475             sha_off += blocks;
476             key->md.Nh += blocks >> 29;
477             key->md.Nl += blocks <<= 3;
478             if (key->md.Nl < (unsigned int)blocks)
479                 key->md.Nh++;
480         } else {
481             sha_off = 0;
482         }
483 # endif
484         sha_off += iv;
485         SHA256_Update(&key->md, in + sha_off, plen - sha_off);
486
487         if (plen != len) {      /* "TLS" mode of operation */
488             if (in != out)
489                 memcpy(out + aes_off, in + aes_off, plen - aes_off);
490
491             /* calculate HMAC and append it to payload */
492             SHA256_Final(out + plen, &key->md);
493             key->md = key->tail;
494             SHA256_Update(&key->md, out + plen, SHA256_DIGEST_LENGTH);
495             SHA256_Final(out + plen, &key->md);
496
497             /* pad the payload|hmac */
498             plen += SHA256_DIGEST_LENGTH;
499             for (l = len - plen - 1; plen < len; plen++)
500                 out[plen] = l;
501             /* encrypt HMAC|padding at once */
502             aesni_cbc_encrypt(out + aes_off, out + aes_off, len - aes_off,
503                               &key->ks, EVP_CIPHER_CTX_iv_noconst(ctx), 1);
504         } else {
505             aesni_cbc_encrypt(in + aes_off, out + aes_off, len - aes_off,
506                               &key->ks, EVP_CIPHER_CTX_iv_noconst(ctx), 1);
507         }
508     } else {
509         union {
510             unsigned int u[SHA256_DIGEST_LENGTH / sizeof(unsigned int)];
511             unsigned char c[64 + SHA256_DIGEST_LENGTH];
512         } mac, *pmac;
513
514         /* arrange cache line alignment */
515         pmac = (void *)(((size_t)mac.c + 63) & ((size_t)0 - 64));
516
517         /* decrypt HMAC|padding at once */
518         aesni_cbc_encrypt(in, out, len, &key->ks,
519                           EVP_CIPHER_CTX_iv_noconst(ctx), 0);
520
521         if (plen != NO_PAYLOAD_LENGTH) { /* "TLS" mode of operation */
522             size_t inp_len, mask, j, i;
523             unsigned int res, maxpad, pad, bitlen;
524             int ret = 1;
525             union {
526                 unsigned int u[SHA_LBLOCK];
527                 unsigned char c[SHA256_CBLOCK];
528             } *data = (void *)key->md.data;
529
530             if ((key->aux.tls_aad[plen - 4] << 8 | key->aux.tls_aad[plen - 3])
531                 >= TLS1_1_VERSION)
532                 iv = AES_BLOCK_SIZE;
533
534             if (len < (iv + SHA256_DIGEST_LENGTH + 1))
535                 return 0;
536
537             /* omit explicit iv */
538             out += iv;
539             len -= iv;
540
541             /* figure out payload length */
542             pad = out[len - 1];
543             maxpad = len - (SHA256_DIGEST_LENGTH + 1);
544             maxpad |= (255 - maxpad) >> (sizeof(maxpad) * 8 - 8);
545             maxpad &= 255;
546
547             mask = constant_time_ge(maxpad, pad);
548             ret &= mask;
549             /*
550              * If pad is invalid then we will fail the above test but we must
551              * continue anyway because we are in constant time code. However,
552              * we'll use the maxpad value instead of the supplied pad to make
553              * sure we perform well defined pointer arithmetic.
554              */
555             pad = constant_time_select(mask, pad, maxpad);
556
557             inp_len = len - (SHA256_DIGEST_LENGTH + pad + 1);
558
559             key->aux.tls_aad[plen - 2] = inp_len >> 8;
560             key->aux.tls_aad[plen - 1] = inp_len;
561
562             /* calculate HMAC */
563             key->md = key->head;
564             SHA256_Update(&key->md, key->aux.tls_aad, plen);
565
566 # if 1      /* see original reference version in #else */
567             len -= SHA256_DIGEST_LENGTH; /* amend mac */
568             if (len >= (256 + SHA256_CBLOCK)) {
569                 j = (len - (256 + SHA256_CBLOCK)) & (0 - SHA256_CBLOCK);
570                 j += SHA256_CBLOCK - key->md.num;
571                 SHA256_Update(&key->md, out, j);
572                 out += j;
573                 len -= j;
574                 inp_len -= j;
575             }
576
577             /* but pretend as if we hashed padded payload */
578             bitlen = key->md.Nl + (inp_len << 3); /* at most 18 bits */
579 #  ifdef BSWAP4
580             bitlen = BSWAP4(bitlen);
581 #  else
582             mac.c[0] = 0;
583             mac.c[1] = (unsigned char)(bitlen >> 16);
584             mac.c[2] = (unsigned char)(bitlen >> 8);
585             mac.c[3] = (unsigned char)bitlen;
586             bitlen = mac.u[0];
587 #  endif
588
589             pmac->u[0] = 0;
590             pmac->u[1] = 0;
591             pmac->u[2] = 0;
592             pmac->u[3] = 0;
593             pmac->u[4] = 0;
594             pmac->u[5] = 0;
595             pmac->u[6] = 0;
596             pmac->u[7] = 0;
597
598             for (res = key->md.num, j = 0; j < len; j++) {
599                 size_t c = out[j];
600                 mask = (j - inp_len) >> (sizeof(j) * 8 - 8);
601                 c &= mask;
602                 c |= 0x80 & ~mask & ~((inp_len - j) >> (sizeof(j) * 8 - 8));
603                 data->c[res++] = (unsigned char)c;
604
605                 if (res != SHA256_CBLOCK)
606                     continue;
607
608                 /* j is not incremented yet */
609                 mask = 0 - ((inp_len + 7 - j) >> (sizeof(j) * 8 - 1));
610                 data->u[SHA_LBLOCK - 1] |= bitlen & mask;
611                 sha256_block_data_order(&key->md, data, 1);
612                 mask &= 0 - ((j - inp_len - 72) >> (sizeof(j) * 8 - 1));
613                 pmac->u[0] |= key->md.h[0] & mask;
614                 pmac->u[1] |= key->md.h[1] & mask;
615                 pmac->u[2] |= key->md.h[2] & mask;
616                 pmac->u[3] |= key->md.h[3] & mask;
617                 pmac->u[4] |= key->md.h[4] & mask;
618                 pmac->u[5] |= key->md.h[5] & mask;
619                 pmac->u[6] |= key->md.h[6] & mask;
620                 pmac->u[7] |= key->md.h[7] & mask;
621                 res = 0;
622             }
623
624             for (i = res; i < SHA256_CBLOCK; i++, j++)
625                 data->c[i] = 0;
626
627             if (res > SHA256_CBLOCK - 8) {
628                 mask = 0 - ((inp_len + 8 - j) >> (sizeof(j) * 8 - 1));
629                 data->u[SHA_LBLOCK - 1] |= bitlen & mask;
630                 sha256_block_data_order(&key->md, data, 1);
631                 mask &= 0 - ((j - inp_len - 73) >> (sizeof(j) * 8 - 1));
632                 pmac->u[0] |= key->md.h[0] & mask;
633                 pmac->u[1] |= key->md.h[1] & mask;
634                 pmac->u[2] |= key->md.h[2] & mask;
635                 pmac->u[3] |= key->md.h[3] & mask;
636                 pmac->u[4] |= key->md.h[4] & mask;
637                 pmac->u[5] |= key->md.h[5] & mask;
638                 pmac->u[6] |= key->md.h[6] & mask;
639                 pmac->u[7] |= key->md.h[7] & mask;
640
641                 memset(data, 0, SHA256_CBLOCK);
642                 j += 64;
643             }
644             data->u[SHA_LBLOCK - 1] = bitlen;
645             sha256_block_data_order(&key->md, data, 1);
646             mask = 0 - ((j - inp_len - 73) >> (sizeof(j) * 8 - 1));
647             pmac->u[0] |= key->md.h[0] & mask;
648             pmac->u[1] |= key->md.h[1] & mask;
649             pmac->u[2] |= key->md.h[2] & mask;
650             pmac->u[3] |= key->md.h[3] & mask;
651             pmac->u[4] |= key->md.h[4] & mask;
652             pmac->u[5] |= key->md.h[5] & mask;
653             pmac->u[6] |= key->md.h[6] & mask;
654             pmac->u[7] |= key->md.h[7] & mask;
655
656 #  ifdef BSWAP4
657             pmac->u[0] = BSWAP4(pmac->u[0]);
658             pmac->u[1] = BSWAP4(pmac->u[1]);
659             pmac->u[2] = BSWAP4(pmac->u[2]);
660             pmac->u[3] = BSWAP4(pmac->u[3]);
661             pmac->u[4] = BSWAP4(pmac->u[4]);
662             pmac->u[5] = BSWAP4(pmac->u[5]);
663             pmac->u[6] = BSWAP4(pmac->u[6]);
664             pmac->u[7] = BSWAP4(pmac->u[7]);
665 #  else
666             for (i = 0; i < 8; i++) {
667                 res = pmac->u[i];
668                 pmac->c[4 * i + 0] = (unsigned char)(res >> 24);
669                 pmac->c[4 * i + 1] = (unsigned char)(res >> 16);
670                 pmac->c[4 * i + 2] = (unsigned char)(res >> 8);
671                 pmac->c[4 * i + 3] = (unsigned char)res;
672             }
673 #  endif
674             len += SHA256_DIGEST_LENGTH;
675 # else
676             SHA256_Update(&key->md, out, inp_len);
677             res = key->md.num;
678             SHA256_Final(pmac->c, &key->md);
679
680             {
681                 unsigned int inp_blocks, pad_blocks;
682
683                 /* but pretend as if we hashed padded payload */
684                 inp_blocks =
685                     1 + ((SHA256_CBLOCK - 9 - res) >> (sizeof(res) * 8 - 1));
686                 res += (unsigned int)(len - inp_len);
687                 pad_blocks = res / SHA256_CBLOCK;
688                 res %= SHA256_CBLOCK;
689                 pad_blocks +=
690                     1 + ((SHA256_CBLOCK - 9 - res) >> (sizeof(res) * 8 - 1));
691                 for (; inp_blocks < pad_blocks; inp_blocks++)
692                     sha1_block_data_order(&key->md, data, 1);
693             }
694 # endif      /* pre-lucky-13 reference version of above */
695             key->md = key->tail;
696             SHA256_Update(&key->md, pmac->c, SHA256_DIGEST_LENGTH);
697             SHA256_Final(pmac->c, &key->md);
698
699             /* verify HMAC */
700             out += inp_len;
701             len -= inp_len;
702 # if 1      /* see original reference version in #else */
703             {
704                 unsigned char *p =
705                     out + len - 1 - maxpad - SHA256_DIGEST_LENGTH;
706                 size_t off = out - p;
707                 unsigned int c, cmask;
708
709                 maxpad += SHA256_DIGEST_LENGTH;
710                 for (res = 0, i = 0, j = 0; j < maxpad; j++) {
711                     c = p[j];
712                     cmask =
713                         ((int)(j - off - SHA256_DIGEST_LENGTH)) >>
714                         (sizeof(int) * 8 - 1);
715                     res |= (c ^ pad) & ~cmask; /* ... and padding */
716                     cmask &= ((int)(off - 1 - j)) >> (sizeof(int) * 8 - 1);
717                     res |= (c ^ pmac->c[i]) & cmask;
718                     i += 1 & cmask;
719                 }
720                 maxpad -= SHA256_DIGEST_LENGTH;
721
722                 res = 0 - ((0 - res) >> (sizeof(res) * 8 - 1));
723                 ret &= (int)~res;
724             }
725 # else      /* pre-lucky-13 reference version of above */
726             for (res = 0, i = 0; i < SHA256_DIGEST_LENGTH; i++)
727                 res |= out[i] ^ pmac->c[i];
728             res = 0 - ((0 - res) >> (sizeof(res) * 8 - 1));
729             ret &= (int)~res;
730
731             /* verify padding */
732             pad = (pad & ~res) | (maxpad & res);
733             out = out + len - 1 - pad;
734             for (res = 0, i = 0; i < pad; i++)
735                 res |= out[i] ^ pad;
736
737             res = (0 - res) >> (sizeof(res) * 8 - 1);
738             ret &= (int)~res;
739 # endif
740             return ret;
741         } else {
742             SHA256_Update(&key->md, out, len);
743         }
744     }
745
746     return 1;
747 }
748
749 static int aesni_cbc_hmac_sha256_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg,
750                                       void *ptr)
751 {
752     EVP_AES_HMAC_SHA256 *key = data(ctx);
753     unsigned int u_arg = (unsigned int)arg;
754
755     switch (type) {
756     case EVP_CTRL_AEAD_SET_MAC_KEY:
757         {
758             unsigned int i;
759             unsigned char hmac_key[64];
760
761             memset(hmac_key, 0, sizeof(hmac_key));
762
763             if (arg < 0)
764                 return -1;
765
766             if (u_arg > sizeof(hmac_key)) {
767                 SHA256_Init(&key->head);
768                 SHA256_Update(&key->head, ptr, arg);
769                 SHA256_Final(hmac_key, &key->head);
770             } else {
771                 memcpy(hmac_key, ptr, arg);
772             }
773
774             for (i = 0; i < sizeof(hmac_key); i++)
775                 hmac_key[i] ^= 0x36; /* ipad */
776             SHA256_Init(&key->head);
777             SHA256_Update(&key->head, hmac_key, sizeof(hmac_key));
778
779             for (i = 0; i < sizeof(hmac_key); i++)
780                 hmac_key[i] ^= 0x36 ^ 0x5c; /* opad */
781             SHA256_Init(&key->tail);
782             SHA256_Update(&key->tail, hmac_key, sizeof(hmac_key));
783
784             OPENSSL_cleanse(hmac_key, sizeof(hmac_key));
785
786             return 1;
787         }
788     case EVP_CTRL_AEAD_TLS1_AAD:
789         {
790             unsigned char *p = ptr;
791             unsigned int len;
792
793             if (arg != EVP_AEAD_TLS1_AAD_LEN)
794                 return -1;
795
796             len = p[arg - 2] << 8 | p[arg - 1];
797
798             if (EVP_CIPHER_CTX_encrypting(ctx)) {
799                 key->payload_length = len;
800                 if ((key->aux.tls_ver =
801                      p[arg - 4] << 8 | p[arg - 3]) >= TLS1_1_VERSION) {
802                     if (len < AES_BLOCK_SIZE)
803                         return 0;
804                     len -= AES_BLOCK_SIZE;
805                     p[arg - 2] = len >> 8;
806                     p[arg - 1] = len;
807                 }
808                 key->md = key->head;
809                 SHA256_Update(&key->md, p, arg);
810
811                 return (int)(((len + SHA256_DIGEST_LENGTH +
812                                AES_BLOCK_SIZE) & -AES_BLOCK_SIZE)
813                              - len);
814             } else {
815                 memcpy(key->aux.tls_aad, ptr, arg);
816                 key->payload_length = arg;
817
818                 return SHA256_DIGEST_LENGTH;
819             }
820         }
821 # if !defined(OPENSSL_NO_MULTIBLOCK)
822     case EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZE:
823         return (int)(5 + 16 + ((arg + 32 + 16) & -16));
824     case EVP_CTRL_TLS1_1_MULTIBLOCK_AAD:
825         {
826             EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM *param =
827                 (EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM *) ptr;
828             unsigned int n4x = 1, x4;
829             unsigned int frag, last, packlen, inp_len;
830
831             if (arg < 0)
832                 return -1;
833
834             if (u_arg < sizeof(EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM))
835                 return -1;
836
837             inp_len = param->inp[11] << 8 | param->inp[12];
838
839             if (EVP_CIPHER_CTX_encrypting(ctx)) {
840                 if ((param->inp[9] << 8 | param->inp[10]) < TLS1_1_VERSION)
841                     return -1;
842
843                 if (inp_len) {
844                     if (inp_len < 4096)
845                         return 0; /* too short */
846
847                     if (inp_len >= 8192 && OPENSSL_ia32cap_P[2] & (1 << 5))
848                         n4x = 2; /* AVX2 */
849                 } else if ((n4x = param->interleave / 4) && n4x <= 2)
850                     inp_len = param->len;
851                 else
852                     return -1;
853
854                 key->md = key->head;
855                 SHA256_Update(&key->md, param->inp, 13);
856
857                 x4 = 4 * n4x;
858                 n4x += 1;
859
860                 frag = inp_len >> n4x;
861                 last = inp_len + frag - (frag << n4x);
862                 if (last > frag && ((last + 13 + 9) % 64 < (x4 - 1))) {
863                     frag++;
864                     last -= x4 - 1;
865                 }
866
867                 packlen = 5 + 16 + ((frag + 32 + 16) & -16);
868                 packlen = (packlen << n4x) - packlen;
869                 packlen += 5 + 16 + ((last + 32 + 16) & -16);
870
871                 param->interleave = x4;
872
873                 return (int)packlen;
874             } else
875                 return -1;      /* not yet */
876         }
877     case EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT:
878         {
879             EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM *param =
880                 (EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM *) ptr;
881
882             return (int)tls1_1_multi_block_encrypt(key, param->out,
883                                                    param->inp, param->len,
884                                                    param->interleave / 4);
885         }
886     case EVP_CTRL_TLS1_1_MULTIBLOCK_DECRYPT:
887 # endif
888     default:
889         return -1;
890     }
891 }
892
893 static EVP_CIPHER aesni_128_cbc_hmac_sha256_cipher = {
894 # ifdef NID_aes_128_cbc_hmac_sha256
895     NID_aes_128_cbc_hmac_sha256,
896 # else
897     NID_undef,
898 # endif
899     AES_BLOCK_SIZE, 16, AES_BLOCK_SIZE,
900     EVP_CIPH_CBC_MODE | EVP_CIPH_FLAG_DEFAULT_ASN1 |
901         EVP_CIPH_FLAG_AEAD_CIPHER | EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK,
902     aesni_cbc_hmac_sha256_init_key,
903     aesni_cbc_hmac_sha256_cipher,
904     NULL,
905     sizeof(EVP_AES_HMAC_SHA256),
906     EVP_CIPH_FLAG_DEFAULT_ASN1 ? NULL : EVP_CIPHER_set_asn1_iv,
907     EVP_CIPH_FLAG_DEFAULT_ASN1 ? NULL : EVP_CIPHER_get_asn1_iv,
908     aesni_cbc_hmac_sha256_ctrl,
909     NULL
910 };
911
912 static EVP_CIPHER aesni_256_cbc_hmac_sha256_cipher = {
913 # ifdef NID_aes_256_cbc_hmac_sha256
914     NID_aes_256_cbc_hmac_sha256,
915 # else
916     NID_undef,
917 # endif
918     AES_BLOCK_SIZE, 32, AES_BLOCK_SIZE,
919     EVP_CIPH_CBC_MODE | EVP_CIPH_FLAG_DEFAULT_ASN1 |
920         EVP_CIPH_FLAG_AEAD_CIPHER | EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK,
921     aesni_cbc_hmac_sha256_init_key,
922     aesni_cbc_hmac_sha256_cipher,
923     NULL,
924     sizeof(EVP_AES_HMAC_SHA256),
925     EVP_CIPH_FLAG_DEFAULT_ASN1 ? NULL : EVP_CIPHER_set_asn1_iv,
926     EVP_CIPH_FLAG_DEFAULT_ASN1 ? NULL : EVP_CIPHER_get_asn1_iv,
927     aesni_cbc_hmac_sha256_ctrl,
928     NULL
929 };
930
931 const EVP_CIPHER *EVP_aes_128_cbc_hmac_sha256(void)
932 {
933     return ((OPENSSL_ia32cap_P[1] & AESNI_CAPABLE) &&
934             aesni_cbc_sha256_enc(NULL, NULL, 0, NULL, NULL, NULL, NULL) ?
935             &aesni_128_cbc_hmac_sha256_cipher : NULL);
936 }
937
938 const EVP_CIPHER *EVP_aes_256_cbc_hmac_sha256(void)
939 {
940     return ((OPENSSL_ia32cap_P[1] & AESNI_CAPABLE) &&
941             aesni_cbc_sha256_enc(NULL, NULL, 0, NULL, NULL, NULL, NULL) ?
942             &aesni_256_cbc_hmac_sha256_cipher : NULL);
943 }
944 #else
945 const EVP_CIPHER *EVP_aes_128_cbc_hmac_sha256(void)
946 {
947     return NULL;
948 }
949
950 const EVP_CIPHER *EVP_aes_256_cbc_hmac_sha256(void)
951 {
952     return NULL;
953 }
954 #endif