Dead code: if 0 removal from crypto/evp and an unused file.
[openssl.git] / crypto / evp / e_aes.c
1 /* ====================================================================
2  * Copyright (c) 2001-2014 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  *    openssl-core@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
51 #include <openssl/opensslconf.h>
52 #ifndef OPENSSL_NO_AES
53 # include <openssl/evp.h>
54 # include <openssl/err.h>
55 # include <string.h>
56 # include <assert.h>
57 # include <openssl/aes.h>
58 # include "evp_locl.h"
59 # include "modes_lcl.h"
60 # include <openssl/rand.h>
61
62 typedef struct {
63     union {
64         double align;
65         AES_KEY ks;
66     } ks;
67     block128_f block;
68     union {
69         cbc128_f cbc;
70         ctr128_f ctr;
71     } stream;
72 } EVP_AES_KEY;
73
74 typedef struct {
75     union {
76         double align;
77         AES_KEY ks;
78     } ks;                       /* AES key schedule to use */
79     int key_set;                /* Set if key initialised */
80     int iv_set;                 /* Set if an iv is set */
81     GCM128_CONTEXT gcm;
82     unsigned char *iv;          /* Temporary IV store */
83     int ivlen;                  /* IV length */
84     int taglen;
85     int iv_gen;                 /* It is OK to generate IVs */
86     int tls_aad_len;            /* TLS AAD length */
87     ctr128_f ctr;
88 } EVP_AES_GCM_CTX;
89
90 typedef struct {
91     union {
92         double align;
93         AES_KEY ks;
94     } ks1, ks2;                 /* AES key schedules to use */
95     XTS128_CONTEXT xts;
96     void (*stream) (const unsigned char *in,
97                     unsigned char *out, size_t length,
98                     const AES_KEY *key1, const AES_KEY *key2,
99                     const unsigned char iv[16]);
100 } EVP_AES_XTS_CTX;
101
102 typedef struct {
103     union {
104         double align;
105         AES_KEY ks;
106     } ks;                       /* AES key schedule to use */
107     int key_set;                /* Set if key initialised */
108     int iv_set;                 /* Set if an iv is set */
109     int tag_set;                /* Set if tag is valid */
110     int len_set;                /* Set if message length set */
111     int L, M;                   /* L and M parameters from RFC3610 */
112     CCM128_CONTEXT ccm;
113     ccm128_f str;
114 } EVP_AES_CCM_CTX;
115
116 # ifndef OPENSSL_NO_OCB
117 typedef struct {
118     AES_KEY ksenc;              /* AES key schedule to use for encryption */
119     AES_KEY ksdec;              /* AES key schedule to use for decryption */
120     int key_set;                /* Set if key initialised */
121     int iv_set;                 /* Set if an iv is set */
122     OCB128_CONTEXT ocb;
123     unsigned char *iv;          /* Temporary IV store */
124     unsigned char tag[16];
125     unsigned char data_buf[16]; /* Store partial data blocks */
126     unsigned char aad_buf[16];  /* Store partial AAD blocks */
127     int data_buf_len;
128     int aad_buf_len;
129     int ivlen;                  /* IV length */
130     int taglen;
131 } EVP_AES_OCB_CTX;
132 # endif
133
134 # define MAXBITCHUNK     ((size_t)1<<(sizeof(size_t)*8-4))
135
136 # ifdef VPAES_ASM
137 int vpaes_set_encrypt_key(const unsigned char *userKey, int bits,
138                           AES_KEY *key);
139 int vpaes_set_decrypt_key(const unsigned char *userKey, int bits,
140                           AES_KEY *key);
141
142 void vpaes_encrypt(const unsigned char *in, unsigned char *out,
143                    const AES_KEY *key);
144 void vpaes_decrypt(const unsigned char *in, unsigned char *out,
145                    const AES_KEY *key);
146
147 void vpaes_cbc_encrypt(const unsigned char *in,
148                        unsigned char *out,
149                        size_t length,
150                        const AES_KEY *key, unsigned char *ivec, int enc);
151 # endif
152 # ifdef BSAES_ASM
153 void bsaes_cbc_encrypt(const unsigned char *in, unsigned char *out,
154                        size_t length, const AES_KEY *key,
155                        unsigned char ivec[16], int enc);
156 void bsaes_ctr32_encrypt_blocks(const unsigned char *in, unsigned char *out,
157                                 size_t len, const AES_KEY *key,
158                                 const unsigned char ivec[16]);
159 void bsaes_xts_encrypt(const unsigned char *inp, unsigned char *out,
160                        size_t len, const AES_KEY *key1,
161                        const AES_KEY *key2, const unsigned char iv[16]);
162 void bsaes_xts_decrypt(const unsigned char *inp, unsigned char *out,
163                        size_t len, const AES_KEY *key1,
164                        const AES_KEY *key2, const unsigned char iv[16]);
165 # endif
166 # ifdef AES_CTR_ASM
167 void AES_ctr32_encrypt(const unsigned char *in, unsigned char *out,
168                        size_t blocks, const AES_KEY *key,
169                        const unsigned char ivec[AES_BLOCK_SIZE]);
170 # endif
171 # ifdef AES_XTS_ASM
172 void AES_xts_encrypt(const char *inp, char *out, size_t len,
173                      const AES_KEY *key1, const AES_KEY *key2,
174                      const unsigned char iv[16]);
175 void AES_xts_decrypt(const char *inp, char *out, size_t len,
176                      const AES_KEY *key1, const AES_KEY *key2,
177                      const unsigned char iv[16]);
178 # endif
179
180 # if     defined(OPENSSL_CPUID_OBJ) && (defined(__powerpc__) || defined(__ppc__) || defined(_ARCH_PPC))
181 #  include "ppc_arch.h"
182 #  ifdef VPAES_ASM
183 #   define VPAES_CAPABLE (OPENSSL_ppccap_P & PPC_ALTIVEC)
184 #  endif
185 #  define HWAES_CAPABLE  (OPENSSL_ppccap_P & PPC_CRYPTO207)
186 #  define HWAES_set_encrypt_key aes_p8_set_encrypt_key
187 #  define HWAES_set_decrypt_key aes_p8_set_decrypt_key
188 #  define HWAES_encrypt aes_p8_encrypt
189 #  define HWAES_decrypt aes_p8_decrypt
190 #  define HWAES_cbc_encrypt aes_p8_cbc_encrypt
191 #  define HWAES_ctr32_encrypt_blocks aes_p8_ctr32_encrypt_blocks
192 # endif
193
194 # if     defined(AES_ASM) && !defined(I386_ONLY) &&      (  \
195         ((defined(__i386)       || defined(__i386__)    || \
196           defined(_M_IX86)) && defined(OPENSSL_IA32_SSE2))|| \
197         defined(__x86_64)       || defined(__x86_64__)  || \
198         defined(_M_AMD64)       || defined(_M_X64)      || \
199         defined(__INTEL__)                              )
200
201 extern unsigned int OPENSSL_ia32cap_P[];
202
203 #  ifdef VPAES_ASM
204 #   define VPAES_CAPABLE   (OPENSSL_ia32cap_P[1]&(1<<(41-32)))
205 #  endif
206 #  ifdef BSAES_ASM
207 #   define BSAES_CAPABLE   (OPENSSL_ia32cap_P[1]&(1<<(41-32)))
208 #  endif
209 /*
210  * AES-NI section
211  */
212 #  define AESNI_CAPABLE   (OPENSSL_ia32cap_P[1]&(1<<(57-32)))
213
214 int aesni_set_encrypt_key(const unsigned char *userKey, int bits,
215                           AES_KEY *key);
216 int aesni_set_decrypt_key(const unsigned char *userKey, int bits,
217                           AES_KEY *key);
218
219 void aesni_encrypt(const unsigned char *in, unsigned char *out,
220                    const AES_KEY *key);
221 void aesni_decrypt(const unsigned char *in, unsigned char *out,
222                    const AES_KEY *key);
223
224 void aesni_ecb_encrypt(const unsigned char *in,
225                        unsigned char *out,
226                        size_t length, const AES_KEY *key, int enc);
227 void aesni_cbc_encrypt(const unsigned char *in,
228                        unsigned char *out,
229                        size_t length,
230                        const AES_KEY *key, unsigned char *ivec, int enc);
231
232 void aesni_ctr32_encrypt_blocks(const unsigned char *in,
233                                 unsigned char *out,
234                                 size_t blocks,
235                                 const void *key, const unsigned char *ivec);
236
237 void aesni_xts_encrypt(const unsigned char *in,
238                        unsigned char *out,
239                        size_t length,
240                        const AES_KEY *key1, const AES_KEY *key2,
241                        const unsigned char iv[16]);
242
243 void aesni_xts_decrypt(const unsigned char *in,
244                        unsigned char *out,
245                        size_t length,
246                        const AES_KEY *key1, const AES_KEY *key2,
247                        const unsigned char iv[16]);
248
249 void aesni_ccm64_encrypt_blocks(const unsigned char *in,
250                                 unsigned char *out,
251                                 size_t blocks,
252                                 const void *key,
253                                 const unsigned char ivec[16],
254                                 unsigned char cmac[16]);
255
256 void aesni_ccm64_decrypt_blocks(const unsigned char *in,
257                                 unsigned char *out,
258                                 size_t blocks,
259                                 const void *key,
260                                 const unsigned char ivec[16],
261                                 unsigned char cmac[16]);
262
263 #  if defined(__x86_64) || defined(__x86_64__) || defined(_M_AMD64) || defined(_M_X64)
264 size_t aesni_gcm_encrypt(const unsigned char *in,
265                          unsigned char *out,
266                          size_t len,
267                          const void *key, unsigned char ivec[16], u64 *Xi);
268 #   define AES_gcm_encrypt aesni_gcm_encrypt
269 size_t aesni_gcm_decrypt(const unsigned char *in,
270                          unsigned char *out,
271                          size_t len,
272                          const void *key, unsigned char ivec[16], u64 *Xi);
273 #   define AES_gcm_decrypt aesni_gcm_decrypt
274 void gcm_ghash_avx(u64 Xi[2], const u128 Htable[16], const u8 *in,
275                    size_t len);
276 #   define AES_GCM_ASM(gctx)       (gctx->ctr==aesni_ctr32_encrypt_blocks && \
277                                  gctx->gcm.ghash==gcm_ghash_avx)
278 #   define AES_GCM_ASM2(gctx)      (gctx->gcm.block==(block128_f)aesni_encrypt && \
279                                  gctx->gcm.ghash==gcm_ghash_avx)
280 #   undef AES_GCM_ASM2          /* minor size optimization */
281 #  endif
282
283 static int aesni_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
284                           const unsigned char *iv, int enc)
285 {
286     int ret, mode;
287     EVP_AES_KEY *dat = (EVP_AES_KEY *) ctx->cipher_data;
288
289     mode = ctx->cipher->flags & EVP_CIPH_MODE;
290     if ((mode == EVP_CIPH_ECB_MODE || mode == EVP_CIPH_CBC_MODE)
291         && !enc) {
292         ret = aesni_set_decrypt_key(key, ctx->key_len * 8, ctx->cipher_data);
293         dat->block = (block128_f) aesni_decrypt;
294         dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ?
295             (cbc128_f) aesni_cbc_encrypt : NULL;
296     } else {
297         ret = aesni_set_encrypt_key(key, ctx->key_len * 8, ctx->cipher_data);
298         dat->block = (block128_f) aesni_encrypt;
299         if (mode == EVP_CIPH_CBC_MODE)
300             dat->stream.cbc = (cbc128_f) aesni_cbc_encrypt;
301         else if (mode == EVP_CIPH_CTR_MODE)
302             dat->stream.ctr = (ctr128_f) aesni_ctr32_encrypt_blocks;
303         else
304             dat->stream.cbc = NULL;
305     }
306
307     if (ret < 0) {
308         EVPerr(EVP_F_AESNI_INIT_KEY, EVP_R_AES_KEY_SETUP_FAILED);
309         return 0;
310     }
311
312     return 1;
313 }
314
315 static int aesni_cbc_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
316                             const unsigned char *in, size_t len)
317 {
318     aesni_cbc_encrypt(in, out, len, ctx->cipher_data, ctx->iv, ctx->encrypt);
319
320     return 1;
321 }
322
323 static int aesni_ecb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
324                             const unsigned char *in, size_t len)
325 {
326     size_t bl = ctx->cipher->block_size;
327
328     if (len < bl)
329         return 1;
330
331     aesni_ecb_encrypt(in, out, len, ctx->cipher_data, ctx->encrypt);
332
333     return 1;
334 }
335
336 #  define aesni_ofb_cipher aes_ofb_cipher
337 static int aesni_ofb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
338                             const unsigned char *in, size_t len);
339
340 #  define aesni_cfb_cipher aes_cfb_cipher
341 static int aesni_cfb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
342                             const unsigned char *in, size_t len);
343
344 #  define aesni_cfb8_cipher aes_cfb8_cipher
345 static int aesni_cfb8_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
346                              const unsigned char *in, size_t len);
347
348 #  define aesni_cfb1_cipher aes_cfb1_cipher
349 static int aesni_cfb1_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
350                              const unsigned char *in, size_t len);
351
352 #  define aesni_ctr_cipher aes_ctr_cipher
353 static int aesni_ctr_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
354                             const unsigned char *in, size_t len);
355
356 static int aesni_gcm_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
357                               const unsigned char *iv, int enc)
358 {
359     EVP_AES_GCM_CTX *gctx = ctx->cipher_data;
360     if (!iv && !key)
361         return 1;
362     if (key) {
363         aesni_set_encrypt_key(key, ctx->key_len * 8, &gctx->ks.ks);
364         CRYPTO_gcm128_init(&gctx->gcm, &gctx->ks, (block128_f) aesni_encrypt);
365         gctx->ctr = (ctr128_f) aesni_ctr32_encrypt_blocks;
366         /*
367          * If we have an iv can set it directly, otherwise use saved IV.
368          */
369         if (iv == NULL && gctx->iv_set)
370             iv = gctx->iv;
371         if (iv) {
372             CRYPTO_gcm128_setiv(&gctx->gcm, iv, gctx->ivlen);
373             gctx->iv_set = 1;
374         }
375         gctx->key_set = 1;
376     } else {
377         /* If key set use IV, otherwise copy */
378         if (gctx->key_set)
379             CRYPTO_gcm128_setiv(&gctx->gcm, iv, gctx->ivlen);
380         else
381             memcpy(gctx->iv, iv, gctx->ivlen);
382         gctx->iv_set = 1;
383         gctx->iv_gen = 0;
384     }
385     return 1;
386 }
387
388 #  define aesni_gcm_cipher aes_gcm_cipher
389 static int aesni_gcm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
390                             const unsigned char *in, size_t len);
391
392 static int aesni_xts_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
393                               const unsigned char *iv, int enc)
394 {
395     EVP_AES_XTS_CTX *xctx = ctx->cipher_data;
396     if (!iv && !key)
397         return 1;
398
399     if (key) {
400         /* key_len is two AES keys */
401         if (enc) {
402             aesni_set_encrypt_key(key, ctx->key_len * 4, &xctx->ks1.ks);
403             xctx->xts.block1 = (block128_f) aesni_encrypt;
404             xctx->stream = aesni_xts_encrypt;
405         } else {
406             aesni_set_decrypt_key(key, ctx->key_len * 4, &xctx->ks1.ks);
407             xctx->xts.block1 = (block128_f) aesni_decrypt;
408             xctx->stream = aesni_xts_decrypt;
409         }
410
411         aesni_set_encrypt_key(key + ctx->key_len / 2,
412                               ctx->key_len * 4, &xctx->ks2.ks);
413         xctx->xts.block2 = (block128_f) aesni_encrypt;
414
415         xctx->xts.key1 = &xctx->ks1;
416     }
417
418     if (iv) {
419         xctx->xts.key2 = &xctx->ks2;
420         memcpy(ctx->iv, iv, 16);
421     }
422
423     return 1;
424 }
425
426 #  define aesni_xts_cipher aes_xts_cipher
427 static int aesni_xts_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
428                             const unsigned char *in, size_t len);
429
430 static int aesni_ccm_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
431                               const unsigned char *iv, int enc)
432 {
433     EVP_AES_CCM_CTX *cctx = ctx->cipher_data;
434     if (!iv && !key)
435         return 1;
436     if (key) {
437         aesni_set_encrypt_key(key, ctx->key_len * 8, &cctx->ks.ks);
438         CRYPTO_ccm128_init(&cctx->ccm, cctx->M, cctx->L,
439                            &cctx->ks, (block128_f) aesni_encrypt);
440         cctx->str = enc ? (ccm128_f) aesni_ccm64_encrypt_blocks :
441             (ccm128_f) aesni_ccm64_decrypt_blocks;
442         cctx->key_set = 1;
443     }
444     if (iv) {
445         memcpy(ctx->iv, iv, 15 - cctx->L);
446         cctx->iv_set = 1;
447     }
448     return 1;
449 }
450
451 #  define aesni_ccm_cipher aes_ccm_cipher
452 static int aesni_ccm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
453                             const unsigned char *in, size_t len);
454
455 #  ifndef OPENSSL_NO_OCB
456 static int aesni_ocb_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
457                               const unsigned char *iv, int enc)
458 {
459     EVP_AES_OCB_CTX *octx = ctx->cipher_data;
460     if (!iv && !key)
461         return 1;
462     if (key) {
463         do {
464             /*
465              * We set both the encrypt and decrypt key here because decrypt
466              * needs both. We could possibly optimise to remove setting the
467              * decrypt for an encryption operation.
468              */
469             aesni_set_encrypt_key(key, ctx->key_len * 8, &octx->ksenc);
470             aesni_set_decrypt_key(key, ctx->key_len * 8, &octx->ksdec);
471             if (!CRYPTO_ocb128_init(&octx->ocb, &octx->ksenc, &octx->ksdec,
472                                     (block128_f) aesni_encrypt,
473                                     (block128_f) aesni_decrypt))
474                 return 0;
475         }
476         while (0);
477
478         /*
479          * If we have an iv we can set it directly, otherwise use saved IV.
480          */
481         if (iv == NULL && octx->iv_set)
482             iv = octx->iv;
483         if (iv) {
484             if (CRYPTO_ocb128_setiv(&octx->ocb, iv, octx->ivlen, octx->taglen)
485                 != 1)
486                 return 0;
487             octx->iv_set = 1;
488         }
489         octx->key_set = 1;
490     } else {
491         /* If key set use IV, otherwise copy */
492         if (octx->key_set)
493             CRYPTO_ocb128_setiv(&octx->ocb, iv, octx->ivlen, octx->taglen);
494         else
495             memcpy(octx->iv, iv, octx->ivlen);
496         octx->iv_set = 1;
497     }
498     return 1;
499 }
500
501 #   define aesni_ocb_cipher aes_ocb_cipher
502 static int aesni_ocb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
503                             const unsigned char *in, size_t len);
504 #  endif                        /* OPENSSL_NO_OCB */
505
506 #  define BLOCK_CIPHER_generic(nid,keylen,blocksize,ivlen,nmode,mode,MODE,flags) \
507 static const EVP_CIPHER aesni_##keylen##_##mode = { \
508         nid##_##keylen##_##nmode,blocksize,keylen/8,ivlen, \
509         flags|EVP_CIPH_##MODE##_MODE,   \
510         aesni_init_key,                 \
511         aesni_##mode##_cipher,          \
512         NULL,                           \
513         sizeof(EVP_AES_KEY),            \
514         NULL,NULL,NULL,NULL }; \
515 static const EVP_CIPHER aes_##keylen##_##mode = { \
516         nid##_##keylen##_##nmode,blocksize,     \
517         keylen/8,ivlen, \
518         flags|EVP_CIPH_##MODE##_MODE,   \
519         aes_init_key,                   \
520         aes_##mode##_cipher,            \
521         NULL,                           \
522         sizeof(EVP_AES_KEY),            \
523         NULL,NULL,NULL,NULL }; \
524 const EVP_CIPHER *EVP_aes_##keylen##_##mode(void) \
525 { return AESNI_CAPABLE?&aesni_##keylen##_##mode:&aes_##keylen##_##mode; }
526
527 #  define BLOCK_CIPHER_custom(nid,keylen,blocksize,ivlen,mode,MODE,flags) \
528 static const EVP_CIPHER aesni_##keylen##_##mode = { \
529         nid##_##keylen##_##mode,blocksize, \
530         (EVP_CIPH_##MODE##_MODE==EVP_CIPH_XTS_MODE?2:1)*keylen/8, ivlen, \
531         flags|EVP_CIPH_##MODE##_MODE,   \
532         aesni_##mode##_init_key,        \
533         aesni_##mode##_cipher,          \
534         aes_##mode##_cleanup,           \
535         sizeof(EVP_AES_##MODE##_CTX),   \
536         NULL,NULL,aes_##mode##_ctrl,NULL }; \
537 static const EVP_CIPHER aes_##keylen##_##mode = { \
538         nid##_##keylen##_##mode,blocksize, \
539         (EVP_CIPH_##MODE##_MODE==EVP_CIPH_XTS_MODE?2:1)*keylen/8, ivlen, \
540         flags|EVP_CIPH_##MODE##_MODE,   \
541         aes_##mode##_init_key,          \
542         aes_##mode##_cipher,            \
543         aes_##mode##_cleanup,           \
544         sizeof(EVP_AES_##MODE##_CTX),   \
545         NULL,NULL,aes_##mode##_ctrl,NULL }; \
546 const EVP_CIPHER *EVP_aes_##keylen##_##mode(void) \
547 { return AESNI_CAPABLE?&aesni_##keylen##_##mode:&aes_##keylen##_##mode; }
548
549 # elif   defined(AES_ASM) && (defined(__sparc) || defined(__sparc__))
550
551 #  include "sparc_arch.h"
552
553 extern unsigned int OPENSSL_sparcv9cap_P[];
554
555 #  define SPARC_AES_CAPABLE       (OPENSSL_sparcv9cap_P[1] & CFR_AES)
556
557 void aes_t4_set_encrypt_key(const unsigned char *key, int bits, AES_KEY *ks);
558 void aes_t4_set_decrypt_key(const unsigned char *key, int bits, AES_KEY *ks);
559 void aes_t4_encrypt(const unsigned char *in, unsigned char *out,
560                     const AES_KEY *key);
561 void aes_t4_decrypt(const unsigned char *in, unsigned char *out,
562                     const AES_KEY *key);
563 /*
564  * Key-length specific subroutines were chosen for following reason.
565  * Each SPARC T4 core can execute up to 8 threads which share core's
566  * resources. Loading as much key material to registers allows to
567  * minimize references to shared memory interface, as well as amount
568  * of instructions in inner loops [much needed on T4]. But then having
569  * non-key-length specific routines would require conditional branches
570  * either in inner loops or on subroutines' entries. Former is hardly
571  * acceptable, while latter means code size increase to size occupied
572  * by multiple key-length specfic subroutines, so why fight?
573  */
574 void aes128_t4_cbc_encrypt(const unsigned char *in, unsigned char *out,
575                            size_t len, const AES_KEY *key,
576                            unsigned char *ivec);
577 void aes128_t4_cbc_decrypt(const unsigned char *in, unsigned char *out,
578                            size_t len, const AES_KEY *key,
579                            unsigned char *ivec);
580 void aes192_t4_cbc_encrypt(const unsigned char *in, unsigned char *out,
581                            size_t len, const AES_KEY *key,
582                            unsigned char *ivec);
583 void aes192_t4_cbc_decrypt(const unsigned char *in, unsigned char *out,
584                            size_t len, const AES_KEY *key,
585                            unsigned char *ivec);
586 void aes256_t4_cbc_encrypt(const unsigned char *in, unsigned char *out,
587                            size_t len, const AES_KEY *key,
588                            unsigned char *ivec);
589 void aes256_t4_cbc_decrypt(const unsigned char *in, unsigned char *out,
590                            size_t len, const AES_KEY *key,
591                            unsigned char *ivec);
592 void aes128_t4_ctr32_encrypt(const unsigned char *in, unsigned char *out,
593                              size_t blocks, const AES_KEY *key,
594                              unsigned char *ivec);
595 void aes192_t4_ctr32_encrypt(const unsigned char *in, unsigned char *out,
596                              size_t blocks, const AES_KEY *key,
597                              unsigned char *ivec);
598 void aes256_t4_ctr32_encrypt(const unsigned char *in, unsigned char *out,
599                              size_t blocks, const AES_KEY *key,
600                              unsigned char *ivec);
601 void aes128_t4_xts_encrypt(const unsigned char *in, unsigned char *out,
602                            size_t blocks, const AES_KEY *key1,
603                            const AES_KEY *key2, const unsigned char *ivec);
604 void aes128_t4_xts_decrypt(const unsigned char *in, unsigned char *out,
605                            size_t blocks, const AES_KEY *key1,
606                            const AES_KEY *key2, const unsigned char *ivec);
607 void aes256_t4_xts_encrypt(const unsigned char *in, unsigned char *out,
608                            size_t blocks, const AES_KEY *key1,
609                            const AES_KEY *key2, const unsigned char *ivec);
610 void aes256_t4_xts_decrypt(const unsigned char *in, unsigned char *out,
611                            size_t blocks, const AES_KEY *key1,
612                            const AES_KEY *key2, const unsigned char *ivec);
613
614 static int aes_t4_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
615                            const unsigned char *iv, int enc)
616 {
617     int ret, mode, bits;
618     EVP_AES_KEY *dat = (EVP_AES_KEY *) ctx->cipher_data;
619
620     mode = ctx->cipher->flags & EVP_CIPH_MODE;
621     bits = ctx->key_len * 8;
622     if ((mode == EVP_CIPH_ECB_MODE || mode == EVP_CIPH_CBC_MODE)
623         && !enc) {
624         ret = 0;
625         aes_t4_set_decrypt_key(key, bits, ctx->cipher_data);
626         dat->block = (block128_f) aes_t4_decrypt;
627         switch (bits) {
628         case 128:
629             dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ?
630                 (cbc128_f) aes128_t4_cbc_decrypt : NULL;
631             break;
632         case 192:
633             dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ?
634                 (cbc128_f) aes192_t4_cbc_decrypt : NULL;
635             break;
636         case 256:
637             dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ?
638                 (cbc128_f) aes256_t4_cbc_decrypt : NULL;
639             break;
640         default:
641             ret = -1;
642         }
643     } else {
644         ret = 0;
645         aes_t4_set_encrypt_key(key, bits, ctx->cipher_data);
646         dat->block = (block128_f) aes_t4_encrypt;
647         switch (bits) {
648         case 128:
649             if (mode == EVP_CIPH_CBC_MODE)
650                 dat->stream.cbc = (cbc128_f) aes128_t4_cbc_encrypt;
651             else if (mode == EVP_CIPH_CTR_MODE)
652                 dat->stream.ctr = (ctr128_f) aes128_t4_ctr32_encrypt;
653             else
654                 dat->stream.cbc = NULL;
655             break;
656         case 192:
657             if (mode == EVP_CIPH_CBC_MODE)
658                 dat->stream.cbc = (cbc128_f) aes192_t4_cbc_encrypt;
659             else if (mode == EVP_CIPH_CTR_MODE)
660                 dat->stream.ctr = (ctr128_f) aes192_t4_ctr32_encrypt;
661             else
662                 dat->stream.cbc = NULL;
663             break;
664         case 256:
665             if (mode == EVP_CIPH_CBC_MODE)
666                 dat->stream.cbc = (cbc128_f) aes256_t4_cbc_encrypt;
667             else if (mode == EVP_CIPH_CTR_MODE)
668                 dat->stream.ctr = (ctr128_f) aes256_t4_ctr32_encrypt;
669             else
670                 dat->stream.cbc = NULL;
671             break;
672         default:
673             ret = -1;
674         }
675     }
676
677     if (ret < 0) {
678         EVPerr(EVP_F_AES_T4_INIT_KEY, EVP_R_AES_KEY_SETUP_FAILED);
679         return 0;
680     }
681
682     return 1;
683 }
684
685 #  define aes_t4_cbc_cipher aes_cbc_cipher
686 static int aes_t4_cbc_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
687                              const unsigned char *in, size_t len);
688
689 #  define aes_t4_ecb_cipher aes_ecb_cipher
690 static int aes_t4_ecb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
691                              const unsigned char *in, size_t len);
692
693 #  define aes_t4_ofb_cipher aes_ofb_cipher
694 static int aes_t4_ofb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
695                              const unsigned char *in, size_t len);
696
697 #  define aes_t4_cfb_cipher aes_cfb_cipher
698 static int aes_t4_cfb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
699                              const unsigned char *in, size_t len);
700
701 #  define aes_t4_cfb8_cipher aes_cfb8_cipher
702 static int aes_t4_cfb8_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
703                               const unsigned char *in, size_t len);
704
705 #  define aes_t4_cfb1_cipher aes_cfb1_cipher
706 static int aes_t4_cfb1_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
707                               const unsigned char *in, size_t len);
708
709 #  define aes_t4_ctr_cipher aes_ctr_cipher
710 static int aes_t4_ctr_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
711                              const unsigned char *in, size_t len);
712
713 static int aes_t4_gcm_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
714                                const unsigned char *iv, int enc)
715 {
716     EVP_AES_GCM_CTX *gctx = ctx->cipher_data;
717     if (!iv && !key)
718         return 1;
719     if (key) {
720         int bits = ctx->key_len * 8;
721         aes_t4_set_encrypt_key(key, bits, &gctx->ks.ks);
722         CRYPTO_gcm128_init(&gctx->gcm, &gctx->ks,
723                            (block128_f) aes_t4_encrypt);
724         switch (bits) {
725         case 128:
726             gctx->ctr = (ctr128_f) aes128_t4_ctr32_encrypt;
727             break;
728         case 192:
729             gctx->ctr = (ctr128_f) aes192_t4_ctr32_encrypt;
730             break;
731         case 256:
732             gctx->ctr = (ctr128_f) aes256_t4_ctr32_encrypt;
733             break;
734         default:
735             return 0;
736         }
737         /*
738          * If we have an iv can set it directly, otherwise use saved IV.
739          */
740         if (iv == NULL && gctx->iv_set)
741             iv = gctx->iv;
742         if (iv) {
743             CRYPTO_gcm128_setiv(&gctx->gcm, iv, gctx->ivlen);
744             gctx->iv_set = 1;
745         }
746         gctx->key_set = 1;
747     } else {
748         /* If key set use IV, otherwise copy */
749         if (gctx->key_set)
750             CRYPTO_gcm128_setiv(&gctx->gcm, iv, gctx->ivlen);
751         else
752             memcpy(gctx->iv, iv, gctx->ivlen);
753         gctx->iv_set = 1;
754         gctx->iv_gen = 0;
755     }
756     return 1;
757 }
758
759 #  define aes_t4_gcm_cipher aes_gcm_cipher
760 static int aes_t4_gcm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
761                              const unsigned char *in, size_t len);
762
763 static int aes_t4_xts_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
764                                const unsigned char *iv, int enc)
765 {
766     EVP_AES_XTS_CTX *xctx = ctx->cipher_data;
767     if (!iv && !key)
768         return 1;
769
770     if (key) {
771         int bits = ctx->key_len * 4;
772         xctx->stream = NULL;
773         /* key_len is two AES keys */
774         if (enc) {
775             aes_t4_set_encrypt_key(key, bits, &xctx->ks1.ks);
776             xctx->xts.block1 = (block128_f) aes_t4_encrypt;
777             switch (bits) {
778             case 128:
779                 xctx->stream = aes128_t4_xts_encrypt;
780                 break;
781             case 256:
782                 xctx->stream = aes256_t4_xts_encrypt;
783                 break;
784             default:
785                 return 0;
786             }
787         } else {
788             aes_t4_set_decrypt_key(key, ctx->key_len * 4, &xctx->ks1.ks);
789             xctx->xts.block1 = (block128_f) aes_t4_decrypt;
790             switch (bits) {
791             case 128:
792                 xctx->stream = aes128_t4_xts_decrypt;
793                 break;
794             case 256:
795                 xctx->stream = aes256_t4_xts_decrypt;
796                 break;
797             default:
798                 return 0;
799             }
800         }
801
802         aes_t4_set_encrypt_key(key + ctx->key_len / 2,
803                                ctx->key_len * 4, &xctx->ks2.ks);
804         xctx->xts.block2 = (block128_f) aes_t4_encrypt;
805
806         xctx->xts.key1 = &xctx->ks1;
807     }
808
809     if (iv) {
810         xctx->xts.key2 = &xctx->ks2;
811         memcpy(ctx->iv, iv, 16);
812     }
813
814     return 1;
815 }
816
817 #  define aes_t4_xts_cipher aes_xts_cipher
818 static int aes_t4_xts_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
819                              const unsigned char *in, size_t len);
820
821 static int aes_t4_ccm_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
822                                const unsigned char *iv, int enc)
823 {
824     EVP_AES_CCM_CTX *cctx = ctx->cipher_data;
825     if (!iv && !key)
826         return 1;
827     if (key) {
828         int bits = ctx->key_len * 8;
829         aes_t4_set_encrypt_key(key, bits, &cctx->ks.ks);
830         CRYPTO_ccm128_init(&cctx->ccm, cctx->M, cctx->L,
831                            &cctx->ks, (block128_f) aes_t4_encrypt);
832         cctx->key_set = 1;
833     }
834     if (iv) {
835         memcpy(ctx->iv, iv, 15 - cctx->L);
836         cctx->iv_set = 1;
837     }
838     return 1;
839 }
840
841 #  define aes_t4_ccm_cipher aes_ccm_cipher
842 static int aes_t4_ccm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
843                              const unsigned char *in, size_t len);
844
845 #  ifndef OPENSSL_NO_OCB
846 static int aes_t4_ocb_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
847                                const unsigned char *iv, int enc)
848 {
849     EVP_AES_OCB_CTX *octx = ctx->cipher_data;
850     if (!iv && !key)
851         return 1;
852     if (key) {
853         do {
854             /*
855              * We set both the encrypt and decrypt key here because decrypt
856              * needs both. We could possibly optimise to remove setting the
857              * decrypt for an encryption operation.
858              */
859             aes_t4_set_encrypt_key(key, ctx->key_len * 8, &octx->ksenc);
860             aes_t4_set_decrypt_key(key, ctx->key_len * 8, &octx->ksdec);
861             if (!CRYPTO_ocb128_init(&octx->ocb, &octx->ksenc, &octx->ksdec,
862                                     (block128_f) aes_t4_encrypt,
863                                     (block128_f) aes_t4_decrypt))
864                 return 0;
865         }
866         while (0);
867
868         /*
869          * If we have an iv we can set it directly, otherwise use saved IV.
870          */
871         if (iv == NULL && octx->iv_set)
872             iv = octx->iv;
873         if (iv) {
874             if (CRYPTO_ocb128_setiv(&octx->ocb, iv, octx->ivlen, octx->taglen)
875                 != 1)
876                 return 0;
877             octx->iv_set = 1;
878         }
879         octx->key_set = 1;
880     } else {
881         /* If key set use IV, otherwise copy */
882         if (octx->key_set)
883             CRYPTO_ocb128_setiv(&octx->ocb, iv, octx->ivlen, octx->taglen);
884         else
885             memcpy(octx->iv, iv, octx->ivlen);
886         octx->iv_set = 1;
887     }
888     return 1;
889 }
890
891 #   define aes_t4_ocb_cipher aes_ocb_cipher
892 static int aes_t4_ocb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
893                              const unsigned char *in, size_t len);
894 #  endif                        /* OPENSSL_NO_OCB */
895
896 #  define BLOCK_CIPHER_generic(nid,keylen,blocksize,ivlen,nmode,mode,MODE,flags) \
897 static const EVP_CIPHER aes_t4_##keylen##_##mode = { \
898         nid##_##keylen##_##nmode,blocksize,keylen/8,ivlen, \
899         flags|EVP_CIPH_##MODE##_MODE,   \
900         aes_t4_init_key,                \
901         aes_t4_##mode##_cipher,         \
902         NULL,                           \
903         sizeof(EVP_AES_KEY),            \
904         NULL,NULL,NULL,NULL }; \
905 static const EVP_CIPHER aes_##keylen##_##mode = { \
906         nid##_##keylen##_##nmode,blocksize,     \
907         keylen/8,ivlen, \
908         flags|EVP_CIPH_##MODE##_MODE,   \
909         aes_init_key,                   \
910         aes_##mode##_cipher,            \
911         NULL,                           \
912         sizeof(EVP_AES_KEY),            \
913         NULL,NULL,NULL,NULL }; \
914 const EVP_CIPHER *EVP_aes_##keylen##_##mode(void) \
915 { return SPARC_AES_CAPABLE?&aes_t4_##keylen##_##mode:&aes_##keylen##_##mode; }
916
917 #  define BLOCK_CIPHER_custom(nid,keylen,blocksize,ivlen,mode,MODE,flags) \
918 static const EVP_CIPHER aes_t4_##keylen##_##mode = { \
919         nid##_##keylen##_##mode,blocksize, \
920         (EVP_CIPH_##MODE##_MODE==EVP_CIPH_XTS_MODE?2:1)*keylen/8, ivlen, \
921         flags|EVP_CIPH_##MODE##_MODE,   \
922         aes_t4_##mode##_init_key,       \
923         aes_t4_##mode##_cipher,         \
924         aes_##mode##_cleanup,           \
925         sizeof(EVP_AES_##MODE##_CTX),   \
926         NULL,NULL,aes_##mode##_ctrl,NULL }; \
927 static const EVP_CIPHER aes_##keylen##_##mode = { \
928         nid##_##keylen##_##mode,blocksize, \
929         (EVP_CIPH_##MODE##_MODE==EVP_CIPH_XTS_MODE?2:1)*keylen/8, ivlen, \
930         flags|EVP_CIPH_##MODE##_MODE,   \
931         aes_##mode##_init_key,          \
932         aes_##mode##_cipher,            \
933         aes_##mode##_cleanup,           \
934         sizeof(EVP_AES_##MODE##_CTX),   \
935         NULL,NULL,aes_##mode##_ctrl,NULL }; \
936 const EVP_CIPHER *EVP_aes_##keylen##_##mode(void) \
937 { return SPARC_AES_CAPABLE?&aes_t4_##keylen##_##mode:&aes_##keylen##_##mode; }
938
939 # else
940
941 #  define BLOCK_CIPHER_generic(nid,keylen,blocksize,ivlen,nmode,mode,MODE,flags) \
942 static const EVP_CIPHER aes_##keylen##_##mode = { \
943         nid##_##keylen##_##nmode,blocksize,keylen/8,ivlen, \
944         flags|EVP_CIPH_##MODE##_MODE,   \
945         aes_init_key,                   \
946         aes_##mode##_cipher,            \
947         NULL,                           \
948         sizeof(EVP_AES_KEY),            \
949         NULL,NULL,NULL,NULL }; \
950 const EVP_CIPHER *EVP_aes_##keylen##_##mode(void) \
951 { return &aes_##keylen##_##mode; }
952
953 #  define BLOCK_CIPHER_custom(nid,keylen,blocksize,ivlen,mode,MODE,flags) \
954 static const EVP_CIPHER aes_##keylen##_##mode = { \
955         nid##_##keylen##_##mode,blocksize, \
956         (EVP_CIPH_##MODE##_MODE==EVP_CIPH_XTS_MODE?2:1)*keylen/8, ivlen, \
957         flags|EVP_CIPH_##MODE##_MODE,   \
958         aes_##mode##_init_key,          \
959         aes_##mode##_cipher,            \
960         aes_##mode##_cleanup,           \
961         sizeof(EVP_AES_##MODE##_CTX),   \
962         NULL,NULL,aes_##mode##_ctrl,NULL }; \
963 const EVP_CIPHER *EVP_aes_##keylen##_##mode(void) \
964 { return &aes_##keylen##_##mode; }
965
966 # endif
967
968 # if defined(OPENSSL_CPUID_OBJ) && (defined(__arm__) || defined(__arm) || defined(__aarch64__))
969 #  include "arm_arch.h"
970 #  if __ARM_MAX_ARCH__>=7
971 #   if defined(BSAES_ASM)
972 #    define BSAES_CAPABLE (OPENSSL_armcap_P & ARMV7_NEON)
973 #   endif
974 #   define HWAES_CAPABLE (OPENSSL_armcap_P & ARMV8_AES)
975 #   define HWAES_set_encrypt_key aes_v8_set_encrypt_key
976 #   define HWAES_set_decrypt_key aes_v8_set_decrypt_key
977 #   define HWAES_encrypt aes_v8_encrypt
978 #   define HWAES_decrypt aes_v8_decrypt
979 #   define HWAES_cbc_encrypt aes_v8_cbc_encrypt
980 #   define HWAES_ctr32_encrypt_blocks aes_v8_ctr32_encrypt_blocks
981 #  endif
982 # endif
983
984 # if defined(HWAES_CAPABLE)
985 int HWAES_set_encrypt_key(const unsigned char *userKey, const int bits,
986                           AES_KEY *key);
987 int HWAES_set_decrypt_key(const unsigned char *userKey, const int bits,
988                           AES_KEY *key);
989 void HWAES_encrypt(const unsigned char *in, unsigned char *out,
990                    const AES_KEY *key);
991 void HWAES_decrypt(const unsigned char *in, unsigned char *out,
992                    const AES_KEY *key);
993 void HWAES_cbc_encrypt(const unsigned char *in, unsigned char *out,
994                        size_t length, const AES_KEY *key,
995                        unsigned char *ivec, const int enc);
996 void HWAES_ctr32_encrypt_blocks(const unsigned char *in, unsigned char *out,
997                                 size_t len, const AES_KEY *key,
998                                 const unsigned char ivec[16]);
999 # endif
1000
1001 # define BLOCK_CIPHER_generic_pack(nid,keylen,flags)             \
1002         BLOCK_CIPHER_generic(nid,keylen,16,16,cbc,cbc,CBC,flags|EVP_CIPH_FLAG_DEFAULT_ASN1)     \
1003         BLOCK_CIPHER_generic(nid,keylen,16,0,ecb,ecb,ECB,flags|EVP_CIPH_FLAG_DEFAULT_ASN1)      \
1004         BLOCK_CIPHER_generic(nid,keylen,1,16,ofb128,ofb,OFB,flags|EVP_CIPH_FLAG_DEFAULT_ASN1)   \
1005         BLOCK_CIPHER_generic(nid,keylen,1,16,cfb128,cfb,CFB,flags|EVP_CIPH_FLAG_DEFAULT_ASN1)   \
1006         BLOCK_CIPHER_generic(nid,keylen,1,16,cfb1,cfb1,CFB,flags)       \
1007         BLOCK_CIPHER_generic(nid,keylen,1,16,cfb8,cfb8,CFB,flags)       \
1008         BLOCK_CIPHER_generic(nid,keylen,1,16,ctr,ctr,CTR,flags)
1009
1010 static int aes_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
1011                         const unsigned char *iv, int enc)
1012 {
1013     int ret, mode;
1014     EVP_AES_KEY *dat = (EVP_AES_KEY *) ctx->cipher_data;
1015
1016     mode = ctx->cipher->flags & EVP_CIPH_MODE;
1017     if ((mode == EVP_CIPH_ECB_MODE || mode == EVP_CIPH_CBC_MODE)
1018         && !enc)
1019 # ifdef HWAES_CAPABLE
1020         if (HWAES_CAPABLE) {
1021             ret = HWAES_set_decrypt_key(key, ctx->key_len * 8, &dat->ks.ks);
1022             dat->block = (block128_f) HWAES_decrypt;
1023             dat->stream.cbc = NULL;
1024 #  ifdef HWAES_cbc_encrypt
1025             if (mode == EVP_CIPH_CBC_MODE)
1026                 dat->stream.cbc = (cbc128_f) HWAES_cbc_encrypt;
1027 #  endif
1028         } else
1029 # endif
1030 # ifdef BSAES_CAPABLE
1031         if (BSAES_CAPABLE && mode == EVP_CIPH_CBC_MODE) {
1032             ret = AES_set_decrypt_key(key, ctx->key_len * 8, &dat->ks.ks);
1033             dat->block = (block128_f) AES_decrypt;
1034             dat->stream.cbc = (cbc128_f) bsaes_cbc_encrypt;
1035         } else
1036 # endif
1037 # ifdef VPAES_CAPABLE
1038         if (VPAES_CAPABLE) {
1039             ret = vpaes_set_decrypt_key(key, ctx->key_len * 8, &dat->ks.ks);
1040             dat->block = (block128_f) vpaes_decrypt;
1041             dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ?
1042                 (cbc128_f) vpaes_cbc_encrypt : NULL;
1043         } else
1044 # endif
1045         {
1046             ret = AES_set_decrypt_key(key, ctx->key_len * 8, &dat->ks.ks);
1047             dat->block = (block128_f) AES_decrypt;
1048             dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ?
1049                 (cbc128_f) AES_cbc_encrypt : NULL;
1050     } else
1051 # ifdef HWAES_CAPABLE
1052     if (HWAES_CAPABLE) {
1053         ret = HWAES_set_encrypt_key(key, ctx->key_len * 8, &dat->ks.ks);
1054         dat->block = (block128_f) HWAES_encrypt;
1055         dat->stream.cbc = NULL;
1056 #  ifdef HWAES_cbc_encrypt
1057         if (mode == EVP_CIPH_CBC_MODE)
1058             dat->stream.cbc = (cbc128_f) HWAES_cbc_encrypt;
1059         else
1060 #  endif
1061 #  ifdef HWAES_ctr32_encrypt_blocks
1062         if (mode == EVP_CIPH_CTR_MODE)
1063             dat->stream.ctr = (ctr128_f) HWAES_ctr32_encrypt_blocks;
1064         else
1065 #  endif
1066             (void)0;            /* terminate potentially open 'else' */
1067     } else
1068 # endif
1069 # ifdef BSAES_CAPABLE
1070     if (BSAES_CAPABLE && mode == EVP_CIPH_CTR_MODE) {
1071         ret = AES_set_encrypt_key(key, ctx->key_len * 8, &dat->ks.ks);
1072         dat->block = (block128_f) AES_encrypt;
1073         dat->stream.ctr = (ctr128_f) bsaes_ctr32_encrypt_blocks;
1074     } else
1075 # endif
1076 # ifdef VPAES_CAPABLE
1077     if (VPAES_CAPABLE) {
1078         ret = vpaes_set_encrypt_key(key, ctx->key_len * 8, &dat->ks.ks);
1079         dat->block = (block128_f) vpaes_encrypt;
1080         dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ?
1081             (cbc128_f) vpaes_cbc_encrypt : NULL;
1082     } else
1083 # endif
1084     {
1085         ret = AES_set_encrypt_key(key, ctx->key_len * 8, &dat->ks.ks);
1086         dat->block = (block128_f) AES_encrypt;
1087         dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ?
1088             (cbc128_f) AES_cbc_encrypt : NULL;
1089 # ifdef AES_CTR_ASM
1090         if (mode == EVP_CIPH_CTR_MODE)
1091             dat->stream.ctr = (ctr128_f) AES_ctr32_encrypt;
1092 # endif
1093     }
1094
1095     if (ret < 0) {
1096         EVPerr(EVP_F_AES_INIT_KEY, EVP_R_AES_KEY_SETUP_FAILED);
1097         return 0;
1098     }
1099
1100     return 1;
1101 }
1102
1103 static int aes_cbc_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
1104                           const unsigned char *in, size_t len)
1105 {
1106     EVP_AES_KEY *dat = (EVP_AES_KEY *) ctx->cipher_data;
1107
1108     if (dat->stream.cbc)
1109         (*dat->stream.cbc) (in, out, len, &dat->ks, ctx->iv, ctx->encrypt);
1110     else if (ctx->encrypt)
1111         CRYPTO_cbc128_encrypt(in, out, len, &dat->ks, ctx->iv, dat->block);
1112     else
1113         CRYPTO_cbc128_decrypt(in, out, len, &dat->ks, ctx->iv, dat->block);
1114
1115     return 1;
1116 }
1117
1118 static int aes_ecb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
1119                           const unsigned char *in, size_t len)
1120 {
1121     size_t bl = ctx->cipher->block_size;
1122     size_t i;
1123     EVP_AES_KEY *dat = (EVP_AES_KEY *) ctx->cipher_data;
1124
1125     if (len < bl)
1126         return 1;
1127
1128     for (i = 0, len -= bl; i <= len; i += bl)
1129         (*dat->block) (in + i, out + i, &dat->ks);
1130
1131     return 1;
1132 }
1133
1134 static int aes_ofb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
1135                           const unsigned char *in, size_t len)
1136 {
1137     EVP_AES_KEY *dat = (EVP_AES_KEY *) ctx->cipher_data;
1138
1139     CRYPTO_ofb128_encrypt(in, out, len, &dat->ks,
1140                           ctx->iv, &ctx->num, dat->block);
1141     return 1;
1142 }
1143
1144 static int aes_cfb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
1145                           const unsigned char *in, size_t len)
1146 {
1147     EVP_AES_KEY *dat = (EVP_AES_KEY *) ctx->cipher_data;
1148
1149     CRYPTO_cfb128_encrypt(in, out, len, &dat->ks,
1150                           ctx->iv, &ctx->num, ctx->encrypt, dat->block);
1151     return 1;
1152 }
1153
1154 static int aes_cfb8_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
1155                            const unsigned char *in, size_t len)
1156 {
1157     EVP_AES_KEY *dat = (EVP_AES_KEY *) ctx->cipher_data;
1158
1159     CRYPTO_cfb128_8_encrypt(in, out, len, &dat->ks,
1160                             ctx->iv, &ctx->num, ctx->encrypt, dat->block);
1161     return 1;
1162 }
1163
1164 static int aes_cfb1_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
1165                            const unsigned char *in, size_t len)
1166 {
1167     EVP_AES_KEY *dat = (EVP_AES_KEY *) ctx->cipher_data;
1168
1169     if (ctx->flags & EVP_CIPH_FLAG_LENGTH_BITS) {
1170         CRYPTO_cfb128_1_encrypt(in, out, len, &dat->ks,
1171                                 ctx->iv, &ctx->num, ctx->encrypt, dat->block);
1172         return 1;
1173     }
1174
1175     while (len >= MAXBITCHUNK) {
1176         CRYPTO_cfb128_1_encrypt(in, out, MAXBITCHUNK * 8, &dat->ks,
1177                                 ctx->iv, &ctx->num, ctx->encrypt, dat->block);
1178         len -= MAXBITCHUNK;
1179     }
1180     if (len)
1181         CRYPTO_cfb128_1_encrypt(in, out, len * 8, &dat->ks,
1182                                 ctx->iv, &ctx->num, ctx->encrypt, dat->block);
1183
1184     return 1;
1185 }
1186
1187 static int aes_ctr_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
1188                           const unsigned char *in, size_t len)
1189 {
1190     unsigned int num = ctx->num;
1191     EVP_AES_KEY *dat = (EVP_AES_KEY *) ctx->cipher_data;
1192
1193     if (dat->stream.ctr)
1194         CRYPTO_ctr128_encrypt_ctr32(in, out, len, &dat->ks,
1195                                     ctx->iv, ctx->buf, &num, dat->stream.ctr);
1196     else
1197         CRYPTO_ctr128_encrypt(in, out, len, &dat->ks,
1198                               ctx->iv, ctx->buf, &num, dat->block);
1199     ctx->num = (size_t)num;
1200     return 1;
1201 }
1202
1203 BLOCK_CIPHER_generic_pack(NID_aes, 128, 0)
1204     BLOCK_CIPHER_generic_pack(NID_aes, 192, 0)
1205     BLOCK_CIPHER_generic_pack(NID_aes, 256, 0)
1206
1207 static int aes_gcm_cleanup(EVP_CIPHER_CTX *c)
1208 {
1209     EVP_AES_GCM_CTX *gctx = c->cipher_data;
1210     OPENSSL_cleanse(&gctx->gcm, sizeof(gctx->gcm));
1211     if (gctx->iv != c->iv)
1212         OPENSSL_free(gctx->iv);
1213     return 1;
1214 }
1215
1216 /* increment counter (64-bit int) by 1 */
1217 static void ctr64_inc(unsigned char *counter)
1218 {
1219     int n = 8;
1220     unsigned char c;
1221
1222     do {
1223         --n;
1224         c = counter[n];
1225         ++c;
1226         counter[n] = c;
1227         if (c)
1228             return;
1229     } while (n);
1230 }
1231
1232 static int aes_gcm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr)
1233 {
1234     EVP_AES_GCM_CTX *gctx = c->cipher_data;
1235     switch (type) {
1236     case EVP_CTRL_INIT:
1237         gctx->key_set = 0;
1238         gctx->iv_set = 0;
1239         gctx->ivlen = c->cipher->iv_len;
1240         gctx->iv = c->iv;
1241         gctx->taglen = -1;
1242         gctx->iv_gen = 0;
1243         gctx->tls_aad_len = -1;
1244         return 1;
1245
1246     case EVP_CTRL_AEAD_SET_IVLEN:
1247         if (arg <= 0)
1248             return 0;
1249         /* Allocate memory for IV if needed */
1250         if ((arg > EVP_MAX_IV_LENGTH) && (arg > gctx->ivlen)) {
1251             if (gctx->iv != c->iv)
1252                 OPENSSL_free(gctx->iv);
1253             gctx->iv = OPENSSL_malloc(arg);
1254             if (!gctx->iv)
1255                 return 0;
1256         }
1257         gctx->ivlen = arg;
1258         return 1;
1259
1260     case EVP_CTRL_AEAD_SET_TAG:
1261         if (arg <= 0 || arg > 16 || c->encrypt)
1262             return 0;
1263         memcpy(c->buf, ptr, arg);
1264         gctx->taglen = arg;
1265         return 1;
1266
1267     case EVP_CTRL_AEAD_GET_TAG:
1268         if (arg <= 0 || arg > 16 || !c->encrypt || gctx->taglen < 0)
1269             return 0;
1270         memcpy(ptr, c->buf, arg);
1271         return 1;
1272
1273     case EVP_CTRL_GCM_SET_IV_FIXED:
1274         /* Special case: -1 length restores whole IV */
1275         if (arg == -1) {
1276             memcpy(gctx->iv, ptr, gctx->ivlen);
1277             gctx->iv_gen = 1;
1278             return 1;
1279         }
1280         /*
1281          * Fixed field must be at least 4 bytes and invocation field at least
1282          * 8.
1283          */
1284         if ((arg < 4) || (gctx->ivlen - arg) < 8)
1285             return 0;
1286         if (arg)
1287             memcpy(gctx->iv, ptr, arg);
1288         if (c->encrypt && RAND_bytes(gctx->iv + arg, gctx->ivlen - arg) <= 0)
1289             return 0;
1290         gctx->iv_gen = 1;
1291         return 1;
1292
1293     case EVP_CTRL_GCM_IV_GEN:
1294         if (gctx->iv_gen == 0 || gctx->key_set == 0)
1295             return 0;
1296         CRYPTO_gcm128_setiv(&gctx->gcm, gctx->iv, gctx->ivlen);
1297         if (arg <= 0 || arg > gctx->ivlen)
1298             arg = gctx->ivlen;
1299         memcpy(ptr, gctx->iv + gctx->ivlen - arg, arg);
1300         /*
1301          * Invocation field will be at least 8 bytes in size and so no need
1302          * to check wrap around or increment more than last 8 bytes.
1303          */
1304         ctr64_inc(gctx->iv + gctx->ivlen - 8);
1305         gctx->iv_set = 1;
1306         return 1;
1307
1308     case EVP_CTRL_GCM_SET_IV_INV:
1309         if (gctx->iv_gen == 0 || gctx->key_set == 0 || c->encrypt)
1310             return 0;
1311         memcpy(gctx->iv + gctx->ivlen - arg, ptr, arg);
1312         CRYPTO_gcm128_setiv(&gctx->gcm, gctx->iv, gctx->ivlen);
1313         gctx->iv_set = 1;
1314         return 1;
1315
1316     case EVP_CTRL_AEAD_TLS1_AAD:
1317         /* Save the AAD for later use */
1318         if (arg != 13)
1319             return 0;
1320         memcpy(c->buf, ptr, arg);
1321         gctx->tls_aad_len = arg;
1322         {
1323             unsigned int len = c->buf[arg - 2] << 8 | c->buf[arg - 1];
1324             /* Correct length for explicit IV */
1325             len -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
1326             /* If decrypting correct for tag too */
1327             if (!c->encrypt)
1328                 len -= EVP_GCM_TLS_TAG_LEN;
1329             c->buf[arg - 2] = len >> 8;
1330             c->buf[arg - 1] = len & 0xff;
1331         }
1332         /* Extra padding: tag appended to record */
1333         return EVP_GCM_TLS_TAG_LEN;
1334
1335     case EVP_CTRL_COPY:
1336         {
1337             EVP_CIPHER_CTX *out = ptr;
1338             EVP_AES_GCM_CTX *gctx_out = out->cipher_data;
1339             if (gctx->gcm.key) {
1340                 if (gctx->gcm.key != &gctx->ks)
1341                     return 0;
1342                 gctx_out->gcm.key = &gctx_out->ks;
1343             }
1344             if (gctx->iv == c->iv)
1345                 gctx_out->iv = out->iv;
1346             else {
1347                 gctx_out->iv = OPENSSL_malloc(gctx->ivlen);
1348                 if (!gctx_out->iv)
1349                     return 0;
1350                 memcpy(gctx_out->iv, gctx->iv, gctx->ivlen);
1351             }
1352             return 1;
1353         }
1354
1355     default:
1356         return -1;
1357
1358     }
1359 }
1360
1361 static int aes_gcm_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
1362                             const unsigned char *iv, int enc)
1363 {
1364     EVP_AES_GCM_CTX *gctx = ctx->cipher_data;
1365     if (!iv && !key)
1366         return 1;
1367     if (key) {
1368         do {
1369 # ifdef HWAES_CAPABLE
1370             if (HWAES_CAPABLE) {
1371                 HWAES_set_encrypt_key(key, ctx->key_len * 8, &gctx->ks.ks);
1372                 CRYPTO_gcm128_init(&gctx->gcm, &gctx->ks,
1373                                    (block128_f) HWAES_encrypt);
1374 #  ifdef HWAES_ctr32_encrypt_blocks
1375                 gctx->ctr = (ctr128_f) HWAES_ctr32_encrypt_blocks;
1376 #  else
1377                 gctx->ctr = NULL;
1378 #  endif
1379                 break;
1380             } else
1381 # endif
1382 # ifdef BSAES_CAPABLE
1383             if (BSAES_CAPABLE) {
1384                 AES_set_encrypt_key(key, ctx->key_len * 8, &gctx->ks.ks);
1385                 CRYPTO_gcm128_init(&gctx->gcm, &gctx->ks,
1386                                    (block128_f) AES_encrypt);
1387                 gctx->ctr = (ctr128_f) bsaes_ctr32_encrypt_blocks;
1388                 break;
1389             } else
1390 # endif
1391 # ifdef VPAES_CAPABLE
1392             if (VPAES_CAPABLE) {
1393                 vpaes_set_encrypt_key(key, ctx->key_len * 8, &gctx->ks.ks);
1394                 CRYPTO_gcm128_init(&gctx->gcm, &gctx->ks,
1395                                    (block128_f) vpaes_encrypt);
1396                 gctx->ctr = NULL;
1397                 break;
1398             } else
1399 # endif
1400                 (void)0;        /* terminate potentially open 'else' */
1401
1402             AES_set_encrypt_key(key, ctx->key_len * 8, &gctx->ks.ks);
1403             CRYPTO_gcm128_init(&gctx->gcm, &gctx->ks,
1404                                (block128_f) AES_encrypt);
1405 # ifdef AES_CTR_ASM
1406             gctx->ctr = (ctr128_f) AES_ctr32_encrypt;
1407 # else
1408             gctx->ctr = NULL;
1409 # endif
1410         } while (0);
1411
1412         /*
1413          * If we have an iv can set it directly, otherwise use saved IV.
1414          */
1415         if (iv == NULL && gctx->iv_set)
1416             iv = gctx->iv;
1417         if (iv) {
1418             CRYPTO_gcm128_setiv(&gctx->gcm, iv, gctx->ivlen);
1419             gctx->iv_set = 1;
1420         }
1421         gctx->key_set = 1;
1422     } else {
1423         /* If key set use IV, otherwise copy */
1424         if (gctx->key_set)
1425             CRYPTO_gcm128_setiv(&gctx->gcm, iv, gctx->ivlen);
1426         else
1427             memcpy(gctx->iv, iv, gctx->ivlen);
1428         gctx->iv_set = 1;
1429         gctx->iv_gen = 0;
1430     }
1431     return 1;
1432 }
1433
1434 /*
1435  * Handle TLS GCM packet format. This consists of the last portion of the IV
1436  * followed by the payload and finally the tag. On encrypt generate IV,
1437  * encrypt payload and write the tag. On verify retrieve IV, decrypt payload
1438  * and verify tag.
1439  */
1440
1441 static int aes_gcm_tls_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
1442                               const unsigned char *in, size_t len)
1443 {
1444     EVP_AES_GCM_CTX *gctx = ctx->cipher_data;
1445     int rv = -1;
1446     /* Encrypt/decrypt must be performed in place */
1447     if (out != in
1448         || len < (EVP_GCM_TLS_EXPLICIT_IV_LEN + EVP_GCM_TLS_TAG_LEN))
1449         return -1;
1450     /*
1451      * Set IV from start of buffer or generate IV and write to start of
1452      * buffer.
1453      */
1454     if (EVP_CIPHER_CTX_ctrl(ctx, ctx->encrypt ?
1455                             EVP_CTRL_GCM_IV_GEN : EVP_CTRL_GCM_SET_IV_INV,
1456                             EVP_GCM_TLS_EXPLICIT_IV_LEN, out) <= 0)
1457         goto err;
1458     /* Use saved AAD */
1459     if (CRYPTO_gcm128_aad(&gctx->gcm, ctx->buf, gctx->tls_aad_len))
1460         goto err;
1461     /* Fix buffer and length to point to payload */
1462     in += EVP_GCM_TLS_EXPLICIT_IV_LEN;
1463     out += EVP_GCM_TLS_EXPLICIT_IV_LEN;
1464     len -= EVP_GCM_TLS_EXPLICIT_IV_LEN + EVP_GCM_TLS_TAG_LEN;
1465     if (ctx->encrypt) {
1466         /* Encrypt payload */
1467         if (gctx->ctr) {
1468             size_t bulk = 0;
1469 # if defined(AES_GCM_ASM)
1470             if (len >= 32 && AES_GCM_ASM(gctx)) {
1471                 if (CRYPTO_gcm128_encrypt(&gctx->gcm, NULL, NULL, 0))
1472                     return -1;
1473
1474                 bulk = AES_gcm_encrypt(in, out, len,
1475                                        gctx->gcm.key,
1476                                        gctx->gcm.Yi.c, gctx->gcm.Xi.u);
1477                 gctx->gcm.len.u[1] += bulk;
1478             }
1479 # endif
1480             if (CRYPTO_gcm128_encrypt_ctr32(&gctx->gcm,
1481                                             in + bulk,
1482                                             out + bulk,
1483                                             len - bulk, gctx->ctr))
1484                 goto err;
1485         } else {
1486             size_t bulk = 0;
1487 # if defined(AES_GCM_ASM2)
1488             if (len >= 32 && AES_GCM_ASM2(gctx)) {
1489                 if (CRYPTO_gcm128_encrypt(&gctx->gcm, NULL, NULL, 0))
1490                     return -1;
1491
1492                 bulk = AES_gcm_encrypt(in, out, len,
1493                                        gctx->gcm.key,
1494                                        gctx->gcm.Yi.c, gctx->gcm.Xi.u);
1495                 gctx->gcm.len.u[1] += bulk;
1496             }
1497 # endif
1498             if (CRYPTO_gcm128_encrypt(&gctx->gcm,
1499                                       in + bulk, out + bulk, len - bulk))
1500                 goto err;
1501         }
1502         out += len;
1503         /* Finally write tag */
1504         CRYPTO_gcm128_tag(&gctx->gcm, out, EVP_GCM_TLS_TAG_LEN);
1505         rv = len + EVP_GCM_TLS_EXPLICIT_IV_LEN + EVP_GCM_TLS_TAG_LEN;
1506     } else {
1507         /* Decrypt */
1508         if (gctx->ctr) {
1509             size_t bulk = 0;
1510 # if defined(AES_GCM_ASM)
1511             if (len >= 16 && AES_GCM_ASM(gctx)) {
1512                 if (CRYPTO_gcm128_decrypt(&gctx->gcm, NULL, NULL, 0))
1513                     return -1;
1514
1515                 bulk = AES_gcm_decrypt(in, out, len,
1516                                        gctx->gcm.key,
1517                                        gctx->gcm.Yi.c, gctx->gcm.Xi.u);
1518                 gctx->gcm.len.u[1] += bulk;
1519             }
1520 # endif
1521             if (CRYPTO_gcm128_decrypt_ctr32(&gctx->gcm,
1522                                             in + bulk,
1523                                             out + bulk,
1524                                             len - bulk, gctx->ctr))
1525                 goto err;
1526         } else {
1527             size_t bulk = 0;
1528 # if defined(AES_GCM_ASM2)
1529             if (len >= 16 && AES_GCM_ASM2(gctx)) {
1530                 if (CRYPTO_gcm128_decrypt(&gctx->gcm, NULL, NULL, 0))
1531                     return -1;
1532
1533                 bulk = AES_gcm_decrypt(in, out, len,
1534                                        gctx->gcm.key,
1535                                        gctx->gcm.Yi.c, gctx->gcm.Xi.u);
1536                 gctx->gcm.len.u[1] += bulk;
1537             }
1538 # endif
1539             if (CRYPTO_gcm128_decrypt(&gctx->gcm,
1540                                       in + bulk, out + bulk, len - bulk))
1541                 goto err;
1542         }
1543         /* Retrieve tag */
1544         CRYPTO_gcm128_tag(&gctx->gcm, ctx->buf, EVP_GCM_TLS_TAG_LEN);
1545         /* If tag mismatch wipe buffer */
1546         if (memcmp(ctx->buf, in + len, EVP_GCM_TLS_TAG_LEN)) {
1547             OPENSSL_cleanse(out, len);
1548             goto err;
1549         }
1550         rv = len;
1551     }
1552
1553  err:
1554     gctx->iv_set = 0;
1555     gctx->tls_aad_len = -1;
1556     return rv;
1557 }
1558
1559 static int aes_gcm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
1560                           const unsigned char *in, size_t len)
1561 {
1562     EVP_AES_GCM_CTX *gctx = ctx->cipher_data;
1563     /* If not set up, return error */
1564     if (!gctx->key_set)
1565         return -1;
1566
1567     if (gctx->tls_aad_len >= 0)
1568         return aes_gcm_tls_cipher(ctx, out, in, len);
1569
1570     if (!gctx->iv_set)
1571         return -1;
1572     if (in) {
1573         if (out == NULL) {
1574             if (CRYPTO_gcm128_aad(&gctx->gcm, in, len))
1575                 return -1;
1576         } else if (ctx->encrypt) {
1577             if (gctx->ctr) {
1578                 size_t bulk = 0;
1579 # if defined(AES_GCM_ASM)
1580                 if (len >= 32 && AES_GCM_ASM(gctx)) {
1581                     size_t res = (16 - gctx->gcm.mres) % 16;
1582
1583                     if (CRYPTO_gcm128_encrypt(&gctx->gcm, in, out, res))
1584                         return -1;
1585
1586                     bulk = AES_gcm_encrypt(in + res,
1587                                            out + res, len - res,
1588                                            gctx->gcm.key, gctx->gcm.Yi.c,
1589                                            gctx->gcm.Xi.u);
1590                     gctx->gcm.len.u[1] += bulk;
1591                     bulk += res;
1592                 }
1593 # endif
1594                 if (CRYPTO_gcm128_encrypt_ctr32(&gctx->gcm,
1595                                                 in + bulk,
1596                                                 out + bulk,
1597                                                 len - bulk, gctx->ctr))
1598                     return -1;
1599             } else {
1600                 size_t bulk = 0;
1601 # if defined(AES_GCM_ASM2)
1602                 if (len >= 32 && AES_GCM_ASM2(gctx)) {
1603                     size_t res = (16 - gctx->gcm.mres) % 16;
1604
1605                     if (CRYPTO_gcm128_encrypt(&gctx->gcm, in, out, res))
1606                         return -1;
1607
1608                     bulk = AES_gcm_encrypt(in + res,
1609                                            out + res, len - res,
1610                                            gctx->gcm.key, gctx->gcm.Yi.c,
1611                                            gctx->gcm.Xi.u);
1612                     gctx->gcm.len.u[1] += bulk;
1613                     bulk += res;
1614                 }
1615 # endif
1616                 if (CRYPTO_gcm128_encrypt(&gctx->gcm,
1617                                           in + bulk, out + bulk, len - bulk))
1618                     return -1;
1619             }
1620         } else {
1621             if (gctx->ctr) {
1622                 size_t bulk = 0;
1623 # if defined(AES_GCM_ASM)
1624                 if (len >= 16 && AES_GCM_ASM(gctx)) {
1625                     size_t res = (16 - gctx->gcm.mres) % 16;
1626
1627                     if (CRYPTO_gcm128_decrypt(&gctx->gcm, in, out, res))
1628                         return -1;
1629
1630                     bulk = AES_gcm_decrypt(in + res,
1631                                            out + res, len - res,
1632                                            gctx->gcm.key,
1633                                            gctx->gcm.Yi.c, gctx->gcm.Xi.u);
1634                     gctx->gcm.len.u[1] += bulk;
1635                     bulk += res;
1636                 }
1637 # endif
1638                 if (CRYPTO_gcm128_decrypt_ctr32(&gctx->gcm,
1639                                                 in + bulk,
1640                                                 out + bulk,
1641                                                 len - bulk, gctx->ctr))
1642                     return -1;
1643             } else {
1644                 size_t bulk = 0;
1645 # if defined(AES_GCM_ASM2)
1646                 if (len >= 16 && AES_GCM_ASM2(gctx)) {
1647                     size_t res = (16 - gctx->gcm.mres) % 16;
1648
1649                     if (CRYPTO_gcm128_decrypt(&gctx->gcm, in, out, res))
1650                         return -1;
1651
1652                     bulk = AES_gcm_decrypt(in + res,
1653                                            out + res, len - res,
1654                                            gctx->gcm.key,
1655                                            gctx->gcm.Yi.c, gctx->gcm.Xi.u);
1656                     gctx->gcm.len.u[1] += bulk;
1657                     bulk += res;
1658                 }
1659 # endif
1660                 if (CRYPTO_gcm128_decrypt(&gctx->gcm,
1661                                           in + bulk, out + bulk, len - bulk))
1662                     return -1;
1663             }
1664         }
1665         return len;
1666     } else {
1667         if (!ctx->encrypt) {
1668             if (gctx->taglen < 0)
1669                 return -1;
1670             if (CRYPTO_gcm128_finish(&gctx->gcm, ctx->buf, gctx->taglen) != 0)
1671                 return -1;
1672             gctx->iv_set = 0;
1673             return 0;
1674         }
1675         CRYPTO_gcm128_tag(&gctx->gcm, ctx->buf, 16);
1676         gctx->taglen = 16;
1677         /* Don't reuse the IV */
1678         gctx->iv_set = 0;
1679         return 0;
1680     }
1681
1682 }
1683
1684 # define CUSTOM_FLAGS    (EVP_CIPH_FLAG_DEFAULT_ASN1 \
1685                 | EVP_CIPH_CUSTOM_IV | EVP_CIPH_FLAG_CUSTOM_CIPHER \
1686                 | EVP_CIPH_ALWAYS_CALL_INIT | EVP_CIPH_CTRL_INIT \
1687                 | EVP_CIPH_CUSTOM_COPY)
1688
1689 BLOCK_CIPHER_custom(NID_aes, 128, 1, 12, gcm, GCM,
1690                     EVP_CIPH_FLAG_AEAD_CIPHER | CUSTOM_FLAGS)
1691     BLOCK_CIPHER_custom(NID_aes, 192, 1, 12, gcm, GCM,
1692                     EVP_CIPH_FLAG_AEAD_CIPHER | CUSTOM_FLAGS)
1693     BLOCK_CIPHER_custom(NID_aes, 256, 1, 12, gcm, GCM,
1694                     EVP_CIPH_FLAG_AEAD_CIPHER | CUSTOM_FLAGS)
1695
1696 static int aes_xts_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr)
1697 {
1698     EVP_AES_XTS_CTX *xctx = c->cipher_data;
1699     if (type == EVP_CTRL_COPY) {
1700         EVP_CIPHER_CTX *out = ptr;
1701         EVP_AES_XTS_CTX *xctx_out = out->cipher_data;
1702         if (xctx->xts.key1) {
1703             if (xctx->xts.key1 != &xctx->ks1)
1704                 return 0;
1705             xctx_out->xts.key1 = &xctx_out->ks1;
1706         }
1707         if (xctx->xts.key2) {
1708             if (xctx->xts.key2 != &xctx->ks2)
1709                 return 0;
1710             xctx_out->xts.key2 = &xctx_out->ks2;
1711         }
1712         return 1;
1713     } else if (type != EVP_CTRL_INIT)
1714         return -1;
1715     /* key1 and key2 are used as an indicator both key and IV are set */
1716     xctx->xts.key1 = NULL;
1717     xctx->xts.key2 = NULL;
1718     return 1;
1719 }
1720
1721 static int aes_xts_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
1722                             const unsigned char *iv, int enc)
1723 {
1724     EVP_AES_XTS_CTX *xctx = ctx->cipher_data;
1725     if (!iv && !key)
1726         return 1;
1727
1728     if (key)
1729         do {
1730 # ifdef AES_XTS_ASM
1731             xctx->stream = enc ? AES_xts_encrypt : AES_xts_decrypt;
1732 # else
1733             xctx->stream = NULL;
1734 # endif
1735             /* key_len is two AES keys */
1736 # ifdef HWAES_CAPABLE
1737             if (HWAES_CAPABLE) {
1738                 if (enc) {
1739                     HWAES_set_encrypt_key(key, ctx->key_len * 4,
1740                                           &xctx->ks1.ks);
1741                     xctx->xts.block1 = (block128_f) HWAES_encrypt;
1742                 } else {
1743                     HWAES_set_decrypt_key(key, ctx->key_len * 4,
1744                                           &xctx->ks1.ks);
1745                     xctx->xts.block1 = (block128_f) HWAES_decrypt;
1746                 }
1747
1748                 HWAES_set_encrypt_key(key + ctx->key_len / 2,
1749                                       ctx->key_len * 4, &xctx->ks2.ks);
1750                 xctx->xts.block2 = (block128_f) HWAES_encrypt;
1751
1752                 xctx->xts.key1 = &xctx->ks1;
1753                 break;
1754             } else
1755 # endif
1756 # ifdef BSAES_CAPABLE
1757             if (BSAES_CAPABLE)
1758                 xctx->stream = enc ? bsaes_xts_encrypt : bsaes_xts_decrypt;
1759             else
1760 # endif
1761 # ifdef VPAES_CAPABLE
1762             if (VPAES_CAPABLE) {
1763                 if (enc) {
1764                     vpaes_set_encrypt_key(key, ctx->key_len * 4,
1765                                           &xctx->ks1.ks);
1766                     xctx->xts.block1 = (block128_f) vpaes_encrypt;
1767                 } else {
1768                     vpaes_set_decrypt_key(key, ctx->key_len * 4,
1769                                           &xctx->ks1.ks);
1770                     xctx->xts.block1 = (block128_f) vpaes_decrypt;
1771                 }
1772
1773                 vpaes_set_encrypt_key(key + ctx->key_len / 2,
1774                                       ctx->key_len * 4, &xctx->ks2.ks);
1775                 xctx->xts.block2 = (block128_f) vpaes_encrypt;
1776
1777                 xctx->xts.key1 = &xctx->ks1;
1778                 break;
1779             } else
1780 # endif
1781                 (void)0;        /* terminate potentially open 'else' */
1782
1783             if (enc) {
1784                 AES_set_encrypt_key(key, ctx->key_len * 4, &xctx->ks1.ks);
1785                 xctx->xts.block1 = (block128_f) AES_encrypt;
1786             } else {
1787                 AES_set_decrypt_key(key, ctx->key_len * 4, &xctx->ks1.ks);
1788                 xctx->xts.block1 = (block128_f) AES_decrypt;
1789             }
1790
1791             AES_set_encrypt_key(key + ctx->key_len / 2,
1792                                 ctx->key_len * 4, &xctx->ks2.ks);
1793             xctx->xts.block2 = (block128_f) AES_encrypt;
1794
1795             xctx->xts.key1 = &xctx->ks1;
1796         } while (0);
1797
1798     if (iv) {
1799         xctx->xts.key2 = &xctx->ks2;
1800         memcpy(ctx->iv, iv, 16);
1801     }
1802
1803     return 1;
1804 }
1805
1806 static int aes_xts_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
1807                           const unsigned char *in, size_t len)
1808 {
1809     EVP_AES_XTS_CTX *xctx = ctx->cipher_data;
1810     if (!xctx->xts.key1 || !xctx->xts.key2)
1811         return 0;
1812     if (!out || !in || len < AES_BLOCK_SIZE)
1813         return 0;
1814     if (xctx->stream)
1815         (*xctx->stream) (in, out, len,
1816                          xctx->xts.key1, xctx->xts.key2, ctx->iv);
1817     else if (CRYPTO_xts128_encrypt(&xctx->xts, ctx->iv, in, out, len,
1818                                    ctx->encrypt))
1819         return 0;
1820     return 1;
1821 }
1822
1823 # define aes_xts_cleanup NULL
1824
1825 # define XTS_FLAGS       (EVP_CIPH_FLAG_DEFAULT_ASN1 | EVP_CIPH_CUSTOM_IV \
1826                          | EVP_CIPH_ALWAYS_CALL_INIT | EVP_CIPH_CTRL_INIT \
1827                          | EVP_CIPH_CUSTOM_COPY)
1828
1829 BLOCK_CIPHER_custom(NID_aes, 128, 1, 16, xts, XTS, XTS_FLAGS)
1830     BLOCK_CIPHER_custom(NID_aes, 256, 1, 16, xts, XTS, XTS_FLAGS)
1831
1832 static int aes_ccm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr)
1833 {
1834     EVP_AES_CCM_CTX *cctx = c->cipher_data;
1835     switch (type) {
1836     case EVP_CTRL_INIT:
1837         cctx->key_set = 0;
1838         cctx->iv_set = 0;
1839         cctx->L = 8;
1840         cctx->M = 12;
1841         cctx->tag_set = 0;
1842         cctx->len_set = 0;
1843         return 1;
1844
1845     case EVP_CTRL_AEAD_SET_IVLEN:
1846         arg = 15 - arg;
1847     case EVP_CTRL_CCM_SET_L:
1848         if (arg < 2 || arg > 8)
1849             return 0;
1850         cctx->L = arg;
1851         return 1;
1852
1853     case EVP_CTRL_AEAD_SET_TAG:
1854         if ((arg & 1) || arg < 4 || arg > 16)
1855             return 0;
1856         if ((c->encrypt && ptr) || (!c->encrypt && !ptr))
1857             return 0;
1858         if (ptr) {
1859             cctx->tag_set = 1;
1860             memcpy(c->buf, ptr, arg);
1861         }
1862         cctx->M = arg;
1863         return 1;
1864
1865     case EVP_CTRL_AEAD_GET_TAG:
1866         if (!c->encrypt || !cctx->tag_set)
1867             return 0;
1868         if (!CRYPTO_ccm128_tag(&cctx->ccm, ptr, (size_t)arg))
1869             return 0;
1870         cctx->tag_set = 0;
1871         cctx->iv_set = 0;
1872         cctx->len_set = 0;
1873         return 1;
1874
1875     case EVP_CTRL_COPY:
1876         {
1877             EVP_CIPHER_CTX *out = ptr;
1878             EVP_AES_CCM_CTX *cctx_out = out->cipher_data;
1879             if (cctx->ccm.key) {
1880                 if (cctx->ccm.key != &cctx->ks)
1881                     return 0;
1882                 cctx_out->ccm.key = &cctx_out->ks;
1883             }
1884             return 1;
1885         }
1886
1887     default:
1888         return -1;
1889
1890     }
1891 }
1892
1893 static int aes_ccm_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
1894                             const unsigned char *iv, int enc)
1895 {
1896     EVP_AES_CCM_CTX *cctx = ctx->cipher_data;
1897     if (!iv && !key)
1898         return 1;
1899     if (key)
1900         do {
1901 # ifdef HWAES_CAPABLE
1902             if (HWAES_CAPABLE) {
1903                 HWAES_set_encrypt_key(key, ctx->key_len * 8, &cctx->ks.ks);
1904
1905                 CRYPTO_ccm128_init(&cctx->ccm, cctx->M, cctx->L,
1906                                    &cctx->ks, (block128_f) HWAES_encrypt);
1907                 cctx->str = NULL;
1908                 cctx->key_set = 1;
1909                 break;
1910             } else
1911 # endif
1912 # ifdef VPAES_CAPABLE
1913             if (VPAES_CAPABLE) {
1914                 vpaes_set_encrypt_key(key, ctx->key_len * 8, &cctx->ks.ks);
1915                 CRYPTO_ccm128_init(&cctx->ccm, cctx->M, cctx->L,
1916                                    &cctx->ks, (block128_f) vpaes_encrypt);
1917                 cctx->str = NULL;
1918                 cctx->key_set = 1;
1919                 break;
1920             }
1921 # endif
1922             AES_set_encrypt_key(key, ctx->key_len * 8, &cctx->ks.ks);
1923             CRYPTO_ccm128_init(&cctx->ccm, cctx->M, cctx->L,
1924                                &cctx->ks, (block128_f) AES_encrypt);
1925             cctx->str = NULL;
1926             cctx->key_set = 1;
1927         } while (0);
1928     if (iv) {
1929         memcpy(ctx->iv, iv, 15 - cctx->L);
1930         cctx->iv_set = 1;
1931     }
1932     return 1;
1933 }
1934
1935 static int aes_ccm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
1936                           const unsigned char *in, size_t len)
1937 {
1938     EVP_AES_CCM_CTX *cctx = ctx->cipher_data;
1939     CCM128_CONTEXT *ccm = &cctx->ccm;
1940     /* If not set up, return error */
1941     if (!cctx->iv_set && !cctx->key_set)
1942         return -1;
1943     if (!ctx->encrypt && !cctx->tag_set)
1944         return -1;
1945     if (!out) {
1946         if (!in) {
1947             if (CRYPTO_ccm128_setiv(ccm, ctx->iv, 15 - cctx->L, len))
1948                 return -1;
1949             cctx->len_set = 1;
1950             return len;
1951         }
1952         /* If have AAD need message length */
1953         if (!cctx->len_set && len)
1954             return -1;
1955         CRYPTO_ccm128_aad(ccm, in, len);
1956         return len;
1957     }
1958     /* EVP_*Final() doesn't return any data */
1959     if (!in)
1960         return 0;
1961     /* If not set length yet do it */
1962     if (!cctx->len_set) {
1963         if (CRYPTO_ccm128_setiv(ccm, ctx->iv, 15 - cctx->L, len))
1964             return -1;
1965         cctx->len_set = 1;
1966     }
1967     if (ctx->encrypt) {
1968         if (cctx->str ? CRYPTO_ccm128_encrypt_ccm64(ccm, in, out, len,
1969                                                     cctx->str) :
1970             CRYPTO_ccm128_encrypt(ccm, in, out, len))
1971             return -1;
1972         cctx->tag_set = 1;
1973         return len;
1974     } else {
1975         int rv = -1;
1976         if (cctx->str ? !CRYPTO_ccm128_decrypt_ccm64(ccm, in, out, len,
1977                                                      cctx->str) :
1978             !CRYPTO_ccm128_decrypt(ccm, in, out, len)) {
1979             unsigned char tag[16];
1980             if (CRYPTO_ccm128_tag(ccm, tag, cctx->M)) {
1981                 if (!memcmp(tag, ctx->buf, cctx->M))
1982                     rv = len;
1983             }
1984         }
1985         if (rv == -1)
1986             OPENSSL_cleanse(out, len);
1987         cctx->iv_set = 0;
1988         cctx->tag_set = 0;
1989         cctx->len_set = 0;
1990         return rv;
1991     }
1992
1993 }
1994
1995 # define aes_ccm_cleanup NULL
1996
1997 BLOCK_CIPHER_custom(NID_aes, 128, 1, 12, ccm, CCM, CUSTOM_FLAGS)
1998     BLOCK_CIPHER_custom(NID_aes, 192, 1, 12, ccm, CCM, CUSTOM_FLAGS)
1999     BLOCK_CIPHER_custom(NID_aes, 256, 1, 12, ccm, CCM, CUSTOM_FLAGS)
2000
2001 typedef struct {
2002     union {
2003         double align;
2004         AES_KEY ks;
2005     } ks;
2006     /* Indicates if IV has been set */
2007     unsigned char *iv;
2008 } EVP_AES_WRAP_CTX;
2009
2010 static int aes_wrap_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
2011                              const unsigned char *iv, int enc)
2012 {
2013     EVP_AES_WRAP_CTX *wctx = ctx->cipher_data;
2014     if (!iv && !key)
2015         return 1;
2016     if (key) {
2017         if (ctx->encrypt)
2018             AES_set_encrypt_key(key, ctx->key_len * 8, &wctx->ks.ks);
2019         else
2020             AES_set_decrypt_key(key, ctx->key_len * 8, &wctx->ks.ks);
2021         if (!iv)
2022             wctx->iv = NULL;
2023     }
2024     if (iv) {
2025         memcpy(ctx->iv, iv, EVP_CIPHER_CTX_iv_length(ctx));
2026         wctx->iv = ctx->iv;
2027     }
2028     return 1;
2029 }
2030
2031 static int aes_wrap_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
2032                            const unsigned char *in, size_t inlen)
2033 {
2034     EVP_AES_WRAP_CTX *wctx = ctx->cipher_data;
2035     size_t rv;
2036     /* AES wrap with padding has IV length of 4, without padding 8 */
2037     int pad = EVP_CIPHER_CTX_iv_length(ctx) == 4;
2038     /* No final operation so always return zero length */
2039     if (!in)
2040         return 0;
2041     /* Input length must always be non-zero */
2042     if (!inlen)
2043         return -1;
2044     /* If decrypting need at least 16 bytes and multiple of 8 */
2045     if (!ctx->encrypt && (inlen < 16 || inlen & 0x7))
2046         return -1;
2047     /* If not padding input must be multiple of 8 */
2048     if (!pad && inlen & 0x7)
2049         return -1;
2050     if (!out) {
2051         if (ctx->encrypt) {
2052             /* If padding round up to multiple of 8 */
2053             if (pad)
2054                 inlen = (inlen + 7) / 8 * 8;
2055             /* 8 byte prefix */
2056             return inlen + 8;
2057         } else {
2058             /*
2059              * If not padding output will be exactly 8 bytes smaller than
2060              * input. If padding it will be at least 8 bytes smaller but we
2061              * don't know how much.
2062              */
2063             return inlen - 8;
2064         }
2065     }
2066     if (pad) {
2067         if (ctx->encrypt)
2068             rv = CRYPTO_128_wrap_pad(&wctx->ks.ks, wctx->iv,
2069                                      out, in, inlen,
2070                                      (block128_f) AES_encrypt);
2071         else
2072             rv = CRYPTO_128_unwrap_pad(&wctx->ks.ks, wctx->iv,
2073                                        out, in, inlen,
2074                                        (block128_f) AES_decrypt);
2075     } else {
2076         if (ctx->encrypt)
2077             rv = CRYPTO_128_wrap(&wctx->ks.ks, wctx->iv,
2078                                  out, in, inlen, (block128_f) AES_encrypt);
2079         else
2080             rv = CRYPTO_128_unwrap(&wctx->ks.ks, wctx->iv,
2081                                    out, in, inlen, (block128_f) AES_decrypt);
2082     }
2083     return rv ? (int)rv : -1;
2084 }
2085
2086 # define WRAP_FLAGS      (EVP_CIPH_WRAP_MODE \
2087                 | EVP_CIPH_CUSTOM_IV | EVP_CIPH_FLAG_CUSTOM_CIPHER \
2088                 | EVP_CIPH_ALWAYS_CALL_INIT | EVP_CIPH_FLAG_DEFAULT_ASN1)
2089
2090 static const EVP_CIPHER aes_128_wrap = {
2091     NID_id_aes128_wrap,
2092     8, 16, 8, WRAP_FLAGS,
2093     aes_wrap_init_key, aes_wrap_cipher,
2094     NULL,
2095     sizeof(EVP_AES_WRAP_CTX),
2096     NULL, NULL, NULL, NULL
2097 };
2098
2099 const EVP_CIPHER *EVP_aes_128_wrap(void)
2100 {
2101     return &aes_128_wrap;
2102 }
2103
2104 static const EVP_CIPHER aes_192_wrap = {
2105     NID_id_aes192_wrap,
2106     8, 24, 8, WRAP_FLAGS,
2107     aes_wrap_init_key, aes_wrap_cipher,
2108     NULL,
2109     sizeof(EVP_AES_WRAP_CTX),
2110     NULL, NULL, NULL, NULL
2111 };
2112
2113 const EVP_CIPHER *EVP_aes_192_wrap(void)
2114 {
2115     return &aes_192_wrap;
2116 }
2117
2118 static const EVP_CIPHER aes_256_wrap = {
2119     NID_id_aes256_wrap,
2120     8, 32, 8, WRAP_FLAGS,
2121     aes_wrap_init_key, aes_wrap_cipher,
2122     NULL,
2123     sizeof(EVP_AES_WRAP_CTX),
2124     NULL, NULL, NULL, NULL
2125 };
2126
2127 const EVP_CIPHER *EVP_aes_256_wrap(void)
2128 {
2129     return &aes_256_wrap;
2130 }
2131
2132 static const EVP_CIPHER aes_128_wrap_pad = {
2133     NID_id_aes128_wrap_pad,
2134     8, 16, 4, WRAP_FLAGS,
2135     aes_wrap_init_key, aes_wrap_cipher,
2136     NULL,
2137     sizeof(EVP_AES_WRAP_CTX),
2138     NULL, NULL, NULL, NULL
2139 };
2140
2141 const EVP_CIPHER *EVP_aes_128_wrap_pad(void)
2142 {
2143     return &aes_128_wrap_pad;
2144 }
2145
2146 static const EVP_CIPHER aes_192_wrap_pad = {
2147     NID_id_aes192_wrap_pad,
2148     8, 24, 4, WRAP_FLAGS,
2149     aes_wrap_init_key, aes_wrap_cipher,
2150     NULL,
2151     sizeof(EVP_AES_WRAP_CTX),
2152     NULL, NULL, NULL, NULL
2153 };
2154
2155 const EVP_CIPHER *EVP_aes_192_wrap_pad(void)
2156 {
2157     return &aes_192_wrap_pad;
2158 }
2159
2160 static const EVP_CIPHER aes_256_wrap_pad = {
2161     NID_id_aes256_wrap_pad,
2162     8, 32, 4, WRAP_FLAGS,
2163     aes_wrap_init_key, aes_wrap_cipher,
2164     NULL,
2165     sizeof(EVP_AES_WRAP_CTX),
2166     NULL, NULL, NULL, NULL
2167 };
2168
2169 const EVP_CIPHER *EVP_aes_256_wrap_pad(void)
2170 {
2171     return &aes_256_wrap_pad;
2172 }
2173
2174 # ifndef OPENSSL_NO_OCB
2175 static int aes_ocb_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr)
2176 {
2177     EVP_AES_OCB_CTX *octx = c->cipher_data;
2178     EVP_CIPHER_CTX *newc;
2179     EVP_AES_OCB_CTX *new_octx;
2180
2181     switch (type) {
2182     case EVP_CTRL_INIT:
2183         octx->key_set = 0;
2184         octx->iv_set = 0;
2185         octx->ivlen = c->cipher->iv_len;
2186         octx->iv = c->iv;
2187         octx->taglen = 16;
2188         octx->data_buf_len = 0;
2189         octx->aad_buf_len = 0;
2190         return 1;
2191
2192     case EVP_CTRL_AEAD_SET_IVLEN:
2193         /* IV len must be 1 to 15 */
2194         if (arg <= 0 || arg > 15)
2195             return 0;
2196
2197         octx->ivlen = arg;
2198         return 1;
2199
2200     case EVP_CTRL_AEAD_SET_TAG:
2201         if (!ptr) {
2202             /* Tag len must be 0 to 16 */
2203             if (arg < 0 || arg > 16)
2204                 return 0;
2205
2206             octx->taglen = arg;
2207             return 1;
2208         }
2209         if (arg != octx->taglen || c->encrypt)
2210             return 0;
2211         memcpy(octx->tag, ptr, arg);
2212         return 1;
2213
2214     case EVP_CTRL_AEAD_GET_TAG:
2215         if (arg != octx->taglen || !c->encrypt)
2216             return 0;
2217
2218         memcpy(ptr, octx->tag, arg);
2219         return 1;
2220
2221     case EVP_CTRL_COPY:
2222         newc = (EVP_CIPHER_CTX *)ptr;
2223         new_octx = newc->cipher_data;
2224         return CRYPTO_ocb128_copy_ctx(&new_octx->ocb, &octx->ocb,
2225                                       &new_octx->ksenc, &new_octx->ksdec);
2226
2227     default:
2228         return -1;
2229
2230     }
2231 }
2232
2233 static int aes_ocb_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
2234                             const unsigned char *iv, int enc)
2235 {
2236     EVP_AES_OCB_CTX *octx = ctx->cipher_data;
2237     if (!iv && !key)
2238         return 1;
2239     if (key) {
2240         do {
2241             /*
2242              * We set both the encrypt and decrypt key here because decrypt
2243              * needs both. We could possibly optimise to remove setting the
2244              * decrypt for an encryption operation.
2245              */
2246 #  ifdef VPAES_CAPABLE
2247             if (VPAES_CAPABLE) {
2248                 vpaes_set_encrypt_key(key, ctx->key_len * 8, &octx->ksenc);
2249                 vpaes_set_decrypt_key(key, ctx->key_len * 8, &octx->ksdec);
2250                 if (!CRYPTO_ocb128_init
2251                     (&octx->ocb, &octx->ksenc, &octx->ksdec,
2252                      (block128_f) vpaes_encrypt, (block128_f) vpaes_decrypt))
2253                     return 0;
2254                 break;
2255             }
2256 #  endif
2257             AES_set_encrypt_key(key, ctx->key_len * 8, &octx->ksenc);
2258             AES_set_decrypt_key(key, ctx->key_len * 8, &octx->ksdec);
2259             if (!CRYPTO_ocb128_init(&octx->ocb, &octx->ksenc, &octx->ksdec,
2260                                     (block128_f) AES_encrypt,
2261                                     (block128_f) AES_decrypt))
2262                 return 0;
2263         }
2264         while (0);
2265
2266         /*
2267          * If we have an iv we can set it directly, otherwise use saved IV.
2268          */
2269         if (iv == NULL && octx->iv_set)
2270             iv = octx->iv;
2271         if (iv) {
2272             if (CRYPTO_ocb128_setiv(&octx->ocb, iv, octx->ivlen, octx->taglen)
2273                 != 1)
2274                 return 0;
2275             octx->iv_set = 1;
2276         }
2277         octx->key_set = 1;
2278     } else {
2279         /* If key set use IV, otherwise copy */
2280         if (octx->key_set)
2281             CRYPTO_ocb128_setiv(&octx->ocb, iv, octx->ivlen, octx->taglen);
2282         else
2283             memcpy(octx->iv, iv, octx->ivlen);
2284         octx->iv_set = 1;
2285     }
2286     return 1;
2287 }
2288
2289 static int aes_ocb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
2290                           const unsigned char *in, size_t len)
2291 {
2292     unsigned char *buf;
2293     int *buf_len;
2294     int written_len = 0;
2295     size_t trailing_len;
2296     EVP_AES_OCB_CTX *octx = ctx->cipher_data;
2297
2298     /* If IV or Key not set then return error */
2299     if (!octx->iv_set)
2300         return -1;
2301
2302     if (!octx->key_set)
2303         return -1;
2304
2305     if (in) {
2306         /*
2307          * Need to ensure we are only passing full blocks to low level OCB
2308          * routines. We do it here rather than in EVP_EncryptUpdate/
2309          * EVP_DecryptUpdate because we need to pass full blocks of AAD too
2310          * and those routines don't support that
2311          */
2312
2313         /* Are we dealing with AAD or normal data here? */
2314         if (out == NULL) {
2315             buf = octx->aad_buf;
2316             buf_len = &(octx->aad_buf_len);
2317         } else {
2318             buf = octx->data_buf;
2319             buf_len = &(octx->data_buf_len);
2320         }
2321
2322         /*
2323          * If we've got a partially filled buffer from a previous call then
2324          * use that data first
2325          */
2326         if (*buf_len) {
2327             unsigned int remaining;
2328
2329             remaining = 16 - (*buf_len);
2330             if (remaining > len) {
2331                 memcpy(buf + (*buf_len), in, len);
2332                 *(buf_len) += len;
2333                 return 0;
2334             }
2335             memcpy(buf + (*buf_len), in, remaining);
2336
2337             /*
2338              * If we get here we've filled the buffer, so process it
2339              */
2340             len -= remaining;
2341             in += remaining;
2342             if (out == NULL) {
2343                 if (!CRYPTO_ocb128_aad(&octx->ocb, buf, 16))
2344                     return -1;
2345             } else if (ctx->encrypt) {
2346                 if (!CRYPTO_ocb128_encrypt(&octx->ocb, buf, out, 16))
2347                     return -1;
2348             } else {
2349                 if (!CRYPTO_ocb128_decrypt(&octx->ocb, buf, out, 16))
2350                     return -1;
2351             }
2352             written_len = 16;
2353             *buf_len = 0;
2354         }
2355
2356         /* Do we have a partial block to handle at the end? */
2357         trailing_len = len % 16;
2358
2359         /*
2360          * If we've got some full blocks to handle, then process these first
2361          */
2362         if (len != trailing_len) {
2363             if (out == NULL) {
2364                 if (!CRYPTO_ocb128_aad(&octx->ocb, in, len - trailing_len))
2365                     return -1;
2366             } else if (ctx->encrypt) {
2367                 if (!CRYPTO_ocb128_encrypt
2368                     (&octx->ocb, in, out, len - trailing_len))
2369                     return -1;
2370             } else {
2371                 if (!CRYPTO_ocb128_decrypt
2372                     (&octx->ocb, in, out, len - trailing_len))
2373                     return -1;
2374             }
2375             written_len += len - trailing_len;
2376             in += len - trailing_len;
2377         }
2378
2379         /* Handle any trailing partial block */
2380         if (trailing_len) {
2381             memcpy(buf, in, trailing_len);
2382             *buf_len = trailing_len;
2383         }
2384
2385         return written_len;
2386     } else {
2387         /*
2388          * First of all empty the buffer of any partial block that we might
2389          * have been provided - both for data and AAD
2390          */
2391         if (octx->data_buf_len) {
2392             if (ctx->encrypt) {
2393                 if (!CRYPTO_ocb128_encrypt(&octx->ocb, octx->data_buf, out,
2394                                            octx->data_buf_len))
2395                     return -1;
2396             } else {
2397                 if (!CRYPTO_ocb128_decrypt(&octx->ocb, octx->data_buf, out,
2398                                            octx->data_buf_len))
2399                     return -1;
2400             }
2401             written_len = octx->data_buf_len;
2402             octx->data_buf_len = 0;
2403         }
2404         if (octx->aad_buf_len) {
2405             if (!CRYPTO_ocb128_aad
2406                 (&octx->ocb, octx->aad_buf, octx->aad_buf_len))
2407                 return -1;
2408             octx->aad_buf_len = 0;
2409         }
2410         /* If decrypting then verify */
2411         if (!ctx->encrypt) {
2412             if (octx->taglen < 0)
2413                 return -1;
2414             if (CRYPTO_ocb128_finish(&octx->ocb,
2415                                      octx->tag, octx->taglen) != 0)
2416                 return -1;
2417             octx->iv_set = 0;
2418             return written_len;
2419         }
2420         /* If encrypting then just get the tag */
2421         if (CRYPTO_ocb128_tag(&octx->ocb, octx->tag, 16) != 1)
2422             return -1;
2423         /* Don't reuse the IV */
2424         octx->iv_set = 0;
2425         return written_len;
2426     }
2427 }
2428
2429 static int aes_ocb_cleanup(EVP_CIPHER_CTX *c)
2430 {
2431     EVP_AES_OCB_CTX *octx = c->cipher_data;
2432     CRYPTO_ocb128_cleanup(&octx->ocb);
2433     return 1;
2434 }
2435
2436 BLOCK_CIPHER_custom(NID_aes, 128, 16, 12, ocb, OCB, CUSTOM_FLAGS)
2437     BLOCK_CIPHER_custom(NID_aes, 192, 16, 12, ocb, OCB, CUSTOM_FLAGS)
2438     BLOCK_CIPHER_custom(NID_aes, 256, 16, 12, ocb, OCB, CUSTOM_FLAGS)
2439 # endif                         /* OPENSSL_NO_OCB */
2440 #endif