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