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