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