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