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