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