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