2 * Support for VIA PadLock Advanced Cryptography Engine (ACE)
3 * Written by Michal Ludvig <michal@logix.cz>
4 * http://www.logix.cz/michal
6 * Big thanks to Andy Polyakov for a help with optimization,
7 * assembler fixes, port to MS Windows and a lot of other
8 * valuable work on this engine!
11 /* ====================================================================
12 * Copyright (c) 1999-2001 The OpenSSL Project. All rights reserved.
14 * Redistribution and use in source and binary forms, with or without
15 * modification, are permitted provided that the following conditions
18 * 1. Redistributions of source code must retain the above copyright
19 * notice, this list of conditions and the following disclaimer.
21 * 2. Redistributions in binary form must reproduce the above copyright
22 * notice, this list of conditions and the following disclaimer in
23 * the documentation and/or other materials provided with the
26 * 3. All advertising materials mentioning features or use of this
27 * software must display the following acknowledgment:
28 * "This product includes software developed by the OpenSSL Project
29 * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
31 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
32 * endorse or promote products derived from this software without
33 * prior written permission. For written permission, please contact
34 * licensing@OpenSSL.org.
36 * 5. Products derived from this software may not be called "OpenSSL"
37 * nor may "OpenSSL" appear in their names without prior written
38 * permission of the OpenSSL Project.
40 * 6. Redistributions of any form whatsoever must retain the following
42 * "This product includes software developed by the OpenSSL Project
43 * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
45 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
46 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
47 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
48 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
49 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
50 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
51 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
52 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
53 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
54 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
55 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
56 * OF THE POSSIBILITY OF SUCH DAMAGE.
57 * ====================================================================
59 * This product includes cryptographic software written by Eric Young
60 * (eay@cryptsoft.com). This product includes software written by Tim
61 * Hudson (tjh@cryptsoft.com).
68 #include <openssl/opensslconf.h>
69 #include <openssl/crypto.h>
70 #include <openssl/dso.h>
71 #include <openssl/engine.h>
72 #include <openssl/evp.h>
73 #ifndef OPENSSL_NO_AES
74 # include <openssl/aes.h>
76 #include <openssl/rand.h>
77 #include <openssl/err.h>
80 # ifndef OPENSSL_NO_HW_PADLOCK
82 /* Attempt to have a single source for both 0.9.7 and 0.9.8 :-) */
83 # if (OPENSSL_VERSION_NUMBER >= 0x00908000L)
84 # ifndef OPENSSL_NO_DYNAMIC_ENGINE
85 # define DYNAMIC_ENGINE
87 # elif (OPENSSL_VERSION_NUMBER >= 0x00907000L)
88 # ifdef ENGINE_DYNAMIC_SUPPORT
89 # define DYNAMIC_ENGINE
92 # error "Only OpenSSL >= 0.9.7 is supported"
96 * VIA PadLock AES is available *ONLY* on some x86 CPUs. Not only that it
97 * doesn't exist elsewhere, but it even can't be compiled on other platforms!
99 * In addition, because of the heavy use of inline assembler, compiler choice
100 * is limited to GCC and Microsoft C.
102 # undef COMPILE_HW_PADLOCK
103 # if !defined(I386_ONLY) && !defined(OPENSSL_NO_INLINE_ASM)
104 # if (defined(__GNUC__) && (defined(__i386__) || defined(__i386))) || \
105 (defined(_MSC_VER) && defined(_M_IX86))
106 # define COMPILE_HW_PADLOCK
107 static ENGINE *ENGINE_padlock(void);
111 # ifdef OPENSSL_NO_DYNAMIC_ENGINE
113 void ENGINE_load_padlock(void)
115 /* On non-x86 CPUs it just returns. */
116 # ifdef COMPILE_HW_PADLOCK
117 ENGINE *toadd = ENGINE_padlock();
128 # ifdef COMPILE_HW_PADLOCK
130 * We do these includes here to avoid header problems on platforms that do
131 * not have the VIA padlock anyway...
137 # define alloca _alloca
139 # elif defined(__GNUC__)
141 # define alloca(s) __builtin_alloca(s)
145 /* Function for ENGINE detection and control */
146 static int padlock_available(void);
147 static int padlock_init(ENGINE *e);
150 static RAND_METHOD padlock_rand;
153 # ifndef OPENSSL_NO_AES
154 static int padlock_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
155 const int **nids, int nid);
159 static const char *padlock_id = "padlock";
160 static char padlock_name[100];
162 /* Available features */
163 static int padlock_use_ace = 0; /* Advanced Cryptography Engine */
164 static int padlock_use_rng = 0; /* Random Number Generator */
165 # ifndef OPENSSL_NO_AES
166 static int padlock_aes_align_required = 1;
169 /* ===== Engine "management" functions ===== */
171 /* Prepare the ENGINE structure for registration */
172 static int padlock_bind_helper(ENGINE *e)
174 /* Check available features */
177 # if 1 /* disable RNG for now, see commentary in
178 * vicinity of RNG code */
182 /* Generate a nice engine name with available features */
183 BIO_snprintf(padlock_name, sizeof(padlock_name),
184 "VIA PadLock (%s, %s)",
185 padlock_use_rng ? "RNG" : "no-RNG",
186 padlock_use_ace ? "ACE" : "no-ACE");
188 /* Register everything or return with an error */
189 if (!ENGINE_set_id(e, padlock_id) ||
190 !ENGINE_set_name(e, padlock_name) ||
191 !ENGINE_set_init_function(e, padlock_init) ||
192 # ifndef OPENSSL_NO_AES
193 (padlock_use_ace && !ENGINE_set_ciphers(e, padlock_ciphers)) ||
195 (padlock_use_rng && !ENGINE_set_RAND(e, &padlock_rand))) {
199 /* Everything looks good */
204 static ENGINE *ENGINE_padlock(void)
206 ENGINE *eng = ENGINE_new();
212 if (!padlock_bind_helper(eng)) {
220 /* Check availability of the engine */
221 static int padlock_init(ENGINE *e)
223 return (padlock_use_rng || padlock_use_ace);
227 * This stuff is needed if this ENGINE is being compiled into a
228 * self-contained shared-library.
230 # ifdef DYNAMIC_ENGINE
231 static int padlock_bind_fn(ENGINE *e, const char *id)
233 if (id && (strcmp(id, padlock_id) != 0)) {
237 if (!padlock_bind_helper(e)) {
244 IMPLEMENT_DYNAMIC_CHECK_FN()
245 IMPLEMENT_DYNAMIC_BIND_FN(padlock_bind_fn)
246 # endif /* DYNAMIC_ENGINE */
247 /* ===== Here comes the "real" engine ===== */
248 # ifndef OPENSSL_NO_AES
249 /* Some AES-related constants */
250 # define AES_BLOCK_SIZE 16
251 # define AES_KEY_SIZE_128 16
252 # define AES_KEY_SIZE_192 24
253 # define AES_KEY_SIZE_256 32
255 * Here we store the status information relevant to the current context.
258 * BIG FAT WARNING: Inline assembler in PADLOCK_XCRYPT_ASM() depends on
259 * the order of items in this structure. Don't blindly modify, reorder,
262 struct padlock_cipher_data {
263 unsigned char iv[AES_BLOCK_SIZE]; /* Initialization vector */
268 int dgst:1; /* n/a in C3 */
269 int align:1; /* n/a in C3 */
270 int ciphr:1; /* n/a in C3 */
271 unsigned int keygen:1;
273 unsigned int encdec:1;
276 } cword; /* Control word */
277 AES_KEY ks; /* Encryption key */
281 * Essentially this variable belongs in thread local storage.
282 * Having this variable global on the other hand can only cause
283 * few bogus key reloads [if any at all on single-CPU system],
284 * so we accept the penatly...
286 static volatile struct padlock_cipher_data *padlock_saved_context;
290 * =======================================================
291 * Inline assembler section(s).
292 * =======================================================
293 * Order of arguments is chosen to facilitate Windows port
294 * using __fastcall calling convention. If you wish to add
295 * more routines, keep in mind that first __fastcall
296 * argument is passed in %ecx and second - in %edx.
297 * =======================================================
299 # if defined(__GNUC__) && __GNUC__>=2
301 * As for excessive "push %ebx"/"pop %ebx" found all over.
302 * When generating position-independent code GCC won't let
303 * us use "b" in assembler templates nor even respect "ebx"
304 * in "clobber description." Therefore the trouble...
308 * Helper function - check if a CPUID instruction is available on this CPU
310 static int padlock_insn_cpuid_available(void)
315 * We're checking if the bit #21 of EFLAGS can be toggled. If yes =
316 * CPUID is available.
318 asm volatile ("pushf\n"
320 "xorl $0x200000, %%eax\n"
321 "movl %%eax, %%ecx\n"
322 "andl $0x200000, %%ecx\n"
327 "andl $0x200000, %%eax\n"
328 "xorl %%eax, %%ecx\n"
329 "movl %%ecx, %0\n":"=r" (result)::"eax", "ecx");
331 return (result == 0);
335 * Load supported features of the CPU to see if the PadLock is available.
337 static int padlock_available(void)
339 char vendor_string[16];
340 unsigned int eax, edx;
342 /* First check if the CPUID instruction is available at all... */
343 if (!padlock_insn_cpuid_available())
346 /* Are we running on the Centaur (VIA) CPU? */
348 vendor_string[12] = 0;
349 asm volatile ("pushl %%ebx\n"
351 "movl %%ebx,(%%edi)\n"
352 "movl %%edx,4(%%edi)\n"
353 "movl %%ecx,8(%%edi)\n"
354 "popl %%ebx":"+a" (eax):"D"(vendor_string):"ecx", "edx");
355 if (strcmp(vendor_string, "CentaurHauls") != 0)
358 /* Check for Centaur Extended Feature Flags presence */
360 asm volatile ("pushl %%ebx; cpuid; popl %%ebx":"+a" (eax)::"ecx", "edx");
361 if (eax < 0xC0000001)
364 /* Read the Centaur Extended Feature Flags */
366 asm volatile ("pushl %%ebx; cpuid; popl %%ebx":"+a" (eax),
369 /* Fill up some flags */
370 padlock_use_ace = ((edx & (0x3 << 6)) == (0x3 << 6));
371 padlock_use_rng = ((edx & (0x3 << 2)) == (0x3 << 2));
373 return padlock_use_ace + padlock_use_rng;
376 # ifndef OPENSSL_NO_AES
377 /* Our own htonl()/ntohl() */
378 static inline void padlock_bswapl(AES_KEY *ks)
380 size_t i = sizeof(ks->rd_key) / sizeof(ks->rd_key[0]);
381 unsigned int *key = ks->rd_key;
384 asm volatile ("bswapl %0":"+r" (*key));
391 * Force key reload from memory to the CPU microcode. Loading EFLAGS from the
392 * stack clears EFLAGS[30] which does the trick.
394 static inline void padlock_reload_key(void)
396 asm volatile ("pushfl; popfl");
399 # ifndef OPENSSL_NO_AES
401 * This is heuristic key context tracing. At first one
402 * believes that one should use atomic swap instructions,
403 * but it's not actually necessary. Point is that if
404 * padlock_saved_context was changed by another thread
405 * after we've read it and before we compare it with cdata,
406 * our key *shall* be reloaded upon thread context switch
407 * and we are therefore set in either case...
409 static inline void padlock_verify_context(struct padlock_cipher_data *cdata)
411 asm volatile ("pushfl\n"
419 " movl %2,%0":"+m" (padlock_saved_context)
420 :"r"(padlock_saved_context), "r"(cdata):"cc");
423 /* Template for padlock_xcrypt_* modes */
425 * BIG FAT WARNING: The offsets used with 'leal' instructions describe items
426 * of the 'padlock_cipher_data' structure.
428 # define PADLOCK_XCRYPT_ASM(name,rep_xcrypt) \
429 static inline void *name(size_t cnt, \
430 struct padlock_cipher_data *cdata, \
431 void *out, const void *inp) \
433 asm volatile ( "pushl %%ebx\n" \
434 " leal 16(%0),%%edx\n" \
435 " leal 32(%0),%%ebx\n" \
438 : "=a"(iv), "=c"(cnt), "=D"(out), "=S"(inp) \
439 : "0"(cdata), "1"(cnt), "2"(out), "3"(inp) \
440 : "edx", "cc", "memory"); \
444 /* Generate all functions with appropriate opcodes */
446 PADLOCK_XCRYPT_ASM(padlock_xcrypt_ecb, ".byte 0xf3,0x0f,0xa7,0xc8")
448 PADLOCK_XCRYPT_ASM(padlock_xcrypt_cbc, ".byte 0xf3,0x0f,0xa7,0xd0")
450 PADLOCK_XCRYPT_ASM(padlock_xcrypt_cfb, ".byte 0xf3,0x0f,0xa7,0xe0")
452 PADLOCK_XCRYPT_ASM(padlock_xcrypt_ofb, ".byte 0xf3,0x0f,0xa7,0xe8")
454 /* The RNG call itself */
455 static inline unsigned int padlock_xstore(void *addr, unsigned int edx_in)
457 unsigned int eax_out;
459 asm volatile (".byte 0x0f,0xa7,0xc0" /* xstore */
460 :"=a" (eax_out), "=m"(*(unsigned *)addr)
461 :"D"(addr), "d"(edx_in)
468 * Why not inline 'rep movsd'? I failed to find information on what value in
469 * Direction Flag one can expect and consequently have to apply
470 * "better-safe-than-sorry" approach and assume "undefined." I could
471 * explicitly clear it and restore the original value upon return from
472 * padlock_aes_cipher, but it's presumably too much trouble for too little
473 * gain... In case you wonder 'rep xcrypt*' instructions above are *not*
474 * affected by the Direction Flag and pointers advance toward larger
475 * addresses unconditionally.
477 static inline unsigned char *padlock_memcpy(void *dst, const void *src,
491 # elif defined(_MSC_VER)
493 * Unlike GCC these are real functions. In order to minimize impact
494 * on performance we adhere to __fastcall calling convention in
495 * order to get two first arguments passed through %ecx and %edx.
496 * Which kind of suits very well, as instructions in question use
497 * both %ecx and %edx as input:-)
499 # define REP_XCRYPT(code) \
501 _asm _emit 0x0f _asm _emit 0xa7 \
505 * BIG FAT WARNING: The offsets used with 'lea' instructions describe items
506 * of the 'padlock_cipher_data' structure.
508 # define PADLOCK_XCRYPT_ASM(name,code) \
509 static void * __fastcall \
510 name (size_t cnt, void *cdata, \
511 void *outp, const void *inp) \
513 _asm lea edx,[eax+16] \
514 _asm lea ebx,[eax+32] \
520 PADLOCK_XCRYPT_ASM(padlock_xcrypt_ecb,0xc8)
521 PADLOCK_XCRYPT_ASM(padlock_xcrypt_cbc,0xd0)
522 PADLOCK_XCRYPT_ASM(padlock_xcrypt_cfb,0xe0)
523 PADLOCK_XCRYPT_ASM(padlock_xcrypt_ofb,0xe8)
525 static int __fastcall padlock_xstore(void *outp, unsigned int code)
528 _asm _emit 0x0f _asm _emit 0xa7 _asm _emit 0xc0
531 static void __fastcall padlock_reload_key(void)
537 static void __fastcall padlock_verify_context(void *cdata)
543 cmp ecx,padlock_saved_context
548 mov padlock_saved_context,ecx
553 padlock_available(void)
589 mov padlock_use_ace,1
595 mov padlock_use_rng,1
602 static void __fastcall padlock_bswapl(void *key)
619 * MS actually specifies status of Direction Flag and compiler even manages
620 * to compile following as 'rep movsd' all by itself...
622 # define padlock_memcpy(o,i,n) ((unsigned char *)memcpy((o),(i),(n)&~3U))
624 /* ===== AES encryption/decryption ===== */
625 # ifndef OPENSSL_NO_AES
626 # if defined(NID_aes_128_cfb128) && ! defined (NID_aes_128_cfb)
627 # define NID_aes_128_cfb NID_aes_128_cfb128
629 # if defined(NID_aes_128_ofb128) && ! defined (NID_aes_128_ofb)
630 # define NID_aes_128_ofb NID_aes_128_ofb128
632 # if defined(NID_aes_192_cfb128) && ! defined (NID_aes_192_cfb)
633 # define NID_aes_192_cfb NID_aes_192_cfb128
635 # if defined(NID_aes_192_ofb128) && ! defined (NID_aes_192_ofb)
636 # define NID_aes_192_ofb NID_aes_192_ofb128
638 # if defined(NID_aes_256_cfb128) && ! defined (NID_aes_256_cfb)
639 # define NID_aes_256_cfb NID_aes_256_cfb128
641 # if defined(NID_aes_256_ofb128) && ! defined (NID_aes_256_ofb)
642 # define NID_aes_256_ofb NID_aes_256_ofb128
645 * List of supported ciphers.
646 */ static int padlock_cipher_nids[] = {
663 static int padlock_cipher_nids_num = (sizeof(padlock_cipher_nids) /
664 sizeof(padlock_cipher_nids[0]));
666 /* Function prototypes ... */
667 static int padlock_aes_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
668 const unsigned char *iv, int enc);
669 static int padlock_aes_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
670 const unsigned char *in, size_t nbytes);
672 # define NEAREST_ALIGNED(ptr) ( (unsigned char *)(ptr) + \
673 ( (0x10 - ((size_t)(ptr) & 0x0F)) & 0x0F ) )
674 # define ALIGNED_CIPHER_DATA(ctx) ((struct padlock_cipher_data *)\
675 NEAREST_ALIGNED(ctx->cipher_data))
677 # define EVP_CIPHER_block_size_ECB AES_BLOCK_SIZE
678 # define EVP_CIPHER_block_size_CBC AES_BLOCK_SIZE
679 # define EVP_CIPHER_block_size_OFB 1
680 # define EVP_CIPHER_block_size_CFB 1
683 * Declaring so many ciphers by hand would be a pain. Instead introduce a bit
684 * of preprocessor magic :-)
686 # define DECLARE_AES_EVP(ksize,lmode,umode) \
687 static const EVP_CIPHER padlock_aes_##ksize##_##lmode = { \
688 NID_aes_##ksize##_##lmode, \
689 EVP_CIPHER_block_size_##umode, \
690 AES_KEY_SIZE_##ksize, \
692 0 | EVP_CIPH_##umode##_MODE, \
693 padlock_aes_init_key, \
694 padlock_aes_cipher, \
696 sizeof(struct padlock_cipher_data) + 16, \
697 EVP_CIPHER_set_asn1_iv, \
698 EVP_CIPHER_get_asn1_iv, \
703 DECLARE_AES_EVP(128, ecb, ECB);
704 DECLARE_AES_EVP(128, cbc, CBC);
705 DECLARE_AES_EVP(128, cfb, CFB);
706 DECLARE_AES_EVP(128, ofb, OFB);
708 DECLARE_AES_EVP(192, ecb, ECB);
709 DECLARE_AES_EVP(192, cbc, CBC);
710 DECLARE_AES_EVP(192, cfb, CFB);
711 DECLARE_AES_EVP(192, ofb, OFB);
713 DECLARE_AES_EVP(256, ecb, ECB);
714 DECLARE_AES_EVP(256, cbc, CBC);
715 DECLARE_AES_EVP(256, cfb, CFB);
716 DECLARE_AES_EVP(256, ofb, OFB);
719 padlock_ciphers(ENGINE *e, const EVP_CIPHER **cipher, const int **nids,
722 /* No specific cipher => return a list of supported nids ... */
724 *nids = padlock_cipher_nids;
725 return padlock_cipher_nids_num;
728 /* ... or the requested "cipher" otherwise */
730 case NID_aes_128_ecb:
731 *cipher = &padlock_aes_128_ecb;
733 case NID_aes_128_cbc:
734 *cipher = &padlock_aes_128_cbc;
736 case NID_aes_128_cfb:
737 *cipher = &padlock_aes_128_cfb;
739 case NID_aes_128_ofb:
740 *cipher = &padlock_aes_128_ofb;
743 case NID_aes_192_ecb:
744 *cipher = &padlock_aes_192_ecb;
746 case NID_aes_192_cbc:
747 *cipher = &padlock_aes_192_cbc;
749 case NID_aes_192_cfb:
750 *cipher = &padlock_aes_192_cfb;
752 case NID_aes_192_ofb:
753 *cipher = &padlock_aes_192_ofb;
756 case NID_aes_256_ecb:
757 *cipher = &padlock_aes_256_ecb;
759 case NID_aes_256_cbc:
760 *cipher = &padlock_aes_256_cbc;
762 case NID_aes_256_cfb:
763 *cipher = &padlock_aes_256_cfb;
765 case NID_aes_256_ofb:
766 *cipher = &padlock_aes_256_ofb;
770 /* Sorry, we don't support this NID */
778 /* Prepare the encryption key for PadLock usage */
780 padlock_aes_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
781 const unsigned char *iv, int enc)
783 struct padlock_cipher_data *cdata;
784 int key_len = EVP_CIPHER_CTX_key_length(ctx) * 8;
787 return 0; /* ERROR */
789 cdata = ALIGNED_CIPHER_DATA(ctx);
790 memset(cdata, 0, sizeof(struct padlock_cipher_data));
792 /* Prepare Control word. */
793 if (EVP_CIPHER_CTX_mode(ctx) == EVP_CIPH_OFB_MODE)
794 cdata->cword.b.encdec = 0;
796 cdata->cword.b.encdec = (ctx->encrypt == 0);
797 cdata->cword.b.rounds = 10 + (key_len - 128) / 32;
798 cdata->cword.b.ksize = (key_len - 128) / 64;
803 * PadLock can generate an extended key for AES128 in hardware
805 memcpy(cdata->ks.rd_key, key, AES_KEY_SIZE_128);
806 cdata->cword.b.keygen = 0;
812 * Generate an extended AES key in software. Needed for AES192/AES256
815 * Well, the above applies to Stepping 8 CPUs and is listed as
816 * hardware errata. They most likely will fix it at some point and
817 * then a check for stepping would be due here.
819 if (EVP_CIPHER_CTX_mode(ctx) == EVP_CIPH_CFB_MODE ||
820 EVP_CIPHER_CTX_mode(ctx) == EVP_CIPH_OFB_MODE || enc)
821 AES_set_encrypt_key(key, key_len, &cdata->ks);
823 AES_set_decrypt_key(key, key_len, &cdata->ks);
826 * OpenSSL C functions use byte-swapped extended key.
828 padlock_bswapl(&cdata->ks);
830 cdata->cword.b.keygen = 1;
839 * This is done to cover for cases when user reuses the
840 * context for new key. The catch is that if we don't do
841 * this, padlock_eas_cipher might proceed with old key...
843 padlock_reload_key();
849 * Simplified version of padlock_aes_cipher() used when
850 * 1) both input and output buffers are at aligned addresses.
852 * 2) running on a newer CPU that doesn't require aligned buffers.
855 padlock_aes_cipher_omnivorous(EVP_CIPHER_CTX *ctx, unsigned char *out_arg,
856 const unsigned char *in_arg, size_t nbytes)
858 struct padlock_cipher_data *cdata;
861 cdata = ALIGNED_CIPHER_DATA(ctx);
862 padlock_verify_context(cdata);
864 switch (EVP_CIPHER_CTX_mode(ctx)) {
865 case EVP_CIPH_ECB_MODE:
866 padlock_xcrypt_ecb(nbytes / AES_BLOCK_SIZE, cdata, out_arg, in_arg);
869 case EVP_CIPH_CBC_MODE:
870 memcpy(cdata->iv, ctx->iv, AES_BLOCK_SIZE);
871 iv = padlock_xcrypt_cbc(nbytes / AES_BLOCK_SIZE, cdata, out_arg,
873 memcpy(ctx->iv, iv, AES_BLOCK_SIZE);
876 case EVP_CIPH_CFB_MODE:
877 memcpy(cdata->iv, ctx->iv, AES_BLOCK_SIZE);
878 iv = padlock_xcrypt_cfb(nbytes / AES_BLOCK_SIZE, cdata, out_arg,
880 memcpy(ctx->iv, iv, AES_BLOCK_SIZE);
883 case EVP_CIPH_OFB_MODE:
884 memcpy(cdata->iv, ctx->iv, AES_BLOCK_SIZE);
885 padlock_xcrypt_ofb(nbytes / AES_BLOCK_SIZE, cdata, out_arg, in_arg);
886 memcpy(ctx->iv, cdata->iv, AES_BLOCK_SIZE);
893 memset(cdata->iv, 0, AES_BLOCK_SIZE);
898 # ifndef PADLOCK_CHUNK
899 # define PADLOCK_CHUNK 512 /* Must be a power of 2 larger than 16 */
901 # if PADLOCK_CHUNK<16 || PADLOCK_CHUNK&(PADLOCK_CHUNK-1)
902 # error "insane PADLOCK_CHUNK..."
906 * Re-align the arguments to 16-Bytes boundaries and run the encryption
907 * function itself. This function is not AES-specific.
910 padlock_aes_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out_arg,
911 const unsigned char *in_arg, size_t nbytes)
913 struct padlock_cipher_data *cdata;
917 int inp_misaligned, out_misaligned, realign_in_loop;
918 size_t chunk, allocated = 0;
921 * ctx->num is maintained in byte-oriented modes, such as CFB and OFB...
923 if ((chunk = ctx->num)) { /* borrow chunk variable */
924 unsigned char *ivp = ctx->iv;
926 switch (EVP_CIPHER_CTX_mode(ctx)) {
927 case EVP_CIPH_CFB_MODE:
928 if (chunk >= AES_BLOCK_SIZE)
929 return 0; /* bogus value */
932 while (chunk < AES_BLOCK_SIZE && nbytes != 0) {
933 ivp[chunk] = *(out_arg++) = *(in_arg++) ^ ivp[chunk];
936 while (chunk < AES_BLOCK_SIZE && nbytes != 0) {
937 unsigned char c = *(in_arg++);
938 *(out_arg++) = c ^ ivp[chunk];
939 ivp[chunk++] = c, nbytes--;
942 ctx->num = chunk % AES_BLOCK_SIZE;
944 case EVP_CIPH_OFB_MODE:
945 if (chunk >= AES_BLOCK_SIZE)
946 return 0; /* bogus value */
948 while (chunk < AES_BLOCK_SIZE && nbytes != 0) {
949 *(out_arg++) = *(in_arg++) ^ ivp[chunk];
953 ctx->num = chunk % AES_BLOCK_SIZE;
961 if (nbytes % AES_BLOCK_SIZE)
962 return 0; /* are we expected to do tail processing? */
965 * nbytes is always multiple of AES_BLOCK_SIZE in ECB and CBC modes and
966 * arbitrary value in byte-oriented modes, such as CFB and OFB...
971 * VIA promises CPUs that won't require alignment in the future. For now
972 * padlock_aes_align_required is initialized to 1 and the condition is
976 * C7 core is capable to manage unaligned input in non-ECB[!] mode, but
977 * performance penalties appear to be approximately same as for software
978 * alignment below or ~3x. They promise to improve it in the future, but
979 * for now we can just as well pretend that it can only handle aligned
982 if (!padlock_aes_align_required && (nbytes % AES_BLOCK_SIZE) == 0)
983 return padlock_aes_cipher_omnivorous(ctx, out_arg, in_arg, nbytes);
985 inp_misaligned = (((size_t)in_arg) & 0x0F);
986 out_misaligned = (((size_t)out_arg) & 0x0F);
989 * Note that even if output is aligned and input not, I still prefer to
990 * loop instead of copy the whole input and then encrypt in one stroke.
991 * This is done in order to improve L1 cache utilization...
993 realign_in_loop = out_misaligned | inp_misaligned;
995 if (!realign_in_loop && (nbytes % AES_BLOCK_SIZE) == 0)
996 return padlock_aes_cipher_omnivorous(ctx, out_arg, in_arg, nbytes);
998 /* this takes one "if" out of the loops */
1000 chunk %= PADLOCK_CHUNK;
1002 chunk = PADLOCK_CHUNK;
1004 if (out_misaligned) {
1005 /* optmize for small input */
1006 allocated = (chunk < nbytes ? PADLOCK_CHUNK : nbytes);
1007 out = alloca(0x10 + allocated);
1008 out = NEAREST_ALIGNED(out);
1012 cdata = ALIGNED_CIPHER_DATA(ctx);
1013 padlock_verify_context(cdata);
1015 switch (EVP_CIPHER_CTX_mode(ctx)) {
1016 case EVP_CIPH_ECB_MODE:
1019 inp = padlock_memcpy(out, in_arg, chunk);
1024 padlock_xcrypt_ecb(chunk / AES_BLOCK_SIZE, cdata, out, inp);
1027 out_arg = padlock_memcpy(out_arg, out, chunk) + chunk;
1029 out = out_arg += chunk;
1032 chunk = PADLOCK_CHUNK;
1036 case EVP_CIPH_CBC_MODE:
1037 memcpy(cdata->iv, ctx->iv, AES_BLOCK_SIZE);
1040 if (iv != cdata->iv)
1041 memcpy(cdata->iv, iv, AES_BLOCK_SIZE);
1042 chunk = PADLOCK_CHUNK;
1043 cbc_shortcut: /* optimize for small input */
1045 inp = padlock_memcpy(out, in_arg, chunk);
1050 iv = padlock_xcrypt_cbc(chunk / AES_BLOCK_SIZE, cdata, out, inp);
1053 out_arg = padlock_memcpy(out_arg, out, chunk) + chunk;
1055 out = out_arg += chunk;
1057 } while (nbytes -= chunk);
1058 memcpy(ctx->iv, iv, AES_BLOCK_SIZE);
1061 case EVP_CIPH_CFB_MODE:
1062 memcpy(iv = cdata->iv, ctx->iv, AES_BLOCK_SIZE);
1063 chunk &= ~(AES_BLOCK_SIZE - 1);
1069 if (iv != cdata->iv)
1070 memcpy(cdata->iv, iv, AES_BLOCK_SIZE);
1071 chunk = PADLOCK_CHUNK;
1072 cfb_shortcut: /* optimize for small input */
1074 inp = padlock_memcpy(out, in_arg, chunk);
1079 iv = padlock_xcrypt_cfb(chunk / AES_BLOCK_SIZE, cdata, out, inp);
1082 out_arg = padlock_memcpy(out_arg, out, chunk) + chunk;
1084 out = out_arg += chunk;
1087 } while (nbytes >= AES_BLOCK_SIZE);
1091 unsigned char *ivp = cdata->iv;
1094 memcpy(ivp, iv, AES_BLOCK_SIZE);
1098 if (cdata->cword.b.encdec) {
1099 cdata->cword.b.encdec = 0;
1100 padlock_reload_key();
1101 padlock_xcrypt_ecb(1, cdata, ivp, ivp);
1102 cdata->cword.b.encdec = 1;
1103 padlock_reload_key();
1105 unsigned char c = *(in_arg++);
1106 *(out_arg++) = c ^ *ivp;
1107 *(ivp++) = c, nbytes--;
1110 padlock_reload_key();
1111 padlock_xcrypt_ecb(1, cdata, ivp, ivp);
1112 padlock_reload_key();
1114 *ivp = *(out_arg++) = *(in_arg++) ^ *ivp;
1120 memcpy(ctx->iv, iv, AES_BLOCK_SIZE);
1123 case EVP_CIPH_OFB_MODE:
1124 memcpy(cdata->iv, ctx->iv, AES_BLOCK_SIZE);
1125 chunk &= ~(AES_BLOCK_SIZE - 1);
1129 inp = padlock_memcpy(out, in_arg, chunk);
1134 padlock_xcrypt_ofb(chunk / AES_BLOCK_SIZE, cdata, out, inp);
1137 out_arg = padlock_memcpy(out_arg, out, chunk) + chunk;
1139 out = out_arg += chunk;
1142 chunk = PADLOCK_CHUNK;
1143 } while (nbytes >= AES_BLOCK_SIZE);
1146 unsigned char *ivp = cdata->iv;
1149 padlock_reload_key(); /* empirically found */
1150 padlock_xcrypt_ecb(1, cdata, ivp, ivp);
1151 padlock_reload_key(); /* empirically found */
1153 *(out_arg++) = *(in_arg++) ^ *ivp;
1158 memcpy(ctx->iv, cdata->iv, AES_BLOCK_SIZE);
1165 /* Clean the realign buffer if it was used */
1166 if (out_misaligned) {
1167 volatile unsigned long *p = (void *)out;
1168 size_t n = allocated / sizeof(*p);
1173 memset(cdata->iv, 0, AES_BLOCK_SIZE);
1178 # endif /* OPENSSL_NO_AES */
1180 /* ===== Random Number Generator ===== */
1182 * This code is not engaged. The reason is that it does not comply
1183 * with recommendations for VIA RNG usage for secure applications
1184 * (posted at http://www.via.com.tw/en/viac3/c3.jsp) nor does it
1185 * provide meaningful error control...
1188 * Wrapper that provides an interface between the API and the raw PadLock
1191 static int padlock_rand_bytes(unsigned char *output, int count)
1193 unsigned int eax, buf;
1195 while (count >= 8) {
1196 eax = padlock_xstore(output, 0);
1197 if (!(eax & (1 << 6)))
1198 return 0; /* RNG disabled */
1199 /* this ---vv--- covers DC bias, Raw Bits and String Filter */
1200 if (eax & (0x1F << 10))
1202 if ((eax & 0x1F) == 0)
1203 continue; /* no data, retry... */
1204 if ((eax & 0x1F) != 8)
1205 return 0; /* fatal failure... */
1210 eax = padlock_xstore(&buf, 3);
1211 if (!(eax & (1 << 6)))
1212 return 0; /* RNG disabled */
1213 /* this ---vv--- covers DC bias, Raw Bits and String Filter */
1214 if (eax & (0x1F << 10))
1216 if ((eax & 0x1F) == 0)
1217 continue; /* no data, retry... */
1218 if ((eax & 0x1F) != 1)
1219 return 0; /* fatal failure... */
1220 *output++ = (unsigned char)buf;
1223 *(volatile unsigned int *)&buf = 0;
1228 /* Dummy but necessary function */
1229 static int padlock_rand_status(void)
1234 /* Prepare structure for registration */
1235 static RAND_METHOD padlock_rand = {
1237 padlock_rand_bytes, /* bytes */
1240 padlock_rand_bytes, /* pseudorand */
1241 padlock_rand_status, /* rand status */
1244 # else /* !COMPILE_HW_PADLOCK */
1245 # ifndef OPENSSL_NO_DYNAMIC_ENGINE
1247 int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns);
1249 int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns)
1254 IMPLEMENT_DYNAMIC_CHECK_FN()
1256 # endif /* COMPILE_HW_PADLOCK */
1257 # endif /* !OPENSSL_NO_HW_PADLOCK */
1258 #endif /* !OPENSSL_NO_HW */