gcm128.c: commentary and formatting updates.
[openssl.git] / crypto / engine / eng_aesni.c
1 /*
2  * Support for Intel AES-NI intruction set
3  *   Author: Huang Ying <ying.huang@intel.com>
4  *
5  * Intel AES-NI is a new set of Single Instruction Multiple Data
6  * (SIMD) instructions that are going to be introduced in the next
7  * generation of Intel processor, as of 2009. These instructions
8  * enable fast and secure data encryption and decryption, using the
9  * Advanced Encryption Standard (AES), defined by FIPS Publication
10  * number 197.  The architecture introduces six instructions that
11  * offer full hardware support for AES. Four of them support high
12  * performance data encryption and decryption, and the other two
13  * instructions support the AES key expansion procedure.
14  *
15  * The white paper can be downloaded from:
16  *   http://softwarecommunity.intel.com/isn/downloads/intelavx/AES-Instructions-Set_WP.pdf
17  *
18  * This file is based on engines/e_padlock.c
19  */
20
21 /* ====================================================================
22  * Copyright (c) 1999-2001 The OpenSSL Project.  All rights reserved.
23  *
24  * Redistribution and use in source and binary forms, with or without
25  * modification, are permitted provided that the following conditions
26  * are met:
27  *
28  * 1. Redistributions of source code must retain the above copyright
29  *    notice, this list of conditions and the following disclaimer.
30  *
31  * 2. Redistributions in binary form must reproduce the above copyright
32  *    notice, this list of conditions and the following disclaimer in
33  *    the documentation and/or other materials provided with the
34  *    distribution.
35  *
36  * 3. All advertising materials mentioning features or use of this
37  *    software must display the following acknowledgment:
38  *    "This product includes software developed by the OpenSSL Project
39  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
40  *
41  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
42  *    endorse or promote products derived from this software without
43  *    prior written permission. For written permission, please contact
44  *    licensing@OpenSSL.org.
45  *
46  * 5. Products derived from this software may not be called "OpenSSL"
47  *    nor may "OpenSSL" appear in their names without prior written
48  *    permission of the OpenSSL Project.
49  *
50  * 6. Redistributions of any form whatsoever must retain the following
51  *    acknowledgment:
52  *    "This product includes software developed by the OpenSSL Project
53  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
54  *
55  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
56  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
57  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
58  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
59  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
60  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
61  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
62  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
63  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
64  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
65  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
66  * OF THE POSSIBILITY OF SUCH DAMAGE.
67  * ====================================================================
68  *
69  * This product includes cryptographic software written by Eric Young
70  * (eay@cryptsoft.com).  This product includes software written by Tim
71  * Hudson (tjh@cryptsoft.com).
72  *
73  */
74
75
76 #include <openssl/opensslconf.h>
77
78 #if !defined(OPENSSL_NO_HW) && !defined(OPENSSL_NO_HW_AES_NI) && !defined(OPENSSL_NO_AES)
79
80 #include <stdio.h>
81 #include "cryptlib.h"
82 #include <openssl/dso.h>
83 #include <openssl/engine.h>
84 #include <openssl/evp.h>
85 #include <openssl/aes.h>
86 #include <openssl/err.h>
87 #include <openssl/modes.h>
88
89 /* AES-NI is available *ONLY* on some x86 CPUs.  Not only that it
90    doesn't exist elsewhere, but it even can't be compiled on other
91    platforms! */
92 #undef COMPILE_HW_AESNI
93 #if (defined(__x86_64) || defined(__x86_64__) || \
94      defined(_M_AMD64) || defined(_M_X64) || \
95      defined(OPENSSL_IA32_SSE2)) && !defined(OPENSSL_NO_ASM)
96 #define COMPILE_HW_AESNI
97 static ENGINE *ENGINE_aesni (void);
98 #endif
99
100 void ENGINE_load_aesni (void)
101 {
102 /* On non-x86 CPUs it just returns. */
103 #ifdef COMPILE_HW_AESNI
104         ENGINE *toadd = ENGINE_aesni();
105         if (!toadd)
106                 return;
107         ENGINE_add (toadd);
108         ENGINE_free (toadd);
109         ERR_clear_error ();
110 #endif
111 }
112
113 #ifdef COMPILE_HW_AESNI
114
115 typedef unsigned int u32;
116 typedef unsigned char u8;
117
118 #if defined(__GNUC__) && __GNUC__>=2
119 #  define BSWAP4(x) ({  u32 ret=(x);                    \
120                         asm volatile ("bswapl %0"       \
121                         : "+r"(ret));   ret;            })
122 #elif defined(_MSC_VER)
123 # if _MSC_VER>=1300
124 #  pragma intrinsic(_byteswap_ulong)
125 #  define BSWAP4(x)     _byteswap_ulong((u32)(x))
126 # elif defined(_M_IX86)
127    __inline u32 _bswap4(u32 val) {
128         _asm mov eax,val
129         _asm bswap eax
130    }
131 #  define BSWAP4(x)     _bswap4(x)
132 # endif
133 #endif
134
135 #ifdef BSWAP4
136 #define GETU32(p)       BSWAP4(*(const u32 *)(p))
137 #define PUTU32(p,v)     *(u32 *)(p) = BSWAP4(v)
138 #else
139 #define GETU32(p)       ((u32)(p)[0]<<24|(u32)(p)[1]<<16|(u32)(p)[2]<<8|(u32)(p)[3])
140 #define PUTU32(p,v)     ((p)[0]=(u8)((v)>>24),(p)[1]=(u8)((v)>>16),(p)[2]=(u8)((v)>>8),(p)[3]=(u8)(v))
141 #endif
142
143 int aesni_set_encrypt_key(const unsigned char *userKey, int bits,
144                               AES_KEY *key);
145 int aesni_set_decrypt_key(const unsigned char *userKey, int bits,
146                               AES_KEY *key);
147
148 void aesni_encrypt(const unsigned char *in, unsigned char *out,
149                        const AES_KEY *key);
150 void aesni_decrypt(const unsigned char *in, unsigned char *out,
151                        const AES_KEY *key);
152
153 void aesni_ecb_encrypt(const unsigned char *in,
154                            unsigned char *out,
155                            size_t length,
156                            const AES_KEY *key,
157                            int enc);
158 void aesni_cbc_encrypt(const unsigned char *in,
159                            unsigned char *out,
160                            size_t length,
161                            const AES_KEY *key,
162                            unsigned char *ivec, int enc);
163
164 void aesni_ctr32_encrypt_blocks(const unsigned char *in,
165                            unsigned char *out,
166                            size_t blocks,
167                            const AES_KEY *key,
168                            const unsigned char *ivec);
169
170 /* Function for ENGINE detection and control */
171 static int aesni_init(ENGINE *e);
172
173 /* Cipher Stuff */
174 static int aesni_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
175                                 const int **nids, int nid);
176
177 #define AESNI_MIN_ALIGN 16
178 #define AESNI_ALIGN(x) \
179         ((void *)(((unsigned long)(x)+AESNI_MIN_ALIGN-1)&~(AESNI_MIN_ALIGN-1)))
180
181 /* Engine names */
182 static const char   aesni_id[] = "aesni",
183                     aesni_name[] = "Intel AES-NI engine",
184                     no_aesni_name[] = "Intel AES-NI engine (no-aesni)";
185
186 /* ===== Engine "management" functions ===== */
187
188 /* Prepare the ENGINE structure for registration */
189 static int
190 aesni_bind_helper(ENGINE *e)
191 {
192         int engage = (OPENSSL_ia32cap_P[1] & (1 << (57-32))) != 0;
193
194         /* Register everything or return with an error */
195         if (!ENGINE_set_id(e, aesni_id) ||
196             !ENGINE_set_name(e, engage ? aesni_name : no_aesni_name) ||
197
198             !ENGINE_set_init_function(e, aesni_init) ||
199             (engage && !ENGINE_set_ciphers (e, aesni_ciphers))
200             )
201                 return 0;
202
203         /* Everything looks good */
204         return 1;
205 }
206
207 /* Constructor */
208 static ENGINE *
209 ENGINE_aesni(void)
210 {
211         ENGINE *eng = ENGINE_new();
212
213         if (!eng) {
214                 return NULL;
215         }
216
217         if (!aesni_bind_helper(eng)) {
218                 ENGINE_free(eng);
219                 return NULL;
220         }
221
222         return eng;
223 }
224
225 /* Check availability of the engine */
226 static int
227 aesni_init(ENGINE *e)
228 {
229         return 1;
230 }
231
232 #if defined(NID_aes_128_cfb128) && ! defined (NID_aes_128_cfb)
233 #define NID_aes_128_cfb NID_aes_128_cfb128
234 #endif
235
236 #if defined(NID_aes_128_ofb128) && ! defined (NID_aes_128_ofb)
237 #define NID_aes_128_ofb NID_aes_128_ofb128
238 #endif
239
240 #if defined(NID_aes_192_cfb128) && ! defined (NID_aes_192_cfb)
241 #define NID_aes_192_cfb NID_aes_192_cfb128
242 #endif
243
244 #if defined(NID_aes_192_ofb128) && ! defined (NID_aes_192_ofb)
245 #define NID_aes_192_ofb NID_aes_192_ofb128
246 #endif
247
248 #if defined(NID_aes_256_cfb128) && ! defined (NID_aes_256_cfb)
249 #define NID_aes_256_cfb NID_aes_256_cfb128
250 #endif
251
252 #if defined(NID_aes_256_ofb128) && ! defined (NID_aes_256_ofb)
253 #define NID_aes_256_ofb NID_aes_256_ofb128
254 #endif
255
256 /* List of supported ciphers. */
257 static int aesni_cipher_nids[] = {
258         NID_aes_128_ecb,
259         NID_aes_128_cbc,
260         NID_aes_128_cfb,
261         NID_aes_128_ofb,
262         NID_aes_128_ctr,
263
264         NID_aes_192_ecb,
265         NID_aes_192_cbc,
266         NID_aes_192_cfb,
267         NID_aes_192_ofb,
268         NID_aes_192_ctr,
269
270         NID_aes_256_ecb,
271         NID_aes_256_cbc,
272         NID_aes_256_cfb,
273         NID_aes_256_ofb,
274         NID_aes_256_ctr,
275 };
276 static int aesni_cipher_nids_num =
277         (sizeof(aesni_cipher_nids)/sizeof(aesni_cipher_nids[0]));
278
279 typedef struct
280 {
281         AES_KEY ks;
282         unsigned int _pad1[3];
283 } AESNI_KEY;
284
285 static int
286 aesni_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *user_key,
287                     const unsigned char *iv, int enc)
288 {
289         int ret;
290         AES_KEY *key = AESNI_ALIGN(ctx->cipher_data);
291
292         if (((ctx->cipher->flags & EVP_CIPH_MODE) == EVP_CIPH_ECB_MODE
293             || (ctx->cipher->flags & EVP_CIPH_MODE) == EVP_CIPH_CBC_MODE)
294             && !enc)
295                 ret=aesni_set_decrypt_key(user_key, ctx->key_len * 8, key);
296         else
297                 ret=aesni_set_encrypt_key(user_key, ctx->key_len * 8, key);
298
299         if(ret < 0) {
300                 EVPerr(EVP_F_AESNI_INIT_KEY,EVP_R_AES_KEY_SETUP_FAILED);
301                 return 0;
302         }
303
304         if (ctx->cipher->flags&EVP_CIPH_CUSTOM_IV)
305                 {
306                 if (iv!=NULL)
307                         memcpy (ctx->iv,iv,ctx->cipher->iv_len);
308                 else    {
309                         EVPerr(EVP_F_AESNI_INIT_KEY,EVP_R_AES_IV_SETUP_FAILED);
310                         return 0;
311                         }
312                 }
313
314         return 1;
315 }
316
317 static int aesni_cipher_ecb(EVP_CIPHER_CTX *ctx, unsigned char *out,
318                  const unsigned char *in, size_t inl)
319 {       AES_KEY *key = AESNI_ALIGN(ctx->cipher_data);
320         aesni_ecb_encrypt(in, out, inl, key, ctx->encrypt);
321         return 1;
322 }
323 static int aesni_cipher_cbc(EVP_CIPHER_CTX *ctx, unsigned char *out,
324                  const unsigned char *in, size_t inl)
325 {       AES_KEY *key = AESNI_ALIGN(ctx->cipher_data);
326         aesni_cbc_encrypt(in, out, inl, key,
327                               ctx->iv, ctx->encrypt);
328         return 1;
329 }
330 static int aesni_cipher_cfb(EVP_CIPHER_CTX *ctx, unsigned char *out,
331                  const unsigned char *in, size_t inl)
332 {       AES_KEY *key = AESNI_ALIGN(ctx->cipher_data);
333         CRYPTO_cfb128_encrypt(in, out, inl, key, ctx->iv,
334                                 &ctx->num, ctx->encrypt,
335                                 (block128_f)aesni_encrypt);
336         return 1;
337 }
338 static int aesni_cipher_ofb(EVP_CIPHER_CTX *ctx, unsigned char *out,
339                  const unsigned char *in, size_t inl)
340 {       AES_KEY *key = AESNI_ALIGN(ctx->cipher_data);
341         CRYPTO_ofb128_encrypt(in, out, inl, key, ctx->iv,
342                                 &ctx->num, (block128_f)aesni_encrypt);
343         return 1;
344 }
345
346 #define AES_BLOCK_SIZE          16
347
348 #define EVP_CIPHER_block_size_ECB       AES_BLOCK_SIZE
349 #define EVP_CIPHER_block_size_CBC       AES_BLOCK_SIZE
350 #define EVP_CIPHER_block_size_OFB       1
351 #define EVP_CIPHER_block_size_CFB       1
352
353 /* Declaring so many ciphers by hand would be a pain.
354    Instead introduce a bit of preprocessor magic :-) */
355 #define DECLARE_AES_EVP(ksize,lmode,umode)      \
356 static const EVP_CIPHER aesni_##ksize##_##lmode = {     \
357         NID_aes_##ksize##_##lmode,                      \
358         EVP_CIPHER_block_size_##umode,                  \
359         ksize / 8,                                      \
360         AES_BLOCK_SIZE,                                 \
361         0 | EVP_CIPH_##umode##_MODE,                    \
362         aesni_init_key,                         \
363         aesni_cipher_##lmode,                           \
364         NULL,                                           \
365         sizeof(AESNI_KEY),                              \
366         EVP_CIPHER_set_asn1_iv,                         \
367         EVP_CIPHER_get_asn1_iv,                         \
368         NULL,                                           \
369         NULL                                            \
370 }
371
372 DECLARE_AES_EVP(128,ecb,ECB);
373 DECLARE_AES_EVP(128,cbc,CBC);
374 DECLARE_AES_EVP(128,cfb,CFB);
375 DECLARE_AES_EVP(128,ofb,OFB);
376
377 DECLARE_AES_EVP(192,ecb,ECB);
378 DECLARE_AES_EVP(192,cbc,CBC);
379 DECLARE_AES_EVP(192,cfb,CFB);
380 DECLARE_AES_EVP(192,ofb,OFB);
381
382 DECLARE_AES_EVP(256,ecb,ECB);
383 DECLARE_AES_EVP(256,cbc,CBC);
384 DECLARE_AES_EVP(256,cfb,CFB);
385 DECLARE_AES_EVP(256,ofb,OFB);
386
387 static void ctr96_inc(unsigned char *counter) {
388         u32 n=12;
389         u8  c;
390
391         do {
392                 --n;
393                 c = counter[n];
394                 ++c;
395                 counter[n] = c;
396                 if (c) return;
397         } while (n);
398 }
399
400 static int aesni_counter(EVP_CIPHER_CTX *ctx, unsigned char *out,
401                 const unsigned char *in, size_t len)
402 {
403         AES_KEY *key = AESNI_ALIGN(ctx->cipher_data);
404         u32 n, ctr32;
405         n = ctx->num;
406
407         while (n && len) {
408                 *(out++) = *(in++) ^ ctx->buf[n];
409                 --len;
410                 n = (n+1) % 16;
411         }
412
413         ctr32 = GETU32(ctx->iv+12);
414         while (len>=16) {
415                 size_t blocks = len/16;
416                 /*
417                  * 1<<24 is just a not-so-small yet not-so-large number...
418                  */
419                 if (blocks > (1U<<24)) blocks = (1U<<24);
420                 /*
421                  * As aesni_ctr32 operates on 32-bit counter, caller
422                  * has to handle overflow. 'if' below detects the
423                  * overflow, which is then handled by limiting the
424                  * amount of blocks to the exact overflow point...
425                  */
426                 ctr32 += (u32)blocks;
427                 if (ctr32 < blocks) {
428                         blocks -= ctr32;
429                         ctr32   = 0;
430                 }
431                 aesni_ctr32_encrypt_blocks(in,out,blocks,key,ctx->iv);
432                 /* aesni_ctr32 does not update ctx->iv, caller does: */
433                 PUTU32(ctx->iv+12,ctr32);
434                 /* ... overflow was detected, propogate carry. */
435                 if (ctr32 == 0) ctr96_inc(ctx->iv);
436                 blocks *= 16;
437                 len -= blocks;
438                 out += blocks;
439                 in  += blocks;
440         }
441         if (len) {
442                 aesni_encrypt(ctx->iv,ctx->buf,key);
443                 ++ctr32;
444                 PUTU32(ctx->iv+12,ctr32);
445                 if (ctr32 == 0) ctr96_inc(ctx->iv);
446                 while (len--) {
447                         out[n] = in[n] ^ ctx->buf[n];
448                         ++n;
449                 }
450         }
451         ctx->num = n;
452
453         return 1;
454 }
455
456 static const EVP_CIPHER aesni_128_ctr=
457         {
458         NID_aes_128_ctr,1,16,16,
459         EVP_CIPH_CUSTOM_IV,
460         aesni_init_key,
461         aesni_counter,
462         NULL,
463         sizeof(AESNI_KEY),
464         NULL,
465         NULL,
466         NULL,
467         NULL
468         };
469
470 static const EVP_CIPHER aesni_192_ctr=
471         {
472         NID_aes_192_ctr,1,24,16,
473         EVP_CIPH_CUSTOM_IV,
474         aesni_init_key,
475         aesni_counter,
476         NULL,
477         sizeof(AESNI_KEY),
478         NULL,
479         NULL,
480         NULL,
481         NULL
482         };
483
484 static const EVP_CIPHER aesni_256_ctr=
485         {
486         NID_aes_256_ctr,1,32,16,
487         EVP_CIPH_CUSTOM_IV,
488         aesni_init_key,
489         aesni_counter,
490         NULL,
491         sizeof(AESNI_KEY),
492         NULL,
493         NULL,
494         NULL,
495         NULL
496         };
497
498 static int
499 aesni_ciphers (ENGINE *e, const EVP_CIPHER **cipher,
500                       const int **nids, int nid)
501 {
502         /* No specific cipher => return a list of supported nids ... */
503         if (!cipher) {
504                 *nids = aesni_cipher_nids;
505                 return aesni_cipher_nids_num;
506         }
507
508         /* ... or the requested "cipher" otherwise */
509         switch (nid) {
510         case NID_aes_128_ecb:
511                 *cipher = &aesni_128_ecb;
512                 break;
513         case NID_aes_128_cbc:
514                 *cipher = &aesni_128_cbc;
515                 break;
516         case NID_aes_128_cfb:
517                 *cipher = &aesni_128_cfb;
518                 break;
519         case NID_aes_128_ofb:
520                 *cipher = &aesni_128_ofb;
521                 break;
522         case NID_aes_128_ctr:
523                 *cipher = &aesni_128_ctr;
524                 break;
525
526         case NID_aes_192_ecb:
527                 *cipher = &aesni_192_ecb;
528                 break;
529         case NID_aes_192_cbc:
530                 *cipher = &aesni_192_cbc;
531                 break;
532         case NID_aes_192_cfb:
533                 *cipher = &aesni_192_cfb;
534                 break;
535         case NID_aes_192_ofb:
536                 *cipher = &aesni_192_ofb;
537                 break;
538         case NID_aes_192_ctr:
539                 *cipher = &aesni_192_ctr;
540                 break;
541
542         case NID_aes_256_ecb:
543                 *cipher = &aesni_256_ecb;
544                 break;
545         case NID_aes_256_cbc:
546                 *cipher = &aesni_256_cbc;
547                 break;
548         case NID_aes_256_cfb:
549                 *cipher = &aesni_256_cfb;
550                 break;
551         case NID_aes_256_ofb:
552                 *cipher = &aesni_256_ofb;
553                 break;
554         case NID_aes_256_ctr:
555                 *cipher = &aesni_256_ctr;
556                 break;
557
558         default:
559                 /* Sorry, we don't support this NID */
560                 *cipher = NULL;
561                 return 0;
562         }
563
564         return 1;
565 }
566
567 #endif /* COMPILE_HW_AESNI */
568 #endif /* !defined(OPENSSL_NO_HW) && !defined(OPENSSL_NO_HW_AESNI) && !defined(OPENSSL_NO_AES) */